Sources/OrgstarMobile/OrgstarMobileApp.swift

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