Sources/OrgstarMobile/OrgstarMobileApp.swift

c92fb7458e251cf67deb542105eed9683e2079ed
orgstar/Sources/OrgstarMobile/OrgstarMobileApp.swift

586 lines · 26040 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        ClockTask.titleKey = ClockTitleKey.loadOrCreate()
 30        // Read before the app becomes active and clears it.
 31        _ = UnsavedHeldFiles.atLaunch
 32        // Early, so that the watch's actions are taken when iOS wakes the app for them.
 33        WatchLink.shared.activate(MobileModel.shared)
 34    }
 35
 36    var body: some Scene {
 37        WindowGroup {
 38            if let workspace = model.workspace, let agenda = model.agenda {
 39                RootView(model: model, workspace: workspace, agenda: agenda)
 40                    .environment(model)
 41                    .environment(model.clock)
 42                    .onAppear { delegate.model = model }
 43            } else {
 44                ContentUnavailableView("Can't Open the Index", systemImage: "exclamationmark.triangle", description: Text(model.failure ?? ""))
 45            }
 46        }
 47        // For the clock's idle time: time working in another window isn't time away.
 48        .onChange(of: scenePhase) { _, phase in
 49            if phase == .background { model.clock.wentAway() }
 50        }
 51        .commands { AppMenus(model: model) }
 52    }
 53}
 54
 55/// Reminders show while the app is open too, and open their entry when tapped.
 56final class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate {
 57    @MainActor var model: MobileModel?
 58
 59    func application(_ application: UIApplication, didFinishLaunchingWithOptions options: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
 60        UNUserNotificationCenter.current().delegate = self
 61        return true
 62    }
 63
 64    nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification) async -> UNNotificationPresentationOptions {
 65        // A midnight badge update shows nothing else.
 66        if notification.request.content.badge != nil { return [.badge] }
 67        // A countdown's end shows in the app's own message.
 68        if notification.request.identifier == "sh.krz.orgstar.org-timer" { return [] }
 69        return [.banner, .sound, .list]
 70    }
 71
 72    nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {
 73        let info = response.notification.request.content.userInfo
 74        guard let path = info["path"] as? String, let offset = info["offset"] as? Int else { return }
 75        await MainActor.run { model?.openRequest = .offset(path, offset) }
 76    }
 77}
 78
 79/// Files continued from another device, and what Working Copy's syncs come to.
 80private struct HandoffAndSync: ViewModifier {
 81    let model: MobileModel
 82    let open: (HandoffPlace) -> Void
 83    @Binding var message: String?
 84
 85    func body(content: Content) -> some View {
 86        content
 87            .onContinueUserActivity(HandoffPlace.activityType) { activity in
 88                if let place = HandoffPlace(userInfo: activity.userInfo) { open(place) }
 89            }
 90            .onChange(of: model.workingCopy.message) {
 91                guard let text = model.workingCopy.message else { return }
 92                model.workingCopy.message = nil
 93                message = text
 94            }
 95    }
 96}
 97
 98/// A tab on iPhone, or a row of the sidebar on a regular-width iPad, which also lists search
 99/// and each added folder.
100enum AppTab: Hashable { case agenda, search, folders, folder(String), settings }
101
102/// The search screen, pushed from the Agenda and Folders tabs.
103struct SearchRoute: Hashable {}
104
105extension AppTab {
106    /// The tab that shows this on iPhone: search is pushed from Agenda and Folders, and folders
107    /// are listed in Folders.
108    var inTabBar: AppTab {
109        switch self {
110        case .search: .agenda
111        case .folder: .folders
112        default: self
113        }
114    }
115}
116
117extension View {
118    /// Readers pushed for `ReaderRoute`s.
119    func readerDestination(workspace: WorkspaceModel, session: DocumentSession) -> some View {
120        navigationDestination(for: ReaderRoute.self) { route in
121            ReaderScreen(route: route, workspace: workspace, session: session)
122        }
123        .navigationDestination(for: EditorRoute.self) { route in
124            EditorSplitScreen(path: route.path, offset: route.offset, workspace: workspace, session: session)
125        }
126        .navigationDestination(for: SearchRoute.self) { _ in
127            SearchScreen(workspace: workspace, session: session)
128        }
129    }
130}
131
132/// A share of files from the share extension.
133struct SharedFiles: Identifiable {
134    let id = UUID()
135    let batch: URL
136}
137
138/// An org-protocol capture, or a plain one.
139struct CaptureRequest: Identifiable {
140    let id = UUID()
141    var template: String?
142    var properties: [String: String] = [:]
143    /// An agenda day (a `Days` number) the entry is scheduled on.
144    var day: Int?
145    /// An org-roam capture, whose templates take the place of capture.toml's.
146    var roam: RoamCapture?
147}
148
149extension CaptureRequest {
150    /// An `org-protocol://capture` link's request.
151    init?(link: String) {
152        guard case .capture(let template, let properties)? = OrgProtocol.parse(link) else { return nil }
153        self.init(template: template, properties: properties)
154    }
155}
156
157struct RootView: View {
158    let model: MobileModel
159    let workspace: WorkspaceModel
160    let agenda: AgendaModel
161    @State private var capture: CaptureRequest?
162    /// The share extension's link whose capture sheet is showing, with its request's id. The link
163    /// stays in the inbox until the sheet is dismissed.
164    @State private var shared: (link: CaptureInbox.Link, request: UUID)?
165    /// Files from the share extension, waiting for the entry to attach them to.
166    @State private var sharedFiles: SharedFiles?
167    @State private var tab = AppTab.agenda
168    @State private var agendaPath = NavigationPath()
169    @State private var hour = 0
170    @State private var showingClockReport = false
171    @State private var showingBoard = false
172    @State private var message: String?
173    @Environment(\.horizontalSizeClass) private var sizeClass
174    @Environment(\.scenePhase) private var scenePhase
175    @AppStorage(OnboardingScreen.doneKey) private var onboarded = false
176    @State private var onboarding = false
177    @State private var whatsNew: ReleaseNotes?
178
179    private var session: DocumentSession { model.session }
180
181    /// Reminders, widgets and Spotlight following the files. Its own view, so that edits redraw
182    /// only it, not the tabs.
183    private struct BackgroundWork: View {
184        let model: MobileModel
185        let workspace: WorkspaceModel
186        let agenda: AgendaModel
187        let active: Bool
188        /// Notifications and badges ask for permission, which onboarding asks for first.
189        let onboarded: Bool
190        let hour: Int
191
192        private var session: DocumentSession { model.session }
193
194        var body: some View {
195            Color.clear
196                // Reminders follow the files, the settings, coming back to the app and the hour.
197                .task(id: ReminderKey(hidden: HiddenFolders.shared.all, files: workspace.files.count, changed: workspace.changedFile?.version, edits: session.editVersion,
198                                      settings: model.settingsVersion, active: active, onboarded: onboarded, hour: hour)) {
199                    guard active, onboarded else { return }
200                    try? await Task.sleep(for: .seconds(1))
201                    // After the agenda's refresh, whose parsed files these share.
202                    while agenda.isComputing, !Task.isCancelled { try? await Task.sleep(for: .milliseconds(100)) }
203                    guard !Task.isCancelled else { return }
204                    await model.updateReminders()
205                    await model.updateWidgets()
206                }
207                // Spotlight follows the files and saved edits.
208                .task(id: SpotlightKey(files: workspace.files.count, changed: workspace.changedFile?.version, saved: session.dirtyPaths.count)) {
209                    await model.spotlight.update(workspace.files)
210                }
211        }
212    }
213
214    private struct SpotlightKey: Equatable {
215        var files: Int
216        var changed: Int?
217        var saved: Int
218    }
219
220    private struct ReminderKey: Equatable {
221        /// The widgets leave out hidden folders.
222        var hidden: Set<String>
223        var files: Int
224        var changed: Int?
225        var edits: Int
226        var settings: Int
227        var active: Bool
228        var onboarded: Bool
229        var hour: Int
230    }
231
232    /// Tabs on iPhone and in a narrow window; a sidebar beside the content on a wider iPad.
233    private var tabs: some View {
234        TabView(selection: Binding { tab.inTabBar } set: { tab = $0 }) {
235            Tab("Agenda", systemImage: "calendar", value: .agenda) { agendaStack }
236            Tab("Folders", systemImage: "folder", value: .folders) { foldersStack }
237            Tab("Settings", systemImage: "gearshape", value: .settings) { settingsStack }
238        }
239        .clockAccessory(model.clock, perform: clock)
240    }
241
242    private var split: some View {
243        NavigationSplitView {
244            AppSidebar(workspace: workspace, selection: $tab)
245        } detail: {
246            Group {
247                switch tab {
248                case .agenda: agendaStack
249                case .search:
250                    NavigationStack {
251                        SearchScreen(workspace: workspace, session: session)
252                            .toolbar { captureButton }
253                            .readerDestination(workspace: workspace, session: session)
254                    }
255                case .folders: foldersStack
256                case .folder(let root):
257                    NavigationStack {
258                        FolderPage(workspace: workspace, session: session, route: FolderRoute(root: root, folder: ""))
259                            .toolbar { searchButton; captureButton }
260                            .readerDestination(workspace: workspace, session: session)
261                            .navigationDestination(for: FolderRoute.self) { FolderPage(workspace: workspace, session: session, route: $0) }
262                    }
263                    .id(root)
264                case .settings: settingsStack
265                }
266            }
267            .safeAreaInset(edge: .bottom) {
268                if let running = model.clock.running {
269                    ClockAccessory(running: running, clock: model.clock, perform: clock).padding(.vertical, 8).background(.bar)
270                }
271            }
272        }
273    }
274
275    private var agendaStack: some View {
276        NavigationStack(path: $agendaPath) {
277            AgendaScreen(workspace: workspace, session: session, agenda: agenda, scheduler: model.scheduler)
278                .equatable()
279                .toolbar { searchButton; captureButton }
280                .readerDestination(workspace: workspace, session: session)
281        }
282    }
283
284    private var foldersStack: some View {
285        NavigationStack {
286            FoldersScreen(workspace: workspace, session: session)
287                .toolbar { searchButton; captureButton }
288                .readerDestination(workspace: workspace, session: session)
289        }
290    }
291
292    private var settingsStack: some View {
293        NavigationStack { SettingsScreen(model: model) }
294    }
295
296    var body: some View {
297        // One view around both layouts, so that what follows runs once, not again when the
298        // window's width class changes.
299        ZStack {
300            if sizeClass == .regular { split } else { tabs }
301        }
302        .tint(model.theme.accentColor)
303        .focusedSceneValue(\.windowActions, WindowActions(
304            show: show, capture: { capture = CaptureRequest() },
305            addFolder: {
306                tab = .folders
307                model.addingFolder = true
308            },
309            board: { showingBoard = true }, clock: clock))
310        .fullScreenCover(isPresented: $showingBoard) {
311            BoardScreen(workspace: workspace, session: session) { showingBoard = false }
312        }
313        // A removed folder's row goes from the sidebar.
314        .onChange(of: workspace.rootPaths) {
315            if case .folder(let root) = tab, !workspace.rootPaths.contains(root) { tab = .folders }
316        }
317        // Until a folder is added there is nothing for the agenda to show.
318        .onAppear {
319            if workspace.rootPaths.isEmpty { tab = .folders }
320            whatsNew = WhatsNew.pending(firstLaunch: !onboarded)
321            // First launch only; a workspace from before onboarding existed skips it.
322            guard !onboarded else { return }
323            if workspace.rootPaths.isEmpty, ProcessInfo.processInfo.environment["ORGSTAR_ROOT"] == nil {
324                var transaction = Transaction()
325                transaction.disablesAnimations = true
326                withTransaction(transaction) { onboarding = true }
327            } else {
328                onboarded = true
329            }
330        }
331        .fullScreenCover(isPresented: $onboarding) {
332            OnboardingScreen(model: model, workspace: workspace) {
333                onboarding = false
334                onboarded = true
335                if !workspace.rootPaths.isEmpty { tab = .agenda }
336            }
337            .interactiveDismissDisabled()
338        }
339        .sheet(item: $whatsNew) { WhatsNewView(notes: $0) }
340        .modifier(DecryptQuestion())
341        .sheet(item: Bindable(ProAccess.shared).paywall) { ProSheet(feature: $0) }
342        .onChange(of: ProAccess.shared.isUnlocked) {
343            // Calendar and Reminders in the agenda, the widgets and the watch follow Pro.
344            model.reloadConfig()
345            Task { await model.updateWidgets() }
346        }
347        .sheet(item: Binding(get: { model.clockPrompts.pending }, set: { if $0 == nil { model.clockPrompts.answer(nil) } })) { pending in
348            ClockPromptSheet(prompt: pending.prompt) { model.clockPrompts.answer($0) }
349        }
350        // At the top, where the keyboard can't hide it.
351        .message($message, edge: .top)
352        .sheet(isPresented: $showingClockReport) { ClockReportScreen(workspace: workspace) }
353        .onChange(of: model.openRequest) {
354            guard let route = model.openRequest else { return }
355            model.openRequest = nil
356            tab = .agenda
357            agendaPath.append(route)
358        }
359        .onChange(of: model.agendaRequest) {
360            guard let request = model.agendaRequest else { return }
361            model.agendaRequest = nil
362            agenda.mode = .agenda(span: request.count, startOffset: nil)
363            agenda.start = request.start
364            tab = .agenda
365            agendaPath = NavigationPath()
366        }
367        .onChange(of: workspace.changedFile?.version) {
368            // An open file takes in what changed on disk.
369            if let path = workspace.changedFile?.path {
370                session.fileChanged(path)
371                // A clock started or stopped in Emacs or on another device.
372                if path.hasSuffix(".org"), let text = model.clock.sync(session, paths: [path]) { message = text }
373            }
374        }
375        // At launch and as folders load: open clocks in the agenda files.
376        .task(id: workspace.files.count) {
377            guard !workspace.files.isEmpty, let text = model.clock.sync(session, paths: workspace.agendaFilePaths()) else { return }
378            message = text
379        }
380        // Initially too: the capture control may have launched the app.
381        .onChange(of: model.captureRequest?.id, initial: true) {
382            guard let request = model.captureRequest else { return }
383            model.captureRequest = nil
384            capture = request
385        }
386
387        // Another capture took the sheet from a shared one, which stays in the inbox for later.
388        .onChange(of: capture?.id) { _, id in
389            if let id, id != shared?.request { shared = nil }
390        }
391        .sheet(item: $capture, onDismiss: captureDismissed) { request in
392            CaptureScreen(workspace: workspace, session: session, request: request)
393        }
394        .sheet(item: $sharedFiles) { shared in
395            RefileSheet(targets: workspace.refileTargets(openPath: nil, document: nil, settings: RefileSettings(targets: [.init(files: .workspace, spec: .all)])),
396                        title: "Attach to") { target in
397                sharedFiles = nil
398                if let target {
399                    message = session.attach(AttachmentInbox.files(in: shared.batch), to: target.path, at: target.start ?? 0)
400                } else {
401                    message = "The shared files weren't attached"
402                }
403                AttachmentInbox()?.remove(shared.batch)
404                takeShared()
405            }
406        }
407        // After the first frame: removing a pending notification waits on the notification
408        // service, which can take many seconds after the device starts.
409        .task {
410            await Task.yield()
411            model.clock.remindAtEffort(session)
412        }
413        .task {
414            TimerModel.shared.onDone = { message = $0 }
415            if let lost = UnsavedHeldFiles.atLaunch { message = lost }
416            takeShared()
417            // Development: `ORGSTAR_ROOT` adds a folder at launch, as on the Mac.
418            if let root = ProcessInfo.processInfo.environment["ORGSTAR_ROOT"] { try? await workspace.addRoot(URL(fileURLWithPath: root)) }
419            // `ORGSTAR_PASTE_IMAGE`: paste takes this PNG from a pasteboard of the app's own.
420            if let image = ProcessInfo.processInfo.environment["ORGSTAR_PASTE_IMAGE"], let data = try? Data(contentsOf: URL(fileURLWithPath: image)),
421               let pasteboard = UIPasteboard(name: UIPasteboard.Name("orgstar-check"), create: true) {
422                pasteboard.setData(data, forPasteboardType: "public.png")
423                MobileEditor.pasteboard = pasteboard
424            }
425            workspace.startWatching()
426            await workspace.refresh()
427            model.workingCopy.appOpened(roots: workspace.rootPaths, session: session)
428        }
429        .task {
430            while !Task.isCancelled {
431                try? await Task.sleep(for: .seconds(3600))
432                hour += 1
433            }
434        }
435        .background { BackgroundWork(model: model, workspace: workspace, agenda: agenda, active: scenePhase == .active, onboarded: onboarded, hour: hour) }
436        .onContinueUserActivity(CSSearchableItemActionType) { activity in
437            if let path = activity.userInfo?[CSSearchableItemActivityIdentifier] as? String { model.openRequest = .file(path) }
438        }
439        .onChange(of: scenePhase) { _, phase in
440            // Unsaved edits are written before the app may be stopped. A file held for its
441            // passphrase stays in memory; its name is kept so that, if iOS ends the app
442            // meanwhile, the next launch says its edits were lost.
443            if phase == .background {
444                for path in session.dirtyPaths { _ = session.save(path) }
445                UnsavedHeldFiles.record(session.held.keys.filter(session.dirtyPaths.contains).sorted())
446            }
447            if phase == .active { UnsavedHeldFiles.record([]) }
448            // Files and settings synced while away; not every sync tool tells file presenters.
449            guard phase == .active else { return }
450            // iOS has no idle time: time away from the app while a clock ran stands in for it.
451            if let since = model.clock.cameBack(idleMinutes: OrgPreferences.clockIdleTime()) {
452                MobileClock.resolveIdle(since: since, model: model) { message = $0 }
453            }
454            takeShared()
455            model.reloadConfig()
456            model.handoff.update()
457            model.workingCopy.appOpened(roots: workspace.rootPaths, session: session)
458            Task { await workspace.refresh() }
459        }
460        .onOpenURL(perform: handle)
461        .modifier(HandoffAndSync(model: model, open: continueHandoff, message: $message))
462        // The Live Activity follows the clock, wherever it starts or stops.
463        .task {
464            LiveClock.publish(model.clock)
465            await LiveClock.sync(model.clock.running)
466        }
467        .onChange(of: model.clock.running) {
468            LiveClock.publish(model.clock)
469            Task { await LiveClock.sync(model.clock.running) }
470            Task { await model.updateWidgets() }
471        }
472        // A capture dictated on the watch, while the app is open.
473        .onChange(of: model.watchCaptures) { takeShared() }
474    }
475
476    /// What the share extension left, one capture sheet at a time.
477    private func takeShared() {
478        showWaiting()
479        if sharedFiles == nil, let batch = AttachmentInbox()?.batches().first { sharedFiles = SharedFiles(batch: batch) }
480    }
481
482    /// The inbox's oldest capture, unless a capture sheet is showing or being dismissed.
483    private func showWaiting() {
484        guard capture == nil, shared == nil, let inbox = model.inbox else { return }
485        for link in inbox.links() {
486            guard let request = CaptureRequest(link: link.text) else {
487                inbox.remove(link)
488                continue
489            }
490            shared = (link, request.id)
491            capture = request
492            return
493        }
494    }
495
496    /// The shared capture was saved or discarded, so its link goes; then the next one shows.
497    private func captureDismissed() {
498        if let shared { model.inbox?.remove(shared.link) }
499        shared = nil
500        showWaiting()
501    }
502
503    /// A widget's or the Live Activity's link, or an org-protocol URL.
504    private func handle(_ url: URL) {
505        if let callback = WorkingCopy.callback(url) {
506            model.workingCopy.finished(callback, workspace: workspace, session: session)
507        } else if let link = AppLink(url: url) {
508            open(link)
509        } else if let request = CaptureRequest(link: url.absoluteString) {
510            capture = request
511        } else if case .storeLink(let link, let title)? = OrgProtocol.parse(url.absoluteString) {
512            message = StoredLink.add(StoredLink(link: link, description: title), to: &model.storedLinks)
513            UIPasteboard.general.string = link
514        } else if let request = OrgProtocol.parse(url.absoluteString), ProAccess.shared.allows(.roam) {
515            // org-roam-protocol's `roam-ref` and `roam-node`.
516            var actions = RoamActions(session: session, roots: { workspace.rootPaths }, nodes: { try workspace.nodes(overlay: workspace.overlay(session.openDocuments)) },
517                                      show: { message = $0 }, ask: { $1(nil) }, open: { path, offset in model.openRequest = .offset(path, offset) },
518                                      insertLink: { _, _ in }, refresh: { Task { await workspace.refresh() } })
519            actions.capture = { capture = CaptureRequest(roam: $0) }
520            actions.follow(request)
521        } else if url.scheme == "org-protocol" {
522            message = "orgstar handles org-protocol capture and store-link"
523        }
524    }
525
526    /// A file continued from another device, in the editor at the caret's heading or line there.
527    private func continueHandoff(_ place: HandoffPlace) {
528        let match = place.resolve(roots: workspace.rootPaths)
529        guard case .file(let path) = match else { return message = place.problem(match) }
530        let offset = session.text(of: path).map { place.offset(in: $0, settings: session.defaults) } ?? 0
531        tab = .agenda
532        agendaPath.append(EditorRoute(path: path, offset: offset))
533    }
534
535    /// A tab or sidebar row; on iPhone, search is pushed on the agenda.
536    private func show(_ destination: AppTab) {
537        if destination == .search, sizeClass != .regular {
538            tab = .agenda
539            agendaPath.append(SearchRoute())
540        } else {
541            tab = destination
542        }
543    }
544
545    /// A widget's or the Live Activity's link.
546    private func open(_ link: AppLink) {
547        switch link {
548        case .agenda:
549            tab = .agenda
550            agendaPath = NavigationPath()
551        case .entry(let path, let offset):
552            model.openRequest = .offset(path, offset)
553        case .clock:
554            clock("app.clock.goto")
555        case .capture(let template):
556            capture = CaptureRequest(template: template)
557        }
558    }
559
560    private func clock(_ id: String) {
561        if id == "app.clock.report" {
562            showingClockReport = true
563        } else {
564            _ = MobileClock.run(id, model: model, workspace: workspace) { message = $0 }
565        }
566    }
567
568    private var searchButton: some ToolbarContent {
569        ToolbarItem(placement: .primaryAction) {
570            NavigationLink(value: SearchRoute()) { Label("Search", systemImage: "magnifyingglass") }
571        }
572    }
573
574    private var captureButton: some ToolbarContent {
575        ToolbarItem(placement: .primaryAction) {
576            Button("Capture", systemImage: "square.and.pencil") { capture = CaptureRequest() }
577        }
578    }
579}
580#else
581/// The iOS app has nothing to run elsewhere.
582@main
583enum OrgstarMobileUnavailable {
584    static func main() { print("orgstar for iOS runs on iPhone and iPad.") }
585}
586#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