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