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