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