Sources/OrgstarMobile/OrgstarMobileApp.swift
680 lines · 30936 bytes
31 symbols in this file
OrgstarMobileAppAppDelegateapplicationuserNotificationCenteruserNotificationCenterHandoffAndSyncbodyAppTabSearchRoutereaderDestinationSharedFilesCaptureRequestXCallbackApprovalPendingbodyRootViewBackgroundWorkSpotlightKeyReminderKeytakeSharedshowWaitingcaptureDismissedhandlerunreplycontinueHandoffshowopenclockOrgstarMobileUnavailablemain
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
169/// Asks whether an app may use x-callback-url links that write to files or read them.
170private struct XCallbackApproval: ViewModifier {
171 typealias Pending = (request: XCallbackRequest, source: XCallbackApprovals.Source)
172 @Binding var pending: Pending?
173 let allow: (Pending) -> Void
174 let deny: (Pending) -> Void
175
176 func body(content: Content) -> some View {
177 content.alert(pending.map { XCallbackApprovals.question($0.source) } ?? "", isPresented: Binding { pending != nil } set: { if !$0 { pending = nil } },
178 presenting: pending) { pending in
179 Button("Allow") { allow(pending) }
180 Button("Don’t Allow", role: .cancel) { deny(pending) }
181 } message: { pending in
182 Text(XCallbackApprovals.explanation(pending.source))
183 }
184 }
185}
186
187struct RootView: View {
188 let model: MobileModel
189 let workspace: WorkspaceModel
190 let agenda: AgendaModel
191 @State private var capture: CaptureRequest?
192 /// An x-callback-url capture in the sheet: its request, the sheet's request, and the reply
193 /// once it is filed.
194 @State private var xCallbackCapture: (request: XCallbackRequest, id: UUID, filed: XCallbackReply?)?
195 /// An x-callback-url request waiting for the answer to whether its app may use links.
196 @State private var approval: (request: XCallbackRequest, source: XCallbackApprovals.Source)?
197 /// The share extension's link whose capture sheet is showing, with its request's id. The link
198 /// stays in the inbox until the sheet is dismissed.
199 @State private var shared: (link: CaptureInbox.Link, request: UUID)?
200 /// Files from the share extension, waiting for the entry to attach them to.
201 @State private var sharedFiles: SharedFiles?
202 @State private var tab = AppTab.agenda
203 @State private var agendaPath = NavigationPath()
204 @State private var hour = 0
205 @State private var showingClockReport = false
206 @State private var showingBoard = false
207 @State private var message: String?
208 @Environment(\.horizontalSizeClass) private var sizeClass
209 @Environment(\.scenePhase) private var scenePhase
210 @AppStorage(OnboardingScreen.doneKey) private var onboarded = false
211 @State private var onboarding = false
212 @State private var whatsNew: ReleaseNotes?
213
214 private var session: DocumentSession { model.session }
215
216 /// Reminders, widgets and Spotlight following the files. Its own view, so that edits redraw
217 /// only it, not the tabs.
218 private struct BackgroundWork: View {
219 let model: MobileModel
220 let workspace: WorkspaceModel
221 let agenda: AgendaModel
222 let active: Bool
223 /// Notifications and badges ask for permission, which onboarding asks for first.
224 let onboarded: Bool
225 let hour: Int
226
227 private var session: DocumentSession { model.session }
228
229 var body: some View {
230 Color.clear
231 // Reminders follow the files, the settings, coming back to the app and the hour.
232 .task(id: ReminderKey(hidden: HiddenFolders.shared.all, files: workspace.files.count, changed: workspace.changedFile?.version, edits: session.editVersion,
233 settings: model.settingsVersion, active: active, onboarded: onboarded, hour: hour)) {
234 guard active, onboarded else { return }
235 try? await Task.sleep(for: .seconds(1))
236 // After the agenda's refresh, whose parsed files these share.
237 while agenda.isComputing, !Task.isCancelled { try? await Task.sleep(for: .milliseconds(100)) }
238 guard !Task.isCancelled else { return }
239 await model.updateReminders()
240 await model.updateWidgets()
241 }
242 // Spotlight follows the files and saved edits.
243 .task(id: SpotlightKey(files: workspace.files.count, changed: workspace.changedFile?.version, saved: session.dirtyPaths.count)) {
244 await model.spotlight.update(workspace.files)
245 }
246 }
247 }
248
249 private struct SpotlightKey: Equatable {
250 var files: Int
251 var changed: Int?
252 var saved: Int
253 }
254
255 private struct ReminderKey: Equatable {
256 /// The widgets leave out hidden folders.
257 var hidden: Set<String>
258 var files: Int
259 var changed: Int?
260 var edits: Int
261 var settings: Int
262 var active: Bool
263 var onboarded: Bool
264 var hour: Int
265 }
266
267 /// Tabs on iPhone and in a narrow window; a sidebar beside the content on a wider iPad.
268 private var tabs: some View {
269 TabView(selection: Binding { tab.inTabBar } set: { tab = $0 }) {
270 Tab("Agenda", systemImage: "calendar", value: .agenda) { agendaStack }
271 Tab("Folders", systemImage: "folder", value: .folders) { foldersStack }
272 Tab("Settings", systemImage: "gearshape", value: .settings) { settingsStack }
273 }
274 .clockAccessory(model.clock, perform: clock)
275 }
276
277 private var split: some View {
278 NavigationSplitView {
279 AppSidebar(workspace: workspace, selection: $tab)
280 } detail: {
281 Group {
282 switch tab {
283 case .agenda: agendaStack
284 case .search:
285 NavigationStack {
286 SearchScreen(workspace: workspace, session: session)
287 .toolbar { captureButton }
288 .readerDestination(workspace: workspace, session: session)
289 }
290 case .folders: foldersStack
291 case .folder(let root):
292 NavigationStack {
293 FolderPage(workspace: workspace, session: session, route: FolderRoute(root: root, folder: ""))
294 .toolbar { searchButton; captureButton }
295 .readerDestination(workspace: workspace, session: session)
296 .navigationDestination(for: FolderRoute.self) { FolderPage(workspace: workspace, session: session, route: $0) }
297 }
298 .id(root)
299 case .settings: settingsStack
300 }
301 }
302 .safeAreaInset(edge: .bottom) {
303 if let running = model.clock.running {
304 ClockAccessory(running: running, clock: model.clock, perform: clock).padding(.vertical, 8).background(.bar)
305 }
306 }
307 }
308 }
309
310 private var agendaStack: some View {
311 NavigationStack(path: $agendaPath) {
312 AgendaScreen(workspace: workspace, session: session, agenda: agenda, scheduler: model.scheduler)
313 .equatable()
314 .toolbar { searchButton; captureButton }
315 .readerDestination(workspace: workspace, session: session)
316 }
317 }
318
319 private var foldersStack: some View {
320 NavigationStack {
321 FoldersScreen(workspace: workspace, session: session)
322 .toolbar { searchButton; captureButton }
323 .readerDestination(workspace: workspace, session: session)
324 }
325 }
326
327 private var settingsStack: some View {
328 NavigationStack { SettingsScreen(model: model) }
329 }
330
331 var body: some View {
332 // One view around both layouts, so that what follows runs once, not again when the
333 // window's width class changes.
334 ZStack {
335 if sizeClass == .regular { split } else { tabs }
336 }
337 .tint(model.theme.accentColor)
338 .focusedSceneValue(\.windowActions, WindowActions(
339 show: show, capture: { capture = CaptureRequest() },
340 addFolder: {
341 tab = .folders
342 model.addingFolder = true
343 },
344 board: { showingBoard = true }, flashcards: { model.reviewRequested = true }, clock: clock))
345 .fullScreenCover(isPresented: $showingBoard) {
346 BoardScreen(workspace: workspace, session: session) { showingBoard = false }
347 }
348 .fullScreenCover(isPresented: Binding(get: { model.reviewRequested }, set: { model.reviewRequested = $0 })) {
349 FlashcardScreen(workspace: workspace, session: session) { path, offset in
350 model.reviewRequested = false
351 if let path { model.openRequest = .offset(path, offset) }
352 }
353 }
354 // A removed folder's row goes from the sidebar.
355 .onChange(of: workspace.rootPaths) {
356 if case .folder(let root) = tab, !workspace.rootPaths.contains(root) { tab = .folders }
357 }
358 // Until a folder is added there is nothing for the agenda to show.
359 .onAppear {
360 if workspace.rootPaths.isEmpty { tab = .folders }
361 whatsNew = WhatsNew.pending(firstLaunch: !onboarded)
362 // First launch only; a workspace from before onboarding existed skips it.
363 guard !onboarded else { return }
364 if workspace.rootPaths.isEmpty, ProcessInfo.processInfo.environment["ORGSTAR_ROOT"] == nil {
365 var transaction = Transaction()
366 transaction.disablesAnimations = true
367 withTransaction(transaction) { onboarding = true }
368 } else {
369 onboarded = true
370 }
371 }
372 .fullScreenCover(isPresented: $onboarding) {
373 OnboardingScreen(model: model, workspace: workspace) {
374 onboarding = false
375 onboarded = true
376 if !workspace.rootPaths.isEmpty { tab = .agenda }
377 }
378 .interactiveDismissDisabled()
379 }
380 .sheet(item: $whatsNew) { WhatsNewView(notes: $0) }
381 .modifier(DecryptQuestion())
382 .sheet(item: Bindable(ProAccess.shared).paywall) { ProSheet(feature: $0) }
383 .onChange(of: ProAccess.shared.isUnlocked) {
384 // Calendar and Reminders in the agenda, the widgets and the watch follow Pro.
385 model.reloadConfig()
386 Task { await model.updateWidgets() }
387 }
388 .sheet(item: Binding(get: { model.clockPrompts.pending }, set: { if $0 == nil { model.clockPrompts.answer(nil) } })) { pending in
389 ClockPromptSheet(prompt: pending.prompt) { model.clockPrompts.answer($0) }
390 }
391 // At the top, where the keyboard can't hide it.
392 .message($message, edge: .top)
393 .sheet(isPresented: $showingClockReport) { ClockReportScreen(workspace: workspace) }
394 .onChange(of: model.openRequest) {
395 guard let route = model.openRequest else { return }
396 model.openRequest = nil
397 tab = .agenda
398 agendaPath.append(route)
399 }
400 .onChange(of: model.agendaRequest) {
401 guard let request = model.agendaRequest else { return }
402 model.agendaRequest = nil
403 agenda.mode = .agenda(span: request.count, startOffset: nil)
404 agenda.start = request.start
405 tab = .agenda
406 agendaPath = NavigationPath()
407 }
408 .onChange(of: workspace.changedFile?.version) {
409 // An open file takes in what changed on disk.
410 if let path = workspace.changedFile?.path {
411 session.fileChanged(path)
412 // A clock started or stopped in Emacs or on another device.
413 if path.hasSuffix(".org"), let text = model.clock.sync(session, paths: [path]) { message = text }
414 }
415 }
416 // At launch and as folders load: open clocks in the agenda files.
417 .task(id: workspace.files.count) {
418 guard !workspace.files.isEmpty, let text = model.clock.sync(session, paths: workspace.agendaFilePaths()) else { return }
419 message = text
420 }
421 // Initially too: the capture control may have launched the app.
422 .onChange(of: model.captureRequest?.id, initial: true) {
423 guard let request = model.captureRequest else { return }
424 model.captureRequest = nil
425 capture = request
426 }
427
428 // Another capture took the sheet from a shared one, which stays in the inbox for later.
429 .onChange(of: capture?.id) { _, id in
430 if let id, id != shared?.request { shared = nil }
431 }
432 .sheet(item: $capture, onDismiss: captureDismissed) { request in
433 CaptureScreen(workspace: workspace, session: session, request: request) { template, path in
434 if xCallbackCapture?.id == request.id { xCallbackCapture?.filed = xCallbackRunner.captured(template, path: path) }
435 }
436 }
437 .modifier(XCallbackApproval(pending: $approval, allow: { pending in
438 XCallbackApprovals.shared.allow(pending.source)
439 run(pending.request)
440 }, deny: { pending in
441 reply(pending.request, .failure(.notAllowed, "Not allowed"))
442 }))
443 .sheet(item: $sharedFiles) { shared in
444 RefileSheet(targets: workspace.refileTargets(openPath: nil, document: nil, settings: RefileSettings(targets: [.init(files: .workspace, spec: .all)])),
445 title: "Attach to") { target in
446 sharedFiles = nil
447 if let target {
448 message = session.attach(AttachmentInbox.files(in: shared.batch), to: target.path, at: target.start ?? 0)
449 } else {
450 message = "The shared files weren't attached"
451 }
452 AttachmentInbox()?.remove(shared.batch)
453 takeShared()
454 }
455 }
456 // After the first frame: removing a pending notification waits on the notification
457 // service, which can take many seconds after the device starts.
458 .task {
459 await Task.yield()
460 model.clock.remindAtEffort(session)
461 }
462 .task {
463 TimerModel.shared.onDone = { message = $0 }
464 if let lost = UnsavedHeldFiles.atLaunch { message = lost }
465 takeShared()
466 // Development: `ORGSTAR_ROOT` adds a folder at launch, as on the Mac.
467 if let root = ProcessInfo.processInfo.environment["ORGSTAR_ROOT"] { try? await workspace.addRoot(URL(fileURLWithPath: root)) }
468 // `ORGSTAR_PASTE_IMAGE`: paste takes this PNG from a pasteboard of the app's own.
469 if let image = ProcessInfo.processInfo.environment["ORGSTAR_PASTE_IMAGE"], let data = try? Data(contentsOf: URL(fileURLWithPath: image)),
470 let pasteboard = UIPasteboard(name: UIPasteboard.Name("orgstar-check"), create: true) {
471 pasteboard.setData(data, forPasteboardType: "public.png")
472 MobileEditor.pasteboard = pasteboard
473 }
474 workspace.startWatching()
475 await workspace.refresh()
476 model.workingCopy.appOpened(roots: workspace.rootPaths, session: session)
477 }
478 .task {
479 while !Task.isCancelled {
480 try? await Task.sleep(for: .seconds(3600))
481 hour += 1
482 }
483 }
484 .background { BackgroundWork(model: model, workspace: workspace, agenda: agenda, active: scenePhase == .active, onboarded: onboarded, hour: hour) }
485 .onContinueUserActivity(CSSearchableItemActionType) { activity in
486 if let path = activity.userInfo?[CSSearchableItemActivityIdentifier] as? String { model.openRequest = .file(path) }
487 }
488 .onChange(of: scenePhase) { _, phase in
489 // Unsaved edits are written before the app may be stopped. A file held for its
490 // passphrase stays in memory; its name is kept so that, if iOS ends the app
491 // meanwhile, the next launch says its edits were lost.
492 if phase == .background {
493 for path in session.dirtyPaths { _ = session.save(path) }
494 UnsavedHeldFiles.record(session.held.keys.filter(session.dirtyPaths.contains).sorted())
495 }
496 if phase == .active { UnsavedHeldFiles.record([]) }
497 // Files and settings synced while away; not every sync tool tells file presenters.
498 guard phase == .active else { return }
499 // iOS has no idle time: time away from the app while a clock ran stands in for it.
500 if let since = model.clock.cameBack(idleMinutes: OrgPreferences.clockIdleTime()) {
501 MobileClock.resolveIdle(since: since, model: model) { message = $0 }
502 }
503 takeShared()
504 model.reloadConfig()
505 model.handoff.update()
506 model.workingCopy.appOpened(roots: workspace.rootPaths, session: session)
507 Task { await workspace.refresh() }
508 }
509 .onOpenURL(perform: handle)
510 .modifier(HandoffAndSync(model: model, open: continueHandoff, message: $message))
511 // The Live Activity follows the clock, wherever it starts or stops.
512 .task {
513 LiveClock.publish(model.clock)
514 await LiveClock.sync(model.clock.running)
515 }
516 .onChange(of: model.clock.running) {
517 LiveClock.publish(model.clock)
518 Task { await LiveClock.sync(model.clock.running) }
519 Task { await model.updateWidgets() }
520 }
521 // A capture dictated on the watch, while the app is open.
522 .onChange(of: model.watchCaptures) { takeShared() }
523 }
524
525 /// What the share extension left, one capture sheet at a time.
526 private func takeShared() {
527 showWaiting()
528 if sharedFiles == nil, let batch = AttachmentInbox()?.batches().first { sharedFiles = SharedFiles(batch: batch) }
529 }
530
531 /// The inbox's oldest capture, unless a capture sheet is showing or being dismissed.
532 private func showWaiting() {
533 guard capture == nil, shared == nil, let inbox = model.inbox else { return }
534 for link in inbox.links() {
535 guard let request = CaptureRequest(link: link.text) else {
536 inbox.remove(link)
537 continue
538 }
539 shared = (link, request.id)
540 capture = request
541 return
542 }
543 }
544
545 /// The shared capture was saved or discarded, so its link goes; then the next one shows.
546 private func captureDismissed() {
547 if let pending = xCallbackCapture, capture?.id != pending.id {
548 xCallbackCapture = nil
549 reply(pending.request, pending.filed ?? .cancel)
550 }
551 if let shared { model.inbox?.remove(shared.link) }
552 shared = nil
553 showWaiting()
554 }
555
556 /// A widget's or the Live Activity's link, or an org-protocol URL.
557 private func handle(_ url: URL) {
558 if let request = XCallbackRequest(url: url) {
559 run(request)
560 } else if let callback = WorkingCopy.callback(url) {
561 model.workingCopy.finished(callback, workspace: workspace, session: session)
562 } else if let link = AppLink(url: url) {
563 open(link)
564 } else if let request = CaptureRequest(link: url.absoluteString) {
565 capture = request
566 } else if case .storeLink(let link, let title)? = OrgProtocol.parse(url.absoluteString) {
567 message = StoredLink.add(StoredLink(link: link, description: title), to: &model.storedLinks)
568 UIPasteboard.general.string = link
569 } else if let request = OrgProtocol.parse(url.absoluteString), ProAccess.shared.allows(.roam) {
570 // org-roam-protocol's `roam-ref` and `roam-node`.
571 var actions = RoamActions(session: session, roots: { workspace.rootPaths }, nodes: { try workspace.nodes(overlay: workspace.overlay(session.openDocuments)) },
572 show: { message = $0 }, ask: { $1(nil) }, open: { path, offset in model.openRequest = .offset(path, offset) },
573 insertLink: { _, _ in }, refresh: { Task { await workspace.refresh() } })
574 actions.capture = { capture = CaptureRequest(roam: $0) }
575 actions.follow(request)
576 } else if url.scheme == "org-protocol" {
577 message = "orgstar handles org-protocol capture and store-link"
578 }
579 }
580
581 private var xCallbackRunner: XCallbackRunner {
582 XCallbackRunner(workspace: workspace, session: session, clock: model.clock)
583 }
584
585 /// An `orgstar://x-callback-url/…` link.
586 private func run(_ request: XCallbackRequest) {
587 Task {
588 switch await xCallbackRunner.run(request, ask: model.clockPrompts.ask) {
589 case .reply(let reply):
590 // Captures and clocks are written at once, as Shortcuts' are.
591 if [.capture, .clockIn, .clockOut].contains(request.known) {
592 for path in session.dirtyPaths { _ = session.save(path) }
593 }
594 self.reply(request, reply)
595 case .approve(let source):
596 approval = (request, source)
597 case .capture(let template, let properties):
598 if let pending = xCallbackCapture { reply(pending.request, pending.filed ?? .cancel) }
599 let sheet = CaptureRequest(template: template, properties: properties)
600 xCallbackCapture = (request, sheet.id, nil)
601 capture = sheet
602 case .open(let path, let offset, let reply):
603 model.openRequest = .offset(path, offset)
604 self.reply(request, reply)
605 }
606 }
607 }
608
609 /// Opens the request's callback for `reply`; a failure without one shows its message.
610 private func reply(_ request: XCallbackRequest, _ reply: XCallbackReply) {
611 if let url = request.callbackURL(for: reply) {
612 UIApplication.shared.open(url)
613 } else if case .failure(_, let message) = reply {
614 self.message = message
615 }
616 }
617
618 /// A file continued from another device, in the editor at the caret's heading or line there.
619 private func continueHandoff(_ place: HandoffPlace) {
620 let match = place.resolve(roots: workspace.rootPaths)
621 guard case .file(let path) = match else { return message = place.problem(match) }
622 let offset = session.text(of: path).map { place.offset(in: $0, settings: session.defaults) } ?? 0
623 tab = .agenda
624 agendaPath.append(EditorRoute(path: path, offset: offset))
625 }
626
627 /// A tab or sidebar row; on iPhone, search is pushed on the agenda.
628 private func show(_ destination: AppTab) {
629 if destination == .search, sizeClass != .regular {
630 tab = .agenda
631 agendaPath.append(SearchRoute())
632 } else {
633 tab = destination
634 }
635 }
636
637 /// A widget's or the Live Activity's link.
638 private func open(_ link: AppLink) {
639 switch link {
640 case .agenda:
641 tab = .agenda
642 agendaPath = NavigationPath()
643 case .entry(let path, let offset):
644 model.openRequest = .offset(path, offset)
645 case .clock:
646 clock("app.clock.goto")
647 case .capture(let template):
648 capture = CaptureRequest(template: template)
649 case .review:
650 model.reviewRequested = true
651 }
652 }
653
654 private func clock(_ id: String) {
655 if id == "app.clock.report" {
656 showingClockReport = true
657 } else {
658 _ = MobileClock.run(id, model: model, workspace: workspace) { message = $0 }
659 }
660 }
661
662 private var searchButton: some ToolbarContent {
663 ToolbarItem(placement: .primaryAction) {
664 NavigationLink(value: SearchRoute()) { Label("Search", systemImage: "magnifyingglass") }
665 }
666 }
667
668 private var captureButton: some ToolbarContent {
669 ToolbarItem(placement: .primaryAction) {
670 Button("Capture", systemImage: "square.and.pencil") { capture = CaptureRequest() }
671 }
672 }
673}
674#else
675/// The iOS app has nothing to run elsewhere.
676@main
677enum OrgstarMobileUnavailable {
678 static func main() { print("orgstar for iOS runs on iPhone and iPad.") }
679}
680#endif