Sources/OrgstarMobile/OrgstarMobileApp.swift

586bad784d2cb2ad1bb43da0e63f0819913ed1dc
orgstar/Sources/OrgstarMobile/OrgstarMobileApp.swift

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