Sources/OrgstarMobile/OrgstarMobileApp.swift
202 lines · 8327 bytes
1#if os(iOS)
2import OrgApp
3import OrgCore
4import SwiftUI
5import UserNotifications
6
7/// Orgstar on iPhone and iPad: the agenda, capture, and the folders they read.
8@main
9struct OrgstarMobileApp: App {
10 @UIApplicationDelegateAdaptor private var delegate: AppDelegate
11 @State private var model = MobileModel()
12
13 var body: some Scene {
14 WindowGroup {
15 if let workspace = model.workspace, let agenda = model.agenda {
16 RootView(model: model, workspace: workspace, agenda: agenda)
17 .environment(model)
18 .environment(model.clock)
19 .onAppear { delegate.model = model }
20 } else {
21 ContentUnavailableView("Can't open the index", systemImage: "exclamationmark.triangle", description: Text(model.failure ?? ""))
22 }
23 }
24 }
25}
26
27/// Reminders show while the app is open too, and open their entry when tapped.
28final class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate {
29 @MainActor var model: MobileModel?
30
31 func application(_ application: UIApplication, didFinishLaunchingWithOptions options: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
32 UNUserNotificationCenter.current().delegate = self
33 return true
34 }
35
36 nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification) async -> UNNotificationPresentationOptions {
37 [.banner, .sound, .list]
38 }
39
40 nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {
41 let info = response.notification.request.content.userInfo
42 guard let path = info["path"] as? String, let offset = info["offset"] as? Int else { return }
43 await MainActor.run { model?.openRequest = .offset(path, offset) }
44 }
45}
46
47enum AppTab: Hashable { case agenda, folders, settings, search }
48
49extension View {
50 /// Readers pushed for `ReaderRoute`s.
51 func readerDestination(workspace: WorkspaceModel, session: DocumentSession) -> some View {
52 navigationDestination(for: ReaderRoute.self) { route in
53 ReaderScreen(route: route, workspace: workspace, session: session)
54 }
55 .navigationDestination(for: EditorRoute.self) { route in
56 EditorScreen(path: route.path, offset: route.offset, workspace: workspace, session: session)
57 }
58 }
59}
60
61/// An org-protocol capture, or a plain one.
62struct CaptureRequest: Identifiable {
63 let id = UUID()
64 var template: String?
65 var properties: [String: String] = [:]
66}
67
68struct RootView: View {
69 let model: MobileModel
70 let workspace: WorkspaceModel
71 let agenda: AgendaModel
72 @State private var capture: CaptureRequest?
73 @State private var tab = AppTab.agenda
74 @State private var agendaPath = NavigationPath()
75 @State private var hour = 0
76 @State private var showingClockReport = false
77 @State private var message: String?
78 @Environment(\.scenePhase) private var scenePhase
79
80 private var session: DocumentSession { model.session }
81
82 private struct ReminderKey: Equatable {
83 var files: Int
84 var changed: Int?
85 var edits: Int
86 var settings: Int
87 var active: Bool
88 var hour: Int
89 }
90
91 var body: some View {
92 TabView(selection: $tab) {
93 Tab("Agenda", systemImage: "calendar", value: .agenda) {
94 NavigationStack(path: $agendaPath) {
95 AgendaScreen(workspace: workspace, session: session, agenda: agenda, scheduler: model.scheduler)
96 .toolbar { captureButton }
97 .readerDestination(workspace: workspace, session: session)
98 }
99 }
100 Tab("Folders", systemImage: "folder", value: .folders) {
101 NavigationStack {
102 FoldersScreen(workspace: workspace)
103 .toolbar { captureButton }
104 .readerDestination(workspace: workspace, session: session)
105 }
106 }
107 Tab("Settings", systemImage: "gearshape", value: .settings) {
108 NavigationStack { SettingsScreen(model: model) }
109 }
110 Tab(value: .search, role: .search) {
111 NavigationStack {
112 SearchScreen(workspace: workspace, session: session)
113 .readerDestination(workspace: workspace, session: session)
114 }
115 }
116 }
117 .clockAccessory(model.clock.running, perform: clock)
118 .overlay(alignment: .top) {
119 if let message {
120 Text(message).font(.callout).padding(8).frame(maxWidth: .infinity).background(.bar)
121 .onTapGesture { self.message = nil }
122 .task(id: message) {
123 try? await Task.sleep(for: .seconds(4))
124 if self.message == message { self.message = nil }
125 }
126 }
127 }
128 .sheet(isPresented: $showingClockReport) { ClockReportScreen(workspace: workspace) }
129 .onChange(of: model.openRequest) {
130 guard let route = model.openRequest else { return }
131 model.openRequest = nil
132 tab = .agenda
133 agendaPath.append(route)
134 }
135 .onChange(of: workspace.changedFile?.version) {
136 // An open file takes in what changed on disk.
137 if let path = workspace.changedFile?.path { session.fileChanged(path) }
138 }
139 .sheet(item: $capture) { request in
140 CaptureScreen(workspace: workspace, session: session, request: request)
141 }
142 .task {
143 // Development: `ORGSTAR_ROOT` adds a folder at launch, as on the Mac.
144 if let root = ProcessInfo.processInfo.environment["ORGSTAR_ROOT"] { try? await workspace.addRoot(URL(fileURLWithPath: root)) }
145 workspace.startWatching()
146 await workspace.refresh()
147 }
148 .task {
149 while !Task.isCancelled {
150 try? await Task.sleep(for: .seconds(3600))
151 hour += 1
152 }
153 }
154 // Reminders follow the files, the settings, coming back to the app and the hour.
155 .task(id: ReminderKey(files: workspace.files.count, changed: workspace.changedFile?.version, edits: session.editVersion,
156 settings: model.settingsVersion, active: scenePhase == .active, hour: hour)) {
157 guard scenePhase == .active else { return }
158 try? await Task.sleep(for: .seconds(1))
159 guard !Task.isCancelled else { return }
160 await model.updateReminders()
161 }
162 .onChange(of: scenePhase) { _, phase in
163 // Unsaved edits are written before the app may be stopped.
164 if phase == .background {
165 for path in session.dirtyPaths { _ = session.save(path) }
166 }
167 // Files and settings synced while away; not every sync tool tells file presenters.
168 guard phase == .active else { return }
169 model.reloadConfig()
170 Task { await workspace.refresh() }
171 }
172 .onOpenURL { url in
173 if case .capture(let template, let properties)? = OrgProtocol.parse(url.absoluteString) {
174 capture = CaptureRequest(template: template, properties: properties)
175 }
176 }
177 }
178
179 private func clock(_ id: String) {
180 switch id {
181 case "app.clock.out": message = model.clock.clockOut(session)
182 case "app.clock.cancel": message = model.clock.clockOut(session, cancel: true)
183 case "app.clock.goto":
184 if let location = model.clock.location(session) { model.openRequest = .offset(location.path, location.offset) }
185 case "app.clock.report": showingClockReport = true
186 default: break
187 }
188 }
189
190 private var captureButton: some ToolbarContent {
191 ToolbarItem(placement: .primaryAction) {
192 Button("Capture", systemImage: "square.and.pencil") { capture = CaptureRequest() }
193 }
194 }
195}
196#else
197/// The iOS app has nothing to run elsewhere.
198@main
199enum OrgstarMobileUnavailable {
200 static func main() { print("Orgstar for iOS runs on iPhone and iPad.") }
201}
202#endif