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