Sources/OrgstarMobile/OrgstarMobileApp.swift
365 lines · 15409 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 // Early, so that the watch's actions are taken when iOS wakes the app for them.
23 WatchLink.shared.activate(MobileModel.shared)
24 }
25
26 var body: some Scene {
27 WindowGroup {
28 if let workspace = model.workspace, let agenda = model.agenda {
29 RootView(model: model, workspace: workspace, agenda: agenda)
30 .environment(model)
31 .environment(model.clock)
32 .onAppear { delegate.model = model }
33 } else {
34 ContentUnavailableView("Can't open the index", systemImage: "exclamationmark.triangle", description: Text(model.failure ?? ""))
35 }
36 }
37 }
38}
39
40/// Reminders show while the app is open too, and open their entry when tapped.
41final class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate {
42 @MainActor var model: MobileModel?
43
44 func application(_ application: UIApplication, didFinishLaunchingWithOptions options: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
45 UNUserNotificationCenter.current().delegate = self
46 return true
47 }
48
49 nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification) async -> UNNotificationPresentationOptions {
50 // A midnight badge update shows nothing else.
51 if notification.request.content.badge != nil { return [.badge] }
52 // A countdown's end shows in the app's own message.
53 if notification.request.identifier == "sh.krz.orgstar.org-timer" { return [] }
54 return [.banner, .sound, .list]
55 }
56
57 nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {
58 let info = response.notification.request.content.userInfo
59 guard let path = info["path"] as? String, let offset = info["offset"] as? Int else { return }
60 await MainActor.run { model?.openRequest = .offset(path, offset) }
61 }
62}
63
64enum AppTab: Hashable { case agenda, folders, settings }
65
66/// The search screen, pushed from the Agenda and Folders tabs.
67struct SearchRoute: Hashable {}
68
69extension View {
70 /// Readers pushed for `ReaderRoute`s.
71 func readerDestination(workspace: WorkspaceModel, session: DocumentSession) -> some View {
72 navigationDestination(for: ReaderRoute.self) { route in
73 ReaderScreen(route: route, workspace: workspace, session: session)
74 }
75 .navigationDestination(for: EditorRoute.self) { route in
76 EditorSplitScreen(path: route.path, offset: route.offset, workspace: workspace, session: session)
77 }
78 .navigationDestination(for: SearchRoute.self) { _ in
79 SearchScreen(workspace: workspace, session: session)
80 }
81 }
82}
83
84/// A share of files from the share extension.
85struct SharedFiles: Identifiable {
86 let id = UUID()
87 let batch: URL
88}
89
90/// An org-protocol capture, or a plain one.
91struct CaptureRequest: Identifiable {
92 let id = UUID()
93 var template: String?
94 var properties: [String: String] = [:]
95 /// An agenda day (a `Days` number) the entry is scheduled on.
96 var day: Int?
97}
98
99extension CaptureRequest {
100 /// An `org-protocol://capture` link's request.
101 init?(link: String) {
102 guard case .capture(let template, let properties)? = OrgProtocol.parse(link) else { return nil }
103 self.init(template: template, properties: properties)
104 }
105}
106
107struct RootView: View {
108 let model: MobileModel
109 let workspace: WorkspaceModel
110 let agenda: AgendaModel
111 @State private var capture: CaptureRequest?
112 /// Captures from the share extension after the one showing.
113 @State private var waiting: [CaptureRequest] = []
114 /// Files from the share extension, waiting for the entry to attach them to.
115 @State private var sharedFiles: SharedFiles?
116 @State private var tab = AppTab.agenda
117 @State private var agendaPath = NavigationPath()
118 @State private var hour = 0
119 @State private var showingClockReport = false
120 @State private var message: String?
121 @Environment(\.scenePhase) private var scenePhase
122
123 private var session: DocumentSession { model.session }
124
125 /// Reminders, widgets and Spotlight following the files. Its own view, so that edits redraw
126 /// only it, not the tabs.
127 private struct BackgroundWork: View {
128 let model: MobileModel
129 let workspace: WorkspaceModel
130 let agenda: AgendaModel
131 let active: Bool
132 let hour: Int
133
134 private var session: DocumentSession { model.session }
135
136 var body: some View {
137 Color.clear
138 // Reminders follow the files, the settings, coming back to the app and the hour.
139 .task(id: ReminderKey(files: workspace.files.count, changed: workspace.changedFile?.version, edits: session.editVersion,
140 settings: model.settingsVersion, active: active, hour: hour)) {
141 guard active else { return }
142 try? await Task.sleep(for: .seconds(1))
143 // After the agenda's refresh, whose parsed files these share.
144 while agenda.isComputing, !Task.isCancelled { try? await Task.sleep(for: .milliseconds(100)) }
145 guard !Task.isCancelled else { return }
146 await model.updateReminders()
147 await model.updateWidgets()
148 }
149 // Spotlight follows the files and saved edits.
150 .task(id: SpotlightKey(files: workspace.files.count, changed: workspace.changedFile?.version, saved: session.dirtyPaths.count)) {
151 await model.spotlight.update(workspace.files)
152 }
153 }
154 }
155
156 private struct SpotlightKey: Equatable {
157 var files: Int
158 var changed: Int?
159 var saved: Int
160 }
161
162 private struct ReminderKey: Equatable {
163 var files: Int
164 var changed: Int?
165 var edits: Int
166 var settings: Int
167 var active: Bool
168 var hour: Int
169 }
170
171 var body: some View {
172 TabView(selection: $tab) {
173 Tab("Agenda", systemImage: "calendar", value: .agenda) {
174 NavigationStack(path: $agendaPath) {
175 AgendaScreen(workspace: workspace, session: session, agenda: agenda, scheduler: model.scheduler)
176 .equatable()
177 .toolbar { searchButton; captureButton }
178 .readerDestination(workspace: workspace, session: session)
179 }
180 }
181 Tab("Folders", systemImage: "folder", value: .folders) {
182 NavigationStack {
183 FoldersScreen(workspace: workspace, session: session)
184 .toolbar { searchButton; captureButton }
185 .readerDestination(workspace: workspace, session: session)
186 }
187 }
188 Tab("Settings", systemImage: "gearshape", value: .settings) {
189 NavigationStack { SettingsScreen(model: model) }
190 }
191 }
192 .clockAccessory(model.clock, perform: clock)
193 .sheet(item: Binding(get: { model.clockPrompts.pending }, set: { if $0 == nil { model.clockPrompts.answer(nil) } })) { pending in
194 ClockPromptSheet(prompt: pending.prompt) { model.clockPrompts.answer($0) }
195 }
196 // Above the tab bar, clear of every screen's toolbar.
197 .overlay(alignment: .bottom) {
198 if let message {
199 Text(message).font(.callout).padding(.horizontal, 14).padding(.vertical, 8)
200 .background(.regularMaterial, in: Capsule())
201 .padding(.bottom, 150)
202 .onTapGesture { self.message = nil }
203 .task(id: message) {
204 try? await Task.sleep(for: .seconds(4))
205 if self.message == message { self.message = nil }
206 }
207 }
208 }
209 .sheet(isPresented: $showingClockReport) { ClockReportScreen(workspace: workspace) }
210 .onChange(of: model.openRequest) {
211 guard let route = model.openRequest else { return }
212 model.openRequest = nil
213 tab = .agenda
214 agendaPath.append(route)
215 }
216 .onChange(of: model.agendaRequest) {
217 guard let request = model.agendaRequest else { return }
218 model.agendaRequest = nil
219 agenda.mode = .agenda(span: request.count, startOffset: nil)
220 agenda.start = request.start
221 tab = .agenda
222 agendaPath = NavigationPath()
223 }
224 .onChange(of: workspace.changedFile?.version) {
225 // An open file takes in what changed on disk.
226 if let path = workspace.changedFile?.path {
227 session.fileChanged(path)
228 // A clock started or stopped in Emacs or on another device.
229 if path.hasSuffix(".org"), let text = model.clock.sync(session, paths: [path]) { message = text }
230 }
231 }
232 // At launch and as folders load: open clocks in the agenda files.
233 .task(id: workspace.files.count) {
234 guard !workspace.files.isEmpty, let text = model.clock.sync(session, paths: workspace.agendaFilePaths()) else { return }
235 message = text
236 }
237 // Initially too: the capture control may have launched the app.
238 .onChange(of: model.captureRequest?.id, initial: true) {
239 guard let request = model.captureRequest else { return }
240 model.captureRequest = nil
241 capture = request
242 }
243
244 .sheet(item: $capture, onDismiss: showWaiting) { request in
245 CaptureScreen(workspace: workspace, session: session, request: request)
246 }
247 .sheet(item: $sharedFiles) { shared in
248 RefileSheet(targets: workspace.refileTargets(openPath: nil, document: nil, settings: RefileSettings(targets: [.init(files: .workspace, spec: .all)])),
249 title: "Attach to") { target in
250 sharedFiles = nil
251 if let target {
252 message = session.attach(AttachmentInbox.files(in: shared.batch), to: target.path, at: target.start ?? 0)
253 } else {
254 message = "The shared files weren't attached"
255 }
256 AttachmentInbox()?.remove(shared.batch)
257 takeShared()
258 }
259 }
260 .task {
261 TimerModel.shared.onDone = { message = $0 }
262 takeShared()
263 // Development: `ORGSTAR_ROOT` adds a folder at launch, as on the Mac.
264 if let root = ProcessInfo.processInfo.environment["ORGSTAR_ROOT"] { try? await workspace.addRoot(URL(fileURLWithPath: root)) }
265 workspace.startWatching()
266 await workspace.refresh()
267 }
268 .task {
269 while !Task.isCancelled {
270 try? await Task.sleep(for: .seconds(3600))
271 hour += 1
272 }
273 }
274 .background { BackgroundWork(model: model, workspace: workspace, agenda: agenda, active: scenePhase == .active, hour: hour) }
275 .onContinueUserActivity(CSSearchableItemActionType) { activity in
276 if let path = activity.userInfo?[CSSearchableItemActivityIdentifier] as? String { model.openRequest = .file(path) }
277 }
278 .onChange(of: scenePhase) { _, phase in
279 // Unsaved edits are written before the app may be stopped.
280 if phase == .background {
281 for path in session.dirtyPaths { _ = session.save(path) }
282 }
283 // Files and settings synced while away; not every sync tool tells file presenters.
284 guard phase == .active else { return }
285 takeShared()
286 model.reloadConfig()
287 Task { await workspace.refresh() }
288 }
289 .onOpenURL { url in
290 if let link = AppLink(url: url) {
291 open(link)
292 } else if let request = CaptureRequest(link: url.absoluteString) {
293 capture = request
294 } else if case .storeLink(let link, let title)? = OrgProtocol.parse(url.absoluteString) {
295 message = StoredLink.add(StoredLink(link: link, description: title), to: &model.storedLinks)
296 UIPasteboard.general.string = link
297 }
298 }
299 // The Live Activity follows the clock, wherever it starts or stops.
300 .task {
301 LiveClock.publish(model.clock)
302 await LiveClock.sync(model.clock.running)
303 }
304 .onChange(of: model.clock.running) {
305 LiveClock.publish(model.clock)
306 Task { await LiveClock.sync(model.clock.running) }
307 Task { await model.updateWidgets() }
308 }
309 // A capture dictated on the watch, while the app is open.
310 .onChange(of: model.watchCaptures) { takeShared() }
311 }
312
313 /// What the share extension left, one capture sheet at a time.
314 private func takeShared() {
315 waiting += (model.inbox?.take() ?? []).compactMap(CaptureRequest.init(link:))
316 if capture == nil { showWaiting() }
317 if sharedFiles == nil, let batch = AttachmentInbox()?.batches().first { sharedFiles = SharedFiles(batch: batch) }
318 }
319
320 private func showWaiting() {
321 if !waiting.isEmpty { capture = waiting.removeFirst() }
322 }
323
324 /// A widget's or the Live Activity's link.
325 private func open(_ link: AppLink) {
326 switch link {
327 case .agenda:
328 tab = .agenda
329 agendaPath = NavigationPath()
330 case .entry(let path, let offset):
331 model.openRequest = .offset(path, offset)
332 case .clock:
333 clock("app.clock.goto")
334 case .capture(let template):
335 capture = CaptureRequest(template: template)
336 }
337 }
338
339 private func clock(_ id: String) {
340 if id == "app.clock.report" {
341 showingClockReport = true
342 } else {
343 _ = MobileClock.run(id, model: model, workspace: workspace) { message = $0 }
344 }
345 }
346
347 private var searchButton: some ToolbarContent {
348 ToolbarItem(placement: .primaryAction) {
349 NavigationLink(value: SearchRoute()) { Label("Search", systemImage: "magnifyingglass") }
350 }
351 }
352
353 private var captureButton: some ToolbarContent {
354 ToolbarItem(placement: .primaryAction) {
355 Button("Capture", systemImage: "square.and.pencil") { capture = CaptureRequest() }
356 }
357 }
358}
359#else
360/// The iOS app has nothing to run elsewhere.
361@main
362enum OrgstarMobileUnavailable {
363 static func main() { print("orgstar for iOS runs on iPhone and iPad.") }
364}
365#endif