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