Sources/OrgstarMobile/OrgstarMobileApp.swift

376 lines · 16201 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(hidden: HiddenFolders.shared.all, 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        /// The widgets leave out hidden folders.
164        var hidden: Set<String>
165        var files: Int
166        var changed: Int?
167        var edits: Int
168        var settings: Int
169        var active: Bool
170        var hour: Int
171    }
172
173    var body: some View {
174        TabView(selection: $tab) {
175            Tab("Agenda", systemImage: "calendar", value: .agenda) {
176                NavigationStack(path: $agendaPath) {
177                    AgendaScreen(workspace: workspace, session: session, agenda: agenda, scheduler: model.scheduler)
178                        .equatable()
179                        .toolbar { searchButton; captureButton }
180                        .readerDestination(workspace: workspace, session: session)
181                }
182            }
183            Tab("Folders", systemImage: "folder", value: .folders) {
184                NavigationStack {
185                    FoldersScreen(workspace: workspace, session: session)
186                        .toolbar { searchButton; captureButton }
187                        .readerDestination(workspace: workspace, session: session)
188                }
189            }
190            Tab("Settings", systemImage: "gearshape", value: .settings) {
191                NavigationStack { SettingsScreen(model: model) }
192            }
193        }
194        .clockAccessory(model.clock, perform: clock)
195        .tint(model.theme.accentColor)
196        // Until a folder is added there is nothing for the agenda to show.
197        .onAppear { if workspace.rootPaths.isEmpty { tab = .folders } }
198        .sheet(item: Binding(get: { model.clockPrompts.pending }, set: { if $0 == nil { model.clockPrompts.answer(nil) } })) { pending in
199            ClockPromptSheet(prompt: pending.prompt) { model.clockPrompts.answer($0) }
200        }
201        // Above the tab bar, clear of every screen's toolbar.
202        .overlay(alignment: .bottom) {
203            if let message {
204                Text(message).font(.callout).padding(.horizontal, 14).padding(.vertical, 8)
205                    .background(.regularMaterial, in: Capsule())
206                    .padding(.bottom, 150)
207                    .onTapGesture { self.message = nil }
208                    .task(id: message) {
209                        try? await Task.sleep(for: .seconds(4))
210                        if self.message == message { self.message = nil }
211                    }
212            }
213        }
214        .sheet(isPresented: $showingClockReport) { ClockReportScreen(workspace: workspace) }
215        .onChange(of: model.openRequest) {
216            guard let route = model.openRequest else { return }
217            model.openRequest = nil
218            tab = .agenda
219            agendaPath.append(route)
220        }
221        .onChange(of: model.agendaRequest) {
222            guard let request = model.agendaRequest else { return }
223            model.agendaRequest = nil
224            agenda.mode = .agenda(span: request.count, startOffset: nil)
225            agenda.start = request.start
226            tab = .agenda
227            agendaPath = NavigationPath()
228        }
229        .onChange(of: workspace.changedFile?.version) {
230            // An open file takes in what changed on disk.
231            if let path = workspace.changedFile?.path {
232                session.fileChanged(path)
233                // A clock started or stopped in Emacs or on another device.
234                if path.hasSuffix(".org"), let text = model.clock.sync(session, paths: [path]) { message = text }
235            }
236        }
237        // At launch and as folders load: open clocks in the agenda files.
238        .task(id: workspace.files.count) {
239            guard !workspace.files.isEmpty, let text = model.clock.sync(session, paths: workspace.agendaFilePaths()) else { return }
240            message = text
241        }
242        // Initially too: the capture control may have launched the app.
243        .onChange(of: model.captureRequest?.id, initial: true) {
244            guard let request = model.captureRequest else { return }
245            model.captureRequest = nil
246            capture = request
247        }
248
249        .sheet(item: $capture, onDismiss: showWaiting) { request in
250            CaptureScreen(workspace: workspace, session: session, request: request)
251        }
252        .sheet(item: $sharedFiles) { shared in
253            RefileSheet(targets: workspace.refileTargets(openPath: nil, document: nil, settings: RefileSettings(targets: [.init(files: .workspace, spec: .all)])),
254                        title: "Attach to") { target in
255                sharedFiles = nil
256                if let target {
257                    message = session.attach(AttachmentInbox.files(in: shared.batch), to: target.path, at: target.start ?? 0)
258                } else {
259                    message = "The shared files weren't attached"
260                }
261                AttachmentInbox()?.remove(shared.batch)
262                takeShared()
263            }
264        }
265        .task {
266            TimerModel.shared.onDone = { message = $0 }
267            takeShared()
268            // Development: `ORGSTAR_ROOT` adds a folder at launch, as on the Mac.
269            if let root = ProcessInfo.processInfo.environment["ORGSTAR_ROOT"] { try? await workspace.addRoot(URL(fileURLWithPath: root)) }
270            // `ORGSTAR_PASTE_IMAGE`: paste takes this PNG from a pasteboard of the app's own.
271            if let image = ProcessInfo.processInfo.environment["ORGSTAR_PASTE_IMAGE"], let data = try? Data(contentsOf: URL(fileURLWithPath: image)),
272               let pasteboard = UIPasteboard(name: UIPasteboard.Name("orgstar-check"), create: true) {
273                pasteboard.setData(data, forPasteboardType: "public.png")
274                MobileEditor.pasteboard = pasteboard
275            }
276            workspace.startWatching()
277            await workspace.refresh()
278        }
279        .task {
280            while !Task.isCancelled {
281                try? await Task.sleep(for: .seconds(3600))
282                hour += 1
283            }
284        }
285        .background { BackgroundWork(model: model, workspace: workspace, agenda: agenda, active: scenePhase == .active, hour: hour) }
286        .onContinueUserActivity(CSSearchableItemActionType) { activity in
287            if let path = activity.userInfo?[CSSearchableItemActivityIdentifier] as? String { model.openRequest = .file(path) }
288        }
289        .onChange(of: scenePhase) { _, phase in
290            // Unsaved edits are written before the app may be stopped.
291            if phase == .background {
292                for path in session.dirtyPaths { _ = session.save(path) }
293            }
294            // Files and settings synced while away; not every sync tool tells file presenters.
295            guard phase == .active else { return }
296            takeShared()
297            model.reloadConfig()
298            Task { await workspace.refresh() }
299        }
300        .onOpenURL { url in
301            if let link = AppLink(url: url) {
302                open(link)
303            } else if let request = CaptureRequest(link: url.absoluteString) {
304                capture = request
305            } else if case .storeLink(let link, let title)? = OrgProtocol.parse(url.absoluteString) {
306                message = StoredLink.add(StoredLink(link: link, description: title), to: &model.storedLinks)
307                UIPasteboard.general.string = link
308            }
309        }
310        // The Live Activity follows the clock, wherever it starts or stops.
311        .task {
312            LiveClock.publish(model.clock)
313            await LiveClock.sync(model.clock.running)
314        }
315        .onChange(of: model.clock.running) {
316            LiveClock.publish(model.clock)
317            Task { await LiveClock.sync(model.clock.running) }
318            Task { await model.updateWidgets() }
319        }
320        // A capture dictated on the watch, while the app is open.
321        .onChange(of: model.watchCaptures) { takeShared() }
322    }
323
324    /// What the share extension left, one capture sheet at a time.
325    private func takeShared() {
326        waiting += (model.inbox?.take() ?? []).compactMap(CaptureRequest.init(link:))
327        if capture == nil { showWaiting() }
328        if sharedFiles == nil, let batch = AttachmentInbox()?.batches().first { sharedFiles = SharedFiles(batch: batch) }
329    }
330
331    private func showWaiting() {
332        if !waiting.isEmpty { capture = waiting.removeFirst() }
333    }
334
335    /// A widget's or the Live Activity's link.
336    private func open(_ link: AppLink) {
337        switch link {
338        case .agenda:
339            tab = .agenda
340            agendaPath = NavigationPath()
341        case .entry(let path, let offset):
342            model.openRequest = .offset(path, offset)
343        case .clock:
344            clock("app.clock.goto")
345        case .capture(let template):
346            capture = CaptureRequest(template: template)
347        }
348    }
349
350    private func clock(_ id: String) {
351        if id == "app.clock.report" {
352            showingClockReport = true
353        } else {
354            _ = MobileClock.run(id, model: model, workspace: workspace) { message = $0 }
355        }
356    }
357
358    private var searchButton: some ToolbarContent {
359        ToolbarItem(placement: .primaryAction) {
360            NavigationLink(value: SearchRoute()) { Label("Search", systemImage: "magnifyingglass") }
361        }
362    }
363
364    private var captureButton: some ToolbarContent {
365        ToolbarItem(placement: .primaryAction) {
366            Button("Capture", systemImage: "square.and.pencil") { capture = CaptureRequest() }
367        }
368    }
369}
370#else
371/// The iOS app has nothing to run elsewhere.
372@main
373enum OrgstarMobileUnavailable {
374    static func main() { print("orgstar for iOS runs on iPhone and iPad.") }
375}
376#endif