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