Sources/OrgstarMobile/OrgstarMobileApp.swift
318 lines · 13033 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 .onChange(of: model.captureRequest?.id) {
217 guard let request = model.captureRequest else { return }
218 model.captureRequest = nil
219 capture = request
220 }
221 .sheet(item: $capture, onDismiss: showWaiting) { request in
222 CaptureScreen(workspace: workspace, session: session, request: request)
223 }
224 .task {
225 takeShared()
226 // Development: `ORGSTAR_ROOT` adds a folder at launch, as on the Mac.
227 if let root = ProcessInfo.processInfo.environment["ORGSTAR_ROOT"] { try? await workspace.addRoot(URL(fileURLWithPath: root)) }
228 workspace.startWatching()
229 await workspace.refresh()
230 }
231 .task {
232 while !Task.isCancelled {
233 try? await Task.sleep(for: .seconds(3600))
234 hour += 1
235 }
236 }
237 .background { BackgroundWork(model: model, workspace: workspace, agenda: agenda, active: scenePhase == .active, hour: hour) }
238 .onContinueUserActivity(CSSearchableItemActionType) { activity in
239 if let path = activity.userInfo?[CSSearchableItemActivityIdentifier] as? String { model.openRequest = .file(path) }
240 }
241 .onChange(of: scenePhase) { _, phase in
242 // Unsaved edits are written before the app may be stopped.
243 if phase == .background {
244 for path in session.dirtyPaths { _ = session.save(path) }
245 }
246 // Files and settings synced while away; not every sync tool tells file presenters.
247 guard phase == .active else { return }
248 takeShared()
249 model.reloadConfig()
250 Task { await workspace.refresh() }
251 }
252 .onOpenURL { url in
253 if let link = AppLink(url: url) {
254 open(link)
255 } else if let request = CaptureRequest(link: url.absoluteString) {
256 capture = request
257 } else if case .storeLink(let link, let title)? = OrgProtocol.parse(url.absoluteString) {
258 message = StoredLink.add(StoredLink(link: link, description: title), to: &model.storedLinks)
259 UIPasteboard.general.string = link
260 }
261 }
262 // The Live Activity follows the clock, wherever it starts or stops.
263 .task { await LiveClock.sync(model.clock.running) }
264 .onChange(of: model.clock.running) {
265 Task { await LiveClock.sync(model.clock.running) }
266 }
267 }
268
269 /// What the share extension left, one capture sheet at a time.
270 private func takeShared() {
271 waiting += (model.inbox?.take() ?? []).compactMap(CaptureRequest.init(link:))
272 if capture == nil { showWaiting() }
273 }
274
275 private func showWaiting() {
276 if !waiting.isEmpty { capture = waiting.removeFirst() }
277 }
278
279 /// A widget's or the Live Activity's link.
280 private func open(_ link: AppLink) {
281 switch link {
282 case .agenda:
283 tab = .agenda
284 agendaPath = NavigationPath()
285 case .entry(let path, let offset):
286 model.openRequest = .offset(path, offset)
287 case .clock:
288 clock("app.clock.goto")
289 }
290 }
291
292 private func clock(_ id: String) {
293 if id == "app.clock.report" {
294 showingClockReport = true
295 } else {
296 _ = MobileClock.run(id, model: model, workspace: workspace) { message = $0 }
297 }
298 }
299
300 private var searchButton: some ToolbarContent {
301 ToolbarItem(placement: .primaryAction) {
302 NavigationLink(value: SearchRoute()) { Label("Search", systemImage: "magnifyingglass") }
303 }
304 }
305
306 private var captureButton: some ToolbarContent {
307 ToolbarItem(placement: .primaryAction) {
308 Button("Capture", systemImage: "square.and.pencil") { capture = CaptureRequest() }
309 }
310 }
311}
312#else
313/// The iOS app has nothing to run elsewhere.
314@main
315enum OrgstarMobileUnavailable {
316 static func main() { print("orgstar for iOS runs on iPhone and iPad.") }
317}
318#endif