Sources/Orgstar/OrgstarApp.swift

design-themes-widgets
orgstar/Sources/Orgstar/OrgstarApp.swift history · blame · raw

1098 lines · 52295 bytes

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