Sources/Orgstar/OrgstarApp.swift

1075 lines · 50984 bytes

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