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