Sources/Orgstar/ContentView.swift
383 lines · 16418 bytes
1import OrgApp
2import OrgCore
3import OrgEditorAppKit
4import OrgIndex
5import SwiftUI
6
7struct ContentView: View {
8 let workspace: WorkspaceModel
9 let session: DocumentSession
10 @Bindable var commands: AppCommands
11 let scheduler: ReminderScheduler?
12 @AppStorage("reminders") private var remindersEnabled = true
13 @AppStorage("reminderLead") private var reminderLead = 12
14 @AppStorage("agendaSubfolders") private var agendaSubfolders = false
15 @State private var reminderAgenda: AgendaModel?
16 @State private var trust = TrustStore()
17 @State private var hour = 0
18 @AppStorage("saveMode") private var saveMode = SaveMode.automatic
19 @AppStorage("keymap") private var preset = KeymapPreset.emacs
20 @AppStorage("optionAsMeta") private var optionAsMeta = OptionAsMeta.left.rawValue
21 @State private var keymap = KeymapPreset.emacs.keymap
22 @AppStorage("tagsColumn") private var tagsColumn = -77
23 @AppStorage("headingAfterSubtree") private var headingAfterSubtree = true
24 @AppStorage("splitLine") private var splitLine = false
25 @AppStorage("alphabeticalLists") private var alphabeticalLists = true
26 @AppStorage("fillColumn") private var fillColumn = 80
27 @AppStorage("hiddenMarkers") private var hiddenMarkers = true
28 @AppStorage("prettyEntities") private var prettyEntities = true
29
30 private var options: EditingOptions {
31 Preferences.options(
32 tagsColumn: tagsColumn, headingAfterSubtree: headingAfterSubtree, splitLine: splitLine, alphabeticalLists: alphabeticalLists,
33 fillColumn: fillColumn, hiddenMarkers: hiddenMarkers, prettyEntities: prettyEntities
34 )
35 }
36 @State private var selectedFile: String?
37 @State private var query = ""
38 @FocusState private var searchFocused: Bool
39 @Environment(\.openWindow) private var openWindow
40
41 var body: some View {
42 NavigationSplitView {
43 Sidebar(workspace: workspace, selection: $selectedFile)
44 .navigationSplitViewColumnWidth(min: 200, ideal: 260)
45 } content: {
46 Group {
47 if query.isEmpty {
48 OutlineColumn(session: session)
49 } else {
50 SearchResults(results: workspace.search(query, overlay: workspace.overlay(path: session.path, document: session.document))) { location in
51 guard location.path == session.path || UnsavedChanges.resolve(session) else { return }
52 selectedFile = location.path
53 session.show(location)
54 }
55 }
56 }
57 .navigationSplitViewColumnWidth(min: 160, ideal: 220, max: 360)
58 } detail: {
59 if session.path != nil {
60 EditorView(session: session, commands: commands, keymap: keymap, optionAsMeta: OptionAsMeta(rawValue: optionAsMeta), options: options, onAppCommand: perform, onExternal: runExternal)
61 .safeAreaInset(edge: .bottom, spacing: 0) { EchoArea(commands: commands) }
62 } else {
63 ContentUnavailableView(
64 workspace.roots.isEmpty ? "Add a folder of org files" : "Choose a file",
65 systemImage: "doc.text",
66 description: Text(workspace.roots.isEmpty ? "File ▸ Add Folder… (⇧⌘O)" : "Or press ⌘P to open one by name.")
67 )
68 }
69 }
70 .navigationTitle(session.path.map { ($0 as NSString).lastPathComponent } ?? "Orgstar")
71 .navigationSubtitle(session.isReadOnly ? "Read-only: not UTF-8" : "")
72 .searchable(text: $query, placement: .toolbar, prompt: "Search notes")
73 .searchFocused($searchFocused)
74 .toolbar {
75 if workspace.isIndexing { ProgressView().controlSize(.small) }
76 if session.conflict != nil {
77 Button("Conflict", systemImage: "exclamationmark.triangle") { commands.showingConflict = true }
78 .help("The file changed on disk, and the changes conflict with yours")
79 }
80 }
81 .onChange(of: selectedFile) { old, path in
82 guard let path, path != session.path else { return }
83 if UnsavedChanges.resolve(session) {
84 session.open(path)
85 } else {
86 selectedFile = old
87 }
88 }
89 .onChange(of: saveMode, initial: true) { _, mode in session.saveMode = mode }
90 .onChange(of: options, initial: true) { _, options in session.options = options }
91 .onChange(of: preset, initial: true) { loadKeymap() }
92 .sheet(isPresented: $commands.showingPalette) {
93 PaletteView(keymap: keymap) { id in
94 commands.showingPalette = false
95 // After the sheet closes, so app commands can present their own.
96 DispatchQueue.main.async { perform(id) }
97 }
98 }
99 .onChange(of: session.conflict) { _, conflict in
100 if conflict != nil { commands.showingConflict = true }
101 }
102 .alert("Conflicting changes", isPresented: $commands.showingConflict) {
103 Button("Keep Mine") { session.keepMine() }
104 Button("Use Disk Version") { session.useDiskVersion() }
105 Button("Decide Later", role: .cancel) {}
106 } message: {
107 Text((session.conflict ?? "") + " The version you don't keep is saved in the recovery folder.")
108 }
109 .onChange(of: workspace.changedFile?.version) {
110 if let path = workspace.changedFile?.path { session.fileChanged(path) }
111 }
112 .onChange(of: commands.jumpRequest?.id) {
113 guard let request = commands.jumpRequest else { return }
114 if request.path != session.path {
115 guard UnsavedChanges.resolve(session) else { return }
116 session.open(request.path)
117 selectedFile = request.path
118 }
119 session.reveal(request.offset)
120 }
121 .onChange(of: commands.focusSearch) { _, focus in
122 if focus {
123 searchFocused = true
124 commands.focusSearch = false
125 }
126 }
127 .fileImporter(isPresented: $commands.showingFolderPicker, allowedContentTypes: [.folder]) { result in
128 guard case .success(let url) = result else { return }
129 Task {
130 do { try await workspace.addRoot(url) } catch { workspace.lastError = error.localizedDescription }
131 }
132 }
133 .sheet(isPresented: $commands.showingQuickOpen) {
134 QuickOpenView(workspace: workspace) { entry in
135 selectedFile = entry.path
136 commands.showingQuickOpen = false
137 }
138 }
139 .alert("Orgstar", isPresented: errorShown) {
140 Button("OK") {
141 workspace.lastError = nil
142 session.lastError = nil
143 }
144 } message: {
145 Text(workspace.lastError ?? session.lastError ?? "")
146 }
147 .task(id: ReminderKey(
148 enabled: remindersEnabled, lead: reminderLead, subfolders: agendaSubfolders, files: workspace.files.count,
149 changed: workspace.changedFile?.version, edits: session.editVersion, hour: hour
150 )) {
151 await updateReminders()
152 }
153 .task {
154 while !Task.isCancelled {
155 try? await Task.sleep(for: .seconds(3600))
156 hour += 1
157 }
158 }
159 .task {
160 DevelopmentHooks.scheduleSnapshot()
161 if let path = DevelopmentHooks.fileToOpen { selectedFile = path }
162 if let root = DevelopmentHooks.rootToAdd { try? await workspace.addRoot(URL(fileURLWithPath: root)) }
163 if let id = DevelopmentHooks.windowToOpen { openWindow(id: id) }
164 await workspace.refresh()
165 workspace.startWatching()
166 }
167 }
168
169 /// Work a command hands to the platform: tables recalculated in Emacs.
170 private func runExternal(_ request: ExternalRequest) {
171 switch request {
172 case .emacsTable(let table, let point, let form, let reason, let lisp):
173 let run = {
174 commands.show("Recalculating in Emacs (\(reason))…")
175 Task { commands.show(await session.recalculateInEmacs(table: table, point: point, form: form)) }
176 }
177 guard lisp, let path = session.path, let text = session.document?.text else { return run() }
178 let content = (text as NSString).substring(with: NSRange(location: table.lowerBound, length: min((text as NSString).length, table.upperBound + 2000) - table.lowerBound))
179 if trust.isTrusted(path: path, content: content) { return run() }
180 commands.ask(Prompt(key: "confirm", message: "This table's formulas run Lisp. Run them? (yes, no, always)", choices: ["yes", "no", "always"])) { answer in
181 switch answer {
182 case "always":
183 trust.trust(path: path, content: content)
184 run()
185 case "yes": run()
186 default: commands.show("Not recalculated")
187 }
188 }
189 case .babel(let job):
190 let run = {
191 commands.show("Running \(job.language) block…")
192 Task { commands.show(await session.runBabel(job)) }
193 }
194 guard let path = session.path else { return }
195 if !job.alwaysAsk, trust.isTrusted(path: path, content: job.blockText) { return run() }
196 let choices = job.alwaysAsk ? ["yes", "no"] : ["yes", "no", "always"]
197 commands.ask(Prompt(key: "confirm", message: "Run this \(job.language) block? (\(choices.joined(separator: ", ")))", choices: choices)) { answer in
198 switch answer {
199 case "always":
200 trust.trust(path: path, content: job.blockText)
201 run()
202 case "yes": run()
203 default: commands.show("Not run")
204 }
205 }
206 }
207 }
208
209 private struct ReminderKey: Hashable {
210 var enabled: Bool
211 var lead: Int
212 var subfolders: Bool
213 var files: Int
214 var changed: Int?
215 var edits: Int
216 var hour: Int
217 }
218
219 /// Sets the notifications for the next week's timed entries, once edits pause.
220 private func updateReminders() async {
221 guard let scheduler else { return }
222 guard remindersEnabled else {
223 await scheduler.clear()
224 return
225 }
226 try? await Task.sleep(for: .seconds(2))
227 guard !Task.isCancelled, !workspace.files.isEmpty else { return }
228 let agenda = reminderAgenda ?? AgendaModel(workspace: workspace)
229 reminderAgenda = agenda
230 agenda.includeSubfolders = agendaSubfolders
231 let open = session.path.flatMap { path in session.document.map { (path, $0.text) } }
232 let reminders = await agenda.reminders(open: open, lead: reminderLead)
233 guard !Task.isCancelled else { return }
234 await scheduler.reconcile(reminders)
235 }
236
237 private func loadKeymap() {
238 let loaded = KeymapLoader.load(preset)
239 keymap = loaded.keymap
240 if let first = loaded.problems.first {
241 let more = loaded.problems.count > 1 ? " (and \(loaded.problems.count - 1) more)" : ""
242 commands.show("keymap.toml: \(first)\(more)")
243 }
244 }
245
246 /// Runs a command from a key, the palette or the Org menu.
247 private func perform(_ id: String) {
248 switch id {
249 case "app.save":
250 if !session.save(), session.conflict != nil { commands.showingConflict = true }
251 case "app.quick-open": commands.showingQuickOpen = true
252 case "app.palette": commands.showingPalette = true
253 case "app.search": commands.focusSearch = true
254 case "app.reload-keymap":
255 loadKeymap()
256 commands.show("Keymap reloaded")
257 case "app.refile":
258 let targets = workspace.refileTargets(openPath: session.path, document: session.document)
259 commands.ask(Prompt(key: "refile", message: "Refile to:", choices: targets.map(\.label))) { answer in
260 guard let answer, let target = targets.first(where: { $0.label == answer }) else { return }
261 if let message = session.refile(to: target) { commands.show(message) }
262 }
263 case "app.archive":
264 if let message = session.archive() { commands.show(message) }
265 case "app.agenda":
266 openWindow(id: "agenda")
267 default:
268 if let editor = commands.editor { editor.run(id) } else { commands.show("No file is open") }
269 }
270 }
271
272 private var errorShown: Binding<Bool> {
273 Binding(get: { workspace.lastError != nil || session.lastError != nil }, set: { _ in })
274 }
275}
276
277struct Sidebar: View {
278 let workspace: WorkspaceModel
279 @Binding var selection: String?
280
281 var body: some View {
282 List(selection: $selection) {
283 ForEach(workspace.rootPaths, id: \.self) { root in
284 Section((root as NSString).lastPathComponent) {
285 OutlineGroup(workspace.tree(forRoot: root).children ?? [], children: \.children) { node in
286 Label(node.name, systemImage: icon(node))
287 .foregroundStyle(node.file?.kind == .conflict ? .orange : .primary)
288 .tag(node.file?.path)
289 }
290 }
291 .contextMenu {
292 Button("Remove Folder") { try? workspace.removeRoot(path: root) }
293 }
294 }
295 }
296 .listStyle(.sidebar)
297 }
298
299 private func icon(_ node: FileTreeNode) -> String {
300 guard let file = node.file else { return "folder" }
301 switch file.kind {
302 case .org: return "doc.text"
303 case .archive: return "archivebox"
304 case .conflict: return "exclamationmark.triangle"
305 }
306 }
307}
308
309struct OutlineColumn: View {
310 let session: DocumentSession
311
312 var body: some View {
313 List(Array(session.outline.enumerated()), id: \.element.start) { _, entry in
314 Button {
315 session.reveal(entry.start)
316 } label: {
317 Text(entry.title.isEmpty ? "(untitled)" : entry.title)
318 .lineLimit(1)
319 .padding(.leading, CGFloat(entry.level - 1) * 12)
320 }
321 .buttonStyle(.plain)
322 }
323 .overlay {
324 if session.path != nil, session.outline.isEmpty {
325 ContentUnavailableView("No headings", systemImage: "list.bullet.indent")
326 }
327 }
328 }
329}
330
331struct SearchResults: View {
332 let results: [HeadingLocation]
333 let open: (HeadingLocation) -> Void
334
335 var body: some View {
336 List(results, id: \.self) { location in
337 Button {
338 open(location)
339 } label: {
340 VStack(alignment: .leading, spacing: 2) {
341 Text(location.title.isEmpty ? "(untitled)" : location.title).lineLimit(1)
342 Text((location.path as NSString).lastPathComponent).font(.caption).foregroundStyle(.secondary)
343 }
344 }
345 .buttonStyle(.plain)
346 }
347 .overlay {
348 if results.isEmpty { ContentUnavailableView.search }
349 }
350 }
351}
352
353struct QuickOpenView: View {
354 let workspace: WorkspaceModel
355 let open: (FileEntry) -> Void
356 @State private var query = ""
357 @Environment(\.dismiss) private var dismiss
358
359 var body: some View {
360 let matches = workspace.quickOpen(query)
361 VStack(spacing: 0) {
362 TextField("Open file", text: $query)
363 .textFieldStyle(.plain)
364 .font(.title3)
365 .padding(12)
366 .onSubmit { if let first = matches.first { open(first) } }
367 Divider()
368 List(matches) { entry in
369 Button {
370 open(entry)
371 } label: {
372 VStack(alignment: .leading, spacing: 2) {
373 Text(entry.name)
374 Text(entry.relativePath).font(.caption).foregroundStyle(.secondary)
375 }
376 }
377 .buttonStyle(.plain)
378 }
379 }
380 .frame(width: 520, height: 360)
381 .onExitCommand { dismiss() }
382 }
383}