Sources/OrgstarMobile/OrgstarMobileApp.swift

9c8e4f9667c239dbcda0a122d127aa0620db4d35
orgstar/Sources/OrgstarMobile/OrgstarMobileApp.swift

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

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form