Sources/OrgstarMobile/OrgstarMobileApp.swift
417 lines · 18302 bytes
1#if os(iOS)
2import CoreSpotlight
3import OrgApp
4import OrgCore
5import SwiftUI
6import UserNotifications
7
8/// Orgstar on iPhone and iPad: the agenda, capture, and the folders they read.
9@main
10struct OrgstarMobileApp: App {
11 @UIApplicationDelegateAdaptor private var delegate: AppDelegate
12 @State private var model = MobileModel.shared
13 /// The app's phase: in the background only when every window is.
14 @Environment(\.scenePhase) private var scenePhase
15
16 init() {
17 // Debug builds, and runs from Xcode, whose scheme sets ORGSTAR_PERF.
18 #if DEBUG
19 Perf.watchMainThread()
20 #else
21 if ProcessInfo.processInfo.environment["ORGSTAR_PERF"] != nil { Perf.watchMainThread() }
22 #endif
23 LiveClock.install()
24 ProStore.shared.start()
25 // Early, so that the watch's actions are taken when iOS wakes the app for them.
26 WatchLink.shared.activate(MobileModel.shared)
27 }
28
29 var body: some Scene {
30 WindowGroup {
31 if let workspace = model.workspace, let agenda = model.agenda {
32 RootView(model: model, workspace: workspace, agenda: agenda)
33 .environment(model)
34 .environment(model.clock)
35 .onAppear { delegate.model = model }
36 } else {
37 ContentUnavailableView("Can't open the index", systemImage: "exclamationmark.triangle", description: Text(model.failure ?? ""))
38 }
39 }
40 // For the clock's idle time: time working in another window isn't time away.
41 .onChange(of: scenePhase) { _, phase in
42 if phase == .background { model.clock.wentAway() }
43 }
44 }
45}
46
47/// Reminders show while the app is open too, and open their entry when tapped.
48final class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate {
49 @MainActor var model: MobileModel?
50
51 func application(_ application: UIApplication, didFinishLaunchingWithOptions options: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
52 UNUserNotificationCenter.current().delegate = self
53 return true
54 }
55
56 nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification) async -> UNNotificationPresentationOptions {
57 // A midnight badge update shows nothing else.
58 if notification.request.content.badge != nil { return [.badge] }
59 // A countdown's end shows in the app's own message.
60 if notification.request.identifier == "sh.krz.orgstar.org-timer" { return [] }
61 return [.banner, .sound, .list]
62 }
63
64 nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {
65 let info = response.notification.request.content.userInfo
66 guard let path = info["path"] as? String, let offset = info["offset"] as? Int else { return }
67 await MainActor.run { model?.openRequest = .offset(path, offset) }
68 }
69}
70
71enum AppTab: Hashable { case agenda, folders, settings }
72
73/// The search screen, pushed from the Agenda and Folders tabs.
74struct SearchRoute: Hashable {}
75
76extension View {
77 /// Readers pushed for `ReaderRoute`s.
78 func readerDestination(workspace: WorkspaceModel, session: DocumentSession) -> some View {
79 navigationDestination(for: ReaderRoute.self) { route in
80 ReaderScreen(route: route, workspace: workspace, session: session)
81 }
82 .navigationDestination(for: EditorRoute.self) { route in
83 EditorSplitScreen(path: route.path, offset: route.offset, workspace: workspace, session: session)
84 }
85 .navigationDestination(for: SearchRoute.self) { _ in
86 SearchScreen(workspace: workspace, session: session)
87 }
88 }
89}
90
91/// A share of files from the share extension.
92struct SharedFiles: Identifiable {
93 let id = UUID()
94 let batch: URL
95}
96
97/// An org-protocol capture, or a plain one.
98struct CaptureRequest: Identifiable {
99 let id = UUID()
100 var template: String?
101 var properties: [String: String] = [:]
102 /// An agenda day (a `Days` number) the entry is scheduled on.
103 var day: Int?
104}
105
106extension CaptureRequest {
107 /// An `org-protocol://capture` link's request.
108 init?(link: String) {
109 guard case .capture(let template, let properties)? = OrgProtocol.parse(link) else { return nil }
110 self.init(template: template, properties: properties)
111 }
112}
113
114struct RootView: View {
115 let model: MobileModel
116 let workspace: WorkspaceModel
117 let agenda: AgendaModel
118 @State private var capture: CaptureRequest?
119 /// Captures from the share extension after the one showing.
120 @State private var waiting: [CaptureRequest] = []
121 /// Files from the share extension, waiting for the entry to attach them to.
122 @State private var sharedFiles: SharedFiles?
123 @State private var tab = AppTab.agenda
124 @State private var agendaPath = NavigationPath()
125 @State private var hour = 0
126 @State private var showingClockReport = false
127 @State private var message: String?
128 @Environment(\.scenePhase) private var scenePhase
129 @AppStorage(OnboardingScreen.doneKey) private var onboarded = false
130 @State private var onboarding = false
131
132 private var session: DocumentSession { model.session }
133
134 /// Reminders, widgets and Spotlight following the files. Its own view, so that edits redraw
135 /// only it, not the tabs.
136 private struct BackgroundWork: View {
137 let model: MobileModel
138 let workspace: WorkspaceModel
139 let agenda: AgendaModel
140 let active: Bool
141 /// Notifications and badges ask for permission, which onboarding asks for first.
142 let onboarded: Bool
143 let hour: Int
144
145 private var session: DocumentSession { model.session }
146
147 var body: some View {
148 Color.clear
149 // Reminders follow the files, the settings, coming back to the app and the hour.
150 .task(id: ReminderKey(hidden: HiddenFolders.shared.all, files: workspace.files.count, changed: workspace.changedFile?.version, edits: session.editVersion,
151 settings: model.settingsVersion, active: active, onboarded: onboarded, hour: hour)) {
152 guard active, onboarded else { return }
153 try? await Task.sleep(for: .seconds(1))
154 // After the agenda's refresh, whose parsed files these share.
155 while agenda.isComputing, !Task.isCancelled { try? await Task.sleep(for: .milliseconds(100)) }
156 guard !Task.isCancelled else { return }
157 await model.updateReminders()
158 await model.updateWidgets()
159 }
160 // Spotlight follows the files and saved edits.
161 .task(id: SpotlightKey(files: workspace.files.count, changed: workspace.changedFile?.version, saved: session.dirtyPaths.count)) {
162 await model.spotlight.update(workspace.files)
163 }
164 }
165 }
166
167 private struct SpotlightKey: Equatable {
168 var files: Int
169 var changed: Int?
170 var saved: Int
171 }
172
173 private struct ReminderKey: Equatable {
174 /// The widgets leave out hidden folders.
175 var hidden: Set<String>
176 var files: Int
177 var changed: Int?
178 var edits: Int
179 var settings: Int
180 var active: Bool
181 var onboarded: Bool
182 var hour: Int
183 }
184
185 var body: some View {
186 TabView(selection: $tab) {
187 Tab("Agenda", systemImage: "calendar", value: .agenda) {
188 NavigationStack(path: $agendaPath) {
189 AgendaScreen(workspace: workspace, session: session, agenda: agenda, scheduler: model.scheduler)
190 .equatable()
191 .toolbar { searchButton; captureButton }
192 .readerDestination(workspace: workspace, session: session)
193 }
194 }
195 Tab("Folders", systemImage: "folder", value: .folders) {
196 NavigationStack {
197 FoldersScreen(workspace: workspace, session: session)
198 .toolbar { searchButton; captureButton }
199 .readerDestination(workspace: workspace, session: session)
200 }
201 }
202 Tab("Settings", systemImage: "gearshape", value: .settings) {
203 NavigationStack { SettingsScreen(model: model) }
204 }
205 }
206 .clockAccessory(model.clock, perform: clock)
207 .tint(model.theme.accentColor)
208 // Until a folder is added there is nothing for the agenda to show.
209 .onAppear {
210 if workspace.rootPaths.isEmpty { tab = .folders }
211 // First launch only; a workspace from before onboarding existed skips it.
212 guard !onboarded else { return }
213 if workspace.rootPaths.isEmpty, ProcessInfo.processInfo.environment["ORGSTAR_ROOT"] == nil {
214 var transaction = Transaction()
215 transaction.disablesAnimations = true
216 withTransaction(transaction) { onboarding = true }
217 } else {
218 onboarded = true
219 }
220 }
221 .fullScreenCover(isPresented: $onboarding) {
222 OnboardingScreen(model: model, workspace: workspace) {
223 onboarding = false
224 onboarded = true
225 if !workspace.rootPaths.isEmpty { tab = .agenda }
226 }
227 .interactiveDismissDisabled()
228 }
229 .sheet(item: Bindable(ProAccess.shared).paywall) { ProSheet(feature: $0) }
230 .onChange(of: ProAccess.shared.isUnlocked) {
231 // Calendar and Reminders in the agenda, the widgets and the watch follow Pro.
232 model.reloadConfig()
233 Task { await model.updateWidgets() }
234 }
235 .sheet(item: Binding(get: { model.clockPrompts.pending }, set: { if $0 == nil { model.clockPrompts.answer(nil) } })) { pending in
236 ClockPromptSheet(prompt: pending.prompt) { model.clockPrompts.answer($0) }
237 }
238 // Above the tab bar, clear of every screen's toolbar.
239 .overlay(alignment: .bottom) {
240 if let message {
241 Text(message).font(.callout).padding(.horizontal, 14).padding(.vertical, 8)
242 .background(.regularMaterial, in: Capsule())
243 .padding(.bottom, 150)
244 .onTapGesture { self.message = nil }
245 .task(id: message) {
246 try? await Task.sleep(for: .seconds(4))
247 if self.message == message { self.message = nil }
248 }
249 }
250 }
251 .sheet(isPresented: $showingClockReport) { ClockReportScreen(workspace: workspace) }
252 .onChange(of: model.openRequest) {
253 guard let route = model.openRequest else { return }
254 model.openRequest = nil
255 tab = .agenda
256 agendaPath.append(route)
257 }
258 .onChange(of: model.agendaRequest) {
259 guard let request = model.agendaRequest else { return }
260 model.agendaRequest = nil
261 agenda.mode = .agenda(span: request.count, startOffset: nil)
262 agenda.start = request.start
263 tab = .agenda
264 agendaPath = NavigationPath()
265 }
266 .onChange(of: workspace.changedFile?.version) {
267 // An open file takes in what changed on disk.
268 if let path = workspace.changedFile?.path {
269 session.fileChanged(path)
270 // A clock started or stopped in Emacs or on another device.
271 if path.hasSuffix(".org"), let text = model.clock.sync(session, paths: [path]) { message = text }
272 }
273 }
274 // At launch and as folders load: open clocks in the agenda files.
275 .task(id: workspace.files.count) {
276 guard !workspace.files.isEmpty, let text = model.clock.sync(session, paths: workspace.agendaFilePaths()) else { return }
277 message = text
278 }
279 // Initially too: the capture control may have launched the app.
280 .onChange(of: model.captureRequest?.id, initial: true) {
281 guard let request = model.captureRequest else { return }
282 model.captureRequest = nil
283 capture = request
284 }
285
286 .sheet(item: $capture, onDismiss: showWaiting) { request in
287 CaptureScreen(workspace: workspace, session: session, request: request)
288 }
289 .sheet(item: $sharedFiles) { shared in
290 RefileSheet(targets: workspace.refileTargets(openPath: nil, document: nil, settings: RefileSettings(targets: [.init(files: .workspace, spec: .all)])),
291 title: "Attach to") { target in
292 sharedFiles = nil
293 if let target {
294 message = session.attach(AttachmentInbox.files(in: shared.batch), to: target.path, at: target.start ?? 0)
295 } else {
296 message = "The shared files weren't attached"
297 }
298 AttachmentInbox()?.remove(shared.batch)
299 takeShared()
300 }
301 }
302 .task {
303 TimerModel.shared.onDone = { message = $0 }
304 takeShared()
305 // Development: `ORGSTAR_ROOT` adds a folder at launch, as on the Mac.
306 if let root = ProcessInfo.processInfo.environment["ORGSTAR_ROOT"] { try? await workspace.addRoot(URL(fileURLWithPath: root)) }
307 // `ORGSTAR_PASTE_IMAGE`: paste takes this PNG from a pasteboard of the app's own.
308 if let image = ProcessInfo.processInfo.environment["ORGSTAR_PASTE_IMAGE"], let data = try? Data(contentsOf: URL(fileURLWithPath: image)),
309 let pasteboard = UIPasteboard(name: UIPasteboard.Name("orgstar-check"), create: true) {
310 pasteboard.setData(data, forPasteboardType: "public.png")
311 MobileEditor.pasteboard = pasteboard
312 }
313 workspace.startWatching()
314 await workspace.refresh()
315 }
316 .task {
317 while !Task.isCancelled {
318 try? await Task.sleep(for: .seconds(3600))
319 hour += 1
320 }
321 }
322 .background { BackgroundWork(model: model, workspace: workspace, agenda: agenda, active: scenePhase == .active, onboarded: onboarded, hour: hour) }
323 .onContinueUserActivity(CSSearchableItemActionType) { activity in
324 if let path = activity.userInfo?[CSSearchableItemActivityIdentifier] as? String { model.openRequest = .file(path) }
325 }
326 .onChange(of: scenePhase) { _, phase in
327 // Unsaved edits are written before the app may be stopped.
328 if phase == .background {
329 for path in session.dirtyPaths { _ = session.save(path) }
330 }
331 // Files and settings synced while away; not every sync tool tells file presenters.
332 guard phase == .active else { return }
333 // iOS has no idle time: time away from the app while a clock ran stands in for it.
334 if let since = model.clock.cameBack(idleMinutes: OrgPreferences.clockIdleTime()) {
335 MobileClock.resolveIdle(since: since, model: model) { message = $0 }
336 }
337 takeShared()
338 model.reloadConfig()
339 Task { await workspace.refresh() }
340 }
341 .onOpenURL { url in
342 if let link = AppLink(url: url) {
343 open(link)
344 } else if let request = CaptureRequest(link: url.absoluteString) {
345 capture = request
346 } else if case .storeLink(let link, let title)? = OrgProtocol.parse(url.absoluteString) {
347 message = StoredLink.add(StoredLink(link: link, description: title), to: &model.storedLinks)
348 UIPasteboard.general.string = link
349 }
350 }
351 // The Live Activity follows the clock, wherever it starts or stops.
352 .task {
353 LiveClock.publish(model.clock)
354 await LiveClock.sync(model.clock.running)
355 }
356 .onChange(of: model.clock.running) {
357 LiveClock.publish(model.clock)
358 Task { await LiveClock.sync(model.clock.running) }
359 Task { await model.updateWidgets() }
360 }
361 // A capture dictated on the watch, while the app is open.
362 .onChange(of: model.watchCaptures) { takeShared() }
363 }
364
365 /// What the share extension left, one capture sheet at a time.
366 private func takeShared() {
367 waiting += (model.inbox?.take() ?? []).compactMap(CaptureRequest.init(link:))
368 if capture == nil { showWaiting() }
369 if sharedFiles == nil, let batch = AttachmentInbox()?.batches().first { sharedFiles = SharedFiles(batch: batch) }
370 }
371
372 private func showWaiting() {
373 if !waiting.isEmpty { capture = waiting.removeFirst() }
374 }
375
376 /// A widget's or the Live Activity's link.
377 private func open(_ link: AppLink) {
378 switch link {
379 case .agenda:
380 tab = .agenda
381 agendaPath = NavigationPath()
382 case .entry(let path, let offset):
383 model.openRequest = .offset(path, offset)
384 case .clock:
385 clock("app.clock.goto")
386 case .capture(let template):
387 capture = CaptureRequest(template: template)
388 }
389 }
390
391 private func clock(_ id: String) {
392 if id == "app.clock.report" {
393 showingClockReport = true
394 } else {
395 _ = MobileClock.run(id, model: model, workspace: workspace) { message = $0 }
396 }
397 }
398
399 private var searchButton: some ToolbarContent {
400 ToolbarItem(placement: .primaryAction) {
401 NavigationLink(value: SearchRoute()) { Label("Search", systemImage: "magnifyingglass") }
402 }
403 }
404
405 private var captureButton: some ToolbarContent {
406 ToolbarItem(placement: .primaryAction) {
407 Button("Capture", systemImage: "square.and.pencil") { capture = CaptureRequest() }
408 }
409 }
410}
411#else
412/// The iOS app has nothing to run elsewhere.
413@main
414enum OrgstarMobileUnavailable {
415 static func main() { print("orgstar for iOS runs on iPhone and iPad.") }
416}
417#endif