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