Sources/OrgstarMobile/OrgstarMobileApp.swift
216 lines · 8946 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()
13
14 var body: some Scene {
15 WindowGroup {
16 if let workspace = model.workspace, let agenda = model.agenda {
17 RootView(model: model, workspace: workspace, agenda: agenda)
18 .environment(model)
19 .environment(model.clock)
20 .onAppear { delegate.model = model }
21 } else {
22 ContentUnavailableView("Can't open the index", systemImage: "exclamationmark.triangle", description: Text(model.failure ?? ""))
23 }
24 }
25 }
26}
27
28/// Reminders show while the app is open too, and open their entry when tapped.
29final class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate {
30 @MainActor var model: MobileModel?
31
32 func application(_ application: UIApplication, didFinishLaunchingWithOptions options: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
33 UNUserNotificationCenter.current().delegate = self
34 return true
35 }
36
37 nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification) async -> UNNotificationPresentationOptions {
38 [.banner, .sound, .list]
39 }
40
41 nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {
42 let info = response.notification.request.content.userInfo
43 guard let path = info["path"] as? String, let offset = info["offset"] as? Int else { return }
44 await MainActor.run { model?.openRequest = .offset(path, offset) }
45 }
46}
47
48enum AppTab: Hashable { case agenda, folders, settings, search }
49
50extension View {
51 /// Readers pushed for `ReaderRoute`s.
52 func readerDestination(workspace: WorkspaceModel, session: DocumentSession) -> some View {
53 navigationDestination(for: ReaderRoute.self) { route in
54 ReaderScreen(route: route, workspace: workspace, session: session)
55 }
56 .navigationDestination(for: EditorRoute.self) { route in
57 EditorScreen(path: route.path, offset: route.offset, workspace: workspace, session: session)
58 }
59 }
60}
61
62/// An org-protocol capture, or a plain one.
63struct CaptureRequest: Identifiable {
64 let id = UUID()
65 var template: String?
66 var properties: [String: String] = [:]
67}
68
69struct RootView: View {
70 let model: MobileModel
71 let workspace: WorkspaceModel
72 let agenda: AgendaModel
73 @State private var capture: CaptureRequest?
74 @State private var tab = AppTab.agenda
75 @State private var agendaPath = NavigationPath()
76 @State private var hour = 0
77 @State private var showingClockReport = false
78 @State private var message: String?
79 @Environment(\.scenePhase) private var scenePhase
80
81 private var session: DocumentSession { model.session }
82
83 private struct SpotlightKey: Equatable {
84 var files: Int
85 var changed: Int?
86 var saved: Int
87 }
88
89 private struct ReminderKey: Equatable {
90 var files: Int
91 var changed: Int?
92 var edits: Int
93 var settings: Int
94 var active: Bool
95 var hour: Int
96 }
97
98 var body: some View {
99 TabView(selection: $tab) {
100 Tab("Agenda", systemImage: "calendar", value: .agenda) {
101 NavigationStack(path: $agendaPath) {
102 AgendaScreen(workspace: workspace, session: session, agenda: agenda, scheduler: model.scheduler)
103 .toolbar { captureButton }
104 .readerDestination(workspace: workspace, session: session)
105 }
106 }
107 Tab("Folders", systemImage: "folder", value: .folders) {
108 NavigationStack {
109 FoldersScreen(workspace: workspace)
110 .toolbar { captureButton }
111 .readerDestination(workspace: workspace, session: session)
112 }
113 }
114 Tab("Settings", systemImage: "gearshape", value: .settings) {
115 NavigationStack { SettingsScreen(model: model) }
116 }
117 Tab(value: .search, role: .search) {
118 NavigationStack {
119 SearchScreen(workspace: workspace, session: session)
120 .readerDestination(workspace: workspace, session: session)
121 }
122 }
123 }
124 .clockAccessory(model.clock.running, perform: clock)
125 .overlay(alignment: .top) {
126 if let message {
127 Text(message).font(.callout).padding(8).frame(maxWidth: .infinity).background(.bar)
128 .onTapGesture { self.message = nil }
129 .task(id: message) {
130 try? await Task.sleep(for: .seconds(4))
131 if self.message == message { self.message = nil }
132 }
133 }
134 }
135 .sheet(isPresented: $showingClockReport) { ClockReportScreen(workspace: workspace) }
136 .onChange(of: model.openRequest) {
137 guard let route = model.openRequest else { return }
138 model.openRequest = nil
139 tab = .agenda
140 agendaPath.append(route)
141 }
142 .onChange(of: workspace.changedFile?.version) {
143 // An open file takes in what changed on disk.
144 if let path = workspace.changedFile?.path { session.fileChanged(path) }
145 }
146 .sheet(item: $capture) { request in
147 CaptureScreen(workspace: workspace, session: session, request: request)
148 }
149 .task {
150 // Development: `ORGSTAR_ROOT` adds a folder at launch, as on the Mac.
151 if let root = ProcessInfo.processInfo.environment["ORGSTAR_ROOT"] { try? await workspace.addRoot(URL(fileURLWithPath: root)) }
152 workspace.startWatching()
153 await workspace.refresh()
154 }
155 .task {
156 while !Task.isCancelled {
157 try? await Task.sleep(for: .seconds(3600))
158 hour += 1
159 }
160 }
161 // Reminders follow the files, the settings, coming back to the app and the hour.
162 .task(id: ReminderKey(files: workspace.files.count, changed: workspace.changedFile?.version, edits: session.editVersion,
163 settings: model.settingsVersion, active: scenePhase == .active, hour: hour)) {
164 guard scenePhase == .active else { return }
165 try? await Task.sleep(for: .seconds(1))
166 guard !Task.isCancelled else { return }
167 await model.updateReminders()
168 }
169 // Spotlight follows the files and saved edits.
170 .task(id: SpotlightKey(files: workspace.files.count, changed: workspace.changedFile?.version, saved: session.dirtyPaths.count)) {
171 await model.spotlight.update(workspace.files)
172 }
173 .onContinueUserActivity(CSSearchableItemActionType) { activity in
174 if let path = activity.userInfo?[CSSearchableItemActivityIdentifier] as? String { model.openRequest = .file(path) }
175 }
176 .onChange(of: scenePhase) { _, phase in
177 // Unsaved edits are written before the app may be stopped.
178 if phase == .background {
179 for path in session.dirtyPaths { _ = session.save(path) }
180 }
181 // Files and settings synced while away; not every sync tool tells file presenters.
182 guard phase == .active else { return }
183 model.reloadConfig()
184 Task { await workspace.refresh() }
185 }
186 .onOpenURL { url in
187 if case .capture(let template, let properties)? = OrgProtocol.parse(url.absoluteString) {
188 capture = CaptureRequest(template: template, properties: properties)
189 }
190 }
191 }
192
193 private func clock(_ id: String) {
194 switch id {
195 case "app.clock.out": message = model.clock.clockOut(session)
196 case "app.clock.cancel": message = model.clock.clockOut(session, cancel: true)
197 case "app.clock.goto":
198 if let location = model.clock.location(session) { model.openRequest = .offset(location.path, location.offset) }
199 case "app.clock.report": showingClockReport = true
200 default: break
201 }
202 }
203
204 private var captureButton: some ToolbarContent {
205 ToolbarItem(placement: .primaryAction) {
206 Button("Capture", systemImage: "square.and.pencil") { capture = CaptureRequest() }
207 }
208 }
209}
210#else
211/// The iOS app has nothing to run elsewhere.
212@main
213enum OrgstarMobileUnavailable {
214 static func main() { print("Orgstar for iOS runs on iPhone and iPad.") }
215}
216#endif