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