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