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