Sources/Orgstar/OrgstarApp.swift

963 lines · 46037 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        // Debug builds, and runs with ORGSTAR_PERF set: main-thread stalls in the console.
328        #if DEBUG
329        Perf.watchMainThread()
330        #else
331        if ProcessInfo.processInfo.environment["ORGSTAR_PERF"] != nil { Perf.watchMainThread() }
332        #endif
333    }
334
335    var body: some Scene {
336        Window("orgstar", id: "main") {
337            switch workspace {
338            case .success(let model):
339                ContentView(workspace: model, session: session, commands: commands, scheduler: scheduler, clock: clock)
340                    .environment(\.orgTheme, ConfigSync.shared.theme)
341                    .tint(ConfigSync.shared.theme.color("accent"))
342                    .onAppear {
343                        delegate.session = session
344                        delegate.commands = commands
345                        CaptureIntent.environment = (model, session, clock, commands)
346                    }
347            case .failure(let error):
348                ContentUnavailableView("Can't open the index", systemImage: "exclamationmark.triangle", description: Text(error.localizedDescription))
349            }
350        }
351        .defaultSize(width: 1280, height: 860)
352        WindowGroup("Editor", id: "editor") {
353            if case .success = workspace {
354                EditorWindowView(session: session, commands: commands, clock: clock)
355                    .environment(\.orgTheme, ConfigSync.shared.theme)
356                    .tint(ConfigSync.shared.theme.color("accent"))
357            }
358        }
359        .defaultSize(width: 900, height: 700)
360        .commandsRemoved()
361        Window("Agenda", id: "agenda") {
362            if case .success(let model) = workspace {
363                AgendaView(workspace: model, session: session, commands: commands, scheduler: scheduler, clock: clock)
364                    .environment(\.orgTheme, ConfigSync.shared.theme)
365                    .tint(ConfigSync.shared.theme.color("accent"))
366            }
367        }
368        .defaultSize(width: 760, height: 720)
369        Window("Board", id: "board") {
370            if case .success(let model) = workspace {
371                BoardView(workspace: model, session: session, commands: commands)
372                    .environment(\.orgTheme, ConfigSync.shared.theme)
373                    .tint(ConfigSync.shared.theme.color("accent"))
374            }
375        }
376        .defaultSize(width: 1100, height: 700)
377        Window("Clock Report", id: "clock-report") {
378            if case .success(let model) = workspace {
379                ClockReportView(workspace: model, session: session)
380            }
381        }
382        .defaultSize(width: 860, height: 560)
383        Window("Capture", id: "capture") {
384            if case .success(let model) = workspace {
385                CaptureView(workspace: model, session: session, commands: commands, clock: clock)
386            }
387        }
388        .windowResizability(.contentSize)
389        .windowLevel(.floating)
390        .commands {
391            CommandGroup(after: .newItem) {
392                Button("Add Folder…") { commands.showingFolderPicker = true }
393                    .keyboardShortcut("o", modifiers: [.command, .shift])
394                Button("Quick Open…") { commands.showingQuickOpen = true }
395                    .keyboardShortcut("p")
396                Button("Command Palette…") { commands.showingPalette = true }
397                    .keyboardShortcut("p", modifiers: [.command, .shift])
398            }
399            CommandGroup(after: .saveItem) {
400                Menu("Export") {
401                    ForEach(EditorCommands.all.filter { $0.id.hasPrefix("app.export.") }, id: \.id) { command in
402                        Button(command.title) { commands.run(command.id) }
403                    }
404                }
405                .disabled(session.path == nil)
406                Menu("Publish") {
407                    ForEach(EditorCommands.all.filter { $0.id.hasPrefix("app.publish") }, id: \.id) { command in
408                        Button(command.title) { commands.run(command.id) }
409                    }
410                }
411                Divider()
412                Button("Revert to File on Disk") { commands.run("app.revert") }
413                    .disabled(session.path == nil)
414                Button("Resolve Sync Conflicts…") { commands.run("app.sync-conflicts") }
415                    .disabled(session.path == nil)
416                Button("Recovery Versions…") { commands.run("app.recovery") }
417                    .disabled(session.path == nil)
418            }
419            CommandGroup(replacing: .saveItem) {
420                Button("Close Buffer") {
421                    // ⌘W closes the buffer in the main window, and other windows themselves.
422                    if let key = NSApp.keyWindow, key.identifier?.rawValue.contains("main") != true {
423                        key.performClose(nil)
424                    } else {
425                        commands.run("app.buffer.kill")
426                    }
427                }
428                .keyboardShortcut("w")
429                Button("Close Window") { NSApp.keyWindow?.performClose(nil) }
430                    .keyboardShortcut("w", modifiers: [.command, .shift])
431                Divider()
432                Button("Save") {
433                    if !session.save(), session.conflict != nil { commands.showingConflict = true }
434                }
435                .keyboardShortcut("s")
436                .disabled(session.path == nil || session.isReadOnly)
437                Button("Save All") { commands.run("app.save-all") }
438                    .keyboardShortcut("s", modifiers: [.command, .option])
439                    .disabled(session.dirtyPaths.isEmpty)
440            }
441            CommandGroup(after: .sidebar) {
442                Button("Split Pane Below") { commands.run("app.split-below") }
443                    .keyboardShortcut("2", modifiers: [.command, .control])
444                Button("Split Pane Right") { commands.run("app.split-right") }
445                    .keyboardShortcut("3", modifiers: [.command, .control])
446                Button("Close Pane") { commands.run("app.pane-close") }
447                    .keyboardShortcut("0", modifiers: [.command, .control])
448                Button("Close Other Panes") { commands.run("app.pane-only") }
449                    .keyboardShortcut("1", modifiers: [.command, .control])
450                Button("Next Pane") { commands.run("app.pane-next") }
451                    .keyboardShortcut("`", modifiers: [.command, .option])
452                Divider()
453                Button("Show or Hide Outline") { commands.run("app.toggle-outline") }
454                    .keyboardShortcut("o", modifiers: [.command, .option])
455                Button("Show or Hide Backlinks") { commands.run("app.toggle-backlinks") }
456                Button("Show or Hide Columns and Clock") { commands.run("app.toggle-inspector") }
457                    .keyboardShortcut("i", modifiers: [.command, .option])
458                MarkupToggle()
459                Button("Truncate or Wrap Long Lines") { commands.run("editor.toggle-truncate-lines") }
460                Button("Turn Auto Fill On or Off") { commands.run("editor.toggle-auto-fill") }
461                Button("Check Spelling While Typing") { commands.editor?.run("editor.toggle-spell-check") }
462                    .disabled(commands.editor == nil)
463            }
464            CommandGroup(after: .pasteboard) {
465                Divider()
466                FindMenu(commands: commands)
467            }
468            CommandGroup(after: .textEditing) {
469                Button("Cancel Running Task") { commands.run("app.babel.cancel") }
470                    .keyboardShortcut(".")
471                    .disabled(!session.isRunningBabel && commands.emacsTask == nil)
472                Button("Search Notes") { commands.focusSearch = true }
473                    .keyboardShortcut("f", modifiers: [.command, .shift])
474            }
475            CommandGroup(before: .windowList) {
476                AgendaMenuItem()
477                Divider()
478                Button("Switch to Buffer…") { commands.run("app.buffer.switch") }
479                Button("Next Buffer") { commands.run("app.buffer.next") }
480                    .keyboardShortcut("]", modifiers: [.command, .shift])
481                Button("Previous Buffer") { commands.run("app.buffer.previous") }
482                    .keyboardShortcut("[", modifiers: [.command, .shift])
483                Divider()
484            }
485            CommandGroup(after: .newItem) {
486                Button("Capture…") { commands.run("app.capture") }
487                    .keyboardShortcut("n", modifiers: [.command, .shift])
488                Button("New Window") { commands.run("app.window-new") }
489                    .keyboardShortcut("n", modifiers: [.command, .option])
490            }
491        }
492        .commands {
493            CommandMenu("Org") {
494                ClockMenu(commands: commands, clock: clock)
495                Divider()
496                OrgMenuItems(commands: commands)
497            }
498        }
499        .commands {
500            CommandGroup(after: .appSettings) {
501                Button("Edit Config File") { commands.jump(path: UserConfig.configFile.path, offset: 0) }
502                    .keyboardShortcut(",", modifiers: [.command, .option])
503            }
504            CommandGroup(after: .appInfo) {
505                CheckForUpdatesItem(updates: delegate.updates)
506            }
507        }
508        Settings {
509            SettingsView(commands: commands, workspace: try? workspace.get(), updates: delegate.updates)
510        }
511    }
512}
513
514/// The Org menu: every org command, with the keys that run it in the current keymap.
515struct OrgMenuItems: View {
516    let commands: AppCommands
517
518    var body: some View {
519        ForEach(EditorCommands.all.filter { $0.id.hasPrefix("org.") }, id: \.id) { command in
520            Button {
521                commands.editor?.run(command.id)
522            } label: {
523                Text(command.title)
524                if let keys = commands.keyLabel(for: command.id) { Text(keys) }
525            }
526            .disabled(commands.editor == nil)
527        }
528    }
529}
530
531/// View ▸ Show Markup (link brackets and targets, emphasis markers) and Show Line Numbers.
532struct MarkupToggle: View {
533    @AppStorage("showTabBar") private var showTabBar = false
534    @AppStorage("showMarkup") private var showMarkup = false
535    @AppStorage("showLineNumbers") private var showLineNumbers = false
536    @AppStorage("lineNumbersType") private var lineNumbersType = "t"
537
538    var body: some View {
539        Toggle("Show Markup", isOn: $showMarkup)
540            .keyboardShortcut("m", modifiers: [.command, .shift])
541        Toggle("Show Line Numbers", isOn: $showLineNumbers)
542            .keyboardShortcut("l", modifiers: [.command, .shift])
543        Picker("Line Numbers", selection: $lineNumbersType) {
544            Text("Absolute").tag("t")
545            Text("Relative").tag("relative")
546            Text("Visual").tag("visual")
547        }
548        Toggle("Show Tab Bar", isOn: $showTabBar)
549    }
550}
551
552/// Edit ▸ Find: the editor's find bar.
553struct FindMenu: View {
554    let commands: AppCommands
555
556    var body: some View {
557        Menu("Find") {
558            item("Find…", "edit.find", "f")
559            item("Find and Replace…", "edit.replace", "f", [.command, .option])
560            item("Find Next", "edit.find-next", "g")
561            item("Find Previous", "edit.find-previous", "g", [.command, .shift])
562            item("Use Selection for Find", "edit.use-selection-for-find", "e")
563        }
564    }
565
566    private func item(_ title: String, _ id: String, _ key: KeyEquivalent, _ modifiers: EventModifiers = .command) -> some View {
567        Button(title) { commands.editor?.run(id) }
568            .keyboardShortcut(key, modifiers: modifiers)
569            .disabled(commands.editor == nil)
570    }
571}
572
573/// Window ▸ Agenda.
574struct AgendaMenuItem: View {
575    @Environment(\.openWindow) private var openWindow
576
577    var body: some View {
578        Button("Agenda") { openWindow(id: "agenda") }
579            .keyboardShortcut("a", modifiers: [.command, .shift])
580        Button("Board") { openWindow(id: "board") }
581            .keyboardShortcut("b", modifiers: [.command, .shift])
582    }
583}
584
585struct SettingsView: View {
586    let commands: AppCommands
587    let workspace: WorkspaceModel?
588    let updates: Updates
589    @State private var importing = false
590    @Environment(\.openWindow) private var openWindow
591    @AppStorage("saveMode") private var saveMode = SaveMode.automatic
592    @AppStorage("keymap") private var preset = KeymapPreset.emacs
593    @AppStorage("optionAsMeta") private var optionAsMeta = OptionAsMeta.left.rawValue
594    @AppStorage("tagsColumn") private var tagsColumn = -77
595    @AppStorage("headingAfterSubtree") private var headingAfterSubtree = false
596    @AppStorage("splitLine") private var splitLine = false
597    @AppStorage("alphabeticalLists") private var alphabeticalLists = true
598    @AppStorage("fillColumn") private var fillColumn = 80
599    @AppStorage("hiddenMarkers") private var hiddenMarkers = true
600    @AppStorage("prettyEntities") private var prettyEntities = true
601    @AppStorage("startupTruncated") private var startupTruncated = false
602    @AppStorage("todoKeywords") private var todoKeywords = Preferences.defaultTodoKeywords
603    @AppStorage("logDone") private var logDone = "nil"
604    @AppStorage("logIntoDrawer") private var logIntoDrawer = ""
605    @AppStorage("useSpeedCommands") private var useSpeedCommands = false
606    @AppStorage("spellCheck") private var spellCheck = false
607    @AppStorage("enforceTodoDependencies") private var enforceTodoDependencies = false
608    @AppStorage("enforceTodoCheckboxDependencies") private var enforceTodoCheckboxDependencies = false
609    @AppStorage("agendaSpan") private var agendaSpan = 10
610    @AppStorage("agendaStartOffset") private var agendaStartOffset = 0
611    @AppStorage("agendaSubfolders") private var agendaSubfolders = false
612    @AppStorage("agendaShowAllDates") private var agendaShowAllDates = false
613    @AppStorage("habitsOnlyForToday") private var habitsOnlyForToday = true
614    @AppStorage("agendaDimBlockedTasks") private var agendaDimBlockedTasks = "t"
615    @AppStorage("calendarEvents") private var calendarEvents = false
616    @AppStorage("calendarEventCalendars") private var calendarEventCalendars = ""
617    @State private var calendars: [(id: String, title: String, color: RGBA?)] = []
618    @AppStorage("agendaReminders") private var agendaReminders = false
619    @AppStorage("agendaReminderLists") private var agendaReminderLists = ""
620    @State private var reminderLists: [(id: String, title: String, color: RGBA?)] = []
621    @AppStorage("reminders") private var reminders = true
622    @AppStorage("reminderLead") private var reminderLead = 12
623    @AppStorage("clockIdleTime") private var clockIdleTime = 0
624    @AppStorage("clockHistoryLength") private var clockHistoryLength = 5
625    @AppStorage("globalCapture") private var globalCapture = true
626    @AppStorage("settingsTab") private var tab = "general"
627    @AppStorage("showHiddenFiles") private var showHiddenFiles = true
628    @AppStorage("themeFont") private var themeFont = ""
629    @AppStorage("themeBodyFont") private var themeBodyFont = ""
630    @AppStorage("themeFontSize") private var themeFontSize = 13
631    @AppStorage("themeLineSpacing") private var themeLineSpacing = 2
632    @AppStorage("themeTextWidth") private var themeTextWidth = 0
633    @AppStorage("themeHeadingStep") private var themeHeadingStep = 1
634
635    /// Installed font families that aren't monospaced, for body text.
636    private static let proportionalFamilies: [String] = NSFontManager.shared.availableFontFamilies.filter { family in
637        NSFontManager.shared.font(withFamily: family, traits: [], weight: 5, size: 13)?.isFixedPitch == false
638    }
639
640    /// Installed monospaced font families.
641    private static let monospacedFamilies: [String] = NSFontManager.shared.availableFontFamilies.filter { family in
642        NSFontManager.shared.font(withFamily: family, traits: [], weight: 5, size: 13)?.isFixedPitch == true
643    }
644
645    var body: some View {
646        TabView(selection: $tab) {
647            Tab("General", systemImage: "gearshape", value: "general") { general }
648            Tab("Editing", systemImage: "text.alignleft", value: "editing") { editing }
649            Tab("Appearance", systemImage: "paintpalette", value: "appearance") { appearance }
650            Tab("Agenda", systemImage: "calendar", value: "agenda") { agenda }
651            Tab("Capture", systemImage: "tray.and.arrow.down", value: "capture") { capture }
652        }
653        .frame(width: 600)
654    }
655
656    private func editConfig() {
657        ConfigSync.shared.start()
658        openWindow(id: "main")
659        commands.jump(path: UserConfig.configFile.path, offset: 0)
660    }
661
662    private var general: some View {
663        Form {
664            Section {
665                LabeledContent("config.toml") {
666                    HStack {
667                        Button("Edit in orgstar") { editConfig() }
668                        Button("Open with Default App") { NSWorkspace.shared.open(UserConfig.configFile) }
669                        Button("Show in Finder") { NSWorkspace.shared.activateFileViewerSelecting([UserConfig.configFile]) }
670                    }
671                }
672                LabeledContent("Emacs") {
673                    Button("Import from Emacs…") { importing = true }
674                }
675            } footer: {
676                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.")
677                    .settingsFooter()
678            }
679            if updates.canCheck {
680                Section {
681                    Toggle("Check for updates automatically", isOn: Binding(get: { updates.automatically }, set: { updates.automatically = $0 }))
682                } footer: {
683                    Text("Once a day, from the app's own feed. orgstar ▸ Check for Updates… checks now.")
684                        .settingsFooter()
685                }
686            }
687            Section {
688                Picker("Save files", selection: $saveMode) {
689                    Text("Automatically, when typing stops").tag(SaveMode.automatic)
690                    Text("Only with File ▸ Save (⌘S)").tag(SaveMode.explicit)
691                }
692                .pickerStyle(.radioGroup)
693            }
694            Section {
695                Picker("Keys", selection: $preset) {
696                    ForEach(KeymapPreset.allCases, id: \.self) { Text($0.title).tag($0) }
697                }
698                Toggle("Show hidden files and folders", isOn: $showHiddenFiles)
699                Picker("Option as Meta", selection: $optionAsMeta) {
700                    Text("Left Option").tag(OptionAsMeta.left.rawValue)
701                    Text("Right Option").tag(OptionAsMeta.right.rawValue)
702                    Text("Both").tag(OptionAsMeta([.left, .right]).rawValue)
703                    Text("Neither").tag(0)
704                }
705            } footer: {
706                Text("Your own bindings go in \(KeymapLoader.userFile.path), on top of the preset.")
707                    .settingsFooter()
708            }
709        }
710        .formStyle(.grouped)
711        .frame(height: 330)
712        .sheet(isPresented: $importing) { EmacsImportView(workspace: workspace) }
713    }
714
715    private var editing: some View {
716        Form {
717            Section {
718                Picker("Tags", selection: $tagsColumn) {
719                    Text("Aligned to end at column 77").tag(-77)
720                    Text("One space after the title").tag(0)
721                }
722                Toggle("M-RET adds the new heading after the subtree", isOn: $headingAfterSubtree)
723                Toggle("M-RET splits the line at the caret", isOn: $splitLine)
724                Toggle("Lists can use letters (a. b. c.)", isOn: $alphabeticalLists)
725                Stepper("M-q fills to column \(fillColumn)", value: $fillColumn, in: 40...200)
726            }
727            Section {
728                Toggle("Long lines run off the edge instead of wrapping (org-startup-truncated)", isOn: $startupTruncated)
729            } footer: {
730                Text("Applies to files as they open. View ▸ Truncate or Wrap Long Lines switches the current file.")
731                    .settingsFooter()
732            }
733            Section {
734                Toggle("Emacs hides emphasis markers (org-hide-emphasis-markers)", isOn: $hiddenMarkers)
735                Toggle("Emacs shows entities as characters (org-pretty-entities)", isOn: $prettyEntities)
736            } footer: {
737                Text("Tags, tables and M-q measure text as your Emacs displays it, so both write the same file.")
738                    .settingsFooter()
739            }
740            Section {
741                TextField("Default TODO keywords", text: $todoKeywords, axis: .vertical)
742            } footer: {
743                Text("For files without #+TODO, in #+TODO syntax, one sequence per line. Takes effect when orgstar restarts.")
744                    .settingsFooter()
745            }
746            Section {
747                Toggle("Entries can't be done before their TODO children (org-enforce-todo-dependencies)", isOn: $enforceTodoDependencies)
748                Toggle("Entries can't be done with unchecked boxes (org-enforce-todo-checkbox-dependencies)", isOn: $enforceTodoCheckboxDependencies)
749            } footer: {
750                Text("Under a parent with the ORDERED property (Toggle ORDERED Property, C-c C-x o), TODO children are also done in order.")
751                    .settingsFooter()
752            }
753            Section {
754                Picker("When an entry is done (org-log-done)", selection: $logDone) {
755                    Text("Record nothing").tag("nil")
756                    Text("Record the time, as CLOSED").tag("time")
757                    Text("Record the time and ask for a note").tag("note")
758                }
759                Toggle("State notes go in a LOGBOOK drawer (org-log-into-drawer)", isOn: logIntoDrawerOn)
760            } footer: {
761                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.")
762                    .settingsFooter()
763            }
764            Section {
765                Toggle("Speed keys: single letters at the start of a heading line run commands (org-use-speed-commands)", isOn: $useSpeedCommands)
766                Toggle("Check spelling while typing (spell-check)", isOn: $spellCheck)
767            } footer: {
768                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.")
769                    .settingsFooter()
770            }
771        }
772        .formStyle(.grouped)
773        .frame(height: 860)
774    }
775
776    /// `org-log-into-drawer` as a switch: on is "LOGBOOK" (Emacs's t); a drawer name of its own counts as on.
777    private var logIntoDrawerOn: Binding<Bool> {
778        Binding(get: { !logIntoDrawer.isEmpty }, set: { logIntoDrawer = $0 ? "LOGBOOK" : "" })
779    }
780
781    private var appearance: some View {
782        Form {
783            ThemePickerSection()
784            AppIconSection()
785            Section {
786                Picker("Font", selection: $themeFont) {
787                    Text("System monospaced").tag("")
788                    Divider()
789                    ForEach(Self.monospacedFamilies, id: \.self) { Text($0).tag($0) }
790                    if !themeFont.isEmpty, !Self.monospacedFamilies.contains(themeFont) { Text(themeFont).tag(themeFont) }
791                }
792                Picker("Body text", selection: $themeBodyFont) {
793                    Text("Same as Font").tag("")
794                    Text("System").tag("system")
795                    Divider()
796                    ForEach(Self.proportionalFamilies, id: \.self) { Text($0).tag($0) }
797                    if !["", "system"].contains(themeBodyFont), !Self.proportionalFamilies.contains(themeBodyFont) { Text(themeBodyFont).tag(themeBodyFont) }
798                }
799                Stepper("Size: \(themeFontSize) pt", value: $themeFontSize, in: 8...36)
800                Stepper("Line spacing: \(themeLineSpacing) pt", value: $themeLineSpacing, in: 0...16)
801                Picker("Text width", selection: $themeTextWidth) {
802                    Text("Whole editor").tag(0)
803                    ForEach([60, 70, 80, 90, 100, 120], id: \.self) { Text("\($0) columns").tag($0) }
804                    if ![0, 60, 70, 80, 90, 100, 120].contains(themeTextWidth) { Text("\(themeTextWidth) columns").tag(themeTextWidth) }
805                }
806                Stepper("Headings grow by \(themeHeadingStep) pt a level", value: $themeHeadingStep, in: 0...8)
807            } footer: {
808                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.")
809                    .settingsFooter()
810            }
811            Section {
812                LabeledContent("Colors") {
813                    HStack {
814                        Button("Edit in config.toml") { editConfig() }
815                        Button("Show Default Theme") {
816                            openWindow(id: "main")
817                            commands.jump(path: UserConfig.directory.appendingPathComponent("default-theme.toml").path, offset: 0)
818                        }
819                    }
820                }
821            } footer: {
822                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.")
823                    .settingsFooter()
824            }
825        }
826        .formStyle(.grouped)
827        .frame(height: 620)
828    }
829
830    private var agenda: some View {
831        Form {
832            Section {
833                Stepper("Agenda shows \(agendaSpan) days", value: $agendaSpan, in: 1...366)
834                Stepper(agendaStartOffset == 0 ? "Agenda starts today" : "Agenda starts \(-agendaStartOffset) days before today", value: $agendaStartOffset, in: -14...0)
835                Toggle("Include files in subfolders", isOn: $agendaSubfolders)
836                Toggle("Show days without entries", isOn: $agendaShowAllDates)
837                Toggle("Habits only today", isOn: $habitsOnlyForToday)
838                Picker("Blocked entries", selection: $agendaDimBlockedTasks) {
839                    Text("Dimmed").tag("t")
840                    Text("Hidden").tag("invisible")
841                    Text("Shown as usual").tag("nil")
842                }
843            }
844            Section {
845                Toggle("Show events from Calendar", isOn: $calendarEvents)
846                if calendarEvents {
847                    if calendars.isEmpty {
848                        Text(CalendarEvents.isAuthorized ? "No calendars." : "Allow orgstar to read your calendars in System Settings ▸ Privacy & Security ▸ Calendars.")
849                            .foregroundStyle(.secondary)
850                    }
851                    ForEach(calendars, id: \.id) { calendar in
852                        Toggle(isOn: chosen(calendar, among: calendars, setting: $calendarEventCalendars)) {
853                            HStack(spacing: 6) {
854                                Circle()
855                                    .fill(calendar.color.map { Color(.sRGB, red: $0.red, green: $0.green, blue: $0.blue, opacity: $0.alpha) } ?? .secondary)
856                                    .frame(width: 8, height: 8)
857                                Text(calendar.title)
858                            }
859                        }
860                    }
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                if agendaReminders {
873                    if reminderLists.isEmpty {
874                        Text(ReminderLists.isAuthorized ? "No lists." : "Allow orgstar to read your reminders in System Settings ▸ Privacy & Security ▸ Reminders.")
875                            .foregroundStyle(.secondary)
876                    }
877                    ForEach(reminderLists, id: \.id) { list in
878                        Toggle(isOn: chosen(list, among: reminderLists, setting: $agendaReminderLists)) {
879                            HStack(spacing: 6) {
880                                Circle()
881                                    .fill(list.color.map { Color(.sRGB, red: $0.red, green: $0.green, blue: $0.blue, opacity: $0.alpha) } ?? .secondary)
882                                    .frame(width: 8, height: 8)
883                                Text(list.title)
884                            }
885                        }
886                    }
887                }
888            } footer: {
889                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.")
890                    .settingsFooter()
891            }
892            .task(id: agendaReminders) {
893                let allowed = agendaReminders ? await CalendarAccess.reminders.requestAccess() : false
894                reminderLists = allowed ? CalendarAccess.reminders.lists() : []
895            }
896            Section {
897                Toggle("Notify before timed agenda entries", isOn: $reminders)
898                Stepper("\(reminderLead) minutes before", value: $reminderLead, in: 0...120)
899                    .disabled(!reminders)
900            } footer: {
901                Text("An entry's APPT_WARNTIME property overrides the lead time.")
902                    .settingsFooter()
903            }
904            Section {
905                Toggle("Ask what to do with idle time while clocked in", isOn: Binding {
906                    clockIdleTime > 0
907                } set: { on in
908                    clockIdleTime = on ? 15 : 0
909                })
910                Stepper("After \(max(clockIdleTime, 1)) minutes without keyboard or mouse input", value: $clockIdleTime, in: 1...240)
911                    .disabled(clockIdleTime == 0)
912                Stepper("Remember \(clockHistoryLength) recently clocked entries", value: $clockHistoryLength, in: 1...35)
913            } footer: {
914                Text("org-clock-idle-time and org-clock-history-length. Org ▸ Clock lists the recent entries.")
915                    .settingsFooter()
916            }
917        }
918        .formStyle(.grouped)
919        .frame(height: 560)
920    }
921
922    /// `calendar-event-calendars` and `agenda-reminder-lists`: empty for every calendar or
923    /// list, else the titles checked.
924    private func chosen(
925        _ calendar: (id: String, title: String, color: RGBA?), among calendars: [(id: String, title: String, color: RGBA?)], setting: Binding<String>
926    ) -> Binding<Bool> {
927        let chosen = setting.wrappedValue.split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
928        return Binding {
929            CalendarEvents.chooses(id: calendar.id, title: calendar.title, chosen: chosen)
930        } set: { on in
931            var titles = calendars.map(\.title).filter { title in
932                chosen.isEmpty || chosen.contains(title) || chosen.contains(calendars.first { $0.title == title }?.id ?? "")
933            }
934            titles.removeAll { $0 == calendar.title }
935            if on { titles.append(calendar.title) }
936            // An empty list means every calendar; turning events off hides them all.
937            guard !titles.isEmpty else { return }
938            setting.wrappedValue = Set(titles) == Set(calendars.map(\.title)) ? "" : titles.joined(separator: ", ")
939        }
940    }
941
942    private var capture: some View {
943        Form {
944            Section {
945                Toggle("⌃⌥Space opens Capture from any app", isOn: $globalCapture)
946            } footer: {
947                Text("Templates go in \(CaptureTemplates.userFile.path).")
948                    .settingsFooter()
949            }
950        }
951        .formStyle(.grouped)
952        .frame(height: 160)
953    }
954}
955
956extension Text {
957    func settingsFooter() -> some View {
958        font(.caption)
959            .foregroundStyle(.secondary)
960            .textSelection(.enabled)
961            .frame(maxWidth: .infinity, alignment: .leading)
962    }
963}