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