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