Sources/OrgstarMobile/OrgstarMobileApp.swift

b3620724ba167f6d64229f61c4cb5b7612687077
orgstar/Sources/OrgstarMobile/OrgstarMobileApp.swift

577 lines · 25230 bytes

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