Sources/OrgstarMobile/OrgstarMobileApp.swift

10c0d64a19b13f9e27044e7dd3edb2b708038aed
orgstar/Sources/OrgstarMobile/OrgstarMobileApp.swift

422 lines · 18541 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    @State private var whatsNew: ReleaseNotes?
134
135    private var session: DocumentSession { model.session }
136
137    /// Reminders, widgets and Spotlight following the files. Its own view, so that edits redraw
138    /// only it, not the tabs.
139    private struct BackgroundWork: View {
140        let model: MobileModel
141        let workspace: WorkspaceModel
142        let agenda: AgendaModel
143        let active: Bool
144        /// Notifications and badges ask for permission, which onboarding asks for first.
145        let onboarded: Bool
146        let hour: Int
147
148        private var session: DocumentSession { model.session }
149
150        var body: some View {
151            Color.clear
152                // Reminders follow the files, the settings, coming back to the app and the hour.
153                .task(id: ReminderKey(hidden: HiddenFolders.shared.all, files: workspace.files.count, changed: workspace.changedFile?.version, edits: session.editVersion,
154                                      settings: model.settingsVersion, active: active, onboarded: onboarded, hour: hour)) {
155                    guard active, onboarded else { return }
156                    try? await Task.sleep(for: .seconds(1))
157                    // After the agenda's refresh, whose parsed files these share.
158                    while agenda.isComputing, !Task.isCancelled { try? await Task.sleep(for: .milliseconds(100)) }
159                    guard !Task.isCancelled else { return }
160                    await model.updateReminders()
161                    await model.updateWidgets()
162                }
163                // Spotlight follows the files and saved edits.
164                .task(id: SpotlightKey(files: workspace.files.count, changed: workspace.changedFile?.version, saved: session.dirtyPaths.count)) {
165                    await model.spotlight.update(workspace.files)
166                }
167        }
168    }
169
170    private struct SpotlightKey: Equatable {
171        var files: Int
172        var changed: Int?
173        var saved: Int
174    }
175
176    private struct ReminderKey: Equatable {
177        /// The widgets leave out hidden folders.
178        var hidden: Set<String>
179        var files: Int
180        var changed: Int?
181        var edits: Int
182        var settings: Int
183        var active: Bool
184        var onboarded: Bool
185        var hour: Int
186    }
187
188    var body: some View {
189        TabView(selection: $tab) {
190            Tab("Agenda", systemImage: "calendar", value: .agenda) {
191                NavigationStack(path: $agendaPath) {
192                    AgendaScreen(workspace: workspace, session: session, agenda: agenda, scheduler: model.scheduler)
193                        .equatable()
194                        .toolbar { searchButton; captureButton }
195                        .readerDestination(workspace: workspace, session: session)
196                }
197            }
198            Tab("Folders", systemImage: "folder", value: .folders) {
199                NavigationStack {
200                    FoldersScreen(workspace: workspace, session: session)
201                        .toolbar { searchButton; captureButton }
202                        .readerDestination(workspace: workspace, session: session)
203                }
204            }
205            Tab("Settings", systemImage: "gearshape", value: .settings) {
206                NavigationStack { SettingsScreen(model: model) }
207            }
208        }
209        .clockAccessory(model.clock, perform: clock)
210        .tint(model.theme.accentColor)
211        // Until a folder is added there is nothing for the agenda to show.
212        .onAppear {
213            if workspace.rootPaths.isEmpty { tab = .folders }
214            whatsNew = WhatsNew.pending(firstLaunch: !onboarded)
215            // First launch only; a workspace from before onboarding existed skips it.
216            guard !onboarded else { return }
217            if workspace.rootPaths.isEmpty, ProcessInfo.processInfo.environment["ORGSTAR_ROOT"] == nil {
218                var transaction = Transaction()
219                transaction.disablesAnimations = true
220                withTransaction(transaction) { onboarding = true }
221            } else {
222                onboarded = true
223            }
224        }
225        .fullScreenCover(isPresented: $onboarding) {
226            OnboardingScreen(model: model, workspace: workspace) {
227                onboarding = false
228                onboarded = true
229                if !workspace.rootPaths.isEmpty { tab = .agenda }
230            }
231            .interactiveDismissDisabled()
232        }
233        .sheet(item: $whatsNew) { WhatsNewView(notes: $0) }
234        .sheet(item: Bindable(ProAccess.shared).paywall) { ProSheet(feature: $0) }
235        .onChange(of: ProAccess.shared.isUnlocked) {
236            // Calendar and Reminders in the agenda, the widgets and the watch follow Pro.
237            model.reloadConfig()
238            Task { await model.updateWidgets() }
239        }
240        .sheet(item: Binding(get: { model.clockPrompts.pending }, set: { if $0 == nil { model.clockPrompts.answer(nil) } })) { pending in
241            ClockPromptSheet(prompt: pending.prompt) { model.clockPrompts.answer($0) }
242        }
243        // Above the tab bar, clear of every screen's toolbar.
244        .overlay(alignment: .bottom) {
245            if let message {
246                Text(message).font(.callout).padding(.horizontal, 14).padding(.vertical, 8)
247                    .background(.regularMaterial, in: Capsule())
248                    .padding(.bottom, 150)
249                    .onTapGesture { self.message = nil }
250                    .task(id: message) {
251                        try? await Task.sleep(for: .seconds(4))
252                        if self.message == message { self.message = nil }
253                    }
254            }
255        }
256        .sheet(isPresented: $showingClockReport) { ClockReportScreen(workspace: workspace) }
257        .onChange(of: model.openRequest) {
258            guard let route = model.openRequest else { return }
259            model.openRequest = nil
260            tab = .agenda
261            agendaPath.append(route)
262        }
263        .onChange(of: model.agendaRequest) {
264            guard let request = model.agendaRequest else { return }
265            model.agendaRequest = nil
266            agenda.mode = .agenda(span: request.count, startOffset: nil)
267            agenda.start = request.start
268            tab = .agenda
269            agendaPath = NavigationPath()
270        }
271        .onChange(of: workspace.changedFile?.version) {
272            // An open file takes in what changed on disk.
273            if let path = workspace.changedFile?.path {
274                session.fileChanged(path)
275                // A clock started or stopped in Emacs or on another device.
276                if path.hasSuffix(".org"), let text = model.clock.sync(session, paths: [path]) { message = text }
277            }
278        }
279        // At launch and as folders load: open clocks in the agenda files.
280        .task(id: workspace.files.count) {
281            guard !workspace.files.isEmpty, let text = model.clock.sync(session, paths: workspace.agendaFilePaths()) else { return }
282            message = text
283        }
284        // Initially too: the capture control may have launched the app.
285        .onChange(of: model.captureRequest?.id, initial: true) {
286            guard let request = model.captureRequest else { return }
287            model.captureRequest = nil
288            capture = request
289        }
290
291        .sheet(item: $capture, onDismiss: showWaiting) { request in
292            CaptureScreen(workspace: workspace, session: session, request: request)
293        }
294        .sheet(item: $sharedFiles) { shared in
295            RefileSheet(targets: workspace.refileTargets(openPath: nil, document: nil, settings: RefileSettings(targets: [.init(files: .workspace, spec: .all)])),
296                        title: "Attach to") { target in
297                sharedFiles = nil
298                if let target {
299                    message = session.attach(AttachmentInbox.files(in: shared.batch), to: target.path, at: target.start ?? 0)
300                } else {
301                    message = "The shared files weren't attached"
302                }
303                AttachmentInbox()?.remove(shared.batch)
304                takeShared()
305            }
306        }
307        .task {
308            TimerModel.shared.onDone = { message = $0 }
309            takeShared()
310            // Development: `ORGSTAR_ROOT` adds a folder at launch, as on the Mac.
311            if let root = ProcessInfo.processInfo.environment["ORGSTAR_ROOT"] { try? await workspace.addRoot(URL(fileURLWithPath: root)) }
312            // `ORGSTAR_PASTE_IMAGE`: paste takes this PNG from a pasteboard of the app's own.
313            if let image = ProcessInfo.processInfo.environment["ORGSTAR_PASTE_IMAGE"], let data = try? Data(contentsOf: URL(fileURLWithPath: image)),
314               let pasteboard = UIPasteboard(name: UIPasteboard.Name("orgstar-check"), create: true) {
315                pasteboard.setData(data, forPasteboardType: "public.png")
316                MobileEditor.pasteboard = pasteboard
317            }
318            workspace.startWatching()
319            await workspace.refresh()
320        }
321        .task {
322            while !Task.isCancelled {
323                try? await Task.sleep(for: .seconds(3600))
324                hour += 1
325            }
326        }
327        .background { BackgroundWork(model: model, workspace: workspace, agenda: agenda, active: scenePhase == .active, onboarded: onboarded, hour: hour) }
328        .onContinueUserActivity(CSSearchableItemActionType) { activity in
329            if let path = activity.userInfo?[CSSearchableItemActivityIdentifier] as? String { model.openRequest = .file(path) }
330        }
331        .onChange(of: scenePhase) { _, phase in
332            // Unsaved edits are written before the app may be stopped.
333            if phase == .background {
334                for path in session.dirtyPaths { _ = session.save(path) }
335            }
336            // Files and settings synced while away; not every sync tool tells file presenters.
337            guard phase == .active else { return }
338            // iOS has no idle time: time away from the app while a clock ran stands in for it.
339            if let since = model.clock.cameBack(idleMinutes: OrgPreferences.clockIdleTime()) {
340                MobileClock.resolveIdle(since: since, model: model) { message = $0 }
341            }
342            takeShared()
343            model.reloadConfig()
344            Task { await workspace.refresh() }
345        }
346        .onOpenURL { url in
347            if let link = AppLink(url: url) {
348                open(link)
349            } else if let request = CaptureRequest(link: url.absoluteString) {
350                capture = request
351            } else if case .storeLink(let link, let title)? = OrgProtocol.parse(url.absoluteString) {
352                message = StoredLink.add(StoredLink(link: link, description: title), to: &model.storedLinks)
353                UIPasteboard.general.string = link
354            }
355        }
356        // The Live Activity follows the clock, wherever it starts or stops.
357        .task {
358            LiveClock.publish(model.clock)
359            await LiveClock.sync(model.clock.running)
360        }
361        .onChange(of: model.clock.running) {
362            LiveClock.publish(model.clock)
363            Task { await LiveClock.sync(model.clock.running) }
364            Task { await model.updateWidgets() }
365        }
366        // A capture dictated on the watch, while the app is open.
367        .onChange(of: model.watchCaptures) { takeShared() }
368    }
369
370    /// What the share extension left, one capture sheet at a time.
371    private func takeShared() {
372        waiting += (model.inbox?.take() ?? []).compactMap(CaptureRequest.init(link:))
373        if capture == nil { showWaiting() }
374        if sharedFiles == nil, let batch = AttachmentInbox()?.batches().first { sharedFiles = SharedFiles(batch: batch) }
375    }
376
377    private func showWaiting() {
378        if !waiting.isEmpty { capture = waiting.removeFirst() }
379    }
380
381    /// A widget's or the Live Activity's link.
382    private func open(_ link: AppLink) {
383        switch link {
384        case .agenda:
385            tab = .agenda
386            agendaPath = NavigationPath()
387        case .entry(let path, let offset):
388            model.openRequest = .offset(path, offset)
389        case .clock:
390            clock("app.clock.goto")
391        case .capture(let template):
392            capture = CaptureRequest(template: template)
393        }
394    }
395
396    private func clock(_ id: String) {
397        if id == "app.clock.report" {
398            showingClockReport = true
399        } else {
400            _ = MobileClock.run(id, model: model, workspace: workspace) { message = $0 }
401        }
402    }
403
404    private var searchButton: some ToolbarContent {
405        ToolbarItem(placement: .primaryAction) {
406            NavigationLink(value: SearchRoute()) { Label("Search", systemImage: "magnifyingglass") }
407        }
408    }
409
410    private var captureButton: some ToolbarContent {
411        ToolbarItem(placement: .primaryAction) {
412            Button("Capture", systemImage: "square.and.pencil") { capture = CaptureRequest() }
413        }
414    }
415}
416#else
417/// The iOS app has nothing to run elsewhere.
418@main
419enum OrgstarMobileUnavailable {
420    static func main() { print("orgstar for iOS runs on iPhone and iPad.") }
421}
422#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