Sources/OrgstarMobile/OrgstarMobileApp.swift

7119821e1398fbe6bc6b8362f2b2f6df5d8001ab
orgstar/Sources/OrgstarMobile/OrgstarMobileApp.swift

445 lines · 19456 bytes

  1#if os(iOS)
  2import CoreSpotlight
  3import OrgApp
  4import OrgCore
  5import OrgMathJax
  6import SwiftUI
  7import UserNotifications
  8
  9/// Orgstar on iPhone and iPad: the agenda, capture, and the folders they read.
 10@main
 11struct OrgstarMobileApp: App {
 12    @UIApplicationDelegateAdaptor private var delegate: AppDelegate
 13    @State private var model = MobileModel.shared
 14    /// The app's phase: in the background only when every window is.
 15    @Environment(\.scenePhase) private var scenePhase
 16
 17    init() {
 18        PDFExport.mathJaxURL = OrgMathJax.script
 19        DiagramBlocks.vizURL = OrgMathJax.viz
 20        DiagramBlocks.mermaidURL = OrgMathJax.mermaid
 21        // Debug builds, and runs from Xcode, whose scheme sets ORGSTAR_PERF.
 22        #if DEBUG
 23        Perf.watchMainThread()
 24        #else
 25        if ProcessInfo.processInfo.environment["ORGSTAR_PERF"] != nil { Perf.watchMainThread() }
 26        #endif
 27        LiveClock.install()
 28        ProStore.shared.start()
 29        // Early, so that the watch's actions are taken when iOS wakes the app for them.
 30        WatchLink.shared.activate(MobileModel.shared)
 31    }
 32
 33    var body: some Scene {
 34        WindowGroup {
 35            if let workspace = model.workspace, let agenda = model.agenda {
 36                RootView(model: model, workspace: workspace, agenda: agenda)
 37                    .environment(model)
 38                    .environment(model.clock)
 39                    .onAppear { delegate.model = model }
 40            } else {
 41                ContentUnavailableView("Can't open the index", systemImage: "exclamationmark.triangle", description: Text(model.failure ?? ""))
 42            }
 43        }
 44        // For the clock's idle time: time working in another window isn't time away.
 45        .onChange(of: scenePhase) { _, phase in
 46            if phase == .background { model.clock.wentAway() }
 47        }
 48    }
 49}
 50
 51/// Reminders show while the app is open too, and open their entry when tapped.
 52final class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate {
 53    @MainActor var model: MobileModel?
 54
 55    func application(_ application: UIApplication, didFinishLaunchingWithOptions options: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
 56        UNUserNotificationCenter.current().delegate = self
 57        return true
 58    }
 59
 60    nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification) async -> UNNotificationPresentationOptions {
 61        // A midnight badge update shows nothing else.
 62        if notification.request.content.badge != nil { return [.badge] }
 63        // A countdown's end shows in the app's own message.
 64        if notification.request.identifier == "sh.krz.orgstar.org-timer" { return [] }
 65        return [.banner, .sound, .list]
 66    }
 67
 68    nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {
 69        let info = response.notification.request.content.userInfo
 70        guard let path = info["path"] as? String, let offset = info["offset"] as? Int else { return }
 71        await MainActor.run { model?.openRequest = .offset(path, offset) }
 72    }
 73}
 74
 75enum AppTab: Hashable { case agenda, folders, settings }
 76
 77/// The search screen, pushed from the Agenda and Folders tabs.
 78struct SearchRoute: Hashable {}
 79
 80extension View {
 81    /// Readers pushed for `ReaderRoute`s.
 82    func readerDestination(workspace: WorkspaceModel, session: DocumentSession) -> some View {
 83        navigationDestination(for: ReaderRoute.self) { route in
 84            ReaderScreen(route: route, workspace: workspace, session: session)
 85        }
 86        .navigationDestination(for: EditorRoute.self) { route in
 87            EditorSplitScreen(path: route.path, offset: route.offset, workspace: workspace, session: session)
 88        }
 89        .navigationDestination(for: SearchRoute.self) { _ in
 90            SearchScreen(workspace: workspace, session: session)
 91        }
 92    }
 93}
 94
 95/// A share of files from the share extension.
 96struct SharedFiles: Identifiable {
 97    let id = UUID()
 98    let batch: URL
 99}
100
101/// An org-protocol capture, or a plain one.
102struct CaptureRequest: Identifiable {
103    let id = UUID()
104    var template: String?
105    var properties: [String: String] = [:]
106    /// An agenda day (a `Days` number) the entry is scheduled on.
107    var day: Int?
108}
109
110extension CaptureRequest {
111    /// An `org-protocol://capture` link's request.
112    init?(link: String) {
113        guard case .capture(let template, let properties)? = OrgProtocol.parse(link) else { return nil }
114        self.init(template: template, properties: properties)
115    }
116}
117
118struct RootView: View {
119    let model: MobileModel
120    let workspace: WorkspaceModel
121    let agenda: AgendaModel
122    @State private var capture: CaptureRequest?
123    /// The share extension's link whose capture sheet is showing, with its request's id. The link
124    /// stays in the inbox until the sheet is dismissed.
125    @State private var shared: (link: CaptureInbox.Link, request: UUID)?
126    /// Files from the share extension, waiting for the entry to attach them to.
127    @State private var sharedFiles: SharedFiles?
128    @State private var tab = AppTab.agenda
129    @State private var agendaPath = NavigationPath()
130    @State private var hour = 0
131    @State private var showingClockReport = false
132    @State private var message: String?
133    @Environment(\.scenePhase) private var scenePhase
134    @AppStorage(OnboardingScreen.doneKey) private var onboarded = false
135    @State private var onboarding = false
136    @State private var whatsNew: ReleaseNotes?
137
138    private var session: DocumentSession { model.session }
139
140    /// Reminders, widgets and Spotlight following the files. Its own view, so that edits redraw
141    /// only it, not the tabs.
142    private struct BackgroundWork: View {
143        let model: MobileModel
144        let workspace: WorkspaceModel
145        let agenda: AgendaModel
146        let active: Bool
147        /// Notifications and badges ask for permission, which onboarding asks for first.
148        let onboarded: Bool
149        let hour: Int
150
151        private var session: DocumentSession { model.session }
152
153        var body: some View {
154            Color.clear
155                // Reminders follow the files, the settings, coming back to the app and the hour.
156                .task(id: ReminderKey(hidden: HiddenFolders.shared.all, files: workspace.files.count, changed: workspace.changedFile?.version, edits: session.editVersion,
157                                      settings: model.settingsVersion, active: active, onboarded: onboarded, hour: hour)) {
158                    guard active, onboarded else { return }
159                    try? await Task.sleep(for: .seconds(1))
160                    // After the agenda's refresh, whose parsed files these share.
161                    while agenda.isComputing, !Task.isCancelled { try? await Task.sleep(for: .milliseconds(100)) }
162                    guard !Task.isCancelled else { return }
163                    await model.updateReminders()
164                    await model.updateWidgets()
165                }
166                // Spotlight follows the files and saved edits.
167                .task(id: SpotlightKey(files: workspace.files.count, changed: workspace.changedFile?.version, saved: session.dirtyPaths.count)) {
168                    await model.spotlight.update(workspace.files)
169                }
170        }
171    }
172
173    private struct SpotlightKey: Equatable {
174        var files: Int
175        var changed: Int?
176        var saved: Int
177    }
178
179    private struct ReminderKey: Equatable {
180        /// The widgets leave out hidden folders.
181        var hidden: Set<String>
182        var files: Int
183        var changed: Int?
184        var edits: Int
185        var settings: Int
186        var active: Bool
187        var onboarded: Bool
188        var hour: Int
189    }
190
191    var body: some View {
192        TabView(selection: $tab) {
193            Tab("Agenda", systemImage: "calendar", value: .agenda) {
194                NavigationStack(path: $agendaPath) {
195                    AgendaScreen(workspace: workspace, session: session, agenda: agenda, scheduler: model.scheduler)
196                        .equatable()
197                        .toolbar { searchButton; captureButton }
198                        .readerDestination(workspace: workspace, session: session)
199                }
200            }
201            Tab("Folders", systemImage: "folder", value: .folders) {
202                NavigationStack {
203                    FoldersScreen(workspace: workspace, session: session)
204                        .toolbar { searchButton; captureButton }
205                        .readerDestination(workspace: workspace, session: session)
206                }
207            }
208            Tab("Settings", systemImage: "gearshape", value: .settings) {
209                NavigationStack { SettingsScreen(model: model) }
210            }
211        }
212        .clockAccessory(model.clock, perform: clock)
213        .tint(model.theme.accentColor)
214        // Until a folder is added there is nothing for the agenda to show.
215        .onAppear {
216            if workspace.rootPaths.isEmpty { tab = .folders }
217            whatsNew = WhatsNew.pending(firstLaunch: !onboarded)
218            // First launch only; a workspace from before onboarding existed skips it.
219            guard !onboarded else { return }
220            if workspace.rootPaths.isEmpty, ProcessInfo.processInfo.environment["ORGSTAR_ROOT"] == nil {
221                var transaction = Transaction()
222                transaction.disablesAnimations = true
223                withTransaction(transaction) { onboarding = true }
224            } else {
225                onboarded = true
226            }
227        }
228        .fullScreenCover(isPresented: $onboarding) {
229            OnboardingScreen(model: model, workspace: workspace) {
230                onboarding = false
231                onboarded = true
232                if !workspace.rootPaths.isEmpty { tab = .agenda }
233            }
234            .interactiveDismissDisabled()
235        }
236        .sheet(item: $whatsNew) { WhatsNewView(notes: $0) }
237        .sheet(item: Bindable(ProAccess.shared).paywall) { ProSheet(feature: $0) }
238        .onChange(of: ProAccess.shared.isUnlocked) {
239            // Calendar and Reminders in the agenda, the widgets and the watch follow Pro.
240            model.reloadConfig()
241            Task { await model.updateWidgets() }
242        }
243        .sheet(item: Binding(get: { model.clockPrompts.pending }, set: { if $0 == nil { model.clockPrompts.answer(nil) } })) { pending in
244            ClockPromptSheet(prompt: pending.prompt) { model.clockPrompts.answer($0) }
245        }
246        // At the top, where the keyboard can't hide it.
247        .message($message, edge: .top)
248        .sheet(isPresented: $showingClockReport) { ClockReportScreen(workspace: workspace) }
249        .onChange(of: model.openRequest) {
250            guard let route = model.openRequest else { return }
251            model.openRequest = nil
252            tab = .agenda
253            agendaPath.append(route)
254        }
255        .onChange(of: model.agendaRequest) {
256            guard let request = model.agendaRequest else { return }
257            model.agendaRequest = nil
258            agenda.mode = .agenda(span: request.count, startOffset: nil)
259            agenda.start = request.start
260            tab = .agenda
261            agendaPath = NavigationPath()
262        }
263        .onChange(of: workspace.changedFile?.version) {
264            // An open file takes in what changed on disk.
265            if let path = workspace.changedFile?.path {
266                session.fileChanged(path)
267                // A clock started or stopped in Emacs or on another device.
268                if path.hasSuffix(".org"), let text = model.clock.sync(session, paths: [path]) { message = text }
269            }
270        }
271        // At launch and as folders load: open clocks in the agenda files.
272        .task(id: workspace.files.count) {
273            guard !workspace.files.isEmpty, let text = model.clock.sync(session, paths: workspace.agendaFilePaths()) else { return }
274            message = text
275        }
276        // Initially too: the capture control may have launched the app.
277        .onChange(of: model.captureRequest?.id, initial: true) {
278            guard let request = model.captureRequest else { return }
279            model.captureRequest = nil
280            capture = request
281        }
282
283        // Another capture took the sheet from a shared one, which stays in the inbox for later.
284        .onChange(of: capture?.id) { _, id in
285            if let id, id != shared?.request { shared = nil }
286        }
287        .sheet(item: $capture, onDismiss: captureDismissed) { request in
288            CaptureScreen(workspace: workspace, session: session, request: request)
289        }
290        .sheet(item: $sharedFiles) { shared in
291            RefileSheet(targets: workspace.refileTargets(openPath: nil, document: nil, settings: RefileSettings(targets: [.init(files: .workspace, spec: .all)])),
292                        title: "Attach to") { target in
293                sharedFiles = nil
294                if let target {
295                    message = session.attach(AttachmentInbox.files(in: shared.batch), to: target.path, at: target.start ?? 0)
296                } else {
297                    message = "The shared files weren't attached"
298                }
299                AttachmentInbox()?.remove(shared.batch)
300                takeShared()
301            }
302        }
303        // After the first frame: removing a pending notification waits on the notification
304        // service, which can take many seconds after the device starts.
305        .task {
306            await Task.yield()
307            model.clock.remindAtEffort(session)
308        }
309        .task {
310            TimerModel.shared.onDone = { message = $0 }
311            takeShared()
312            // Development: `ORGSTAR_ROOT` adds a folder at launch, as on the Mac.
313            if let root = ProcessInfo.processInfo.environment["ORGSTAR_ROOT"] { try? await workspace.addRoot(URL(fileURLWithPath: root)) }
314            // `ORGSTAR_PASTE_IMAGE`: paste takes this PNG from a pasteboard of the app's own.
315            if let image = ProcessInfo.processInfo.environment["ORGSTAR_PASTE_IMAGE"], let data = try? Data(contentsOf: URL(fileURLWithPath: image)),
316               let pasteboard = UIPasteboard(name: UIPasteboard.Name("orgstar-check"), create: true) {
317                pasteboard.setData(data, forPasteboardType: "public.png")
318                MobileEditor.pasteboard = pasteboard
319            }
320            workspace.startWatching()
321            await workspace.refresh()
322        }
323        .task {
324            while !Task.isCancelled {
325                try? await Task.sleep(for: .seconds(3600))
326                hour += 1
327            }
328        }
329        .background { BackgroundWork(model: model, workspace: workspace, agenda: agenda, active: scenePhase == .active, onboarded: onboarded, hour: hour) }
330        .onContinueUserActivity(CSSearchableItemActionType) { activity in
331            if let path = activity.userInfo?[CSSearchableItemActivityIdentifier] as? String { model.openRequest = .file(path) }
332        }
333        .onChange(of: scenePhase) { _, phase in
334            // Unsaved edits are written before the app may be stopped.
335            if phase == .background {
336                for path in session.dirtyPaths { _ = session.save(path) }
337            }
338            // Files and settings synced while away; not every sync tool tells file presenters.
339            guard phase == .active else { return }
340            // iOS has no idle time: time away from the app while a clock ran stands in for it.
341            if let since = model.clock.cameBack(idleMinutes: OrgPreferences.clockIdleTime()) {
342                MobileClock.resolveIdle(since: since, model: model) { message = $0 }
343            }
344            takeShared()
345            model.reloadConfig()
346            Task { await workspace.refresh() }
347        }
348        .onOpenURL(perform: handle)
349        // The Live Activity follows the clock, wherever it starts or stops.
350        .task {
351            LiveClock.publish(model.clock)
352            await LiveClock.sync(model.clock.running)
353        }
354        .onChange(of: model.clock.running) {
355            LiveClock.publish(model.clock)
356            Task { await LiveClock.sync(model.clock.running) }
357            Task { await model.updateWidgets() }
358        }
359        // A capture dictated on the watch, while the app is open.
360        .onChange(of: model.watchCaptures) { takeShared() }
361    }
362
363    /// What the share extension left, one capture sheet at a time.
364    private func takeShared() {
365        showWaiting()
366        if sharedFiles == nil, let batch = AttachmentInbox()?.batches().first { sharedFiles = SharedFiles(batch: batch) }
367    }
368
369    /// The inbox's oldest capture, unless a capture sheet is showing or being dismissed.
370    private func showWaiting() {
371        guard capture == nil, shared == nil, let inbox = model.inbox else { return }
372        for link in inbox.links() {
373            guard let request = CaptureRequest(link: link.text) else {
374                inbox.remove(link)
375                continue
376            }
377            shared = (link, request.id)
378            capture = request
379            return
380        }
381    }
382
383    /// The shared capture was saved or discarded, so its link goes; then the next one shows.
384    private func captureDismissed() {
385        if let shared { model.inbox?.remove(shared.link) }
386        shared = nil
387        showWaiting()
388    }
389
390    /// A widget's or the Live Activity's link, or an org-protocol URL.
391    private func handle(_ url: URL) {
392        if let link = AppLink(url: url) {
393            open(link)
394        } else if let request = CaptureRequest(link: url.absoluteString) {
395            capture = request
396        } else if case .storeLink(let link, let title)? = OrgProtocol.parse(url.absoluteString) {
397            message = StoredLink.add(StoredLink(link: link, description: title), to: &model.storedLinks)
398            UIPasteboard.general.string = link
399        } else if url.scheme == "org-protocol" {
400            message = "orgstar handles org-protocol capture and store-link"
401        }
402    }
403
404    /// A widget's or the Live Activity's link.
405    private func open(_ link: AppLink) {
406        switch link {
407        case .agenda:
408            tab = .agenda
409            agendaPath = NavigationPath()
410        case .entry(let path, let offset):
411            model.openRequest = .offset(path, offset)
412        case .clock:
413            clock("app.clock.goto")
414        case .capture(let template):
415            capture = CaptureRequest(template: template)
416        }
417    }
418
419    private func clock(_ id: String) {
420        if id == "app.clock.report" {
421            showingClockReport = true
422        } else {
423            _ = MobileClock.run(id, model: model, workspace: workspace) { message = $0 }
424        }
425    }
426
427    private var searchButton: some ToolbarContent {
428        ToolbarItem(placement: .primaryAction) {
429            NavigationLink(value: SearchRoute()) { Label("Search", systemImage: "magnifyingglass") }
430        }
431    }
432
433    private var captureButton: some ToolbarContent {
434        ToolbarItem(placement: .primaryAction) {
435            Button("Capture", systemImage: "square.and.pencil") { capture = CaptureRequest() }
436        }
437    }
438}
439#else
440/// The iOS app has nothing to run elsewhere.
441@main
442enum OrgstarMobileUnavailable {
443    static func main() { print("orgstar for iOS runs on iPhone and iPad.") }
444}
445#endif
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form