Sources/OrgstarMobile/OrgstarMobileApp.swift

407 lines · 17681 bytes

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