Sources/Orgstar/OrgstarApp.swift
843 lines · 38737 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 }
432 CommandGroup(after: .pasteboard) {
433 Divider()
434 FindMenu(commands: commands)
435 }
436 CommandGroup(after: .textEditing) {
437 Button("Cancel Running Task") { commands.run("app.babel.cancel") }
438 .keyboardShortcut(".")
439 .disabled(!session.isRunningBabel && commands.emacsTask == nil)
440 Button("Search Notes") { commands.focusSearch = true }
441 .keyboardShortcut("f", modifiers: [.command, .shift])
442 }
443 CommandGroup(before: .windowList) {
444 AgendaMenuItem()
445 Divider()
446 Button("Switch to Buffer…") { commands.run("app.buffer.switch") }
447 Button("Next Buffer") { commands.run("app.buffer.next") }
448 .keyboardShortcut("]", modifiers: [.command, .shift])
449 Button("Previous Buffer") { commands.run("app.buffer.previous") }
450 .keyboardShortcut("[", modifiers: [.command, .shift])
451 Divider()
452 }
453 CommandGroup(after: .newItem) {
454 Button("Capture…") { commands.run("app.capture") }
455 .keyboardShortcut("n", modifiers: [.command, .shift])
456 Button("New Window") { commands.run("app.window-new") }
457 .keyboardShortcut("n", modifiers: [.command, .option])
458 }
459 }
460 .commands {
461 CommandMenu("Org") {
462 ClockMenu(commands: commands, clock: clock)
463 Divider()
464 OrgMenuItems(commands: commands)
465 }
466 }
467 .commands {
468 CommandGroup(after: .appSettings) {
469 Button("Edit Config File") { commands.jump(path: UserConfig.configFile.path, offset: 0) }
470 .keyboardShortcut(",", modifiers: [.command, .option])
471 }
472 CommandGroup(after: .appInfo) {
473 CheckForUpdatesItem(updates: delegate.updates)
474 }
475 }
476 Settings {
477 SettingsView(commands: commands, workspace: try? workspace.get(), updates: delegate.updates)
478 }
479 }
480}
481
482/// The Org menu: every org command, with the keys that run it in the current keymap.
483struct OrgMenuItems: View {
484 let commands: AppCommands
485
486 var body: some View {
487 ForEach(EditorCommands.all.filter { $0.id.hasPrefix("org.") }, id: \.id) { command in
488 Button {
489 commands.editor?.run(command.id)
490 } label: {
491 Text(command.title)
492 if let keys = commands.keyLabel(for: command.id) { Text(keys) }
493 }
494 .disabled(commands.editor == nil)
495 }
496 }
497}
498
499/// View ▸ Show Markup (link brackets and targets, emphasis markers) and Show Line Numbers.
500struct MarkupToggle: View {
501 @AppStorage("showTabBar") private var showTabBar = false
502 @AppStorage("showMarkup") private var showMarkup = false
503 @AppStorage("showLineNumbers") private var showLineNumbers = true
504
505 var body: some View {
506 Toggle("Show Markup", isOn: $showMarkup)
507 .keyboardShortcut("m", modifiers: [.command, .shift])
508 Toggle("Show Line Numbers", isOn: $showLineNumbers)
509 .keyboardShortcut("l", modifiers: [.command, .shift])
510 Toggle("Show Tab Bar", isOn: $showTabBar)
511 }
512}
513
514/// Edit ▸ Find: the editor's find bar.
515struct FindMenu: View {
516 let commands: AppCommands
517
518 var body: some View {
519 Menu("Find") {
520 item("Find…", "edit.find", "f")
521 item("Find and Replace…", "edit.replace", "f", [.command, .option])
522 item("Find Next", "edit.find-next", "g")
523 item("Find Previous", "edit.find-previous", "g", [.command, .shift])
524 item("Use Selection for Find", "edit.use-selection-for-find", "e")
525 }
526 }
527
528 private func item(_ title: String, _ id: String, _ key: KeyEquivalent, _ modifiers: EventModifiers = .command) -> some View {
529 Button(title) { commands.editor?.run(id) }
530 .keyboardShortcut(key, modifiers: modifiers)
531 .disabled(commands.editor == nil)
532 }
533}
534
535/// Window ▸ Agenda.
536struct AgendaMenuItem: View {
537 @Environment(\.openWindow) private var openWindow
538
539 var body: some View {
540 Button("Agenda") { openWindow(id: "agenda") }
541 .keyboardShortcut("a", modifiers: [.command, .shift])
542 Button("Board") { openWindow(id: "board") }
543 .keyboardShortcut("b", modifiers: [.command, .shift])
544 }
545}
546
547struct SettingsView: View {
548 let commands: AppCommands
549 let workspace: WorkspaceModel?
550 let updates: Updates
551 @State private var importing = false
552 @Environment(\.openWindow) private var openWindow
553 @AppStorage("saveMode") private var saveMode = SaveMode.automatic
554 @AppStorage("keymap") private var preset = KeymapPreset.emacs
555 @AppStorage("optionAsMeta") private var optionAsMeta = OptionAsMeta.left.rawValue
556 @AppStorage("tagsColumn") private var tagsColumn = -77
557 @AppStorage("headingAfterSubtree") private var headingAfterSubtree = true
558 @AppStorage("splitLine") private var splitLine = false
559 @AppStorage("alphabeticalLists") private var alphabeticalLists = true
560 @AppStorage("fillColumn") private var fillColumn = 80
561 @AppStorage("hiddenMarkers") private var hiddenMarkers = true
562 @AppStorage("prettyEntities") private var prettyEntities = true
563 @AppStorage("startupTruncated") private var startupTruncated = false
564 @AppStorage("todoKeywords") private var todoKeywords = Preferences.defaultTodoKeywords
565 @AppStorage("enforceTodoDependencies") private var enforceTodoDependencies = false
566 @AppStorage("enforceTodoCheckboxDependencies") private var enforceTodoCheckboxDependencies = false
567 @AppStorage("agendaSpan") private var agendaSpan = 10
568 @AppStorage("agendaStartOffset") private var agendaStartOffset = 0
569 @AppStorage("agendaSubfolders") private var agendaSubfolders = false
570 @AppStorage("agendaShowAllDates") private var agendaShowAllDates = false
571 @AppStorage("agendaDimBlockedTasks") private var agendaDimBlockedTasks = "t"
572 @AppStorage("calendarEvents") private var calendarEvents = false
573 @AppStorage("calendarEventCalendars") private var calendarEventCalendars = ""
574 @State private var calendars: [(id: String, title: String, color: RGBA?)] = []
575 @AppStorage("reminders") private var reminders = true
576 @AppStorage("reminderLead") private var reminderLead = 12
577 @AppStorage("clockIdleTime") private var clockIdleTime = 0
578 @AppStorage("clockHistoryLength") private var clockHistoryLength = 5
579 @AppStorage("globalCapture") private var globalCapture = true
580 @AppStorage("settingsTab") private var tab = "general"
581 @AppStorage("showHiddenFiles") private var showHiddenFiles = true
582 @AppStorage("themeFont") private var themeFont = ""
583 @AppStorage("themeFontSize") private var themeFontSize = 13
584 @AppStorage("themeLineSpacing") private var themeLineSpacing = 2
585 @AppStorage("themeHeadingStep") private var themeHeadingStep = 1
586
587 /// Installed monospaced font families.
588 private static let monospacedFamilies: [String] = NSFontManager.shared.availableFontFamilies.filter { family in
589 NSFontManager.shared.font(withFamily: family, traits: [], weight: 5, size: 13)?.isFixedPitch == true
590 }
591
592 var body: some View {
593 TabView(selection: $tab) {
594 Tab("General", systemImage: "gearshape", value: "general") { general }
595 Tab("Editing", systemImage: "text.alignleft", value: "editing") { editing }
596 Tab("Appearance", systemImage: "paintpalette", value: "appearance") { appearance }
597 Tab("Agenda", systemImage: "calendar", value: "agenda") { agenda }
598 Tab("Capture", systemImage: "tray.and.arrow.down", value: "capture") { capture }
599 }
600 .frame(width: 600)
601 }
602
603 private func editConfig() {
604 ConfigSync.shared.start()
605 openWindow(id: "main")
606 commands.jump(path: UserConfig.configFile.path, offset: 0)
607 }
608
609 private var general: some View {
610 Form {
611 Section {
612 LabeledContent("config.toml") {
613 HStack {
614 Button("Edit in orgstar") { editConfig() }
615 Button("Open with Default App") { NSWorkspace.shared.open(UserConfig.configFile) }
616 Button("Show in Finder") { NSWorkspace.shared.activateFileViewerSelecting([UserConfig.configFile]) }
617 }
618 }
619 LabeledContent("Emacs") {
620 Button("Import from Emacs…") { importing = true }
621 }
622 } footer: {
623 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.")
624 .settingsFooter()
625 }
626 if updates.canCheck {
627 Section {
628 Toggle("Check for updates automatically", isOn: Binding(get: { updates.automatically }, set: { updates.automatically = $0 }))
629 } footer: {
630 Text("Once a day, from the app's own feed. orgstar ▸ Check for Updates… checks now.")
631 .settingsFooter()
632 }
633 }
634 Section {
635 Picker("Save files", selection: $saveMode) {
636 Text("Automatically, when typing stops").tag(SaveMode.automatic)
637 Text("Only with File ▸ Save (⌘S)").tag(SaveMode.explicit)
638 }
639 .pickerStyle(.radioGroup)
640 }
641 Section {
642 Picker("Keys", selection: $preset) {
643 ForEach(KeymapPreset.allCases, id: \.self) { Text($0.title).tag($0) }
644 }
645 Toggle("Show hidden files and folders", isOn: $showHiddenFiles)
646 Picker("Option as Meta", selection: $optionAsMeta) {
647 Text("Left Option").tag(OptionAsMeta.left.rawValue)
648 Text("Right Option").tag(OptionAsMeta.right.rawValue)
649 Text("Both").tag(OptionAsMeta([.left, .right]).rawValue)
650 Text("Neither").tag(0)
651 }
652 } footer: {
653 Text("Your own bindings go in \(KeymapLoader.userFile.path), on top of the preset.")
654 .settingsFooter()
655 }
656 }
657 .formStyle(.grouped)
658 .frame(height: 330)
659 .sheet(isPresented: $importing) { EmacsImportView(workspace: workspace) }
660 }
661
662 private var editing: some View {
663 Form {
664 Section {
665 Picker("Tags", selection: $tagsColumn) {
666 Text("Aligned to end at column 77").tag(-77)
667 Text("One space after the title").tag(0)
668 }
669 Toggle("M-RET adds the new heading after the subtree", isOn: $headingAfterSubtree)
670 Toggle("M-RET splits the line at the caret", isOn: $splitLine)
671 Toggle("Lists can use letters (a. b. c.)", isOn: $alphabeticalLists)
672 Stepper("M-q fills to column \(fillColumn)", value: $fillColumn, in: 40...200)
673 }
674 Section {
675 Toggle("Long lines run off the edge instead of wrapping (org-startup-truncated)", isOn: $startupTruncated)
676 } footer: {
677 Text("Applies to files as they open. View ▸ Truncate or Wrap Long Lines switches the current file.")
678 .settingsFooter()
679 }
680 Section {
681 Toggle("Emacs hides emphasis markers (org-hide-emphasis-markers)", isOn: $hiddenMarkers)
682 Toggle("Emacs shows entities as characters (org-pretty-entities)", isOn: $prettyEntities)
683 } footer: {
684 Text("Tags, tables and M-q measure text as your Emacs displays it, so both write the same file.")
685 .settingsFooter()
686 }
687 Section {
688 TextField("Default TODO keywords", text: $todoKeywords, axis: .vertical)
689 } footer: {
690 Text("For files without #+TODO, in #+TODO syntax, one sequence per line. Takes effect when orgstar restarts.")
691 .settingsFooter()
692 }
693 Section {
694 Toggle("Entries can't be done before their TODO children (org-enforce-todo-dependencies)", isOn: $enforceTodoDependencies)
695 Toggle("Entries can't be done with unchecked boxes (org-enforce-todo-checkbox-dependencies)", isOn: $enforceTodoCheckboxDependencies)
696 } footer: {
697 Text("Under a parent with the ORDERED property (Toggle ORDERED Property, C-c C-x o), TODO children are also done in order.")
698 .settingsFooter()
699 }
700 }
701 .formStyle(.grouped)
702 .frame(height: 640)
703 }
704
705 private var appearance: some View {
706 Form {
707 Section {
708 Picker("Font", selection: $themeFont) {
709 Text("System monospaced").tag("")
710 Divider()
711 ForEach(Self.monospacedFamilies, id: \.self) { Text($0).tag($0) }
712 if !themeFont.isEmpty, !Self.monospacedFamilies.contains(themeFont) { Text(themeFont).tag(themeFont) }
713 }
714 Stepper("Size: \(themeFontSize) pt", value: $themeFontSize, in: 8...36)
715 Stepper("Line spacing: \(themeLineSpacing) pt", value: $themeLineSpacing, in: 0...16)
716 Stepper("Headings grow by \(themeHeadingStep) pt a level", value: $themeHeadingStep, in: 0...8)
717 } footer: {
718 Text("Tags and tables line up in columns, so a monospaced font keeps them straight.")
719 .settingsFooter()
720 }
721 Section {
722 LabeledContent("Colors") {
723 HStack {
724 Button("Edit in config.toml") { editConfig() }
725 Button("Show Default Theme") {
726 openWindow(id: "main")
727 commands.jump(path: UserConfig.directory.appendingPathComponent("default-theme.toml").path, offset: 0)
728 }
729 }
730 }
731 } footer: {
732 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.")
733 .settingsFooter()
734 }
735 }
736 .formStyle(.grouped)
737 .frame(height: 380)
738 }
739
740 private var agenda: some View {
741 Form {
742 Section {
743 Stepper("Agenda shows \(agendaSpan) days", value: $agendaSpan, in: 1...366)
744 Stepper(agendaStartOffset == 0 ? "Agenda starts today" : "Agenda starts \(-agendaStartOffset) days before today", value: $agendaStartOffset, in: -14...0)
745 Toggle("Include files in subfolders", isOn: $agendaSubfolders)
746 Toggle("Show days without entries", isOn: $agendaShowAllDates)
747 Picker("Blocked entries", selection: $agendaDimBlockedTasks) {
748 Text("Dimmed").tag("t")
749 Text("Hidden").tag("invisible")
750 Text("Shown as usual").tag("nil")
751 }
752 }
753 Section {
754 Toggle("Show events from Calendar", isOn: $calendarEvents)
755 if calendarEvents {
756 if calendars.isEmpty {
757 Text(CalendarEvents.isAuthorized ? "No calendars." : "Allow orgstar to read your calendars in System Settings ▸ Privacy & Security ▸ Calendars.")
758 .foregroundStyle(.secondary)
759 }
760 ForEach(calendars, id: \.id) { calendar in
761 Toggle(isOn: calendarChosen(calendar)) {
762 HStack(spacing: 6) {
763 Circle()
764 .fill(calendar.color.map { Color(.sRGB, red: $0.red, green: $0.green, blue: $0.blue, opacity: $0.alpha) } ?? .secondary)
765 .frame(width: 8, height: 8)
766 Text(calendar.title)
767 }
768 }
769 }
770 }
771 } footer: {
772 Text("Events show in the agenda read-only; double-click one to open it in Calendar. New calendars show while every calendar is checked.")
773 .settingsFooter()
774 }
775 .task(id: calendarEvents) {
776 let allowed = calendarEvents ? await CalendarAccess.events.requestAccess() : false
777 calendars = allowed ? CalendarAccess.events.calendars() : []
778 }
779 Section {
780 Toggle("Notify before timed agenda entries", isOn: $reminders)
781 Stepper("\(reminderLead) minutes before", value: $reminderLead, in: 0...120)
782 .disabled(!reminders)
783 } footer: {
784 Text("An entry's APPT_WARNTIME property overrides the lead time.")
785 .settingsFooter()
786 }
787 Section {
788 Toggle("Ask what to do with idle time while clocked in", isOn: Binding {
789 clockIdleTime > 0
790 } set: { on in
791 clockIdleTime = on ? 15 : 0
792 })
793 Stepper("After \(max(clockIdleTime, 1)) minutes without keyboard or mouse input", value: $clockIdleTime, in: 1...240)
794 .disabled(clockIdleTime == 0)
795 Stepper("Remember \(clockHistoryLength) recently clocked entries", value: $clockHistoryLength, in: 1...35)
796 } footer: {
797 Text("org-clock-idle-time and org-clock-history-length. Org ▸ Clock lists the recent entries.")
798 .settingsFooter()
799 }
800 }
801 .formStyle(.grouped)
802 .frame(height: 560)
803 }
804
805 /// `calendar-event-calendars`: empty for every calendar, else the titles checked.
806 private func calendarChosen(_ calendar: (id: String, title: String, color: RGBA?)) -> Binding<Bool> {
807 let chosen = calendarEventCalendars.split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
808 return Binding {
809 CalendarEvents.chooses(id: calendar.id, title: calendar.title, chosen: chosen)
810 } set: { on in
811 var titles = calendars.map(\.title).filter { title in
812 chosen.isEmpty || chosen.contains(title) || chosen.contains(calendars.first { $0.title == title }?.id ?? "")
813 }
814 titles.removeAll { $0 == calendar.title }
815 if on { titles.append(calendar.title) }
816 // An empty list means every calendar; turning events off hides them all.
817 guard !titles.isEmpty else { return }
818 calendarEventCalendars = Set(titles) == Set(calendars.map(\.title)) ? "" : titles.joined(separator: ", ")
819 }
820 }
821
822 private var capture: some View {
823 Form {
824 Section {
825 Toggle("⌃⌥Space opens Capture from any app", isOn: $globalCapture)
826 } footer: {
827 Text("Templates go in \(CaptureTemplates.userFile.path).")
828 .settingsFooter()
829 }
830 }
831 .formStyle(.grouped)
832 .frame(height: 160)
833 }
834}
835
836private extension Text {
837 func settingsFooter() -> some View {
838 font(.caption)
839 .foregroundStyle(.secondary)
840 .textSelection(.enabled)
841 .frame(maxWidth: .infinity, alignment: .leading)
842 }
843}