Sources/OrgstarMobile/OrgstarMobileApp.swift

a15a7c83754a4ddcc5ba21c6f5e2ab5977f728d7
orgstar/Sources/OrgstarMobile/OrgstarMobileApp.swift

310 lines · 12679 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    }
 23
 24    var body: some Scene {
 25        WindowGroup {
 26            if let workspace = model.workspace, let agenda = model.agenda {
 27                RootView(model: model, workspace: workspace, agenda: agenda)
 28                    .environment(model)
 29                    .environment(model.clock)
 30                    .onAppear { delegate.model = model }
 31            } else {
 32                ContentUnavailableView("Can't open the index", systemImage: "exclamationmark.triangle", description: Text(model.failure ?? ""))
 33            }
 34        }
 35    }
 36}
 37
 38/// Reminders show while the app is open too, and open their entry when tapped.
 39final class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate {
 40    @MainActor var model: MobileModel?
 41
 42    func application(_ application: UIApplication, didFinishLaunchingWithOptions options: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
 43        UNUserNotificationCenter.current().delegate = self
 44        return true
 45    }
 46
 47    nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification) async -> UNNotificationPresentationOptions {
 48        [.banner, .sound, .list]
 49    }
 50
 51    nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {
 52        let info = response.notification.request.content.userInfo
 53        guard let path = info["path"] as? String, let offset = info["offset"] as? Int else { return }
 54        await MainActor.run { model?.openRequest = .offset(path, offset) }
 55    }
 56}
 57
 58enum AppTab: Hashable { case agenda, folders, settings, search }
 59
 60extension View {
 61    /// Readers pushed for `ReaderRoute`s.
 62    func readerDestination(workspace: WorkspaceModel, session: DocumentSession) -> some View {
 63        navigationDestination(for: ReaderRoute.self) { route in
 64            ReaderScreen(route: route, workspace: workspace, session: session)
 65        }
 66        .navigationDestination(for: EditorRoute.self) { route in
 67            EditorScreen(path: route.path, offset: route.offset, workspace: workspace, session: session)
 68        }
 69    }
 70}
 71
 72/// An org-protocol capture, or a plain one.
 73struct CaptureRequest: Identifiable {
 74    let id = UUID()
 75    var template: String?
 76    var properties: [String: String] = [:]
 77    /// An agenda day (a `Days` number) the entry is scheduled on.
 78    var day: Int?
 79}
 80
 81extension CaptureRequest {
 82    /// An `org-protocol://capture` link's request.
 83    init?(link: String) {
 84        guard case .capture(let template, let properties)? = OrgProtocol.parse(link) else { return nil }
 85        self.init(template: template, properties: properties)
 86    }
 87}
 88
 89struct RootView: View {
 90    let model: MobileModel
 91    let workspace: WorkspaceModel
 92    let agenda: AgendaModel
 93    @State private var capture: CaptureRequest?
 94    /// Captures from the share extension after the one showing.
 95    @State private var waiting: [CaptureRequest] = []
 96    @State private var tab = AppTab.agenda
 97    @State private var agendaPath = NavigationPath()
 98    @State private var hour = 0
 99    @State private var showingClockReport = false
100    @State private var message: String?
101    @Environment(\.scenePhase) private var scenePhase
102
103    private var session: DocumentSession { model.session }
104
105    /// Reminders, widgets and Spotlight following the files. Its own view, so that edits redraw
106    /// only it, not the tabs.
107    private struct BackgroundWork: View {
108        let model: MobileModel
109        let workspace: WorkspaceModel
110        let agenda: AgendaModel
111        let active: Bool
112        let hour: Int
113
114        private var session: DocumentSession { model.session }
115
116        var body: some View {
117            Color.clear
118                // Reminders follow the files, the settings, coming back to the app and the hour.
119                .task(id: ReminderKey(files: workspace.files.count, changed: workspace.changedFile?.version, edits: session.editVersion,
120                                      settings: model.settingsVersion, active: active, hour: hour)) {
121                    guard active else { return }
122                    try? await Task.sleep(for: .seconds(1))
123                    // After the agenda's refresh, whose parsed files these share.
124                    while agenda.isComputing, !Task.isCancelled { try? await Task.sleep(for: .milliseconds(100)) }
125                    guard !Task.isCancelled else { return }
126                    await model.updateReminders()
127                    await model.updateWidgets()
128                }
129                // Spotlight follows the files and saved edits.
130                .task(id: SpotlightKey(files: workspace.files.count, changed: workspace.changedFile?.version, saved: session.dirtyPaths.count)) {
131                    await model.spotlight.update(workspace.files)
132                }
133        }
134    }
135
136    private struct SpotlightKey: Equatable {
137        var files: Int
138        var changed: Int?
139        var saved: Int
140    }
141
142    private struct ReminderKey: Equatable {
143        var files: Int
144        var changed: Int?
145        var edits: Int
146        var settings: Int
147        var active: Bool
148        var hour: Int
149    }
150
151    var body: some View {
152        TabView(selection: $tab) {
153            Tab("Agenda", systemImage: "calendar", value: .agenda) {
154                NavigationStack(path: $agendaPath) {
155                    AgendaScreen(workspace: workspace, session: session, agenda: agenda, scheduler: model.scheduler)
156                        .equatable()
157                        .toolbar { captureButton }
158                        .readerDestination(workspace: workspace, session: session)
159                }
160            }
161            Tab("Folders", systemImage: "folder", value: .folders) {
162                NavigationStack {
163                    FoldersScreen(workspace: workspace)
164                        .toolbar { captureButton }
165                        .readerDestination(workspace: workspace, session: session)
166                }
167            }
168            Tab("Settings", systemImage: "gearshape", value: .settings) {
169                NavigationStack { SettingsScreen(model: model) }
170            }
171            Tab(value: .search, role: .search) {
172                NavigationStack {
173                    SearchScreen(workspace: workspace, session: session)
174                        .readerDestination(workspace: workspace, session: session)
175                }
176            }
177        }
178        .clockAccessory(model.clock, perform: clock)
179        .sheet(item: Binding(get: { model.clockPrompts.pending }, set: { if $0 == nil { model.clockPrompts.answer(nil) } })) { pending in
180            ClockPromptSheet(prompt: pending.prompt) { model.clockPrompts.answer($0) }
181        }
182        // Above the tab bar, clear of every screen's toolbar.
183        .overlay(alignment: .bottom) {
184            if let message {
185                Text(message).font(.callout).padding(.horizontal, 14).padding(.vertical, 8)
186                    .background(.regularMaterial, in: Capsule())
187                    .padding(.bottom, 150)
188                    .onTapGesture { self.message = nil }
189                    .task(id: message) {
190                        try? await Task.sleep(for: .seconds(4))
191                        if self.message == message { self.message = nil }
192                    }
193            }
194        }
195        .sheet(isPresented: $showingClockReport) { ClockReportScreen(workspace: workspace) }
196        .onChange(of: model.openRequest) {
197            guard let route = model.openRequest else { return }
198            model.openRequest = nil
199            tab = .agenda
200            agendaPath.append(route)
201        }
202        .onChange(of: model.agendaRequest) {
203            guard let request = model.agendaRequest else { return }
204            model.agendaRequest = nil
205            agenda.mode = .agenda(span: request.count, startOffset: nil)
206            agenda.start = request.start
207            tab = .agenda
208            agendaPath = NavigationPath()
209        }
210        .onChange(of: workspace.changedFile?.version) {
211            // An open file takes in what changed on disk.
212            if let path = workspace.changedFile?.path { session.fileChanged(path) }
213        }
214        .onChange(of: model.captureRequest?.id) {
215            guard let request = model.captureRequest else { return }
216            model.captureRequest = nil
217            capture = request
218        }
219        .sheet(item: $capture, onDismiss: showWaiting) { request in
220            CaptureScreen(workspace: workspace, session: session, request: request)
221        }
222        .task {
223            takeShared()
224            // Development: `ORGSTAR_ROOT` adds a folder at launch, as on the Mac.
225            if let root = ProcessInfo.processInfo.environment["ORGSTAR_ROOT"] { try? await workspace.addRoot(URL(fileURLWithPath: root)) }
226            workspace.startWatching()
227            await workspace.refresh()
228        }
229        .task {
230            while !Task.isCancelled {
231                try? await Task.sleep(for: .seconds(3600))
232                hour += 1
233            }
234        }
235        .background { BackgroundWork(model: model, workspace: workspace, agenda: agenda, active: scenePhase == .active, hour: hour) }
236        .onContinueUserActivity(CSSearchableItemActionType) { activity in
237            if let path = activity.userInfo?[CSSearchableItemActivityIdentifier] as? String { model.openRequest = .file(path) }
238        }
239        .onChange(of: scenePhase) { _, phase in
240            // Unsaved edits are written before the app may be stopped.
241            if phase == .background {
242                for path in session.dirtyPaths { _ = session.save(path) }
243            }
244            // Files and settings synced while away; not every sync tool tells file presenters.
245            guard phase == .active else { return }
246            takeShared()
247            model.reloadConfig()
248            Task { await workspace.refresh() }
249        }
250        .onOpenURL { url in
251            if let link = AppLink(url: url) {
252                open(link)
253            } else if let request = CaptureRequest(link: url.absoluteString) {
254                capture = request
255            } else if case .storeLink(let link, let title)? = OrgProtocol.parse(url.absoluteString) {
256                message = StoredLink.add(StoredLink(link: link, description: title), to: &model.storedLinks)
257                UIPasteboard.general.string = link
258            }
259        }
260        // The Live Activity follows the clock, wherever it starts or stops.
261        .task { await LiveClock.sync(model.clock.running) }
262        .onChange(of: model.clock.running) {
263            Task { await LiveClock.sync(model.clock.running) }
264        }
265    }
266
267    /// What the share extension left, one capture sheet at a time.
268    private func takeShared() {
269        waiting += (model.inbox?.take() ?? []).compactMap(CaptureRequest.init(link:))
270        if capture == nil { showWaiting() }
271    }
272
273    private func showWaiting() {
274        if !waiting.isEmpty { capture = waiting.removeFirst() }
275    }
276
277    /// A widget's or the Live Activity's link.
278    private func open(_ link: AppLink) {
279        switch link {
280        case .agenda:
281            tab = .agenda
282            agendaPath = NavigationPath()
283        case .entry(let path, let offset):
284            model.openRequest = .offset(path, offset)
285        case .clock:
286            clock("app.clock.goto")
287        }
288    }
289
290    private func clock(_ id: String) {
291        if id == "app.clock.report" {
292            showingClockReport = true
293        } else {
294            _ = MobileClock.run(id, model: model, workspace: workspace) { message = $0 }
295        }
296    }
297
298    private var captureButton: some ToolbarContent {
299        ToolbarItem(placement: .primaryAction) {
300            Button("Capture", systemImage: "square.and.pencil") { capture = CaptureRequest() }
301        }
302    }
303}
304#else
305/// The iOS app has nothing to run elsewhere.
306@main
307enum OrgstarMobileUnavailable {
308    static func main() { print("Orgstar for iOS runs on iPhone and iPad.") }
309}
310#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