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