Sources/Orgstar/OrgstarApp.swift
792 lines · 35890 bytes
1import AppKit
2import OrgApp
3import OrgCore
4import OrgEditorAppKit
5import OrgPresentation
6import SwiftUI
7import UserNotifications
8
9/// Window-level requests the menu bar makes.
10@MainActor
11@Observable
12final class AppCommands {
13 var showingQuickOpen = false
14 var showingFolderPicker = false
15 var focusSearch = false
16 var showingConflict = false
17 var showingPalette = false
18 /// A location another window asked the main window to show.
19 private(set) var jumpRequest: (path: String, offset: Int, id: Int)?
20 private var jumpID = 0
21 /// Days the agenda window should show, from a followed timestamp.
22 var agendaRequest: (start: Int, days: Int)?
23 /// The editor showing the open file, for menus and the palette.
24 var editor: OrgEditor?
25 /// The pending key prefix, and what can follow it.
26 var pendingKeys: String?
27 /// The editor's evil state in the Doom preset.
28 var editorState: String?
29 /// The keymap in use, for showing keys in menus and the palette.
30 var keymap = KeymapPreset.emacs.keymap
31 var modal = false
32 /// `org-stored-links`, most recent first; kept for the session, as in Emacs.
33 var storedLinks: [StoredLink] = []
34
35 /// Puts `link` first in `storedLinks` and says what happened.
36 func storeLink(_ link: StoredLink) {
37 show(StoredLink.add(link, to: &storedLinks))
38 }
39
40 /// The keys that run `command`, as menus and the palette show them.
41 func keyLabel(for command: String) -> String? {
42 let labels = keymap.keyLabels(for: command, modes: modal ? ["normal", "insert"] : [nil])
43 return labels.isEmpty ? nil : labels.joined(separator: ", ")
44 }
45
46 /// The editor's selection, for the modeline.
47 var selection = NSRange(location: 0, length: 0)
48 var keyHints: [KeyHint] = []
49 /// A question a command asked, answered in the echo area.
50 private(set) var prompt: PromptRequest?
51 /// The last message from a command or the keymap, cleared after a few seconds.
52 private(set) var message: String?
53 private var messageID = 0
54
55 func ask(_ prompt: Prompt, reply: @escaping (String?) -> Void) {
56 self.prompt = PromptRequest(prompt: prompt, reply: reply)
57 }
58
59 /// Clock questions in the echo area.
60 var askClock: ClockModel.Ask {
61 { [self] prompt in
62 await withCheckedContinuation { continuation in
63 ask(prompt) { continuation.resume(returning: $0) }
64 }
65 }
66 }
67
68 /// Ends the prompt with an answer, or nil to cancel, and gives the editor the keys back.
69 func answer(_ text: String?) {
70 guard let request = prompt else { return }
71 prompt = nil
72 if let textView = editor?.textView { textView.window?.makeFirstResponder(textView) }
73 request.reply(text)
74 }
75
76 /// An export or table recalculation running in Emacs, for Cancel Running Task.
77 private(set) var emacsTask: Task<Void, Never>?
78 private var emacsSerial = 0
79
80 /// Runs `work` as the Emacs task, cancelling the one before.
81 func runInEmacs(_ work: @escaping @MainActor () async -> Void) {
82 emacsTask?.cancel()
83 emacsSerial += 1
84 let serial = emacsSerial
85 emacsTask = Task {
86 await work()
87 if emacsSerial == serial { emacsTask = nil }
88 }
89 }
90
91 /// An app command from a menu, run by the main window.
92 private(set) var runRequest: (id: String, serial: Int)?
93 private var runSerial = 0
94
95 func run(_ id: String) {
96 runSerial += 1
97 runRequest = (id, runSerial)
98 }
99
100 /// A capture waiting for the capture window: the template key and the link properties for
101 /// its escapes (org-protocol), or the agenda day to schedule the entry on.
102 var captureRequest: (template: String?, properties: [String: String], day: Int?, serial: Int)?
103 private var captureSerial = 0
104
105 /// Capture from an agenda day, as `org-agenda-capture`: that day is the capture's date, and
106 /// the entry is scheduled on it. The caller opens the capture window.
107 func capture(on day: Int) {
108 captureSerial += 1
109 captureRequest = (nil, [:], day, captureSerial)
110 }
111
112 /// `org-protocol://capture` and `store-link`.
113 func handle(protocolURL url: String) {
114 switch OrgProtocol.parse(url) {
115 case .capture(let template, let properties):
116 captureSerial += 1
117 captureRequest = (template, properties, nil, captureSerial)
118 run("app.capture")
119 case .storeLink(let link, let title):
120 storeLink(StoredLink(link: link, description: title))
121 NSPasteboard.general.clearContents()
122 NSPasteboard.general.setString(link, forType: .string)
123 case nil:
124 show("Orgstar handles org-protocol capture and store-link")
125 }
126 }
127
128 func jump(path: String, offset: Int) {
129 jumpID += 1
130 jumpRequest = (path, offset, jumpID)
131 }
132
133 func show(_ text: String) {
134 messageID += 1
135 let id = messageID
136 message = text
137 Task {
138 try? await Task.sleep(for: .seconds(4))
139 if messageID == id { message = nil }
140 }
141 }
142}
143
144struct PromptRequest: Identifiable {
145 let id = UUID()
146 let prompt: Prompt
147 let reply: (String?) -> Void
148}
149
150@MainActor
151final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCenterDelegate {
152 var session: DocumentSession?
153 var commands: AppCommands?
154
155 func applicationDidFinishLaunching(_ notification: Notification) {
156 if SystemReminderCenter.isAvailable { UNUserNotificationCenter.current().delegate = self }
157 }
158
159 /// `:session` interpreters end with the app.
160 func applicationWillTerminate(_ notification: Notification) {
161 BabelSessions.shared.stopAll()
162 }
163
164 /// Reminders show while Orgstar is in front too.
165 nonisolated func userNotificationCenter(
166 _ center: UNUserNotificationCenter, willPresent notification: UNNotification
167 ) async -> UNNotificationPresentationOptions {
168 [.banner, .sound, .list]
169 }
170
171 /// Clicking a reminder shows its entry.
172 nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {
173 let info = response.notification.request.content.userInfo
174 guard let path = info["path"] as? String, let offset = info["offset"] as? Int else { return }
175 await MainActor.run {
176 NSApp.activate()
177 commands?.jump(path: path, offset: offset)
178 }
179 }
180
181 /// Files opened from Finder, `open`, or a drop on the Dock icon: each opens as a buffer.
182 /// Ones that arrive before the window is ready wait for it (`pendingOpens`).
183 static var pendingOpens: [String] = []
184
185 func application(_ application: NSApplication, open urls: [URL]) {
186 let paths = urls.filter(\.isFileURL).map(\.path)
187 let links = urls.filter { $0.scheme == "org-protocol" }.map(\.absoluteString)
188 guard let commands, let session else {
189 Self.pendingOpens += paths
190 Self.pendingLinks += links
191 return
192 }
193 NSApp.activate()
194 for path in paths { session.open(path) }
195 for link in links { commands.handle(protocolURL: link) }
196 }
197
198 /// org-protocol links that arrive before the window is ready.
199 static var pendingLinks: [String] = []
200
201 func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { true }
202
203 func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {
204 guard let session else { return .terminateNow }
205 BufferRestore.save(session)
206 return UnsavedChanges.resolve(session, paths: session.openPaths) ? .terminateNow : .terminateCancel
207 }
208}
209
210/// Unsaved edits when leaving a file or quitting.
211@MainActor
212enum UnsavedChanges {
213 /// Whether the open file can be left: saved in automatic mode, or as the user chooses in
214 /// explicit mode. A save that fails or conflicts keeps the file open.
215 static func resolve(_ session: DocumentSession) -> Bool {
216 guard session.isDirty else { return true }
217 if session.saveMode == .automatic { return session.save() }
218 let alert = NSAlert()
219 alert.messageText = "Save changes to \(session.path.map { ($0 as NSString).lastPathComponent } ?? "this file")?"
220 alert.informativeText = "Your changes will be lost if you don't save them."
221 alert.addButton(withTitle: "Save")
222 alert.addButton(withTitle: "Don't Save")
223 alert.addButton(withTitle: "Cancel")
224 switch alert.runModal() {
225 case .alertFirstButtonReturn: return session.save()
226 case .alertSecondButtonReturn: return true
227 default: return false
228 }
229 }
230
231 /// Whether the buffers of `paths` can be closed: saved in automatic mode, or as the user
232 /// chooses for all of them in explicit mode.
233 static func resolve(_ session: DocumentSession, paths: [String]) -> Bool {
234 let dirty = paths.filter(session.dirtyPaths.contains)
235 guard !dirty.isEmpty else { return true }
236 if session.saveMode == .automatic { return dirty.map(session.save).allSatisfy { $0 } }
237 if dirty == [session.path] { return resolve(session) }
238 let alert = NSAlert()
239 alert.messageText = "Save changes to \(dirty.count) files?"
240 alert.informativeText = dirty.map { ($0 as NSString).lastPathComponent }.joined(separator: ", ")
241 alert.addButton(withTitle: "Save All")
242 alert.addButton(withTitle: "Don't Save")
243 alert.addButton(withTitle: "Cancel")
244 switch alert.runModal() {
245 case .alertFirstButtonReturn: return dirty.map(session.save).allSatisfy { $0 }
246 case .alertSecondButtonReturn: return true
247 default: return false
248 }
249 }
250}
251
252/// The open buffers, their order and carets, kept for the next launch.
253@MainActor
254enum BufferRestore {
255 private static let key = "openBuffers"
256
257 struct State: Codable {
258 var paths: [String]
259 var current: String?
260 var carets: [String: Int]
261 }
262
263 static func save(_ session: DocumentSession, defaults: UserDefaults = .standard) {
264 var carets: [String: Int] = [:]
265 for path in session.openPaths { carets[path] = session.caret(of: path) }
266 let state = State(paths: session.openPaths, current: session.path, carets: carets)
267 if let data = try? JSONEncoder().encode(state) { defaults.set(data, forKey: key) }
268 }
269
270 /// Opens the buffers that were open, in order, and returns the carets to show them at.
271 static func restore(_ session: DocumentSession, defaults: UserDefaults = .standard) -> [String: Int] {
272 guard let data = defaults.data(forKey: key), let state = try? JSONDecoder().decode(State.self, from: data) else { return [:] }
273 let existing = state.paths.filter { FileManager.default.fileExists(atPath: $0) }
274 for path in existing { session.open(path) }
275 if let current = state.current, existing.contains(current) { session.open(current) }
276 return state.carets
277 }
278}
279
280@main
281struct OrgstarApp: App {
282 @NSApplicationDelegateAdaptor private var delegate: AppDelegate
283 @State private var workspace = Result {
284 try WorkspaceModel(directory: WorkspaceModel.defaultDirectory, settings: .with(todoKeywords: Preferences.orgSettings))
285 }
286 @State private var commands = AppCommands()
287 @State private var clock = ClockModel()
288 @State private var scheduler = SystemReminderCenter.isAvailable ? ReminderScheduler(center: SystemReminderCenter()) : nil
289 @State private var session: DocumentSession = {
290 let session = DocumentSession()
291 session.defaults = Preferences.orgSettings
292 return session
293 }()
294
295 init() {
296 // Debug builds, and runs with ORGSTAR_PERF set: main-thread stalls in the console.
297 #if DEBUG
298 Perf.watchMainThread()
299 #else
300 if ProcessInfo.processInfo.environment["ORGSTAR_PERF"] != nil { Perf.watchMainThread() }
301 #endif
302 }
303
304 var body: some Scene {
305 Window("Orgstar", id: "main") {
306 switch workspace {
307 case .success(let model):
308 ContentView(workspace: model, session: session, commands: commands, scheduler: scheduler, clock: clock)
309 .environment(\.orgTheme, ConfigSync.shared.theme)
310 .onAppear {
311 delegate.session = session
312 delegate.commands = commands
313 CaptureIntent.environment = (model, session, clock, commands)
314 }
315 case .failure(let error):
316 ContentUnavailableView("Can't open the index", systemImage: "exclamationmark.triangle", description: Text(error.localizedDescription))
317 }
318 }
319 .defaultSize(width: 1280, height: 860)
320 Window("Agenda", id: "agenda") {
321 if case .success(let model) = workspace {
322 AgendaView(workspace: model, session: session, commands: commands, scheduler: scheduler, clock: clock)
323 .environment(\.orgTheme, ConfigSync.shared.theme)
324 }
325 }
326 .defaultSize(width: 760, height: 720)
327 Window("Board", id: "board") {
328 if case .success(let model) = workspace {
329 BoardView(workspace: model, session: session, commands: commands)
330 .environment(\.orgTheme, ConfigSync.shared.theme)
331 }
332 }
333 .defaultSize(width: 1100, height: 700)
334 Window("Clock Report", id: "clock-report") {
335 if case .success(let model) = workspace {
336 ClockReportView(workspace: model)
337 }
338 }
339 .defaultSize(width: 860, height: 560)
340 Window("Capture", id: "capture") {
341 if case .success(let model) = workspace {
342 CaptureView(workspace: model, session: session, commands: commands, clock: clock)
343 }
344 }
345 .windowResizability(.contentSize)
346 .windowLevel(.floating)
347 .commands {
348 CommandGroup(after: .newItem) {
349 Button("Add Folder…") { commands.showingFolderPicker = true }
350 .keyboardShortcut("o", modifiers: [.command, .shift])
351 Button("Quick Open…") { commands.showingQuickOpen = true }
352 .keyboardShortcut("p")
353 Button("Command Palette…") { commands.showingPalette = true }
354 .keyboardShortcut("p", modifiers: [.command, .shift])
355 }
356 CommandGroup(after: .saveItem) {
357 Menu("Export") {
358 ForEach(EditorCommands.all.filter { $0.id.hasPrefix("app.export.") }, id: \.id) { command in
359 Button(command.title) { commands.run(command.id) }
360 }
361 }
362 .disabled(session.path == nil)
363 }
364 CommandGroup(replacing: .saveItem) {
365 Button("Close Buffer") {
366 // ⌘W closes the buffer in the main window, and other windows themselves.
367 if let key = NSApp.keyWindow, key.identifier?.rawValue.contains("main") != true {
368 key.performClose(nil)
369 } else {
370 commands.run("app.buffer.kill")
371 }
372 }
373 .keyboardShortcut("w")
374 Button("Close Window") { NSApp.keyWindow?.performClose(nil) }
375 .keyboardShortcut("w", modifiers: [.command, .shift])
376 Divider()
377 Button("Save") {
378 if !session.save(), session.conflict != nil { commands.showingConflict = true }
379 }
380 .keyboardShortcut("s")
381 .disabled(session.path == nil || session.isReadOnly)
382 Button("Save All") { commands.run("app.save-all") }
383 .keyboardShortcut("s", modifiers: [.command, .option])
384 .disabled(session.dirtyPaths.isEmpty)
385 }
386 CommandGroup(after: .sidebar) {
387 Button("Show or Hide Outline") { commands.run("app.toggle-outline") }
388 .keyboardShortcut("o", modifiers: [.command, .option])
389 Button("Show or Hide Backlinks") { commands.run("app.toggle-backlinks") }
390 Button("Show or Hide Columns and Clock") { commands.run("app.toggle-inspector") }
391 .keyboardShortcut("i", modifiers: [.command, .option])
392 MarkupToggle()
393 Button("Truncate or Wrap Long Lines") { commands.run("editor.toggle-truncate-lines") }
394 }
395 CommandGroup(after: .pasteboard) {
396 Divider()
397 FindMenu(commands: commands)
398 }
399 CommandGroup(after: .textEditing) {
400 Button("Cancel Running Task") { commands.run("app.babel.cancel") }
401 .keyboardShortcut(".")
402 .disabled(!session.isRunningBabel && commands.emacsTask == nil)
403 Button("Search Notes") { commands.focusSearch = true }
404 .keyboardShortcut("f", modifiers: [.command, .shift])
405 }
406 CommandGroup(before: .windowList) {
407 AgendaMenuItem()
408 Divider()
409 Button("Switch to Buffer…") { commands.run("app.buffer.switch") }
410 Button("Next Buffer") { commands.run("app.buffer.next") }
411 .keyboardShortcut("]", modifiers: [.command, .shift])
412 Button("Previous Buffer") { commands.run("app.buffer.previous") }
413 .keyboardShortcut("[", modifiers: [.command, .shift])
414 Divider()
415 }
416 CommandGroup(after: .newItem) {
417 Button("Capture…") { commands.run("app.capture") }
418 .keyboardShortcut("n", modifiers: [.command, .shift])
419 }
420 }
421 .commands {
422 CommandMenu("Org") {
423 ClockMenu(commands: commands, clock: clock)
424 Divider()
425 OrgMenuItems(commands: commands)
426 }
427 }
428 .commands {
429 CommandGroup(after: .appSettings) {
430 Button("Edit Config File") { commands.jump(path: UserConfig.configFile.path, offset: 0) }
431 .keyboardShortcut(",", modifiers: [.command, .option])
432 }
433 }
434 Settings {
435 SettingsView(commands: commands, workspace: try? workspace.get())
436 }
437 }
438}
439
440/// The Org menu: every org command, with the keys that run it in the current keymap.
441struct OrgMenuItems: View {
442 let commands: AppCommands
443
444 var body: some View {
445 ForEach(EditorCommands.all.filter { $0.id.hasPrefix("org.") }, id: \.id) { command in
446 Button {
447 commands.editor?.run(command.id)
448 } label: {
449 Text(command.title)
450 if let keys = commands.keyLabel(for: command.id) { Text(keys) }
451 }
452 .disabled(commands.editor == nil)
453 }
454 }
455}
456
457/// View ▸ Show Markup (link brackets and targets, emphasis markers) and Show Line Numbers.
458struct MarkupToggle: View {
459 @AppStorage("showTabBar") private var showTabBar = false
460 @AppStorage("showMarkup") private var showMarkup = false
461 @AppStorage("showLineNumbers") private var showLineNumbers = true
462
463 var body: some View {
464 Toggle("Show Markup", isOn: $showMarkup)
465 .keyboardShortcut("m", modifiers: [.command, .shift])
466 Toggle("Show Line Numbers", isOn: $showLineNumbers)
467 .keyboardShortcut("l", modifiers: [.command, .shift])
468 Toggle("Show Tab Bar", isOn: $showTabBar)
469 }
470}
471
472/// Edit ▸ Find: the editor's find bar.
473struct FindMenu: View {
474 let commands: AppCommands
475
476 var body: some View {
477 Menu("Find") {
478 item("Find…", "edit.find", "f")
479 item("Find and Replace…", "edit.replace", "f", [.command, .option])
480 item("Find Next", "edit.find-next", "g")
481 item("Find Previous", "edit.find-previous", "g", [.command, .shift])
482 item("Use Selection for Find", "edit.use-selection-for-find", "e")
483 }
484 }
485
486 private func item(_ title: String, _ id: String, _ key: KeyEquivalent, _ modifiers: EventModifiers = .command) -> some View {
487 Button(title) { commands.editor?.run(id) }
488 .keyboardShortcut(key, modifiers: modifiers)
489 .disabled(commands.editor == nil)
490 }
491}
492
493/// Window ▸ Agenda.
494struct AgendaMenuItem: View {
495 @Environment(\.openWindow) private var openWindow
496
497 var body: some View {
498 Button("Agenda") { openWindow(id: "agenda") }
499 .keyboardShortcut("a", modifiers: [.command, .shift])
500 Button("Board") { openWindow(id: "board") }
501 .keyboardShortcut("b", modifiers: [.command, .shift])
502 }
503}
504
505struct SettingsView: View {
506 let commands: AppCommands
507 let workspace: WorkspaceModel?
508 @State private var importing = false
509 @Environment(\.openWindow) private var openWindow
510 @AppStorage("saveMode") private var saveMode = SaveMode.automatic
511 @AppStorage("keymap") private var preset = KeymapPreset.emacs
512 @AppStorage("optionAsMeta") private var optionAsMeta = OptionAsMeta.left.rawValue
513 @AppStorage("tagsColumn") private var tagsColumn = -77
514 @AppStorage("headingAfterSubtree") private var headingAfterSubtree = true
515 @AppStorage("splitLine") private var splitLine = false
516 @AppStorage("alphabeticalLists") private var alphabeticalLists = true
517 @AppStorage("fillColumn") private var fillColumn = 80
518 @AppStorage("hiddenMarkers") private var hiddenMarkers = true
519 @AppStorage("prettyEntities") private var prettyEntities = true
520 @AppStorage("startupTruncated") private var startupTruncated = false
521 @AppStorage("todoKeywords") private var todoKeywords = Preferences.defaultTodoKeywords
522 @AppStorage("enforceTodoDependencies") private var enforceTodoDependencies = false
523 @AppStorage("enforceTodoCheckboxDependencies") private var enforceTodoCheckboxDependencies = false
524 @AppStorage("agendaSpan") private var agendaSpan = 10
525 @AppStorage("agendaStartOffset") private var agendaStartOffset = 0
526 @AppStorage("agendaSubfolders") private var agendaSubfolders = false
527 @AppStorage("agendaShowAllDates") private var agendaShowAllDates = false
528 @AppStorage("agendaDimBlockedTasks") private var agendaDimBlockedTasks = "t"
529 @AppStorage("calendarEvents") private var calendarEvents = false
530 @AppStorage("calendarEventCalendars") private var calendarEventCalendars = ""
531 @State private var calendars: [(id: String, title: String, color: RGBA?)] = []
532 @AppStorage("reminders") private var reminders = true
533 @AppStorage("reminderLead") private var reminderLead = 12
534 @AppStorage("clockIdleTime") private var clockIdleTime = 0
535 @AppStorage("clockHistoryLength") private var clockHistoryLength = 5
536 @AppStorage("globalCapture") private var globalCapture = true
537 @AppStorage("settingsTab") private var tab = "general"
538 @AppStorage("showHiddenFiles") private var showHiddenFiles = true
539 @AppStorage("themeFont") private var themeFont = ""
540 @AppStorage("themeFontSize") private var themeFontSize = 13
541 @AppStorage("themeLineSpacing") private var themeLineSpacing = 2
542 @AppStorage("themeHeadingStep") private var themeHeadingStep = 1
543
544 /// Installed monospaced font families.
545 private static let monospacedFamilies: [String] = NSFontManager.shared.availableFontFamilies.filter { family in
546 NSFontManager.shared.font(withFamily: family, traits: [], weight: 5, size: 13)?.isFixedPitch == true
547 }
548
549 var body: some View {
550 TabView(selection: $tab) {
551 Tab("General", systemImage: "gearshape", value: "general") { general }
552 Tab("Editing", systemImage: "text.alignleft", value: "editing") { editing }
553 Tab("Appearance", systemImage: "paintpalette", value: "appearance") { appearance }
554 Tab("Agenda", systemImage: "calendar", value: "agenda") { agenda }
555 Tab("Capture", systemImage: "tray.and.arrow.down", value: "capture") { capture }
556 }
557 .frame(width: 600)
558 }
559
560 private func editConfig() {
561 ConfigSync.shared.start()
562 openWindow(id: "main")
563 commands.jump(path: UserConfig.configFile.path, offset: 0)
564 }
565
566 private var general: some View {
567 Form {
568 Section {
569 LabeledContent("config.toml") {
570 HStack {
571 Button("Edit in Orgstar") { editConfig() }
572 Button("Open with Default App") { NSWorkspace.shared.open(UserConfig.configFile) }
573 Button("Show in Finder") { NSWorkspace.shared.activateFileViewerSelecting([UserConfig.configFile]) }
574 }
575 }
576 LabeledContent("Emacs") {
577 Button("Import from Emacs…") { importing = true }
578 }
579 } footer: {
580 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.")
581 .settingsFooter()
582 }
583 Section {
584 Picker("Save files", selection: $saveMode) {
585 Text("Automatically, when typing stops").tag(SaveMode.automatic)
586 Text("Only with File ▸ Save (⌘S)").tag(SaveMode.explicit)
587 }
588 .pickerStyle(.radioGroup)
589 }
590 Section {
591 Picker("Keys", selection: $preset) {
592 ForEach(KeymapPreset.allCases, id: \.self) { Text($0.title).tag($0) }
593 }
594 Toggle("Show hidden files and folders", isOn: $showHiddenFiles)
595 Picker("Option as Meta", selection: $optionAsMeta) {
596 Text("Left Option").tag(OptionAsMeta.left.rawValue)
597 Text("Right Option").tag(OptionAsMeta.right.rawValue)
598 Text("Both").tag(OptionAsMeta([.left, .right]).rawValue)
599 Text("Neither").tag(0)
600 }
601 } footer: {
602 Text("Your own bindings go in \(KeymapLoader.userFile.path), on top of the preset.")
603 .settingsFooter()
604 }
605 }
606 .formStyle(.grouped)
607 .frame(height: 330)
608 .sheet(isPresented: $importing) { EmacsImportView(workspace: workspace) }
609 }
610
611 private var editing: some View {
612 Form {
613 Section {
614 Picker("Tags", selection: $tagsColumn) {
615 Text("Aligned to end at column 77").tag(-77)
616 Text("One space after the title").tag(0)
617 }
618 Toggle("M-RET adds the new heading after the subtree", isOn: $headingAfterSubtree)
619 Toggle("M-RET splits the line at the caret", isOn: $splitLine)
620 Toggle("Lists can use letters (a. b. c.)", isOn: $alphabeticalLists)
621 Stepper("M-q fills to column \(fillColumn)", value: $fillColumn, in: 40...200)
622 }
623 Section {
624 Toggle("Long lines run off the edge instead of wrapping (org-startup-truncated)", isOn: $startupTruncated)
625 } footer: {
626 Text("Applies to files as they open. View ▸ Truncate or Wrap Long Lines switches the current file.")
627 .settingsFooter()
628 }
629 Section {
630 Toggle("Emacs hides emphasis markers (org-hide-emphasis-markers)", isOn: $hiddenMarkers)
631 Toggle("Emacs shows entities as characters (org-pretty-entities)", isOn: $prettyEntities)
632 } footer: {
633 Text("Tags, tables and M-q measure text as your Emacs displays it, so both write the same file.")
634 .settingsFooter()
635 }
636 Section {
637 TextField("Default TODO keywords", text: $todoKeywords, axis: .vertical)
638 } footer: {
639 Text("For files without #+TODO, in #+TODO syntax, one sequence per line. Takes effect when Orgstar restarts.")
640 .settingsFooter()
641 }
642 Section {
643 Toggle("Entries can't be done before their TODO children (org-enforce-todo-dependencies)", isOn: $enforceTodoDependencies)
644 Toggle("Entries can't be done with unchecked boxes (org-enforce-todo-checkbox-dependencies)", isOn: $enforceTodoCheckboxDependencies)
645 } footer: {
646 Text("Under a parent with the ORDERED property (Toggle ORDERED Property, C-c C-x o), TODO children are also done in order.")
647 .settingsFooter()
648 }
649 }
650 .formStyle(.grouped)
651 .frame(height: 640)
652 }
653
654 private var appearance: some View {
655 Form {
656 Section {
657 Picker("Font", selection: $themeFont) {
658 Text("System monospaced").tag("")
659 Divider()
660 ForEach(Self.monospacedFamilies, id: \.self) { Text($0).tag($0) }
661 if !themeFont.isEmpty, !Self.monospacedFamilies.contains(themeFont) { Text(themeFont).tag(themeFont) }
662 }
663 Stepper("Size: \(themeFontSize) pt", value: $themeFontSize, in: 8...36)
664 Stepper("Line spacing: \(themeLineSpacing) pt", value: $themeLineSpacing, in: 0...16)
665 Stepper("Headings grow by \(themeHeadingStep) pt a level", value: $themeHeadingStep, in: 0...8)
666 } footer: {
667 Text("Tags and tables line up in columns, so a monospaced font keeps them straight.")
668 .settingsFooter()
669 }
670 Section {
671 LabeledContent("Colors") {
672 HStack {
673 Button("Edit in config.toml") { editConfig() }
674 Button("Show Default Theme") {
675 openWindow(id: "main")
676 commands.jump(path: UserConfig.directory.appendingPathComponent("default-theme.toml").path, offset: 0)
677 }
678 }
679 }
680 } footer: {
681 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.")
682 .settingsFooter()
683 }
684 }
685 .formStyle(.grouped)
686 .frame(height: 380)
687 }
688
689 private var agenda: some View {
690 Form {
691 Section {
692 Stepper("Agenda shows \(agendaSpan) days", value: $agendaSpan, in: 1...366)
693 Stepper(agendaStartOffset == 0 ? "Agenda starts today" : "Agenda starts \(-agendaStartOffset) days before today", value: $agendaStartOffset, in: -14...0)
694 Toggle("Include files in subfolders", isOn: $agendaSubfolders)
695 Toggle("Show days without entries", isOn: $agendaShowAllDates)
696 Picker("Blocked entries", selection: $agendaDimBlockedTasks) {
697 Text("Dimmed").tag("t")
698 Text("Hidden").tag("invisible")
699 Text("Shown as usual").tag("nil")
700 }
701 }
702 Section {
703 Toggle("Show events from Calendar", isOn: $calendarEvents)
704 if calendarEvents {
705 if calendars.isEmpty {
706 Text(CalendarEvents.isAuthorized ? "No calendars." : "Allow Orgstar to read your calendars in System Settings ▸ Privacy & Security ▸ Calendars.")
707 .foregroundStyle(.secondary)
708 }
709 ForEach(calendars, id: \.id) { calendar in
710 Toggle(isOn: calendarChosen(calendar)) {
711 HStack(spacing: 6) {
712 Circle()
713 .fill(calendar.color.map { Color(.sRGB, red: $0.red, green: $0.green, blue: $0.blue, opacity: $0.alpha) } ?? .secondary)
714 .frame(width: 8, height: 8)
715 Text(calendar.title)
716 }
717 }
718 }
719 }
720 } footer: {
721 Text("Events show in the agenda read-only; double-click one to open it in Calendar. New calendars show while every calendar is checked.")
722 .settingsFooter()
723 }
724 .task(id: calendarEvents) {
725 let allowed = calendarEvents ? await CalendarAccess.events.requestAccess() : false
726 calendars = allowed ? CalendarAccess.events.calendars() : []
727 }
728 Section {
729 Toggle("Notify before timed agenda entries", isOn: $reminders)
730 Stepper("\(reminderLead) minutes before", value: $reminderLead, in: 0...120)
731 .disabled(!reminders)
732 } footer: {
733 Text("An entry's APPT_WARNTIME property overrides the lead time.")
734 .settingsFooter()
735 }
736 Section {
737 Toggle("Ask what to do with idle time while clocked in", isOn: Binding {
738 clockIdleTime > 0
739 } set: { on in
740 clockIdleTime = on ? 15 : 0
741 })
742 Stepper("After \(max(clockIdleTime, 1)) minutes without keyboard or mouse input", value: $clockIdleTime, in: 1...240)
743 .disabled(clockIdleTime == 0)
744 Stepper("Remember \(clockHistoryLength) recently clocked entries", value: $clockHistoryLength, in: 1...35)
745 } footer: {
746 Text("org-clock-idle-time and org-clock-history-length. Org ▸ Clock lists the recent entries.")
747 .settingsFooter()
748 }
749 }
750 .formStyle(.grouped)
751 .frame(height: 560)
752 }
753
754 /// `calendar-event-calendars`: empty for every calendar, else the titles checked.
755 private func calendarChosen(_ calendar: (id: String, title: String, color: RGBA?)) -> Binding<Bool> {
756 let chosen = calendarEventCalendars.split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
757 return Binding {
758 CalendarEvents.chooses(id: calendar.id, title: calendar.title, chosen: chosen)
759 } set: { on in
760 var titles = calendars.map(\.title).filter { title in
761 chosen.isEmpty || chosen.contains(title) || chosen.contains(calendars.first { $0.title == title }?.id ?? "")
762 }
763 titles.removeAll { $0 == calendar.title }
764 if on { titles.append(calendar.title) }
765 // An empty list means every calendar; turning events off hides them all.
766 guard !titles.isEmpty else { return }
767 calendarEventCalendars = Set(titles) == Set(calendars.map(\.title)) ? "" : titles.joined(separator: ", ")
768 }
769 }
770
771 private var capture: some View {
772 Form {
773 Section {
774 Toggle("⌃⌥Space opens Capture from any app", isOn: $globalCapture)
775 } footer: {
776 Text("Templates go in \(CaptureTemplates.userFile.path).")
777 .settingsFooter()
778 }
779 }
780 .formStyle(.grouped)
781 .frame(height: 160)
782 }
783}
784
785private extension Text {
786 func settingsFooter() -> some View {
787 font(.caption)
788 .foregroundStyle(.secondary)
789 .textSelection(.enabled)
790 .frame(maxWidth: .infinity, alignment: .leading)
791 }
792}