Sources/OrgstarMobile/OrgstarMobileApp.swift

06941b2cf25c6ccc1629723cd7951910ce15e67a
orgstar/Sources/OrgstarMobile/OrgstarMobileApp.swift history · blame · raw

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