Sources/Orgstar/ContentView.swift
854 lines · 40097 bytes
1import AppKit
2import OrgApp
3import OrgCore
4import OrgEditorAppKit
5import OrgPresentation
6import OrgWorkspace
7import OrgIndex
8import SwiftUI
9import UniformTypeIdentifiers
10
11struct ContentView: View {
12 let workspace: WorkspaceModel
13 let session: DocumentSession
14 @Bindable var commands: AppCommands
15 let scheduler: ReminderScheduler?
16 let clock: ClockModel
17 @AppStorage("reminders") private var remindersEnabled = true
18 @AppStorage("reminderLead") private var reminderLead = 12
19 @AppStorage("agendaSubfolders") private var agendaSubfolders = false
20 @State private var reminderAgenda: AgendaModel?
21 @State private var trust = TrustStore()
22 @State private var hotKey: GlobalHotKey?
23 @State private var statusItem: ClockStatusItem?
24 @AppStorage("globalCapture") private var globalCapture = true
25 @State private var hour = 0
26 @AppStorage("saveMode") private var saveMode = SaveMode.automatic
27 @AppStorage("keymap") private var preset = KeymapPreset.emacs
28 @AppStorage("optionAsMeta") private var optionAsMeta = OptionAsMeta.left.rawValue
29 @State private var keymap = KeymapPreset.emacs.keymap
30 @AppStorage("tagsColumn") private var tagsColumn = -77
31 @AppStorage("headingAfterSubtree") private var headingAfterSubtree = true
32 @AppStorage("splitLine") private var splitLine = false
33 @AppStorage("alphabeticalLists") private var alphabeticalLists = true
34 @AppStorage("fillColumn") private var fillColumn = 80
35 @AppStorage("hiddenMarkers") private var hiddenMarkers = true
36 @AppStorage("prettyEntities") private var prettyEntities = true
37 @AppStorage("logDone") private var logDone = "nil"
38 @AppStorage("logIntoDrawer") private var logIntoDrawer = ""
39 @AppStorage("logReschedule") private var logReschedule = "nil"
40 @AppStorage("logRedeadline") private var logRedeadline = "nil"
41 @AppStorage("useSpeedCommands") private var useSpeedCommands = false
42 @AppStorage("hideDrawerStartup") private var hideDrawerStartup = true
43 @AppStorage("hideBlockStartup") private var hideBlockStartup = false
44
45 private var options: EditingOptions {
46 Preferences.options(
47 tagsColumn: tagsColumn, headingAfterSubtree: headingAfterSubtree, splitLine: splitLine, alphabeticalLists: alphabeticalLists,
48 fillColumn: fillColumn, hiddenMarkers: hiddenMarkers, prettyEntities: prettyEntities, logDone: logDone, logIntoDrawer: logIntoDrawer,
49 hideDrawerStartup: hideDrawerStartup, hideBlockStartup: hideBlockStartup, logReschedule: logReschedule, logRedeadline: logRedeadline,
50 useSpeedCommands: useSpeedCommands
51 )
52 }
53 /// A block being edited apart (`org-edit-special`).
54 @State private var blockEdit: BlockEditRequest?
55
56 @State private var selectedFile: String?
57 /// A file that isn't text, shown as a preview instead of the open document.
58 @State private var previewPath: String?
59 @AppStorage("outlineShown") private var orgOutlineShown = true
60 @AppStorage("outlineWidth") private var outlineWidth = 220.0
61 @AppStorage("showMarkup") private var showMarkup = false
62 @AppStorage("showLineNumbers") private var showLineNumbers = true
63 @AppStorage("showHiddenFiles") private var showHiddenFiles = true
64 @AppStorage("ignoredFolders") private var ignoredFolders = ScanRules.defaultIgnoredFolders.sorted().joined(separator: " ")
65 @AppStorage("themeFont") private var themeFont = ""
66 @AppStorage("themeFontSize") private var themeFontSize = 13
67 @AppStorage("themeLineSpacing") private var themeLineSpacing = 2
68 @AppStorage("themeHeadingStep") private var themeHeadingStep = 1
69
70 /// The theme's colors from config.toml with the type settings.
71 private var theme: ThemeSpec {
72 var spec = ConfigSync.shared.theme
73 spec.font = themeFont
74 spec.fontSize = themeFontSize
75 spec.lineSpacing = themeLineSpacing
76 spec.headingSizeStep = themeHeadingStep
77 return spec
78 }
79 /// The outline for a file that isn't org, off until asked for.
80 @State private var plainOutlineShown = false
81 @State private var showingImport = false
82 @AppStorage("showTabBar") private var showTabBar = false
83 /// Carets of restored buffers, shown when each first shows.
84 @State private var pendingCarets: [String: Int] = [:]
85 @State private var query = ""
86 @FocusState private var searchFocused: Bool
87 @Environment(\.openWindow) private var openWindow
88 @Environment(\.openSettings) private var openSettings
89
90 /// Whether the outline pane shows: remembered for org files, hidden by default for
91 /// other files, and always shown while search results are up.
92 private var outlineShown: Bool {
93 !query.isEmpty || (previewPath == nil && (session.isOrg ? orgOutlineShown : plainOutlineShown))
94 }
95
96 private func toggleOutline() {
97 if session.isOrg { orgOutlineShown.toggle() } else { plainOutlineShown.toggle() }
98 }
99
100 @ViewBuilder
101 private var detail: some View {
102 if let previewPath {
103 FilePreview(path: previewPath)
104 } else if session.path != nil {
105 VStack(spacing: 0) {
106 if showTabBar { BufferTabs(session: session) }
107 EditorView(session: session, commands: commands, keymap: keymap, modal: preset.isModal, optionAsMeta: OptionAsMeta(rawValue: optionAsMeta), options: options, showMarkup: showMarkup, showLineNumbers: showLineNumbers, theme: theme, onAppCommand: perform, onExternal: runExternal, knownTags: { [index = workspace.index] in (try? index.tags()) ?? [] })
108 }
109 .safeAreaInset(edge: .bottom, spacing: 0) {
110 VStack(spacing: 0) {
111 ModeLine(session: session, commands: commands, clock: clock, perform: perform)
112 EchoArea(commands: commands)
113 }
114 }
115 } else {
116 ContentUnavailableView(
117 workspace.roots.isEmpty ? "Add a folder of org files" : "Choose a file",
118 systemImage: "doc.text",
119 description: Text(workspace.roots.isEmpty ? "File ▸ Add Folder… (⇧⌘O)" : "Or press ⌘P to open one by name.")
120 )
121 }
122 }
123
124 @ToolbarContentBuilder
125 private var toolbarItems: some ToolbarContent {
126 ToolbarItem(placement: .navigation) {
127 Button(outlineShown ? "Hide Outline" : "Show Outline", systemImage: "list.bullet.indent") { toggleOutline() }
128 .help(outlineShown ? "Hide the outline (⌥⌘O)" : "Show the outline (⌥⌘O)")
129 .disabled(!query.isEmpty || previewPath != nil || session.path == nil)
130 }
131 if workspace.isIndexing {
132 ToolbarItem { ProgressView().controlSize(.small) }
133 }
134 if let running = clock.running {
135 ToolbarItem {
136 Menu {
137 Button("Clock Out") { perform("app.clock.out") }
138 Button("Cancel Clock") { perform("app.clock.cancel") }
139 Button("Go to Clocked Entry") { perform("app.clock.goto") }
140 } label: {
141 TimelineView(.periodic(from: .now, by: 30)) { context in
142 Text("⏱ \(running.heading) \(clockElapsed(running, now: context.date))").lineLimit(1)
143 }
144 }
145 .help("Clocked in since \(running.startedAt.formatted(date: .omitted, time: .shortened))")
146 }
147 }
148 if session.conflict != nil {
149 ToolbarItem {
150 Button("Conflict", systemImage: "exclamationmark.triangle") { commands.showingConflict = true }
151 .help("The file changed on disk, and the changes conflict with yours")
152 }
153 }
154 }
155
156 private var main: some View {
157 NavigationSplitView {
158 Sidebar(workspace: workspace, session: session, selection: $selectedFile) { commands.showingFolderPicker = true }
159 .navigationSplitViewColumnWidth(min: 200, ideal: 260)
160 } detail: {
161 HStack(spacing: 0) {
162 if outlineShown {
163 Group {
164 if query.isEmpty {
165 OutlineColumn(session: session)
166 } else {
167 SearchResults(results: workspace.search(query, overlay: workspace.overlay(session.openDocuments))) { location in
168 selectedFile = location.path
169 session.show(location)
170 }
171 }
172 }
173 .frame(width: CGFloat(outlineWidth))
174 PaneDivider(width: $outlineWidth, range: 160...400)
175 }
176 detail
177 .frame(maxWidth: .infinity)
178 }
179 }
180 .navigationTitle((previewPath ?? session.path).map { ($0 as NSString).lastPathComponent } ?? "Orgstar")
181 .navigationSubtitle(session.isReadOnly ? "Read-only: not UTF-8" : "")
182 .searchable(text: $query, placement: .toolbar, prompt: "Search notes")
183 .searchFocused($searchFocused)
184 .toolbar { toolbarItems }
185 .onChange(of: session.path) { plainOutlineShown = false }
186 .onChange(of: ScanRules(hiddenFiles: showHiddenFiles, ignoredFolders: Set(ignoredFolders.split(separator: " ").map(String.init))), initial: true) { _, rules in
187 workspace.scanRules = rules
188 }
189 .onChange(of: selectedFile) { old, path in
190 guard let path else { return }
191 if !DocumentSession.isOrgPath(path), !FileTypes.isText(path) {
192 previewPath = path
193 return
194 }
195 previewPath = nil
196 guard path != session.path else { return }
197 session.open(path)
198 }
199 .onChange(of: session.path) {
200 // Buffers switched by keys show in the sidebar too; a restored caret shows once.
201 if let path = session.path, selectedFile != path { selectedFile = path }
202 if let path = session.path, let caret = pendingCarets.removeValue(forKey: path) { session.reveal(caret) }
203 BufferRestore.save(session)
204 }
205 .onChange(of: session.openPaths) { BufferRestore.save(session) }
206 .onChange(of: saveMode, initial: true) { _, mode in session.saveMode = mode }
207 .onChange(of: options, initial: true) { _, options in session.options = options }
208 .onChange(of: preset, initial: true) { loadKeymap() }
209 .sheet(isPresented: $showingImport) { EmacsImportView(workspace: workspace) }
210 .sheet(item: $blockEdit) { request in
211 BlockEditorView(edit: request.edit) { content in
212 blockEdit = nil
213 guard let content else { return }
214 commands.editor?.perform(ReplaceBlockLines(edit: request.edit, content: content))
215 }
216 }
217 .sheet(isPresented: $commands.showingPalette) {
218 PaletteView(commands: commands) { id in
219 commands.showingPalette = false
220 // After the sheet closes, so app commands can present their own.
221 DispatchQueue.main.async { perform(id) }
222 }
223 }
224 .onChange(of: session.conflict) { _, conflict in
225 if conflict != nil { commands.showingConflict = true }
226 }
227 .alert("Conflicting changes", isPresented: $commands.showingConflict) {
228 Button("Keep Mine") { session.keepMine() }
229 Button("Use Disk Version") { session.useDiskVersion() }
230 Button("Decide Later", role: .cancel) {}
231 } message: {
232 Text((session.conflict ?? "") + " The version you don't keep is saved in the recovery folder.")
233 }
234 .onChange(of: workspace.changedFile?.version) {
235 if let path = workspace.changedFile?.path { session.fileChanged(path) }
236 }
237 }
238
239 var body: some View {
240 main
241 .onChange(of: clock.running, initial: true) { _, running in
242 if statusItem == nil { statusItem = ClockStatusItem { commands.run($0) } }
243 statusItem?.update(running)
244 }
245 .onChange(of: globalCapture, initial: true) { _, enabled in
246 hotKey?.unregister()
247 hotKey = enabled ? GlobalHotKey { perform("app.capture") } : nil
248 }
249 .onChange(of: commands.runRequest?.serial) {
250 if let id = commands.runRequest?.id { perform(id) }
251 }
252 .onChange(of: ConfigSync.shared.problems, initial: true) { _, problems in
253 if let first = problems.first {
254 commands.show(first + (problems.count > 1 ? " (and \(problems.count - 1) more)" : ""))
255 }
256 }
257 .onChange(of: ConfigSync.shared.changedFile?.serial) {
258 if ConfigSync.shared.changedFile?.name == "keymap.toml" { loadKeymap() }
259 }
260 .onChange(of: commands.jumpRequest?.id) {
261 guard let request = commands.jumpRequest else { return }
262 if request.path != session.path {
263 session.open(request.path)
264 selectedFile = request.path
265 }
266 session.reveal(request.offset)
267 }
268 .onChange(of: commands.focusSearch) { _, focus in
269 if focus {
270 searchFocused = true
271 commands.focusSearch = false
272 }
273 }
274 .fileImporter(isPresented: $commands.showingFolderPicker, allowedContentTypes: [.folder]) { result in
275 guard case .success(let url) = result else { return }
276 Task {
277 do { try await workspace.addRoot(url) } catch { workspace.lastError = error.localizedDescription }
278 }
279 }
280 .sheet(isPresented: $commands.showingQuickOpen) {
281 QuickOpenView(workspace: workspace) { entry in
282 selectedFile = entry.path
283 commands.showingQuickOpen = false
284 }
285 }
286 .alert("Orgstar", isPresented: errorShown) {
287 Button("OK") {
288 workspace.lastError = nil
289 session.lastError = nil
290 }
291 } message: {
292 Text(workspace.lastError ?? session.lastError ?? "")
293 }
294 .task(id: ReminderKey(
295 enabled: remindersEnabled, lead: reminderLead, subfolders: agendaSubfolders, files: workspace.files.count,
296 changed: workspace.changedFile?.version, edits: session.editVersion, hour: hour
297 )) {
298 await updateReminders()
299 }
300 .task {
301 while !Task.isCancelled {
302 try? await Task.sleep(for: .seconds(3600))
303 hour += 1
304 }
305 }
306 .task {
307 DevelopmentHooks.scheduleSnapshot()
308 pendingCarets = BufferRestore.restore(session)
309 if let path = session.path, let caret = pendingCarets.removeValue(forKey: path) { session.reveal(caret) }
310 // Files handed over at launch open after the restored buffers, and show.
311 for path in AppDelegate.pendingOpens { session.open(path) }
312 AppDelegate.pendingOpens = []
313 if let path = DevelopmentHooks.fileToOpen { selectedFile = path }
314 if let root = DevelopmentHooks.rootToAdd { try? await workspace.addRoot(URL(fileURLWithPath: root)) }
315 if let commandList = DevelopmentHooks.commandToRun {
316 // The file opened above needs its editor first.
317 for _ in 0..<20 where DevelopmentHooks.fileToOpen != nil && commands.editor == nil { try? await Task.sleep(for: .milliseconds(100)) }
318 for command in commandList.split(separator: ",") { perform(String(command)) }
319 for answer in DevelopmentHooks.answers {
320 for _ in 0..<20 where commands.prompt == nil { try? await Task.sleep(for: .milliseconds(100)) }
321 commands.answer(answer)
322 }
323 }
324 if let id = DevelopmentHooks.windowToOpen {
325 if id == "settings" { openSettings() } else { openWindow(id: id) }
326 }
327 await workspace.refresh()
328 workspace.startWatching()
329 }
330 }
331
332 /// Writes the export beside the file, as Emacs's export dispatcher does.
333 private func export(_ format: String) {
334 guard let path = session.path, let text = session.document?.text else {
335 commands.show("No file is open")
336 return
337 }
338 let url = URL(fileURLWithPath: path)
339 let base = url.deletingPathExtension()
340 let defaults = Preferences.orgSettings
341 switch format {
342 case "html", "html-open", "markdown":
343 let target = base.appendingPathExtension(format == "markdown" ? "md" : "html")
344 let content = format == "markdown"
345 ? MarkdownExport.document(text, settings: defaults)
346 : HTMLExport.page(text, fallbackTitle: base.lastPathComponent, settings: defaults)
347 do {
348 try content.write(to: target, atomically: true, encoding: .utf8)
349 commands.show("Exported to \(target.lastPathComponent)")
350 if format == "html-open" { NSWorkspace.shared.open(target) }
351 } catch {
352 commands.show("Can't write \(target.lastPathComponent): \(error.localizedDescription)")
353 }
354 default:
355 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"]
356 guard let function = functions[format] else { return }
357 commands.show("Exporting with Emacs…")
358 Task {
359 do {
360 let written = try await EmacsRunner.export(text: text, path: path, function: function)
361 commands.show("Exported to \((written as NSString).lastPathComponent)")
362 } catch {
363 commands.show("\(error)")
364 }
365 }
366 }
367 }
368
369 /// Work a command hands to the platform: tables recalculated in Emacs.
370 private func runExternal(_ request: ExternalRequest) {
371 switch request {
372 case .openLink(let link):
373 if let message = LinkOpener.open(link, session: session, workspace: workspace) { commands.show(message) }
374 case .editBlock(let edit):
375 blockEdit = BlockEditRequest(edit: edit)
376 case .emacsTable(let table, let point, let form, let reason, let lisp):
377 let run = {
378 commands.show("Recalculating in Emacs (\(reason))…")
379 Task { commands.show(await session.recalculateInEmacs(table: table, point: point, form: form)) }
380 }
381 guard lisp, let path = session.path, let text = session.document?.text else { return run() }
382 let content = (text as NSString).substring(with: NSRange(location: table.lowerBound, length: min((text as NSString).length, table.upperBound + 2000) - table.lowerBound))
383 if trust.isTrusted(path: path, content: content) { return run() }
384 commands.ask(Prompt(key: "confirm", message: "This table's formulas run Lisp. Run them? (yes, no, always)", choices: ["yes", "no", "always"])) { answer in
385 switch answer {
386 case "always":
387 trust.trust(path: path, content: content)
388 run()
389 case "yes": run()
390 default: commands.show("Not recalculated")
391 }
392 }
393 case .babel(let job):
394 let run = {
395 commands.show("Running \(job.language) block… (⌘. to cancel)")
396 session.startBabel(job) { commands.show($0) }
397 }
398 guard let path = session.path else { return }
399 if !job.alwaysAsk, trust.isTrusted(path: path, content: job.blockText) { return run() }
400 let choices = job.alwaysAsk ? ["yes", "no"] : ["yes", "no", "always"]
401 commands.ask(Prompt(key: "confirm", message: "Run this \(job.language) block? (\(choices.joined(separator: ", ")))", choices: choices)) { answer in
402 switch answer {
403 case "always":
404 trust.trust(path: path, content: job.blockText)
405 run()
406 case "yes": run()
407 default: commands.show("Not run")
408 }
409 }
410 }
411 }
412
413 private struct ReminderKey: Hashable {
414 var enabled: Bool
415 var lead: Int
416 var subfolders: Bool
417 var files: Int
418 var changed: Int?
419 var edits: Int
420 var hour: Int
421 }
422
423 /// Sets the notifications for the next week's timed entries, once edits pause.
424 private func updateReminders() async {
425 guard let scheduler else { return }
426 guard remindersEnabled else {
427 await scheduler.clear()
428 return
429 }
430 try? await Task.sleep(for: .seconds(2))
431 guard !Task.isCancelled, !workspace.files.isEmpty else { return }
432 let agenda = reminderAgenda ?? AgendaModel(workspace: workspace)
433 reminderAgenda = agenda
434 agenda.includeSubfolders = agendaSubfolders
435 let open = session.openTexts
436 let reminders = await agenda.reminders(open: open, lead: reminderLead)
437 guard !Task.isCancelled else { return }
438 await scheduler.reconcile(reminders)
439 }
440
441 private func loadKeymap() {
442 let loaded = KeymapLoader.load(preset)
443 keymap = loaded.keymap
444 commands.keymap = loaded.keymap
445 commands.modal = preset.isModal
446 if let first = loaded.problems.first {
447 let more = loaded.problems.count > 1 ? " (and \(loaded.problems.count - 1) more)" : ""
448 commands.show("keymap.toml: \(first)\(more)")
449 }
450 }
451
452 /// `SPC b b`: open buffers, most recent first, by name (with the folder when names repeat).
453 private func switchBuffer() {
454 let paths = session.recentPaths.dropFirst() + session.recentPaths.prefix(1)
455 let names = paths.map { ($0 as NSString).lastPathComponent }
456 let labels = paths.map { path in
457 let name = (path as NSString).lastPathComponent
458 guard names.filter({ $0 == name }).count > 1 else { return name }
459 return name + " — " + ((path as NSString).deletingLastPathComponent as NSString).lastPathComponent
460 }
461 guard !labels.isEmpty else { return commands.show("No buffers are open") }
462 commands.ask(Prompt(key: "buffer", message: "Switch to buffer:", choices: labels)) { answer in
463 guard let answer, let index = labels.firstIndex(of: answer) else { return }
464 session.open(Array(paths)[index])
465 }
466 }
467
468 /// Runs a command from a key, the palette or the Org menu.
469 private func perform(_ id: String) {
470 let orgOnly = ["app.refile", "app.archive", "app.clock.in"].contains(id) || id.hasPrefix("app.export.") || id.hasPrefix("org.")
471 if orgOnly, !session.isOrg {
472 commands.show("Not an org file")
473 return
474 }
475 switch id {
476 case "app.save":
477 if !session.save(), session.conflict != nil { commands.showingConflict = true }
478 case "app.quit": NSApp.terminate(nil)
479 case "app.save-all":
480 if !session.saveAll(), session.conflict != nil { commands.showingConflict = true }
481 case "app.buffer.switch": switchBuffer()
482 case "app.buffer.next": session.cycle(1)
483 case "app.buffer.previous": session.cycle(-1)
484 case "app.buffer.last": session.showPrevious()
485 case "app.buffer.kill":
486 guard let path = session.path else {
487 NSApp.keyWindow?.performClose(nil)
488 return
489 }
490 if UnsavedChanges.resolve(session) { session.kill(path) }
491 case "app.buffer.kill-others":
492 let others = session.openPaths.filter { $0 != session.path }
493 if UnsavedChanges.resolve(session, paths: others) { others.forEach(session.kill) }
494 case "app.buffer.kill-all":
495 let all = session.openPaths
496 if UnsavedChanges.resolve(session, paths: all) { all.forEach(session.kill) }
497 case "app.toggle-tab-bar": showTabBar.toggle()
498 case "app.babel.cancel":
499 if session.isRunningBabel { session.cancelBabel() } else { commands.show("No block is running") }
500 case "app.toggle-outline": toggleOutline()
501 case "app.toggle-markup": showMarkup.toggle()
502 case "app.toggle-line-numbers": showLineNumbers.toggle()
503 case "app.import-emacs": showingImport = true
504 case "app.edit-config": commands.jump(path: UserConfig.configFile.path, offset: 0)
505 case "app.quick-open": commands.showingQuickOpen = true
506 case "app.palette": commands.showingPalette = true
507 case "app.search": commands.focusSearch = true
508 case "app.reload-keymap":
509 loadKeymap()
510 commands.show("Keymap reloaded")
511 case "app.refile":
512 let targets = workspace.refileTargets(openPath: session.path, document: session.document)
513 commands.ask(Prompt(key: "refile", message: "Refile to:", choices: targets.map(\.label))) { answer in
514 guard let answer, let target = targets.first(where: { $0.label == answer }) else { return }
515 if let message = session.refile(to: target) { commands.show(message) }
516 }
517 case "app.archive":
518 if let message = session.archive() { commands.show(message) }
519 case "app.table-import":
520 // `org-table-import`: a TSV, CSV or space-separated file becomes a table at point.
521 guard let editor = commands.editor else { return commands.show("No file is open") }
522 let panel = NSOpenPanel()
523 panel.allowedContentTypes = [.commaSeparatedText, .tabSeparatedText, .plainText]
524 guard panel.runModal() == .OK, let url = panel.url else { return }
525 guard let contents = try? String(contentsOf: url, encoding: .utf8) else { return commands.show("Can't read \(url.lastPathComponent)") }
526 editor.perform(ImportTable(contents: contents))
527 case "app.table-export":
528 // `org-table-export`: CSV for a .csv name, else TSV.
529 guard let editor = commands.editor else { return commands.show("No file is open") }
530 let context = editor.context()
531 guard ImportTable.exportText(context.text, at: context.caret, path: "") != nil else { return commands.show("No table at point") }
532 let panel = NSSavePanel()
533 panel.nameFieldStringValue = "table.csv"
534 guard panel.runModal() == .OK, let url = panel.url,
535 let text = ImportTable.exportText(context.text, at: context.caret, path: url.path) else { return }
536 do {
537 try text.write(to: url, atomically: true, encoding: .utf8)
538 commands.show("Export done.")
539 } catch {
540 commands.show("File not written: \(error.localizedDescription)")
541 }
542 case "org.subtree.paste":
543 guard let text = NSPasteboard.general.string(forType: .string) else { return commands.show("The clipboard is empty") }
544 commands.editor?.perform(PasteSubtree(text: text))
545 case "org.link.insert":
546 commands.editor?.perform(InsertLink(stored: commands.storedLinks, file: session.path))
547 case "org.link.store":
548 guard let editor = commands.editor, let path = session.path else { return commands.show("No method for storing a link from this buffer") }
549 commands.storeLink(Links.store(in: editor.context(), path: Links.abbreviate(path, home: NSHomeDirectory())))
550 case "org.id.store-link":
551 guard let editor = commands.editor, let path = session.path else { return }
552 if case .commit = editor.perform(CreateID()),
553 let link = Links.storeID(in: editor.context(), fileName: (path as NSString).lastPathComponent) {
554 commands.storeLink(link)
555 }
556 case "app.agenda":
557 openWindow(id: "agenda")
558 case "app.clock.in":
559 commands.show(clock.clockIn(session))
560 case "app.clock.out":
561 commands.show(clock.clockOut(session))
562 case "app.clock.cancel":
563 commands.show(clock.clockOut(session, cancel: true))
564 case "app.clock.goto":
565 if let location = clock.location(session) { commands.jump(path: location.path, offset: location.offset) } else { commands.show("No active clock") }
566 case "app.clock.report":
567 openWindow(id: "clock-report")
568 case "app.board":
569 openWindow(id: "board")
570 case "app.capture":
571 NSApp.activate()
572 openWindow(id: "capture")
573 case let id where id.hasPrefix("app.export."):
574 export(String(id.dropFirst("app.export.".count)))
575 default:
576 if let editor = commands.editor { editor.run(id) } else { commands.show("No file is open") }
577 }
578 }
579
580 private var errorShown: Binding<Bool> {
581 Binding(get: { workspace.lastError != nil || session.lastError != nil }, set: { _ in })
582 }
583}
584
585struct Sidebar: View {
586 let workspace: WorkspaceModel
587 let session: DocumentSession
588 @Binding var selection: String?
589 var addFolder: () -> Void = {}
590 /// Folders shown collapsed, by path, one per line.
591 @AppStorage("collapsedFolders") private var collapsedText = ""
592 @State private var removing: String?
593 /// A file operation waiting for a name or a confirmation.
594 @Environment(\.orgTheme) private var theme
595 @State var pending: FileOperation?
596 @State var name = ""
597 @State var failure: String?
598
599 private var collapsed: Set<String> { Set(collapsedText.split(separator: "\n").map(String.init)) }
600
601 private func expanded(_ root: String) -> Binding<Bool> {
602 Binding {
603 !collapsed.contains(root)
604 } set: { isExpanded in
605 var set = collapsed
606 if isExpanded { set.remove(root) } else { set.insert(root) }
607 collapsedText = set.sorted().joined(separator: "\n")
608 }
609 }
610
611 var body: some View {
612 List(selection: $selection) {
613 ForEach(workspace.rootPaths, id: \.self) { root in
614 Section(isExpanded: expanded(root)) {
615 OutlineGroup(workspace.tree(forRoot: root).children ?? [], children: \.children) { node in
616 Label(node.name, systemImage: icon(node))
617 .foregroundStyle(node.file?.kind == .conflict ? .orange : theme.color("sidebar-foreground") ?? .primary)
618 .tag(node.file?.path)
619 .contextMenu { fileMenu(node) }
620 }
621 } header: {
622 Text((root as NSString).lastPathComponent)
623 .foregroundStyle(theme.color("sidebar-header") ?? .secondary)
624 .help(root)
625 .contextMenu { folderMenu(root) }
626 }
627 }
628 }
629 .listStyle(.sidebar)
630 .themedListBackground(theme.color("sidebar-background"))
631 .safeAreaInset(edge: .bottom, spacing: 0) {
632 HStack(spacing: 4) {
633 Button("Add Folder…", systemImage: "plus", action: addFolder)
634 .help("Add a folder (⇧⌘O)")
635 Menu {
636 ForEach(workspace.rootPaths, id: \.self) { root in
637 Button((root as NSString).lastPathComponent) { removing = root }
638 }
639 } label: {
640 Label("Remove Folder", systemImage: "minus")
641 }
642 .menuIndicator(.hidden)
643 .fixedSize()
644 .disabled(workspace.rootPaths.isEmpty)
645 .help("Remove a folder from the sidebar")
646 Spacer()
647 }
648 .labelStyle(.iconOnly)
649 .buttonStyle(.borderless)
650 .menuStyle(.borderlessButton)
651 .padding(.horizontal, 10)
652 .padding(.vertical, 6)
653 }
654 .confirmationDialog(
655 "Remove “\(removing.map { ($0 as NSString).lastPathComponent } ?? "")” from the sidebar?",
656 isPresented: Binding { removing != nil } set: { if !$0 { removing = nil } }
657 ) {
658 Button("Remove") {
659 if let root = removing { try? workspace.removeRoot(path: root) }
660 removing = nil
661 }
662 } message: {
663 Text("The folder and its files stay on disk.")
664 }
665 .fileOperations(self)
666 }
667
668 @ViewBuilder
669 private func folderMenu(_ root: String) -> some View {
670 Button("New File…") { ask(.create(folder: root)) }
671 Divider()
672 Button(collapsed.contains(root) ? "Expand" : "Collapse") { expanded(root).wrappedValue.toggle() }
673 Button("Show in Finder") { NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: root)]) }
674 Divider()
675 Button("Remove from Sidebar…") { removing = root }
676 }
677
678 private func icon(_ node: FileTreeNode) -> String {
679 guard let file = node.file else { return "folder" }
680 switch file.kind {
681 case .org: return "doc.text"
682 case .archive: return "archivebox"
683 case .conflict: return "exclamationmark.triangle"
684 case .other:
685 guard let type = UTType(filenameExtension: (file.path as NSString).pathExtension) else { return "doc" }
686 if type.conforms(to: .image) { return "photo" }
687 if type.conforms(to: .pdf) { return "doc.richtext" }
688 if type.conforms(to: .audiovisualContent) { return "play.rectangle" }
689 if type.conforms(to: .sourceCode) || type.conforms(to: .script) { return "chevron.left.forwardslash.chevron.right" }
690 if type.conforms(to: .text) { return "doc.plaintext" }
691 return "doc"
692 }
693 }
694}
695
696struct OutlineColumn: View {
697 let session: DocumentSession
698 @Environment(\.orgTheme) private var theme
699
700 var body: some View {
701 List(Array(session.outline.enumerated()), id: \.element.start) { _, entry in
702 Button {
703 session.reveal(entry.start)
704 } label: {
705 Text(entry.title.isEmpty ? "(untitled)" : entry.title)
706 .foregroundStyle(theme.color("sidebar-foreground") ?? .primary)
707 .lineLimit(1)
708 .padding(.leading, CGFloat(entry.level - 1) * 12)
709 }
710 .buttonStyle(.plain)
711 }
712 .themedListBackground(theme.color("sidebar-background"))
713 .overlay {
714 if session.path != nil, !session.isOrg {
715 ContentUnavailableView("No outline", systemImage: "doc.plaintext", description: Text("Only org files have an outline."))
716 } else if session.path != nil, session.outline.isEmpty {
717 ContentUnavailableView("No headings", systemImage: "list.bullet.indent")
718 }
719 }
720 }
721}
722
723struct SearchResults: View {
724 let results: [HeadingLocation]
725 let open: (HeadingLocation) -> Void
726
727 var body: some View {
728 List(results, id: \.self) { location in
729 Button {
730 open(location)
731 } label: {
732 VStack(alignment: .leading, spacing: 2) {
733 Text(location.title.isEmpty ? "(untitled)" : location.title).lineLimit(1)
734 Text((location.path as NSString).lastPathComponent).font(.caption).foregroundStyle(.secondary)
735 }
736 }
737 .buttonStyle(.plain)
738 }
739 .overlay {
740 if results.isEmpty { ContentUnavailableView.search }
741 }
742 }
743}
744
745struct QuickOpenView: View {
746 let workspace: WorkspaceModel
747 let open: (FileEntry) -> Void
748 @State private var query = ""
749 @Environment(\.dismiss) private var dismiss
750
751 var body: some View {
752 let matches = workspace.quickOpen(query)
753 VStack(spacing: 0) {
754 TextField("Open file", text: $query)
755 .textFieldStyle(.plain)
756 .font(.title3)
757 .padding(12)
758 .onSubmit { if let first = matches.first { open(first) } }
759 Divider()
760 List(matches) { entry in
761 Button {
762 open(entry)
763 } label: {
764 VStack(alignment: .leading, spacing: 2) {
765 Text(entry.name)
766 Text(entry.relativePath).font(.caption).foregroundStyle(.secondary)
767 }
768 }
769 .buttonStyle(.plain)
770 }
771 }
772 .frame(width: 520, height: 360)
773 .onExitCommand { dismiss() }
774 }
775}
776
777/// A divider that resizes the pane before it by dragging. An `HSplitView` inside the window's
778/// split view loops on its size constraints in short windows, so this sets a width instead.
779struct PaneDivider: View {
780 @Binding var width: Double
781 let range: ClosedRange<Double>
782 @State private var start: Double?
783
784 var body: some View {
785 Rectangle()
786 .fill(Color(nsColor: .separatorColor))
787 .frame(width: 1)
788 .frame(maxHeight: .infinity)
789 .overlay(Color.clear.frame(width: 7).contentShape(Rectangle()).onHover { inside in
790 if inside { NSCursor.resizeLeftRight.push() } else { NSCursor.pop() }
791 }
792 .gesture(DragGesture(minimumDistance: 1).onChanged { drag in
793 let base = start ?? width
794 start = base
795 width = min(max(base + drag.translation.width, range.lowerBound), range.upperBound)
796 }.onEnded { _ in start = nil }))
797 .accessibilityHidden(true)
798 }
799}
800
801/// A tab for each open buffer: click to show it, × to close it, a dot for unsaved edits.
802struct BufferTabs: View {
803 let session: DocumentSession
804 @Environment(\.orgTheme) private var theme
805
806 var body: some View {
807 ScrollView(.horizontal, showsIndicators: false) {
808 HStack(spacing: 0) {
809 ForEach(session.openPaths, id: \.self) { path in
810 tab(path)
811 }
812 }
813 }
814 .frame(height: 28)
815 .background { Rectangle().fill(theme.color("modeline-background").map(AnyShapeStyle.init) ?? AnyShapeStyle(.bar)) }
816 .overlay(alignment: .bottom) { Divider() }
817 }
818
819 private func tab(_ path: String) -> some View {
820 let current = path == session.path
821 return HStack(spacing: 6) {
822 Text((path as NSString).lastPathComponent)
823 .lineLimit(1)
824 .foregroundStyle(current ? .primary : .secondary)
825 Button {
826 if path == session.path {
827 if UnsavedChanges.resolve(session) { session.kill(path) }
828 } else if UnsavedChanges.resolve(session, paths: [path]) {
829 session.kill(path)
830 }
831 } label: {
832 Image(systemName: session.dirtyPaths.contains(path) ? "circle.fill" : "xmark")
833 .font(.system(size: session.dirtyPaths.contains(path) ? 6 : 9, weight: .semibold))
834 .frame(width: 12, height: 12)
835 }
836 .buttonStyle(.borderless)
837 .help("Close")
838 }
839 .font(.callout)
840 .padding(.horizontal, 12)
841 .frame(maxHeight: .infinity)
842 // A shape, not a color: a color background runs up under the toolbar.
843 .background { Rectangle().fill(current ? theme.color("background") ?? Color(nsColor: .textBackgroundColor) : .clear) }
844 .overlay(alignment: .trailing) { Divider() }
845 .contentShape(Rectangle())
846 .onTapGesture { session.open(path) }
847 .help(path)
848 }
849}
850
851struct BlockEditRequest: Identifiable {
852 let id = UUID()
853 let edit: BlockEdit
854}