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