Sources/OrgstarMobile/OrgstarMobileApp.swift

424 lines · 18641 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    /// Captures from the share extension after the one showing.
124    @State private var waiting: [CaptureRequest] = []
125    /// Files from the share extension, waiting for the entry to attach them to.
126    @State private var sharedFiles: SharedFiles?
127    @State private var tab = AppTab.agenda
128    @State private var agendaPath = NavigationPath()
129    @State private var hour = 0
130    @State private var showingClockReport = false
131    @State private var message: String?
132    @Environment(\.scenePhase) private var scenePhase
133    @AppStorage(OnboardingScreen.doneKey) private var onboarded = false
134    @State private var onboarding = false
135    @State private var whatsNew: ReleaseNotes?
136
137    private var session: DocumentSession { model.session }
138
139    /// Reminders, widgets and Spotlight following the files. Its own view, so that edits redraw
140    /// only it, not the tabs.
141    private struct BackgroundWork: View {
142        let model: MobileModel
143        let workspace: WorkspaceModel
144        let agenda: AgendaModel
145        let active: Bool
146        /// Notifications and badges ask for permission, which onboarding asks for first.
147        let onboarded: Bool
148        let hour: Int
149
150        private var session: DocumentSession { model.session }
151
152        var body: some View {
153            Color.clear
154                // Reminders follow the files, the settings, coming back to the app and the hour.
155                .task(id: ReminderKey(hidden: HiddenFolders.shared.all, files: workspace.files.count, changed: workspace.changedFile?.version, edits: session.editVersion,
156                                      settings: model.settingsVersion, active: active, onboarded: onboarded, hour: hour)) {
157                    guard active, onboarded else { return }
158                    try? await Task.sleep(for: .seconds(1))
159                    // After the agenda's refresh, whose parsed files these share.
160                    while agenda.isComputing, !Task.isCancelled { try? await Task.sleep(for: .milliseconds(100)) }
161                    guard !Task.isCancelled else { return }
162                    await model.updateReminders()
163                    await model.updateWidgets()
164                }
165                // Spotlight follows the files and saved edits.
166                .task(id: SpotlightKey(files: workspace.files.count, changed: workspace.changedFile?.version, saved: session.dirtyPaths.count)) {
167                    await model.spotlight.update(workspace.files)
168                }
169        }
170    }
171
172    private struct SpotlightKey: Equatable {
173        var files: Int
174        var changed: Int?
175        var saved: Int
176    }
177
178    private struct ReminderKey: Equatable {
179        /// The widgets leave out hidden folders.
180        var hidden: Set<String>
181        var files: Int
182        var changed: Int?
183        var edits: Int
184        var settings: Int
185        var active: Bool
186        var onboarded: Bool
187        var hour: Int
188    }
189
190    var body: some View {
191        TabView(selection: $tab) {
192            Tab("Agenda", systemImage: "calendar", value: .agenda) {
193                NavigationStack(path: $agendaPath) {
194                    AgendaScreen(workspace: workspace, session: session, agenda: agenda, scheduler: model.scheduler)
195                        .equatable()
196                        .toolbar { searchButton; captureButton }
197                        .readerDestination(workspace: workspace, session: session)
198                }
199            }
200            Tab("Folders", systemImage: "folder", value: .folders) {
201                NavigationStack {
202                    FoldersScreen(workspace: workspace, session: session)
203                        .toolbar { searchButton; captureButton }
204                        .readerDestination(workspace: workspace, session: session)
205                }
206            }
207            Tab("Settings", systemImage: "gearshape", value: .settings) {
208                NavigationStack { SettingsScreen(model: model) }
209            }
210        }
211        .clockAccessory(model.clock, perform: clock)
212        .tint(model.theme.accentColor)
213        // Until a folder is added there is nothing for the agenda to show.
214        .onAppear {
215            if workspace.rootPaths.isEmpty { tab = .folders }
216            whatsNew = WhatsNew.pending(firstLaunch: !onboarded)
217            // First launch only; a workspace from before onboarding existed skips it.
218            guard !onboarded else { return }
219            if workspace.rootPaths.isEmpty, ProcessInfo.processInfo.environment["ORGSTAR_ROOT"] == nil {
220                var transaction = Transaction()
221                transaction.disablesAnimations = true
222                withTransaction(transaction) { onboarding = true }
223            } else {
224                onboarded = true
225            }
226        }
227        .fullScreenCover(isPresented: $onboarding) {
228            OnboardingScreen(model: model, workspace: workspace) {
229                onboarding = false
230                onboarded = true
231                if !workspace.rootPaths.isEmpty { tab = .agenda }
232            }
233            .interactiveDismissDisabled()
234        }
235        .sheet(item: $whatsNew) { WhatsNewView(notes: $0) }
236        .sheet(item: Bindable(ProAccess.shared).paywall) { ProSheet(feature: $0) }
237        .onChange(of: ProAccess.shared.isUnlocked) {
238            // Calendar and Reminders in the agenda, the widgets and the watch follow Pro.
239            model.reloadConfig()
240            Task { await model.updateWidgets() }
241        }
242        .sheet(item: Binding(get: { model.clockPrompts.pending }, set: { if $0 == nil { model.clockPrompts.answer(nil) } })) { pending in
243            ClockPromptSheet(prompt: pending.prompt) { model.clockPrompts.answer($0) }
244        }
245        // Above the tab bar, clear of every screen's toolbar.
246        .overlay(alignment: .bottom) {
247            if let message {
248                Text(message).font(.callout).padding(.horizontal, 14).padding(.vertical, 8)
249                    .background(.regularMaterial, in: Capsule())
250                    .padding(.bottom, 150)
251                    .onTapGesture { self.message = nil }
252                    .task(id: message) {
253                        try? await Task.sleep(for: .seconds(4))
254                        if self.message == message { self.message = nil }
255                    }
256            }
257        }
258        .sheet(isPresented: $showingClockReport) { ClockReportScreen(workspace: workspace) }
259        .onChange(of: model.openRequest) {
260            guard let route = model.openRequest else { return }
261            model.openRequest = nil
262            tab = .agenda
263            agendaPath.append(route)
264        }
265        .onChange(of: model.agendaRequest) {
266            guard let request = model.agendaRequest else { return }
267            model.agendaRequest = nil
268            agenda.mode = .agenda(span: request.count, startOffset: nil)
269            agenda.start = request.start
270            tab = .agenda
271            agendaPath = NavigationPath()
272        }
273        .onChange(of: workspace.changedFile?.version) {
274            // An open file takes in what changed on disk.
275            if let path = workspace.changedFile?.path {
276                session.fileChanged(path)
277                // A clock started or stopped in Emacs or on another device.
278                if path.hasSuffix(".org"), let text = model.clock.sync(session, paths: [path]) { message = text }
279            }
280        }
281        // At launch and as folders load: open clocks in the agenda files.
282        .task(id: workspace.files.count) {
283            guard !workspace.files.isEmpty, let text = model.clock.sync(session, paths: workspace.agendaFilePaths()) else { return }
284            message = text
285        }
286        // Initially too: the capture control may have launched the app.
287        .onChange(of: model.captureRequest?.id, initial: true) {
288            guard let request = model.captureRequest else { return }
289            model.captureRequest = nil
290            capture = request
291        }
292
293        .sheet(item: $capture, onDismiss: showWaiting) { request in
294            CaptureScreen(workspace: workspace, session: session, request: request)
295        }
296        .sheet(item: $sharedFiles) { shared in
297            RefileSheet(targets: workspace.refileTargets(openPath: nil, document: nil, settings: RefileSettings(targets: [.init(files: .workspace, spec: .all)])),
298                        title: "Attach to") { target in
299                sharedFiles = nil
300                if let target {
301                    message = session.attach(AttachmentInbox.files(in: shared.batch), to: target.path, at: target.start ?? 0)
302                } else {
303                    message = "The shared files weren't attached"
304                }
305                AttachmentInbox()?.remove(shared.batch)
306                takeShared()
307            }
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 { url in
349            if let link = AppLink(url: url) {
350                open(link)
351            } else if let request = CaptureRequest(link: url.absoluteString) {
352                capture = request
353            } else if case .storeLink(let link, let title)? = OrgProtocol.parse(url.absoluteString) {
354                message = StoredLink.add(StoredLink(link: link, description: title), to: &model.storedLinks)
355                UIPasteboard.general.string = link
356            }
357        }
358        // The Live Activity follows the clock, wherever it starts or stops.
359        .task {
360            LiveClock.publish(model.clock)
361            await LiveClock.sync(model.clock.running)
362        }
363        .onChange(of: model.clock.running) {
364            LiveClock.publish(model.clock)
365            Task { await LiveClock.sync(model.clock.running) }
366            Task { await model.updateWidgets() }
367        }
368        // A capture dictated on the watch, while the app is open.
369        .onChange(of: model.watchCaptures) { takeShared() }
370    }
371
372    /// What the share extension left, one capture sheet at a time.
373    private func takeShared() {
374        waiting += (model.inbox?.take() ?? []).compactMap(CaptureRequest.init(link:))
375        if capture == nil { showWaiting() }
376        if sharedFiles == nil, let batch = AttachmentInbox()?.batches().first { sharedFiles = SharedFiles(batch: batch) }
377    }
378
379    private func showWaiting() {
380        if !waiting.isEmpty { capture = waiting.removeFirst() }
381    }
382
383    /// A widget's or the Live Activity's link.
384    private func open(_ link: AppLink) {
385        switch link {
386        case .agenda:
387            tab = .agenda
388            agendaPath = NavigationPath()
389        case .entry(let path, let offset):
390            model.openRequest = .offset(path, offset)
391        case .clock:
392            clock("app.clock.goto")
393        case .capture(let template):
394            capture = CaptureRequest(template: template)
395        }
396    }
397
398    private func clock(_ id: String) {
399        if id == "app.clock.report" {
400            showingClockReport = true
401        } else {
402            _ = MobileClock.run(id, model: model, workspace: workspace) { message = $0 }
403        }
404    }
405
406    private var searchButton: some ToolbarContent {
407        ToolbarItem(placement: .primaryAction) {
408            NavigationLink(value: SearchRoute()) { Label("Search", systemImage: "magnifyingglass") }
409        }
410    }
411
412    private var captureButton: some ToolbarContent {
413        ToolbarItem(placement: .primaryAction) {
414            Button("Capture", systemImage: "square.and.pencil") { capture = CaptureRequest() }
415        }
416    }
417}
418#else
419/// The iOS app has nothing to run elsewhere.
420@main
421enum OrgstarMobileUnavailable {
422    static func main() { print("orgstar for iOS runs on iPhone and iPad.") }
423}
424#endif