Sources/OrgstarMobile/OrgstarMobileApp.swift

9a7439fd01e4ce5041bc5fab90542f083143ae10
orgstar/Sources/OrgstarMobile/OrgstarMobileApp.swift history · blame · raw

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