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