Sources/OrgstarMobile/OrgstarMobileApp.swift

a866e469a3568bf7a2829a8dd2a56317ced4736e
orgstar/Sources/OrgstarMobile/OrgstarMobileApp.swift history · blame · raw

313 lines · 12930 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, search }
 61
 62extension View {
 63    /// Readers pushed for `ReaderRoute`s.
 64    func readerDestination(workspace: WorkspaceModel, session: DocumentSession) -> some View {
 65        navigationDestination(for: ReaderRoute.self) { route in
 66            ReaderScreen(route: route, workspace: workspace, session: session)
 67        }
 68        .navigationDestination(for: EditorRoute.self) { route in
 69            EditorScreen(path: route.path, offset: route.offset, workspace: workspace, session: session)
 70        }
 71    }
 72}
 73
 74/// An org-protocol capture, or a plain one.
 75struct CaptureRequest: Identifiable {
 76    let id = UUID()
 77    var template: String?
 78    var properties: [String: String] = [:]
 79    /// An agenda day (a `Days` number) the entry is scheduled on.
 80    var day: Int?
 81}
 82
 83extension CaptureRequest {
 84    /// An `org-protocol://capture` link's request.
 85    init?(link: String) {
 86        guard case .capture(let template, let properties)? = OrgProtocol.parse(link) else { return nil }
 87        self.init(template: template, properties: properties)
 88    }
 89}
 90
 91struct RootView: View {
 92    let model: MobileModel
 93    let workspace: WorkspaceModel
 94    let agenda: AgendaModel
 95    @State private var capture: CaptureRequest?
 96    /// Captures from the share extension after the one showing.
 97    @State private var waiting: [CaptureRequest] = []
 98    @State private var tab = AppTab.agenda
 99    @State private var agendaPath = NavigationPath()
100    @State private var hour = 0
101    @State private var showingClockReport = false
102    @State private var message: String?
103    @Environment(\.scenePhase) private var scenePhase
104
105    private var session: DocumentSession { model.session }
106
107    /// Reminders, widgets and Spotlight following the files. Its own view, so that edits redraw
108    /// only it, not the tabs.
109    private struct BackgroundWork: View {
110        let model: MobileModel
111        let workspace: WorkspaceModel
112        let agenda: AgendaModel
113        let active: Bool
114        let hour: Int
115
116        private var session: DocumentSession { model.session }
117
118        var body: some View {
119            Color.clear
120                // Reminders follow the files, the settings, coming back to the app and the hour.
121                .task(id: ReminderKey(files: workspace.files.count, changed: workspace.changedFile?.version, edits: session.editVersion,
122                                      settings: model.settingsVersion, active: active, hour: hour)) {
123                    guard active else { return }
124                    try? await Task.sleep(for: .seconds(1))
125                    // After the agenda's refresh, whose parsed files these share.
126                    while agenda.isComputing, !Task.isCancelled { try? await Task.sleep(for: .milliseconds(100)) }
127                    guard !Task.isCancelled else { return }
128                    await model.updateReminders()
129                    await model.updateWidgets()
130                }
131                // Spotlight follows the files and saved edits.
132                .task(id: SpotlightKey(files: workspace.files.count, changed: workspace.changedFile?.version, saved: session.dirtyPaths.count)) {
133                    await model.spotlight.update(workspace.files)
134                }
135        }
136    }
137
138    private struct SpotlightKey: Equatable {
139        var files: Int
140        var changed: Int?
141        var saved: Int
142    }
143
144    private struct ReminderKey: Equatable {
145        var files: Int
146        var changed: Int?
147        var edits: Int
148        var settings: Int
149        var active: Bool
150        var hour: Int
151    }
152
153    var body: some View {
154        TabView(selection: $tab) {
155            Tab("Agenda", systemImage: "calendar", value: .agenda) {
156                NavigationStack(path: $agendaPath) {
157                    AgendaScreen(workspace: workspace, session: session, agenda: agenda, scheduler: model.scheduler)
158                        .equatable()
159                        .toolbar { captureButton }
160                        .readerDestination(workspace: workspace, session: session)
161                }
162            }
163            Tab("Folders", systemImage: "folder", value: .folders) {
164                NavigationStack {
165                    FoldersScreen(workspace: workspace)
166                        .toolbar { captureButton }
167                        .readerDestination(workspace: workspace, session: session)
168                }
169            }
170            // An ordinary tab, not the search role, which the tab bar always puts last.
171            Tab("Search", systemImage: "magnifyingglass", value: .search) {
172                NavigationStack {
173                    SearchScreen(workspace: workspace, session: session)
174                        .readerDestination(workspace: workspace, session: session)
175                }
176            }
177            Tab("Settings", systemImage: "gearshape", value: .settings) {
178                NavigationStack { SettingsScreen(model: model) }
179            }
180        }
181        .clockAccessory(model.clock, perform: clock)
182        .sheet(item: Binding(get: { model.clockPrompts.pending }, set: { if $0 == nil { model.clockPrompts.answer(nil) } })) { pending in
183            ClockPromptSheet(prompt: pending.prompt) { model.clockPrompts.answer($0) }
184        }
185        // Above the tab bar, clear of every screen's toolbar.
186        .overlay(alignment: .bottom) {
187            if let message {
188                Text(message).font(.callout).padding(.horizontal, 14).padding(.vertical, 8)
189                    .background(.regularMaterial, in: Capsule())
190                    .padding(.bottom, 150)
191                    .onTapGesture { self.message = nil }
192                    .task(id: message) {
193                        try? await Task.sleep(for: .seconds(4))
194                        if self.message == message { self.message = nil }
195                    }
196            }
197        }
198        .sheet(isPresented: $showingClockReport) { ClockReportScreen(workspace: workspace) }
199        .onChange(of: model.openRequest) {
200            guard let route = model.openRequest else { return }
201            model.openRequest = nil
202            tab = .agenda
203            agendaPath.append(route)
204        }
205        .onChange(of: model.agendaRequest) {
206            guard let request = model.agendaRequest else { return }
207            model.agendaRequest = nil
208            agenda.mode = .agenda(span: request.count, startOffset: nil)
209            agenda.start = request.start
210            tab = .agenda
211            agendaPath = NavigationPath()
212        }
213        .onChange(of: workspace.changedFile?.version) {
214            // An open file takes in what changed on disk.
215            if let path = workspace.changedFile?.path { session.fileChanged(path) }
216        }
217        .onChange(of: model.captureRequest?.id) {
218            guard let request = model.captureRequest else { return }
219            model.captureRequest = nil
220            capture = request
221        }
222        .sheet(item: $capture, onDismiss: showWaiting) { request in
223            CaptureScreen(workspace: workspace, session: session, request: request)
224        }
225        .task {
226            takeShared()
227            // Development: `ORGSTAR_ROOT` adds a folder at launch, as on the Mac.
228            if let root = ProcessInfo.processInfo.environment["ORGSTAR_ROOT"] { try? await workspace.addRoot(URL(fileURLWithPath: root)) }
229            workspace.startWatching()
230            await workspace.refresh()
231        }
232        .task {
233            while !Task.isCancelled {
234                try? await Task.sleep(for: .seconds(3600))
235                hour += 1
236            }
237        }
238        .background { BackgroundWork(model: model, workspace: workspace, agenda: agenda, active: scenePhase == .active, hour: hour) }
239        .onContinueUserActivity(CSSearchableItemActionType) { activity in
240            if let path = activity.userInfo?[CSSearchableItemActivityIdentifier] as? String { model.openRequest = .file(path) }
241        }
242        .onChange(of: scenePhase) { _, phase in
243            // Unsaved edits are written before the app may be stopped.
244            if phase == .background {
245                for path in session.dirtyPaths { _ = session.save(path) }
246            }
247            // Files and settings synced while away; not every sync tool tells file presenters.
248            guard phase == .active else { return }
249            takeShared()
250            model.reloadConfig()
251            Task { await workspace.refresh() }
252        }
253        .onOpenURL { url in
254            if let link = AppLink(url: url) {
255                open(link)
256            } else if let request = CaptureRequest(link: url.absoluteString) {
257                capture = request
258            } else if case .storeLink(let link, let title)? = OrgProtocol.parse(url.absoluteString) {
259                message = StoredLink.add(StoredLink(link: link, description: title), to: &model.storedLinks)
260                UIPasteboard.general.string = link
261            }
262        }
263        // The Live Activity follows the clock, wherever it starts or stops.
264        .task { await LiveClock.sync(model.clock.running) }
265        .onChange(of: model.clock.running) {
266            Task { await LiveClock.sync(model.clock.running) }
267        }
268    }
269
270    /// What the share extension left, one capture sheet at a time.
271    private func takeShared() {
272        waiting += (model.inbox?.take() ?? []).compactMap(CaptureRequest.init(link:))
273        if capture == nil { showWaiting() }
274    }
275
276    private func showWaiting() {
277        if !waiting.isEmpty { capture = waiting.removeFirst() }
278    }
279
280    /// A widget's or the Live Activity's link.
281    private func open(_ link: AppLink) {
282        switch link {
283        case .agenda:
284            tab = .agenda
285            agendaPath = NavigationPath()
286        case .entry(let path, let offset):
287            model.openRequest = .offset(path, offset)
288        case .clock:
289            clock("app.clock.goto")
290        }
291    }
292
293    private func clock(_ id: String) {
294        if id == "app.clock.report" {
295            showingClockReport = true
296        } else {
297            _ = MobileClock.run(id, model: model, workspace: workspace) { message = $0 }
298        }
299    }
300
301    private var captureButton: some ToolbarContent {
302        ToolbarItem(placement: .primaryAction) {
303            Button("Capture", systemImage: "square.and.pencil") { capture = CaptureRequest() }
304        }
305    }
306}
307#else
308/// The iOS app has nothing to run elsewhere.
309@main
310enum OrgstarMobileUnavailable {
311    static func main() { print("orgstar for iOS runs on iPhone and iPad.") }
312}
313#endif