Sources/OrgstarMobile/OrgstarMobileApp.swift

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