Sources/OrgstarMobile/OrgstarMobileApp.swift

58f3b73e8ff337e5a15111fbb32c0d57cf2346da
orgstar/Sources/OrgstarMobile/OrgstarMobileApp.swift history · blame · raw

450 lines · 19703 bytes

22 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        // 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        // Above the tab bar, clear of every screen's toolbar.
247        .overlay(alignment: .bottom) {
248            if let message {
249                Text(message).font(.callout).padding(.horizontal, 14).padding(.vertical, 8)
250                    .background(.regularMaterial, in: Capsule())
251                    .padding(.bottom, 150)
252                    .onTapGesture { self.message = nil }
253                    .task(id: message) {
254                        try? await Task.sleep(for: .seconds(4))
255                        if self.message == message { self.message = nil }
256                    }
257            }
258        }
259        .sheet(isPresented: $showingClockReport) { ClockReportScreen(workspace: workspace) }
260        .onChange(of: model.openRequest) {
261            guard let route = model.openRequest else { return }
262            model.openRequest = nil
263            tab = .agenda
264            agendaPath.append(route)
265        }
266        .onChange(of: model.agendaRequest) {
267            guard let request = model.agendaRequest else { return }
268            model.agendaRequest = nil
269            agenda.mode = .agenda(span: request.count, startOffset: nil)
270            agenda.start = request.start
271            tab = .agenda
272            agendaPath = NavigationPath()
273        }
274        .onChange(of: workspace.changedFile?.version) {
275            // An open file takes in what changed on disk.
276            if let path = workspace.changedFile?.path {
277                session.fileChanged(path)
278                // A clock started or stopped in Emacs or on another device.
279                if path.hasSuffix(".org"), let text = model.clock.sync(session, paths: [path]) { message = text }
280            }
281        }
282        // At launch and as folders load: open clocks in the agenda files.
283        .task(id: workspace.files.count) {
284            guard !workspace.files.isEmpty, let text = model.clock.sync(session, paths: workspace.agendaFilePaths()) else { return }
285            message = text
286        }
287        // Initially too: the capture control may have launched the app.
288        .onChange(of: model.captureRequest?.id, initial: true) {
289            guard let request = model.captureRequest else { return }
290            model.captureRequest = nil
291            capture = request
292        }
293
294        // Another capture took the sheet from a shared one, which stays in the inbox for later.
295        .onChange(of: capture?.id) { _, id in
296            if let id, id != shared?.request { shared = nil }
297        }
298        .sheet(item: $capture, onDismiss: captureDismissed) { request in
299            CaptureScreen(workspace: workspace, session: session, request: request)
300        }
301        .sheet(item: $sharedFiles) { shared in
302            RefileSheet(targets: workspace.refileTargets(openPath: nil, document: nil, settings: RefileSettings(targets: [.init(files: .workspace, spec: .all)])),
303                        title: "Attach to") { target in
304                sharedFiles = nil
305                if let target {
306                    message = session.attach(AttachmentInbox.files(in: shared.batch), to: target.path, at: target.start ?? 0)
307                } else {
308                    message = "The shared files weren't attached"
309                }
310                AttachmentInbox()?.remove(shared.batch)
311                takeShared()
312            }
313        }
314        .task {
315            TimerModel.shared.onDone = { message = $0 }
316            takeShared()
317            // Development: `ORGSTAR_ROOT` adds a folder at launch, as on the Mac.
318            if let root = ProcessInfo.processInfo.environment["ORGSTAR_ROOT"] { try? await workspace.addRoot(URL(fileURLWithPath: root)) }
319            // `ORGSTAR_PASTE_IMAGE`: paste takes this PNG from a pasteboard of the app's own.
320            if let image = ProcessInfo.processInfo.environment["ORGSTAR_PASTE_IMAGE"], let data = try? Data(contentsOf: URL(fileURLWithPath: image)),
321               let pasteboard = UIPasteboard(name: UIPasteboard.Name("orgstar-check"), create: true) {
322                pasteboard.setData(data, forPasteboardType: "public.png")
323                MobileEditor.pasteboard = pasteboard
324            }
325            workspace.startWatching()
326            await workspace.refresh()
327        }
328        .task {
329            while !Task.isCancelled {
330                try? await Task.sleep(for: .seconds(3600))
331                hour += 1
332            }
333        }
334        .background { BackgroundWork(model: model, workspace: workspace, agenda: agenda, active: scenePhase == .active, onboarded: onboarded, hour: hour) }
335        .onContinueUserActivity(CSSearchableItemActionType) { activity in
336            if let path = activity.userInfo?[CSSearchableItemActivityIdentifier] as? String { model.openRequest = .file(path) }
337        }
338        .onChange(of: scenePhase) { _, phase in
339            // Unsaved edits are written before the app may be stopped.
340            if phase == .background {
341                for path in session.dirtyPaths { _ = session.save(path) }
342            }
343            // Files and settings synced while away; not every sync tool tells file presenters.
344            guard phase == .active else { return }
345            // iOS has no idle time: time away from the app while a clock ran stands in for it.
346            if let since = model.clock.cameBack(idleMinutes: OrgPreferences.clockIdleTime()) {
347                MobileClock.resolveIdle(since: since, model: model) { message = $0 }
348            }
349            takeShared()
350            model.reloadConfig()
351            Task { await workspace.refresh() }
352        }
353        .onOpenURL(perform: handle)
354        // The Live Activity follows the clock, wherever it starts or stops.
355        .task {
356            LiveClock.publish(model.clock)
357            await LiveClock.sync(model.clock.running)
358        }
359        .onChange(of: model.clock.running) {
360            LiveClock.publish(model.clock)
361            Task { await LiveClock.sync(model.clock.running) }
362            Task { await model.updateWidgets() }
363        }
364        // A capture dictated on the watch, while the app is open.
365        .onChange(of: model.watchCaptures) { takeShared() }
366    }
367
368    /// What the share extension left, one capture sheet at a time.
369    private func takeShared() {
370        showWaiting()
371        if sharedFiles == nil, let batch = AttachmentInbox()?.batches().first { sharedFiles = SharedFiles(batch: batch) }
372    }
373
374    /// The inbox's oldest capture, unless a capture sheet is showing or being dismissed.
375    private func showWaiting() {
376        guard capture == nil, shared == nil, let inbox = model.inbox else { return }
377        for link in inbox.links() {
378            guard let request = CaptureRequest(link: link.text) else {
379                inbox.remove(link)
380                continue
381            }
382            shared = (link, request.id)
383            capture = request
384            return
385        }
386    }
387
388    /// The shared capture was saved or discarded, so its link goes; then the next one shows.
389    private func captureDismissed() {
390        if let shared { model.inbox?.remove(shared.link) }
391        shared = nil
392        showWaiting()
393    }
394
395    /// A widget's or the Live Activity's link, or an org-protocol URL.
396    private func handle(_ url: URL) {
397        if let link = AppLink(url: url) {
398            open(link)
399        } else if let request = CaptureRequest(link: url.absoluteString) {
400            capture = request
401        } else if case .storeLink(let link, let title)? = OrgProtocol.parse(url.absoluteString) {
402            message = StoredLink.add(StoredLink(link: link, description: title), to: &model.storedLinks)
403            UIPasteboard.general.string = link
404        } else if url.scheme == "org-protocol" {
405            message = "orgstar handles org-protocol capture and store-link"
406        }
407    }
408
409    /// A widget's or the Live Activity's link.
410    private func open(_ link: AppLink) {
411        switch link {
412        case .agenda:
413            tab = .agenda
414            agendaPath = NavigationPath()
415        case .entry(let path, let offset):
416            model.openRequest = .offset(path, offset)
417        case .clock:
418            clock("app.clock.goto")
419        case .capture(let template):
420            capture = CaptureRequest(template: template)
421        }
422    }
423
424    private func clock(_ id: String) {
425        if id == "app.clock.report" {
426            showingClockReport = true
427        } else {
428            _ = MobileClock.run(id, model: model, workspace: workspace) { message = $0 }
429        }
430    }
431
432    private var searchButton: some ToolbarContent {
433        ToolbarItem(placement: .primaryAction) {
434            NavigationLink(value: SearchRoute()) { Label("Search", systemImage: "magnifyingglass") }
435        }
436    }
437
438    private var captureButton: some ToolbarContent {
439        ToolbarItem(placement: .primaryAction) {
440            Button("Capture", systemImage: "square.and.pencil") { capture = CaptureRequest() }
441        }
442    }
443}
444#else
445/// The iOS app has nothing to run elsewhere.
446@main
447enum OrgstarMobileUnavailable {
448    static func main() { print("orgstar for iOS runs on iPhone and iPad.") }
449}
450#endif