Sources/OrgstarMobile/OrgstarMobileApp.swift

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