Sources/Orgstar/OrgstarApp.swift
604 lines · 26238 bytes
1import AppKit
2import OrgApp
3import OrgCore
4import OrgEditorAppKit
5import SwiftUI
6import UserNotifications
7
8/// Window-level requests the menu bar makes.
9@MainActor
10@Observable
11final class AppCommands {
12 var showingQuickOpen = false
13 var showingFolderPicker = false
14 var focusSearch = false
15 var showingConflict = false
16 var showingPalette = false
17 /// A location another window asked the main window to show.
18 private(set) var jumpRequest: (path: String, offset: Int, id: Int)?
19 private var jumpID = 0
20 /// The editor showing the open file, for menus and the palette.
21 var editor: OrgEditor?
22 /// The pending key prefix, and what can follow it.
23 var pendingKeys: String?
24 /// The editor's evil state in the Doom preset.
25 var editorState: String?
26 /// The keymap in use, for showing keys in menus and the palette.
27 var keymap = KeymapPreset.emacs.keymap
28 var modal = false
29
30 /// The keys that run `command`, as menus and the palette show them.
31 func keyLabel(for command: String) -> String? {
32 let labels = keymap.keyLabels(for: command, modes: modal ? ["normal", "insert"] : [nil])
33 return labels.isEmpty ? nil : labels.joined(separator: ", ")
34 }
35
36 /// The editor's selection, for the modeline.
37 var selection = NSRange(location: 0, length: 0)
38 var keyHints: [KeyHint] = []
39 /// A question a command asked, answered in the echo area.
40 private(set) var prompt: PromptRequest?
41 /// The last message from a command or the keymap, cleared after a few seconds.
42 private(set) var message: String?
43 private var messageID = 0
44
45 func ask(_ prompt: Prompt, reply: @escaping (String?) -> Void) {
46 self.prompt = PromptRequest(prompt: prompt, reply: reply)
47 }
48
49 /// Ends the prompt with an answer, or nil to cancel, and gives the editor the keys back.
50 func answer(_ text: String?) {
51 guard let request = prompt else { return }
52 prompt = nil
53 if let textView = editor?.textView { textView.window?.makeFirstResponder(textView) }
54 request.reply(text)
55 }
56
57 /// An app command from a menu, run by the main window.
58 private(set) var runRequest: (id: String, serial: Int)?
59 private var runSerial = 0
60
61 func run(_ id: String) {
62 runSerial += 1
63 runRequest = (id, runSerial)
64 }
65
66 func jump(path: String, offset: Int) {
67 jumpID += 1
68 jumpRequest = (path, offset, jumpID)
69 }
70
71 func show(_ text: String) {
72 messageID += 1
73 let id = messageID
74 message = text
75 Task {
76 try? await Task.sleep(for: .seconds(4))
77 if messageID == id { message = nil }
78 }
79 }
80}
81
82struct PromptRequest: Identifiable {
83 let id = UUID()
84 let prompt: Prompt
85 let reply: (String?) -> Void
86}
87
88@MainActor
89final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCenterDelegate {
90 var session: DocumentSession?
91 var commands: AppCommands?
92
93 func applicationDidFinishLaunching(_ notification: Notification) {
94 if SystemReminderCenter.isAvailable { UNUserNotificationCenter.current().delegate = self }
95 }
96
97 /// Reminders show while Orgstar is in front too.
98 nonisolated func userNotificationCenter(
99 _ center: UNUserNotificationCenter, willPresent notification: UNNotification
100 ) async -> UNNotificationPresentationOptions {
101 [.banner, .sound, .list]
102 }
103
104 /// Clicking a reminder shows its entry.
105 nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {
106 let info = response.notification.request.content.userInfo
107 guard let path = info["path"] as? String, let offset = info["offset"] as? Int else { return }
108 await MainActor.run {
109 NSApp.activate()
110 commands?.jump(path: path, offset: offset)
111 }
112 }
113
114 func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { true }
115
116 func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {
117 guard let session else { return .terminateNow }
118 BufferRestore.save(session)
119 return UnsavedChanges.resolve(session, paths: session.openPaths) ? .terminateNow : .terminateCancel
120 }
121}
122
123/// Unsaved edits when leaving a file or quitting.
124@MainActor
125enum UnsavedChanges {
126 /// Whether the open file can be left: saved in automatic mode, or as the user chooses in
127 /// explicit mode. A save that fails or conflicts keeps the file open.
128 static func resolve(_ session: DocumentSession) -> Bool {
129 guard session.isDirty else { return true }
130 if session.saveMode == .automatic { return session.save() }
131 let alert = NSAlert()
132 alert.messageText = "Save changes to \(session.path.map { ($0 as NSString).lastPathComponent } ?? "this file")?"
133 alert.informativeText = "Your changes will be lost if you don't save them."
134 alert.addButton(withTitle: "Save")
135 alert.addButton(withTitle: "Don't Save")
136 alert.addButton(withTitle: "Cancel")
137 switch alert.runModal() {
138 case .alertFirstButtonReturn: return session.save()
139 case .alertSecondButtonReturn: return true
140 default: return false
141 }
142 }
143
144 /// Whether the buffers of `paths` can be closed: saved in automatic mode, or as the user
145 /// chooses for all of them in explicit mode.
146 static func resolve(_ session: DocumentSession, paths: [String]) -> Bool {
147 let dirty = paths.filter(session.dirtyPaths.contains)
148 guard !dirty.isEmpty else { return true }
149 if session.saveMode == .automatic { return dirty.map(session.save).allSatisfy { $0 } }
150 if dirty == [session.path] { return resolve(session) }
151 let alert = NSAlert()
152 alert.messageText = "Save changes to \(dirty.count) files?"
153 alert.informativeText = dirty.map { ($0 as NSString).lastPathComponent }.joined(separator: ", ")
154 alert.addButton(withTitle: "Save All")
155 alert.addButton(withTitle: "Don't Save")
156 alert.addButton(withTitle: "Cancel")
157 switch alert.runModal() {
158 case .alertFirstButtonReturn: return dirty.map(session.save).allSatisfy { $0 }
159 case .alertSecondButtonReturn: return true
160 default: return false
161 }
162 }
163}
164
165/// The open buffers, their order and carets, kept for the next launch.
166@MainActor
167enum BufferRestore {
168 private static let key = "openBuffers"
169
170 struct State: Codable {
171 var paths: [String]
172 var current: String?
173 var carets: [String: Int]
174 }
175
176 static func save(_ session: DocumentSession, defaults: UserDefaults = .standard) {
177 var carets: [String: Int] = [:]
178 for path in session.openPaths { carets[path] = session.caret(of: path) }
179 let state = State(paths: session.openPaths, current: session.path, carets: carets)
180 if let data = try? JSONEncoder().encode(state) { defaults.set(data, forKey: key) }
181 }
182
183 /// Opens the buffers that were open, in order, and returns the carets to show them at.
184 static func restore(_ session: DocumentSession, defaults: UserDefaults = .standard) -> [String: Int] {
185 guard let data = defaults.data(forKey: key), let state = try? JSONDecoder().decode(State.self, from: data) else { return [:] }
186 let existing = state.paths.filter { FileManager.default.fileExists(atPath: $0) }
187 for path in existing { session.open(path) }
188 if let current = state.current, existing.contains(current) { session.open(current) }
189 return state.carets
190 }
191}
192
193@main
194struct OrgstarApp: App {
195 @NSApplicationDelegateAdaptor private var delegate: AppDelegate
196 @State private var workspace = Result {
197 try WorkspaceModel(directory: WorkspaceModel.defaultDirectory, settings: .with(todoKeywords: Preferences.orgSettings))
198 }
199 @State private var commands = AppCommands()
200 @State private var clock = ClockModel()
201 @State private var scheduler = SystemReminderCenter.isAvailable ? ReminderScheduler(center: SystemReminderCenter()) : nil
202 @State private var session: DocumentSession = {
203 let session = DocumentSession()
204 session.defaults = Preferences.orgSettings
205 return session
206 }()
207
208 var body: some Scene {
209 Window("Orgstar", id: "main") {
210 switch workspace {
211 case .success(let model):
212 ContentView(workspace: model, session: session, commands: commands, scheduler: scheduler, clock: clock)
213 .environment(\.orgTheme, ConfigSync.shared.theme)
214 .onAppear {
215 delegate.session = session
216 delegate.commands = commands
217 }
218 case .failure(let error):
219 ContentUnavailableView("Can't open the index", systemImage: "exclamationmark.triangle", description: Text(error.localizedDescription))
220 }
221 }
222 .defaultSize(width: 1280, height: 860)
223 Window("Agenda", id: "agenda") {
224 if case .success(let model) = workspace {
225 AgendaView(workspace: model, session: session, commands: commands, scheduler: scheduler)
226 .environment(\.orgTheme, ConfigSync.shared.theme)
227 }
228 }
229 .defaultSize(width: 760, height: 720)
230 Window("Board", id: "board") {
231 if case .success(let model) = workspace {
232 BoardView(workspace: model, session: session, commands: commands)
233 .environment(\.orgTheme, ConfigSync.shared.theme)
234 }
235 }
236 .defaultSize(width: 1100, height: 700)
237 Window("Clock Report", id: "clock-report") {
238 if case .success(let model) = workspace {
239 ClockReportView(workspace: model)
240 }
241 }
242 .defaultSize(width: 860, height: 560)
243 Window("Capture", id: "capture") {
244 if case .success(let model) = workspace {
245 CaptureView(workspace: model, session: session, commands: commands)
246 }
247 }
248 .windowResizability(.contentSize)
249 .windowLevel(.floating)
250 .commands {
251 CommandGroup(after: .newItem) {
252 Button("Add Folder…") { commands.showingFolderPicker = true }
253 .keyboardShortcut("o", modifiers: [.command, .shift])
254 Button("Quick Open…") { commands.showingQuickOpen = true }
255 .keyboardShortcut("p")
256 Button("Command Palette…") { commands.showingPalette = true }
257 .keyboardShortcut("p", modifiers: [.command, .shift])
258 }
259 CommandGroup(after: .saveItem) {
260 Menu("Export") {
261 ForEach(EditorCommands.all.filter { $0.id.hasPrefix("app.export.") }, id: \.id) { command in
262 Button(command.title) { commands.run(command.id) }
263 }
264 }
265 .disabled(session.path == nil)
266 }
267 CommandGroup(replacing: .saveItem) {
268 Button("Close Buffer") {
269 // ⌘W closes the buffer in the main window, and other windows themselves.
270 if let key = NSApp.keyWindow, key.identifier?.rawValue.contains("main") != true {
271 key.performClose(nil)
272 } else {
273 commands.run("app.buffer.kill")
274 }
275 }
276 .keyboardShortcut("w")
277 Button("Close Window") { NSApp.keyWindow?.performClose(nil) }
278 .keyboardShortcut("w", modifiers: [.command, .shift])
279 Divider()
280 Button("Save") {
281 if !session.save(), session.conflict != nil { commands.showingConflict = true }
282 }
283 .keyboardShortcut("s")
284 .disabled(session.path == nil || session.isReadOnly)
285 Button("Save All") { commands.run("app.save-all") }
286 .keyboardShortcut("s", modifiers: [.command, .option])
287 .disabled(session.dirtyPaths.isEmpty)
288 }
289 CommandGroup(after: .sidebar) {
290 Button("Show or Hide Outline") { commands.run("app.toggle-outline") }
291 .keyboardShortcut("o", modifiers: [.command, .option])
292 MarkupToggle()
293 }
294 CommandGroup(after: .pasteboard) {
295 Divider()
296 FindMenu(commands: commands)
297 }
298 CommandGroup(after: .textEditing) {
299 Button("Cancel Running Block") { commands.run("app.babel.cancel") }
300 .keyboardShortcut(".")
301 .disabled(!session.isRunningBabel)
302 Button("Search Notes") { commands.focusSearch = true }
303 .keyboardShortcut("f", modifiers: [.command, .shift])
304 }
305 CommandGroup(before: .windowList) {
306 AgendaMenuItem()
307 Divider()
308 Button("Switch to Buffer…") { commands.run("app.buffer.switch") }
309 Button("Next Buffer") { commands.run("app.buffer.next") }
310 .keyboardShortcut("]", modifiers: [.command, .shift])
311 Button("Previous Buffer") { commands.run("app.buffer.previous") }
312 .keyboardShortcut("[", modifiers: [.command, .shift])
313 Divider()
314 }
315 CommandGroup(after: .newItem) {
316 Button("Capture…") { commands.run("app.capture") }
317 .keyboardShortcut("n", modifiers: [.command, .shift])
318 }
319 }
320 .commands {
321 CommandMenu("Org") {
322 OrgMenuItems(commands: commands)
323 }
324 }
325 .commands {
326 CommandGroup(after: .appSettings) {
327 Button("Edit Config File") { commands.jump(path: UserConfig.configFile.path, offset: 0) }
328 .keyboardShortcut(",", modifiers: [.command, .option])
329 }
330 }
331 Settings {
332 SettingsView(commands: commands, workspace: try? workspace.get())
333 }
334 }
335}
336
337/// The Org menu: every org command, with the keys that run it in the current keymap.
338struct OrgMenuItems: View {
339 let commands: AppCommands
340
341 var body: some View {
342 ForEach(EditorCommands.all.filter { $0.id.hasPrefix("org.") }, id: \.id) { command in
343 Button {
344 commands.editor?.run(command.id)
345 } label: {
346 Text(command.title)
347 if let keys = commands.keyLabel(for: command.id) { Text(keys) }
348 }
349 .disabled(commands.editor == nil)
350 }
351 }
352}
353
354/// View ▸ Show Markup (link brackets and targets, emphasis markers) and Show Line Numbers.
355struct MarkupToggle: View {
356 @AppStorage("showTabBar") private var showTabBar = false
357 @AppStorage("showMarkup") private var showMarkup = false
358 @AppStorage("showLineNumbers") private var showLineNumbers = true
359
360 var body: some View {
361 Toggle("Show Markup", isOn: $showMarkup)
362 .keyboardShortcut("m", modifiers: [.command, .shift])
363 Toggle("Show Line Numbers", isOn: $showLineNumbers)
364 .keyboardShortcut("l", modifiers: [.command, .shift])
365 Toggle("Show Tab Bar", isOn: $showTabBar)
366 }
367}
368
369/// Edit ▸ Find: the editor's find bar.
370struct FindMenu: View {
371 let commands: AppCommands
372
373 var body: some View {
374 Menu("Find") {
375 item("Find…", "edit.find", "f")
376 item("Find and Replace…", "edit.replace", "f", [.command, .option])
377 item("Find Next", "edit.find-next", "g")
378 item("Find Previous", "edit.find-previous", "g", [.command, .shift])
379 item("Use Selection for Find", "edit.use-selection-for-find", "e")
380 }
381 }
382
383 private func item(_ title: String, _ id: String, _ key: KeyEquivalent, _ modifiers: EventModifiers = .command) -> some View {
384 Button(title) { commands.editor?.run(id) }
385 .keyboardShortcut(key, modifiers: modifiers)
386 .disabled(commands.editor == nil)
387 }
388}
389
390/// Window ▸ Agenda.
391struct AgendaMenuItem: View {
392 @Environment(\.openWindow) private var openWindow
393
394 var body: some View {
395 Button("Agenda") { openWindow(id: "agenda") }
396 .keyboardShortcut("a", modifiers: [.command, .shift])
397 Button("Board") { openWindow(id: "board") }
398 .keyboardShortcut("b", modifiers: [.command, .shift])
399 }
400}
401
402struct SettingsView: View {
403 let commands: AppCommands
404 let workspace: WorkspaceModel?
405 @State private var importing = false
406 @Environment(\.openWindow) private var openWindow
407 @AppStorage("saveMode") private var saveMode = SaveMode.automatic
408 @AppStorage("keymap") private var preset = KeymapPreset.emacs
409 @AppStorage("optionAsMeta") private var optionAsMeta = OptionAsMeta.left.rawValue
410 @AppStorage("tagsColumn") private var tagsColumn = -77
411 @AppStorage("headingAfterSubtree") private var headingAfterSubtree = true
412 @AppStorage("splitLine") private var splitLine = false
413 @AppStorage("alphabeticalLists") private var alphabeticalLists = true
414 @AppStorage("fillColumn") private var fillColumn = 80
415 @AppStorage("hiddenMarkers") private var hiddenMarkers = true
416 @AppStorage("prettyEntities") private var prettyEntities = true
417 @AppStorage("todoKeywords") private var todoKeywords = Preferences.defaultTodoKeywords
418 @AppStorage("agendaSpan") private var agendaSpan = 10
419 @AppStorage("agendaStartOffset") private var agendaStartOffset = -3
420 @AppStorage("agendaSubfolders") private var agendaSubfolders = false
421 @AppStorage("reminders") private var reminders = true
422 @AppStorage("reminderLead") private var reminderLead = 12
423 @AppStorage("globalCapture") private var globalCapture = true
424 @AppStorage("settingsTab") private var tab = "general"
425 @AppStorage("showHiddenFiles") private var showHiddenFiles = true
426 @AppStorage("themeFont") private var themeFont = ""
427 @AppStorage("themeFontSize") private var themeFontSize = 13
428 @AppStorage("themeLineSpacing") private var themeLineSpacing = 2
429 @AppStorage("themeHeadingStep") private var themeHeadingStep = 1
430
431 /// Installed monospaced font families.
432 private static let monospacedFamilies: [String] = NSFontManager.shared.availableFontFamilies.filter { family in
433 NSFontManager.shared.font(withFamily: family, traits: [], weight: 5, size: 13)?.isFixedPitch == true
434 }
435
436 var body: some View {
437 TabView(selection: $tab) {
438 Tab("General", systemImage: "gearshape", value: "general") { general }
439 Tab("Editing", systemImage: "text.alignleft", value: "editing") { editing }
440 Tab("Appearance", systemImage: "paintpalette", value: "appearance") { appearance }
441 Tab("Agenda", systemImage: "calendar", value: "agenda") { agenda }
442 Tab("Capture", systemImage: "tray.and.arrow.down", value: "capture") { capture }
443 }
444 .frame(width: 600)
445 }
446
447 private func editConfig() {
448 ConfigSync.shared.start()
449 openWindow(id: "main")
450 commands.jump(path: UserConfig.configFile.path, offset: 0)
451 }
452
453 private var general: some View {
454 Form {
455 Section {
456 LabeledContent("config.toml") {
457 HStack {
458 Button("Edit in Orgstar") { editConfig() }
459 Button("Open with Default App") { NSWorkspace.shared.open(UserConfig.configFile) }
460 Button("Show in Finder") { NSWorkspace.shared.activateFileViewerSelecting([UserConfig.configFile]) }
461 }
462 }
463 LabeledContent("Emacs") {
464 Button("Import from Emacs…") { importing = true }
465 }
466 } footer: {
467 Text("Every setting here is also in \(UserConfig.configFile.path), which you can edit, share or keep with your dotfiles. Changes in either place show up in the other.")
468 .settingsFooter()
469 }
470 Section {
471 Picker("Save files", selection: $saveMode) {
472 Text("Automatically, when typing stops").tag(SaveMode.automatic)
473 Text("Only with File ▸ Save (⌘S)").tag(SaveMode.explicit)
474 }
475 .pickerStyle(.radioGroup)
476 }
477 Section {
478 Picker("Keys", selection: $preset) {
479 ForEach(KeymapPreset.allCases, id: \.self) { Text($0.title).tag($0) }
480 }
481 Toggle("Show hidden files and folders", isOn: $showHiddenFiles)
482 Picker("Option as Meta", selection: $optionAsMeta) {
483 Text("Left Option").tag(OptionAsMeta.left.rawValue)
484 Text("Right Option").tag(OptionAsMeta.right.rawValue)
485 Text("Both").tag(OptionAsMeta([.left, .right]).rawValue)
486 Text("Neither").tag(0)
487 }
488 } footer: {
489 Text("Your own bindings go in \(KeymapLoader.userFile.path), on top of the preset.")
490 .settingsFooter()
491 }
492 }
493 .formStyle(.grouped)
494 .frame(height: 330)
495 .sheet(isPresented: $importing) { EmacsImportView(workspace: workspace) }
496 }
497
498 private var editing: some View {
499 Form {
500 Section {
501 Picker("Tags", selection: $tagsColumn) {
502 Text("Aligned to end at column 77").tag(-77)
503 Text("One space after the title").tag(0)
504 }
505 Toggle("M-RET adds the new heading after the subtree", isOn: $headingAfterSubtree)
506 Toggle("M-RET splits the line at the caret", isOn: $splitLine)
507 Toggle("Lists can use letters (a. b. c.)", isOn: $alphabeticalLists)
508 Stepper("M-q fills to column \(fillColumn)", value: $fillColumn, in: 40...200)
509 }
510 Section {
511 Toggle("Emacs hides emphasis markers (org-hide-emphasis-markers)", isOn: $hiddenMarkers)
512 Toggle("Emacs shows entities as characters (org-pretty-entities)", isOn: $prettyEntities)
513 } footer: {
514 Text("Tags, tables and M-q measure text as your Emacs displays it, so both write the same file.")
515 .settingsFooter()
516 }
517 Section {
518 TextField("Default TODO keywords", text: $todoKeywords)
519 } footer: {
520 Text("For files without #+TODO, in #+TODO syntax. Takes effect when Orgstar restarts.")
521 .settingsFooter()
522 }
523 }
524 .formStyle(.grouped)
525 .frame(height: 450)
526 }
527
528 private var appearance: some View {
529 Form {
530 Section {
531 Picker("Font", selection: $themeFont) {
532 Text("System monospaced").tag("")
533 Divider()
534 ForEach(Self.monospacedFamilies, id: \.self) { Text($0).tag($0) }
535 if !themeFont.isEmpty, !Self.monospacedFamilies.contains(themeFont) { Text(themeFont).tag(themeFont) }
536 }
537 Stepper("Size: \(themeFontSize) pt", value: $themeFontSize, in: 8...36)
538 Stepper("Line spacing: \(themeLineSpacing) pt", value: $themeLineSpacing, in: 0...16)
539 Stepper("Headings grow by \(themeHeadingStep) pt a level", value: $themeHeadingStep, in: 0...8)
540 } footer: {
541 Text("Tags and tables line up in columns, so a monospaced font keeps them straight.")
542 .settingsFooter()
543 }
544 Section {
545 LabeledContent("Colors") {
546 HStack {
547 Button("Edit in config.toml") { editConfig() }
548 Button("Show Default Theme") {
549 openWindow(id: "main")
550 commands.jump(path: UserConfig.directory.appendingPathComponent("default-theme.toml").path, offset: 0)
551 }
552 }
553 }
554 } footer: {
555 Text("Set colors under [theme] (both appearances), [theme.light] or [theme.dark] in config.toml, and TODO keyword colors under [theme.todo]. default-theme.toml lists every color with the default theme's values.")
556 .settingsFooter()
557 }
558 }
559 .formStyle(.grouped)
560 .frame(height: 380)
561 }
562
563 private var agenda: some View {
564 Form {
565 Section {
566 Stepper("Agenda shows \(agendaSpan) days", value: $agendaSpan, in: 1...31)
567 Stepper(agendaStartOffset == 0 ? "Agenda starts today" : "Agenda starts \(-agendaStartOffset) days before today", value: $agendaStartOffset, in: -14...0)
568 Toggle("Include files in subfolders", isOn: $agendaSubfolders)
569 }
570 Section {
571 Toggle("Notify before timed agenda entries", isOn: $reminders)
572 Stepper("\(reminderLead) minutes before", value: $reminderLead, in: 0...120)
573 .disabled(!reminders)
574 } footer: {
575 Text("An entry's APPT_WARNTIME property overrides the lead time.")
576 .settingsFooter()
577 }
578 }
579 .formStyle(.grouped)
580 .frame(height: 290)
581 }
582
583 private var capture: some View {
584 Form {
585 Section {
586 Toggle("⌃⌥Space opens Capture from any app", isOn: $globalCapture)
587 } footer: {
588 Text("Templates go in \(CaptureTemplates.userFile.path).")
589 .settingsFooter()
590 }
591 }
592 .formStyle(.grouped)
593 .frame(height: 160)
594 }
595}
596
597private extension Text {
598 func settingsFooter() -> some View {
599 font(.caption)
600 .foregroundStyle(.secondary)
601 .textSelection(.enabled)
602 .frame(maxWidth: .infinity, alignment: .leading)
603 }
604}