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