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