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