Sources/OrgstarMobile/OrgstarMobileApp.swift

3a5c6a6f0e1b65f57e3697195747679128581b57
orgstar/Sources/OrgstarMobile/OrgstarMobileApp.swift

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