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