Sources/OrgstarMobile/OrgstarMobileApp.swift
598 lines · 26872 bytes
1#if os(iOS)
2import CoreSpotlight
3import OrgApp
4import OrgCore
5import OrgMathJax
6import SwiftUI
7import UserNotifications
8
9/// Orgstar on iPhone and iPad: the agenda, capture, and the folders they read.
10@main
11struct OrgstarMobileApp: App {
12 @UIApplicationDelegateAdaptor private var delegate: AppDelegate
13 @State private var model = MobileModel.shared
14 /// The app's phase: in the background only when every window is.
15 @Environment(\.scenePhase) private var scenePhase
16
17 init() {
18 PDFExport.mathJaxURL = OrgMathJax.script
19 RevealExport.library = OrgMathJax.reveal
20 RevealExport.mathJax = OrgMathJax.script
21 DiagramBlocks.vizURL = OrgMathJax.viz
22 DiagramBlocks.mermaidURL = OrgMathJax.mermaid
23 PythonBlocks.folder = OrgMathJax.pyodide
24 // Debug builds, and runs from Xcode, whose scheme sets ORGSTAR_PERF.
25 #if DEBUG
26 Perf.watchMainThread()
27 #else
28 if ProcessInfo.processInfo.environment["ORGSTAR_PERF"] != nil { Perf.watchMainThread() }
29 #endif
30 LiveClock.install()
31 ProStore.shared.start()
32 ClockTask.titleKey = ClockTitleKey.loadOrCreate()
33 // Read before the app becomes active and clears it.
34 _ = UnsavedHeldFiles.atLaunch
35 // Early, so that the watch's actions are taken when iOS wakes the app for them.
36 WatchLink.shared.activate(MobileModel.shared)
37 }
38
39 var body: some Scene {
40 WindowGroup {
41 if let workspace = model.workspace, let agenda = model.agenda {
42 RootView(model: model, workspace: workspace, agenda: agenda)
43 .environment(model)
44 .environment(model.clock)
45 .onAppear { delegate.model = model }
46 } else {
47 ContentUnavailableView("Can't Open the Index", systemImage: "exclamationmark.triangle", description: Text(model.failure ?? ""))
48 }
49 }
50 // For the clock's idle time: time working in another window isn't time away.
51 .onChange(of: scenePhase) { _, phase in
52 if phase == .background { model.clock.wentAway() }
53 }
54 .commands { AppMenus(model: model) }
55 }
56}
57
58/// Reminders show while the app is open too, and open their entry when tapped.
59final class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate {
60 @MainActor var model: MobileModel?
61
62 func application(_ application: UIApplication, didFinishLaunchingWithOptions options: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
63 UNUserNotificationCenter.current().delegate = self
64 return true
65 }
66
67 nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification) async -> UNNotificationPresentationOptions {
68 // A midnight badge update shows nothing else.
69 if notification.request.content.badge != nil { return [.badge] }
70 // A countdown's end shows in the app's own message.
71 if notification.request.identifier == "sh.krz.orgstar.org-timer" { return [] }
72 return [.banner, .sound, .list]
73 }
74
75 nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {
76 let info = response.notification.request.content.userInfo
77 guard let path = info["path"] as? String, let offset = info["offset"] as? Int else { return }
78 await MainActor.run { model?.openRequest = .offset(path, offset) }
79 }
80}
81
82/// Files continued from another device, and what Working Copy's syncs come to.
83private struct HandoffAndSync: ViewModifier {
84 let model: MobileModel
85 let open: (HandoffPlace) -> Void
86 @Binding var message: String?
87
88 func body(content: Content) -> some View {
89 content
90 .onContinueUserActivity(HandoffPlace.activityType) { activity in
91 if let place = HandoffPlace(userInfo: activity.userInfo) { open(place) }
92 }
93 .onChange(of: model.workingCopy.message) {
94 guard let text = model.workingCopy.message else { return }
95 model.workingCopy.message = nil
96 message = text
97 }
98 }
99}
100
101/// A tab on iPhone, or a row of the sidebar on a regular-width iPad, which also lists search
102/// and each added folder.
103enum AppTab: Hashable { case agenda, search, folders, folder(String), settings }
104
105/// The search screen, pushed from the Agenda and Folders tabs.
106struct SearchRoute: Hashable {}
107
108extension AppTab {
109 /// The tab that shows this on iPhone: search is pushed from Agenda and Folders, and folders
110 /// are listed in Folders.
111 var inTabBar: AppTab {
112 switch self {
113 case .search: .agenda
114 case .folder: .folders
115 default: self
116 }
117 }
118}
119
120extension View {
121 /// Readers pushed for `ReaderRoute`s; Markdown and other text files open in the editor.
122 func readerDestination(workspace: WorkspaceModel, session: DocumentSession) -> some View {
123 navigationDestination(for: ReaderRoute.self) { route in
124 switch route {
125 case .file(let path) where !DocumentSession.isOrgPath(path):
126 EditorSplitScreen(path: path, offset: nil, workspace: workspace, session: session)
127 case .offset(let path, let offset) where !DocumentSession.isOrgPath(path):
128 EditorSplitScreen(path: path, offset: offset, workspace: workspace, session: session)
129 case .heading(let location) where !DocumentSession.isOrgPath(location.path):
130 EditorSplitScreen(path: location.path, offset: location.start, workspace: workspace, session: session)
131 default:
132 ReaderScreen(route: route, workspace: workspace, session: session)
133 }
134 }
135 .navigationDestination(for: EditorRoute.self) { route in
136 EditorSplitScreen(path: route.path, offset: route.offset, workspace: workspace, session: session)
137 }
138 .navigationDestination(for: SearchRoute.self) { _ in
139 SearchScreen(workspace: workspace, session: session)
140 }
141 }
142}
143
144/// A share of files from the share extension.
145struct SharedFiles: Identifiable {
146 let id = UUID()
147 let batch: URL
148}
149
150/// An org-protocol capture, or a plain one.
151struct CaptureRequest: Identifiable {
152 let id = UUID()
153 var template: String?
154 var properties: [String: String] = [:]
155 /// An agenda day (a `Days` number) the entry is scheduled on.
156 var day: Int?
157 /// An org-roam capture, whose templates take the place of capture.toml's.
158 var roam: RoamCapture?
159}
160
161extension CaptureRequest {
162 /// An `org-protocol://capture` link's request.
163 init?(link: String) {
164 guard case .capture(let template, let properties)? = OrgProtocol.parse(link) else { return nil }
165 self.init(template: template, properties: properties)
166 }
167}
168
169struct RootView: View {
170 let model: MobileModel
171 let workspace: WorkspaceModel
172 let agenda: AgendaModel
173 @State private var capture: CaptureRequest?
174 /// The share extension's link whose capture sheet is showing, with its request's id. The link
175 /// stays in the inbox until the sheet is dismissed.
176 @State private var shared: (link: CaptureInbox.Link, request: UUID)?
177 /// Files from the share extension, waiting for the entry to attach them to.
178 @State private var sharedFiles: SharedFiles?
179 @State private var tab = AppTab.agenda
180 @State private var agendaPath = NavigationPath()
181 @State private var hour = 0
182 @State private var showingClockReport = false
183 @State private var showingBoard = false
184 @State private var message: String?
185 @Environment(\.horizontalSizeClass) private var sizeClass
186 @Environment(\.scenePhase) private var scenePhase
187 @AppStorage(OnboardingScreen.doneKey) private var onboarded = false
188 @State private var onboarding = false
189 @State private var whatsNew: ReleaseNotes?
190
191 private var session: DocumentSession { model.session }
192
193 /// Reminders, widgets and Spotlight following the files. Its own view, so that edits redraw
194 /// only it, not the tabs.
195 private struct BackgroundWork: View {
196 let model: MobileModel
197 let workspace: WorkspaceModel
198 let agenda: AgendaModel
199 let active: Bool
200 /// Notifications and badges ask for permission, which onboarding asks for first.
201 let onboarded: Bool
202 let hour: Int
203
204 private var session: DocumentSession { model.session }
205
206 var body: some View {
207 Color.clear
208 // Reminders follow the files, the settings, coming back to the app and the hour.
209 .task(id: ReminderKey(hidden: HiddenFolders.shared.all, files: workspace.files.count, changed: workspace.changedFile?.version, edits: session.editVersion,
210 settings: model.settingsVersion, active: active, onboarded: onboarded, hour: hour)) {
211 guard active, onboarded else { return }
212 try? await Task.sleep(for: .seconds(1))
213 // After the agenda's refresh, whose parsed files these share.
214 while agenda.isComputing, !Task.isCancelled { try? await Task.sleep(for: .milliseconds(100)) }
215 guard !Task.isCancelled else { return }
216 await model.updateReminders()
217 await model.updateWidgets()
218 }
219 // Spotlight follows the files and saved edits.
220 .task(id: SpotlightKey(files: workspace.files.count, changed: workspace.changedFile?.version, saved: session.dirtyPaths.count)) {
221 await model.spotlight.update(workspace.files)
222 }
223 }
224 }
225
226 private struct SpotlightKey: Equatable {
227 var files: Int
228 var changed: Int?
229 var saved: Int
230 }
231
232 private struct ReminderKey: Equatable {
233 /// The widgets leave out hidden folders.
234 var hidden: Set<String>
235 var files: Int
236 var changed: Int?
237 var edits: Int
238 var settings: Int
239 var active: Bool
240 var onboarded: Bool
241 var hour: Int
242 }
243
244 /// Tabs on iPhone and in a narrow window; a sidebar beside the content on a wider iPad.
245 private var tabs: some View {
246 TabView(selection: Binding { tab.inTabBar } set: { tab = $0 }) {
247 Tab("Agenda", systemImage: "calendar", value: .agenda) { agendaStack }
248 Tab("Folders", systemImage: "folder", value: .folders) { foldersStack }
249 Tab("Settings", systemImage: "gearshape", value: .settings) { settingsStack }
250 }
251 .clockAccessory(model.clock, perform: clock)
252 }
253
254 private var split: some View {
255 NavigationSplitView {
256 AppSidebar(workspace: workspace, selection: $tab)
257 } detail: {
258 Group {
259 switch tab {
260 case .agenda: agendaStack
261 case .search:
262 NavigationStack {
263 SearchScreen(workspace: workspace, session: session)
264 .toolbar { captureButton }
265 .readerDestination(workspace: workspace, session: session)
266 }
267 case .folders: foldersStack
268 case .folder(let root):
269 NavigationStack {
270 FolderPage(workspace: workspace, session: session, route: FolderRoute(root: root, folder: ""))
271 .toolbar { searchButton; captureButton }
272 .readerDestination(workspace: workspace, session: session)
273 .navigationDestination(for: FolderRoute.self) { FolderPage(workspace: workspace, session: session, route: $0) }
274 }
275 .id(root)
276 case .settings: settingsStack
277 }
278 }
279 .safeAreaInset(edge: .bottom) {
280 if let running = model.clock.running {
281 ClockAccessory(running: running, clock: model.clock, perform: clock).padding(.vertical, 8).background(.bar)
282 }
283 }
284 }
285 }
286
287 private var agendaStack: some View {
288 NavigationStack(path: $agendaPath) {
289 AgendaScreen(workspace: workspace, session: session, agenda: agenda, scheduler: model.scheduler)
290 .equatable()
291 .toolbar { searchButton; captureButton }
292 .readerDestination(workspace: workspace, session: session)
293 }
294 }
295
296 private var foldersStack: some View {
297 NavigationStack {
298 FoldersScreen(workspace: workspace, session: session)
299 .toolbar { searchButton; captureButton }
300 .readerDestination(workspace: workspace, session: session)
301 }
302 }
303
304 private var settingsStack: some View {
305 NavigationStack { SettingsScreen(model: model) }
306 }
307
308 var body: some View {
309 // One view around both layouts, so that what follows runs once, not again when the
310 // window's width class changes.
311 ZStack {
312 if sizeClass == .regular { split } else { tabs }
313 }
314 .tint(model.theme.accentColor)
315 .focusedSceneValue(\.windowActions, WindowActions(
316 show: show, capture: { capture = CaptureRequest() },
317 addFolder: {
318 tab = .folders
319 model.addingFolder = true
320 },
321 board: { showingBoard = true }, clock: clock))
322 .fullScreenCover(isPresented: $showingBoard) {
323 BoardScreen(workspace: workspace, session: session) { showingBoard = false }
324 }
325 // A removed folder's row goes from the sidebar.
326 .onChange(of: workspace.rootPaths) {
327 if case .folder(let root) = tab, !workspace.rootPaths.contains(root) { tab = .folders }
328 }
329 // Until a folder is added there is nothing for the agenda to show.
330 .onAppear {
331 if workspace.rootPaths.isEmpty { tab = .folders }
332 whatsNew = WhatsNew.pending(firstLaunch: !onboarded)
333 // First launch only; a workspace from before onboarding existed skips it.
334 guard !onboarded else { return }
335 if workspace.rootPaths.isEmpty, ProcessInfo.processInfo.environment["ORGSTAR_ROOT"] == nil {
336 var transaction = Transaction()
337 transaction.disablesAnimations = true
338 withTransaction(transaction) { onboarding = true }
339 } else {
340 onboarded = true
341 }
342 }
343 .fullScreenCover(isPresented: $onboarding) {
344 OnboardingScreen(model: model, workspace: workspace) {
345 onboarding = false
346 onboarded = true
347 if !workspace.rootPaths.isEmpty { tab = .agenda }
348 }
349 .interactiveDismissDisabled()
350 }
351 .sheet(item: $whatsNew) { WhatsNewView(notes: $0) }
352 .modifier(DecryptQuestion())
353 .sheet(item: Bindable(ProAccess.shared).paywall) { ProSheet(feature: $0) }
354 .onChange(of: ProAccess.shared.isUnlocked) {
355 // Calendar and Reminders in the agenda, the widgets and the watch follow Pro.
356 model.reloadConfig()
357 Task { await model.updateWidgets() }
358 }
359 .sheet(item: Binding(get: { model.clockPrompts.pending }, set: { if $0 == nil { model.clockPrompts.answer(nil) } })) { pending in
360 ClockPromptSheet(prompt: pending.prompt) { model.clockPrompts.answer($0) }
361 }
362 // At the top, where the keyboard can't hide it.
363 .message($message, edge: .top)
364 .sheet(isPresented: $showingClockReport) { ClockReportScreen(workspace: workspace) }
365 .onChange(of: model.openRequest) {
366 guard let route = model.openRequest else { return }
367 model.openRequest = nil
368 tab = .agenda
369 agendaPath.append(route)
370 }
371 .onChange(of: model.agendaRequest) {
372 guard let request = model.agendaRequest else { return }
373 model.agendaRequest = nil
374 agenda.mode = .agenda(span: request.count, startOffset: nil)
375 agenda.start = request.start
376 tab = .agenda
377 agendaPath = NavigationPath()
378 }
379 .onChange(of: workspace.changedFile?.version) {
380 // An open file takes in what changed on disk.
381 if let path = workspace.changedFile?.path {
382 session.fileChanged(path)
383 // A clock started or stopped in Emacs or on another device.
384 if path.hasSuffix(".org"), let text = model.clock.sync(session, paths: [path]) { message = text }
385 }
386 }
387 // At launch and as folders load: open clocks in the agenda files.
388 .task(id: workspace.files.count) {
389 guard !workspace.files.isEmpty, let text = model.clock.sync(session, paths: workspace.agendaFilePaths()) else { return }
390 message = text
391 }
392 // Initially too: the capture control may have launched the app.
393 .onChange(of: model.captureRequest?.id, initial: true) {
394 guard let request = model.captureRequest else { return }
395 model.captureRequest = nil
396 capture = request
397 }
398
399 // Another capture took the sheet from a shared one, which stays in the inbox for later.
400 .onChange(of: capture?.id) { _, id in
401 if let id, id != shared?.request { shared = nil }
402 }
403 .sheet(item: $capture, onDismiss: captureDismissed) { request in
404 CaptureScreen(workspace: workspace, session: session, request: request)
405 }
406 .sheet(item: $sharedFiles) { shared in
407 RefileSheet(targets: workspace.refileTargets(openPath: nil, document: nil, settings: RefileSettings(targets: [.init(files: .workspace, spec: .all)])),
408 title: "Attach to") { target in
409 sharedFiles = nil
410 if let target {
411 message = session.attach(AttachmentInbox.files(in: shared.batch), to: target.path, at: target.start ?? 0)
412 } else {
413 message = "The shared files weren't attached"
414 }
415 AttachmentInbox()?.remove(shared.batch)
416 takeShared()
417 }
418 }
419 // After the first frame: removing a pending notification waits on the notification
420 // service, which can take many seconds after the device starts.
421 .task {
422 await Task.yield()
423 model.clock.remindAtEffort(session)
424 }
425 .task {
426 TimerModel.shared.onDone = { message = $0 }
427 if let lost = UnsavedHeldFiles.atLaunch { message = lost }
428 takeShared()
429 // Development: `ORGSTAR_ROOT` adds a folder at launch, as on the Mac.
430 if let root = ProcessInfo.processInfo.environment["ORGSTAR_ROOT"] { try? await workspace.addRoot(URL(fileURLWithPath: root)) }
431 // `ORGSTAR_PASTE_IMAGE`: paste takes this PNG from a pasteboard of the app's own.
432 if let image = ProcessInfo.processInfo.environment["ORGSTAR_PASTE_IMAGE"], let data = try? Data(contentsOf: URL(fileURLWithPath: image)),
433 let pasteboard = UIPasteboard(name: UIPasteboard.Name("orgstar-check"), create: true) {
434 pasteboard.setData(data, forPasteboardType: "public.png")
435 MobileEditor.pasteboard = pasteboard
436 }
437 workspace.startWatching()
438 await workspace.refresh()
439 model.workingCopy.appOpened(roots: workspace.rootPaths, session: session)
440 }
441 .task {
442 while !Task.isCancelled {
443 try? await Task.sleep(for: .seconds(3600))
444 hour += 1
445 }
446 }
447 .background { BackgroundWork(model: model, workspace: workspace, agenda: agenda, active: scenePhase == .active, onboarded: onboarded, hour: hour) }
448 .onContinueUserActivity(CSSearchableItemActionType) { activity in
449 if let path = activity.userInfo?[CSSearchableItemActivityIdentifier] as? String { model.openRequest = .file(path) }
450 }
451 .onChange(of: scenePhase) { _, phase in
452 // Unsaved edits are written before the app may be stopped. A file held for its
453 // passphrase stays in memory; its name is kept so that, if iOS ends the app
454 // meanwhile, the next launch says its edits were lost.
455 if phase == .background {
456 for path in session.dirtyPaths { _ = session.save(path) }
457 UnsavedHeldFiles.record(session.held.keys.filter(session.dirtyPaths.contains).sorted())
458 }
459 if phase == .active { UnsavedHeldFiles.record([]) }
460 // Files and settings synced while away; not every sync tool tells file presenters.
461 guard phase == .active else { return }
462 // iOS has no idle time: time away from the app while a clock ran stands in for it.
463 if let since = model.clock.cameBack(idleMinutes: OrgPreferences.clockIdleTime()) {
464 MobileClock.resolveIdle(since: since, model: model) { message = $0 }
465 }
466 takeShared()
467 model.reloadConfig()
468 model.handoff.update()
469 model.workingCopy.appOpened(roots: workspace.rootPaths, session: session)
470 Task { await workspace.refresh() }
471 }
472 .onOpenURL(perform: handle)
473 .modifier(HandoffAndSync(model: model, open: continueHandoff, message: $message))
474 // The Live Activity follows the clock, wherever it starts or stops.
475 .task {
476 LiveClock.publish(model.clock)
477 await LiveClock.sync(model.clock.running)
478 }
479 .onChange(of: model.clock.running) {
480 LiveClock.publish(model.clock)
481 Task { await LiveClock.sync(model.clock.running) }
482 Task { await model.updateWidgets() }
483 }
484 // A capture dictated on the watch, while the app is open.
485 .onChange(of: model.watchCaptures) { takeShared() }
486 }
487
488 /// What the share extension left, one capture sheet at a time.
489 private func takeShared() {
490 showWaiting()
491 if sharedFiles == nil, let batch = AttachmentInbox()?.batches().first { sharedFiles = SharedFiles(batch: batch) }
492 }
493
494 /// The inbox's oldest capture, unless a capture sheet is showing or being dismissed.
495 private func showWaiting() {
496 guard capture == nil, shared == nil, let inbox = model.inbox else { return }
497 for link in inbox.links() {
498 guard let request = CaptureRequest(link: link.text) else {
499 inbox.remove(link)
500 continue
501 }
502 shared = (link, request.id)
503 capture = request
504 return
505 }
506 }
507
508 /// The shared capture was saved or discarded, so its link goes; then the next one shows.
509 private func captureDismissed() {
510 if let shared { model.inbox?.remove(shared.link) }
511 shared = nil
512 showWaiting()
513 }
514
515 /// A widget's or the Live Activity's link, or an org-protocol URL.
516 private func handle(_ url: URL) {
517 if let callback = WorkingCopy.callback(url) {
518 model.workingCopy.finished(callback, workspace: workspace, session: session)
519 } else if let link = AppLink(url: url) {
520 open(link)
521 } else if let request = CaptureRequest(link: url.absoluteString) {
522 capture = request
523 } else if case .storeLink(let link, let title)? = OrgProtocol.parse(url.absoluteString) {
524 message = StoredLink.add(StoredLink(link: link, description: title), to: &model.storedLinks)
525 UIPasteboard.general.string = link
526 } else if let request = OrgProtocol.parse(url.absoluteString), ProAccess.shared.allows(.roam) {
527 // org-roam-protocol's `roam-ref` and `roam-node`.
528 var actions = RoamActions(session: session, roots: { workspace.rootPaths }, nodes: { try workspace.nodes(overlay: workspace.overlay(session.openDocuments)) },
529 show: { message = $0 }, ask: { $1(nil) }, open: { path, offset in model.openRequest = .offset(path, offset) },
530 insertLink: { _, _ in }, refresh: { Task { await workspace.refresh() } })
531 actions.capture = { capture = CaptureRequest(roam: $0) }
532 actions.follow(request)
533 } else if url.scheme == "org-protocol" {
534 message = "orgstar handles org-protocol capture and store-link"
535 }
536 }
537
538 /// A file continued from another device, in the editor at the caret's heading or line there.
539 private func continueHandoff(_ place: HandoffPlace) {
540 let match = place.resolve(roots: workspace.rootPaths)
541 guard case .file(let path) = match else { return message = place.problem(match) }
542 let offset = session.text(of: path).map { place.offset(in: $0, settings: session.defaults) } ?? 0
543 tab = .agenda
544 agendaPath.append(EditorRoute(path: path, offset: offset))
545 }
546
547 /// A tab or sidebar row; on iPhone, search is pushed on the agenda.
548 private func show(_ destination: AppTab) {
549 if destination == .search, sizeClass != .regular {
550 tab = .agenda
551 agendaPath.append(SearchRoute())
552 } else {
553 tab = destination
554 }
555 }
556
557 /// A widget's or the Live Activity's link.
558 private func open(_ link: AppLink) {
559 switch link {
560 case .agenda:
561 tab = .agenda
562 agendaPath = NavigationPath()
563 case .entry(let path, let offset):
564 model.openRequest = .offset(path, offset)
565 case .clock:
566 clock("app.clock.goto")
567 case .capture(let template):
568 capture = CaptureRequest(template: template)
569 }
570 }
571
572 private func clock(_ id: String) {
573 if id == "app.clock.report" {
574 showingClockReport = true
575 } else {
576 _ = MobileClock.run(id, model: model, workspace: workspace) { message = $0 }
577 }
578 }
579
580 private var searchButton: some ToolbarContent {
581 ToolbarItem(placement: .primaryAction) {
582 NavigationLink(value: SearchRoute()) { Label("Search", systemImage: "magnifyingglass") }
583 }
584 }
585
586 private var captureButton: some ToolbarContent {
587 ToolbarItem(placement: .primaryAction) {
588 Button("Capture", systemImage: "square.and.pencil") { capture = CaptureRequest() }
589 }
590 }
591}
592#else
593/// The iOS app has nothing to run elsewhere.
594@main
595enum OrgstarMobileUnavailable {
596 static func main() { print("orgstar for iOS runs on iPhone and iPad.") }
597}
598#endif