Sources/Orgstar/OrgstarApp.swift

4d8e517de5aef10e915fb482735feba5435a4a21
orgstar/Sources/Orgstar/OrgstarApp.swift

1569 lines · 77572 bytes

60 symbols in this file
   1import AppKit
   2import OrgApp
   3import OrgCore
   4import OrgEditorAppKit
   5import OrgIndex
   6import OrgMathJax
   7import OrgPresentation
   8#if !APPSTORE
   9import OrgPrograms
  10#endif
  11import SwiftUI
  12import UserNotifications
  13
  14/// Window-level requests the menu bar makes.
  15@MainActor
  16@Observable
  17final class AppCommands {
  18    var showingQuickOpen = false
  19    var showingFolderPicker = false
  20    /// The first-launch sheet, while no folder has been added.
  21    var showingWelcome = false
  22    /// The notes the main window shows as a sheet.
  23    var whatsNew: ReleaseNotes?
  24    var focusSearch = false
  25    var showingConflict = false
  26    var showingPalette = false
  27    var showingMessages = false
  28    /// The main window's outline pane is shown, for View ▸ Show Outline.
  29    var outlineShown = false
  30    /// Lint All Folders' last run, which its window shows.
  31    let folderLint = FolderLint()
  32    /// A location another window asked the main window to show.
  33    private(set) var jumpRequest: (path: String, offset: Int, id: Int)?
  34    private var jumpID = 0
  35    /// Days the agenda window should show, from a followed timestamp.
  36    var agendaRequest: (start: Int, days: Int)?
  37    /// File ▸ Print… with the agenda window in front: the agenda window prints what it shows.
  38    var agendaPrintRequested = false
  39    /// The editor with focus, for menus and the palette.
  40    var editor: OrgEditor?
  41    /// The editors and text views of every pane in every window.
  42    let store = EditorStore()
  43    /// The main window is on screen. App commands run there, so an editor window reopens it
  44    /// before asking for one.
  45    var mainWindowOpen = false
  46    /// What every editor is set up with, from the settings; the main window keeps it current.
  47    var editorSettings = EditorSettings()
  48    /// Runs work outside the text (a table recalculation in Emacs); the main window sets it.
  49    var externalHandler: ((ExternalRequest) -> Void)?
  50    /// Runs a user command and says when it has finished; the main window sets it.
  51    var userCommandHandler: ((UserCommandRequest, @escaping @MainActor (String?) -> Void) -> Void)?
  52    /// Files and images pasted or dropped on an editor; the main window sets them.
  53    var filesHandler: (([URL]) -> Void)?
  54    var imageHandler: ((Data, String) -> Void)?
  55    #if APPSTORE
  56    /// Asks for the folders outside the sidebar's folders that paths need; the main window sets it.
  57    var reach: ([String]) -> Bool = { _ in true }
  58    #endif
  59    /// Tags used across the workspace, for tag completion; the main window sets it.
  60    var knownTags: () -> [String] = { [] }
  61    /// The index completion asks for headings, values and words; the main window sets it.
  62    var completionIndex: IndexStore?
  63    /// The pending key prefix, and what can follow it.
  64    var pendingKeys: String?
  65    /// The editor's evil state in the Doom preset.
  66    var editorState: String?
  67    /// The keymap in use, for showing keys in menus and the palette.
  68    var keymap = KeymapPreset.emacs.keymap
  69    var modal = false
  70    /// `org-stored-links`, most recent first; kept for the session, as in Emacs.
  71    var storedLinks: [StoredLink] = []
  72
  73    /// Puts `link` first in `storedLinks` and says what happened.
  74    func storeLink(_ link: StoredLink) {
  75        show(StoredLink.add(link, to: &storedLinks))
  76    }
  77
  78    /// The keys that run `command`, as menus and the palette show them.
  79    func keyLabel(for command: String) -> String? {
  80        let labels = keymap.keyLabels(for: command, modes: modal ? ["normal", "insert"] : [nil])
  81        return labels.isEmpty ? nil : labels.joined(separator: ", ")
  82    }
  83
  84    /// The editor's selection, for the modeline.
  85    var selection = NSRange(location: 0, length: 0)
  86    /// The focused file and caret, advertised for Handoff.
  87    @ObservationIgnored let handoff = HandoffAdvertiser()
  88    /// Opens a file continued from another device; the main window sets it.
  89    @ObservationIgnored var continueHandoff: ((HandoffPlace) -> Void)?
  90    var keyHints: [KeyHint] = []
  91    /// A question a command asked, answered in the echo area.
  92    private(set) var prompt: PromptRequest?
  93    /// The last message from a command or the keymap, kept until the next key or click, as
  94    /// Emacs keeps it.
  95    private(set) var message: String?
  96    /// Recent messages, oldest first, for Messages.
  97    private(set) var messages: [String] = []
  98    @ObservationIgnored private var inputMonitor: Any?
  99
 100    func ask(_ prompt: Prompt, reply: @escaping (String?) -> Void) {
 101        self.prompt = PromptRequest(prompt: prompt, reply: reply)
 102    }
 103
 104    /// Asks with `detail` shown in full above the question.
 105    func ask(_ prompt: Prompt, detail: String, reply: @escaping (String?) -> Void) {
 106        self.prompt = PromptRequest(prompt: prompt, detail: detail, reply: reply)
 107    }
 108
 109    /// Clock questions in the echo area.
 110    var askClock: ClockModel.Ask {
 111        { [self] prompt in
 112            await withCheckedContinuation { continuation in
 113                ask(prompt) { continuation.resume(returning: $0) }
 114            }
 115        }
 116    }
 117
 118    /// Ends the prompt with an answer, or nil to cancel, and gives the editor the keys back.
 119    func answer(_ text: String?) {
 120        guard let request = prompt else { return }
 121        prompt = nil
 122        if let textView = editor?.textView { textView.window?.makeFirstResponder(textView) }
 123        request.reply(text)
 124    }
 125
 126    /// An export or table recalculation running in Emacs, for Cancel Running Task.
 127    private(set) var emacsTask: Task<Void, Never>?
 128    private var emacsSerial = 0
 129
 130    /// Runs `work` as the Emacs task, cancelling the one before.
 131    func runInEmacs(_ work: @escaping @MainActor () async -> Void) {
 132        emacsTask?.cancel()
 133        emacsSerial += 1
 134        let serial = emacsSerial
 135        emacsTask = Task {
 136            await work()
 137            if emacsSerial == serial { emacsTask = nil }
 138        }
 139    }
 140
 141    /// An app command from a menu, run by the main window.
 142    private(set) var runRequest: (id: String, serial: Int)?
 143    private var runSerial = 0
 144
 145    func run(_ id: String) {
 146        runSerial += 1
 147        runRequest = (id, runSerial)
 148    }
 149
 150    /// A capture waiting for the capture window: the template key and the link properties for
 151    /// its escapes (org-protocol), or the agenda day to schedule the entry on.
 152    var captureRequest: (template: String?, properties: [String: String], day: Int?, serial: Int)?
 153    private var captureSerial = 0
 154
 155    /// An org-roam capture waiting for the capture window, with its templates in place of
 156    /// capture.toml's.
 157    var roamCapture: RoamCapture?
 158    /// An org-roam-protocol link waiting for the main window.
 159    var roamProtocol: OrgProtocol.Request?
 160
 161    /// Opens the capture window on an org-roam capture.
 162    func capture(roam: RoamCapture) {
 163        captureSerial += 1
 164        roamCapture = roam
 165        captureRequest = (nil, [:], nil, captureSerial)
 166        run("app.capture")
 167    }
 168
 169    /// Capture from an agenda day, as `org-agenda-capture`: that day is the capture's date, and
 170    /// the entry is scheduled on it. The caller opens the capture window.
 171    func capture(on day: Int) {
 172        captureSerial += 1
 173        captureRequest = (nil, [:], day, captureSerial)
 174    }
 175
 176    /// Runs x-callback-url actions; the main window sets it.
 177    @ObservationIgnored var xCallbackRunner: XCallbackRunner?
 178    /// The x-callback-url capture the capture window shows, with its `captureRequest` serial.
 179    @ObservationIgnored private(set) var captureCallback: (request: XCallbackRequest, serial: Int)?
 180
 181    /// An `orgstar://x-callback-url/…` link.
 182    func handle(xCallback request: XCallbackRequest) {
 183        guard let runner = xCallbackRunner else { return reply(request, .failure(.notReady, "orgstar isn't ready")) }
 184        Task { await take(runner.run(request, ask: askClock), for: request, runner: runner) }
 185    }
 186
 187    private func take(_ step: XCallbackRunner.Step, for request: XCallbackRequest, runner: XCallbackRunner) async {
 188        switch step {
 189        case .reply(let reply):
 190            self.reply(request, reply)
 191        case .approve(let source):
 192            NSApp.activate()
 193            let alert = NSAlert()
 194            alert.messageText = XCallbackApprovals.question(source)
 195            alert.informativeText = XCallbackApprovals.explanation(source)
 196            alert.addButton(withTitle: String(localized: "Allow"))
 197            alert.addButton(withTitle: String(localized: "Don’t Allow"))
 198            guard alert.runModal() == .alertFirstButtonReturn else { return reply(request, .failure(.notAllowed, "Not allowed")) }
 199            runner.approvals.allow(source)
 200            await take(runner.run(request, ask: askClock), for: request, runner: runner)
 201        case .capture(let template, let properties):
 202            if let pending = captureCallback { captureEnded(serial: pending.serial, filed: nil) }
 203            captureSerial += 1
 204            captureRequest = (template, properties, nil, captureSerial)
 205            captureCallback = (request, captureSerial)
 206            run("app.capture")
 207        case .open(let path, let offset, let reply):
 208            NSApp.activate()
 209            jump(path: path, offset: offset)
 210            self.reply(request, reply)
 211        }
 212    }
 213
 214    /// Opens the request's callback for `reply`; a failure without one shows its message.
 215    private func reply(_ request: XCallbackRequest, _ reply: XCallbackReply) {
 216        if let url = request.callbackURL(for: reply) {
 217            NSWorkspace.shared.open(url)
 218        } else if case .failure(_, let message) = reply {
 219            show(message)
 220        }
 221    }
 222
 223    /// The capture window filed the capture with this serial, or closed without filing it.
 224    func captureEnded(serial: Int, filed: (template: CaptureTemplate, path: String)?) {
 225        guard let pending = captureCallback, pending.serial == serial else { return }
 226        captureCallback = nil
 227        reply(pending.request, filed.map { xCallbackRunner?.captured($0.template, path: $0.path) ?? .success([:]) } ?? .cancel)
 228    }
 229
 230    /// `org-protocol://capture` and `store-link`, and the widgets' `orgstar://` links.
 231    func handle(protocolURL url: String) {
 232        if let request = URL(string: url).flatMap(XCallbackRequest.init(url:)) {
 233            handle(xCallback: request)
 234            return
 235        }
 236        if let link = URL(string: url).flatMap(AppLink.init(url:)) {
 237            switch link {
 238            case .agenda: run("app.agenda")
 239            case .clock: run("app.clock.goto")
 240            case .review: run("app.flashcards.review")
 241            case .entry(let path, let offset): jump(path: path, offset: offset)
 242            case .capture(let template):
 243                captureSerial += 1
 244                captureRequest = (template, [:], nil, captureSerial)
 245                run("app.capture")
 246            }
 247            return
 248        }
 249        switch OrgProtocol.parse(url) {
 250        case .capture(let template, let properties):
 251            captureSerial += 1
 252            captureRequest = (template, properties, nil, captureSerial)
 253            run("app.capture")
 254        case .storeLink(let link, let title):
 255            storeLink(StoredLink(link: link, description: title))
 256            NSPasteboard.general.clearContents()
 257            NSPasteboard.general.setString(link, forType: .string)
 258        case .roamRef, .roamNode:
 259            roamProtocol = OrgProtocol.parse(url)
 260            run("app.node.protocol")
 261        case nil:
 262            show(String(localized: "orgstar handles org-protocol capture and store-link"))
 263        }
 264    }
 265
 266    func jump(path: String, offset: Int) {
 267        jumpID += 1
 268        jumpRequest = (path, offset, jumpID)
 269    }
 270
 271    func show(_ text: String) {
 272        message = text
 273        messages.append(text)
 274        if messages.count > 100 { messages.removeFirst(messages.count - 100) }
 275        AccessibilityNotification.Announcement(text).post()
 276        // A local monitor sees an event before it is handled, so a message the key or click
 277        // itself shows is set after this clears the last one.
 278        if inputMonitor == nil {
 279            inputMonitor = NSEvent.addLocalMonitorForEvents(matching: [.keyDown, .leftMouseDown, .rightMouseDown]) { [weak self] event in
 280                MainActor.assumeIsolated {
 281                    if self?.message != nil { self?.message = nil }
 282                }
 283                return event
 284            }
 285        }
 286    }
 287}
 288
 289struct PromptRequest: Identifiable {
 290    let id = UUID()
 291    let prompt: Prompt
 292    /// Lines shown in full above the question.
 293    var detail: String? = nil
 294    let reply: (String?) -> Void
 295}
 296
 297@MainActor
 298final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCenterDelegate {
 299    var session: DocumentSession?
 300    var commands: AppCommands?
 301    #if APPSTORE
 302    var workspace: WorkspaceModel?
 303    #else
 304    let updates = Updates()
 305    #endif
 306
 307    func applicationDidFinishLaunching(_ notification: Notification) {
 308        DockIcon.start()
 309        if SystemReminderCenter.isAvailable { UNUserNotificationCenter.current().delegate = self }
 310        #if !APPSTORE
 311        updates.start()
 312        #endif
 313    }
 314
 315    #if APPSTORE
 316    /// A subscription may have lapsed or renewed while the app was in the background.
 317    func applicationDidBecomeActive(_ notification: Notification) {
 318        Task { await ProStore.shared.refresh() }
 319    }
 320    #endif
 321
 322    /// `:session` interpreters end with the app.
 323    func applicationWillTerminate(_ notification: Notification) {
 324        #if !APPSTORE
 325        BabelSessions.shared.stopAll()
 326        #endif
 327    }
 328
 329    /// Reminders show while Orgstar is in front too.
 330    nonisolated func userNotificationCenter(
 331        _ center: UNUserNotificationCenter, willPresent notification: UNNotification
 332    ) async -> UNNotificationPresentationOptions {
 333        [.banner, .sound, .list]
 334    }
 335
 336    /// Clicking a reminder shows its entry.
 337    nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {
 338        let info = response.notification.request.content.userInfo
 339        guard let path = info["path"] as? String, let offset = info["offset"] as? Int else { return }
 340        await MainActor.run {
 341            NSApp.activate()
 342            commands?.jump(path: path, offset: offset)
 343        }
 344    }
 345
 346    /// Files opened from Finder, `open`, or a drop on the Dock icon: each opens as a buffer.
 347    /// Ones that arrive before the window is ready wait for it (`pendingOpens`).
 348    static var pendingOpens: [String] = []
 349
 350    func application(_ application: NSApplication, open urls: [URL]) {
 351        let paths = urls.filter(\.isFileURL).map(\.path)
 352        let links = urls.filter { $0.scheme == "org-protocol" || $0.scheme == AppLink.scheme }.map(\.absoluteString)
 353        guard let commands, let session else {
 354            Self.pendingOpens += paths
 355            Self.pendingLinks += links
 356            return
 357        }
 358        NSApp.activate()
 359        for path in paths { session.open(path) }
 360        for link in links { commands.handle(protocolURL: link) }
 361    }
 362
 363    /// org-protocol and orgstar:// links that arrive before the window is ready.
 364    static var pendingLinks: [String] = []
 365
 366    /// Files continued from another device before the window is ready.
 367    static var pendingHandoffs: [HandoffPlace] = []
 368
 369    func application(_ application: NSApplication, willContinueUserActivityWithType userActivityType: String) -> Bool {
 370        userActivityType == HandoffPlace.activityType
 371    }
 372
 373    /// Handoff from an iPhone, iPad or another Mac.
 374    func application(_ application: NSApplication, continue userActivity: NSUserActivity,
 375                     restorationHandler: @escaping ([any NSUserActivityRestoring]) -> Void) -> Bool {
 376        guard userActivity.activityType == HandoffPlace.activityType, let place = HandoffPlace(userInfo: userActivity.userInfo) else { return false }
 377        if let handler = commands?.continueHandoff {
 378            NSApp.activate()
 379            handler(place)
 380        } else {
 381            Self.pendingHandoffs.append(place)
 382        }
 383        return true
 384    }
 385
 386    func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { true }
 387
 388    func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {
 389        guard let session else { return .terminateNow }
 390        #if APPSTORE
 391        BufferRestore.save(session, workspace: workspace)
 392        #else
 393        BufferRestore.save(session)
 394        #endif
 395        guard UnsavedChanges.resolve(session, paths: session.openPaths) else { return .terminateCancel }
 396        #if !APPSTORE
 397        // Files saved since their folder's last automatic commit are committed before quitting.
 398        if GitAutoCommit.shared.hasPending {
 399            Task {
 400                await GitAutoCommit.shared.flush()
 401                sender.reply(toApplicationShouldTerminate: true)
 402            }
 403            return .terminateLater
 404        }
 405        #endif
 406        return .terminateNow
 407    }
 408}
 409
 410/// Unsaved edits when leaving a file or quitting.
 411@MainActor
 412enum UnsavedChanges {
 413    /// Whether the open file can be left: saved in automatic mode, or as the user chooses in
 414    /// explicit mode. A save that fails or conflicts keeps the file open.
 415    static func resolve(_ session: DocumentSession) -> Bool {
 416        guard session.isDirty, let path = session.path else { return true }
 417        if session.saveMode == .automatic { return save(session, path) }
 418        let alert = NSAlert()
 419        alert.messageText = session.path.map { String(localized: "Save changes to \(($0 as NSString).lastPathComponent)?") }
 420            ?? String(localized: "Save changes to this file?")
 421        alert.informativeText = String(localized: "Your changes will be lost if you don't save them.")
 422        alert.addButton(withTitle: String(localized: "Save"))
 423        alert.addButton(withTitle: String(localized: "Don't Save"))
 424        alert.addButton(withTitle: String(localized: "Cancel"))
 425        switch alert.runModal() {
 426        case .alertFirstButtonReturn: return save(session, path)
 427        case .alertSecondButtonReturn: return true
 428        default: return false
 429        }
 430    }
 431
 432    /// Whether the buffers of `paths` can be closed: saved in automatic mode, or as the user
 433    /// chooses for all of them in explicit mode.
 434    static func resolve(_ session: DocumentSession, paths: [String]) -> Bool {
 435        let dirty = paths.filter(session.dirtyPaths.contains)
 436        guard !dirty.isEmpty else { return true }
 437        if session.saveMode == .automatic { return dirty.map { save(session, $0) }.allSatisfy { $0 } }
 438        if dirty == [session.path] { return resolve(session) }
 439        let alert = NSAlert()
 440        alert.messageText = String(localized: "Save changes to \(dirty.count) files?")
 441        alert.informativeText = dirty.map { ($0 as NSString).lastPathComponent }.joined(separator: ", ")
 442        alert.addButton(withTitle: String(localized: "Save All"))
 443        alert.addButton(withTitle: String(localized: "Don't Save"))
 444        alert.addButton(withTitle: String(localized: "Cancel"))
 445        switch alert.runModal() {
 446        case .alertFirstButtonReturn: return dirty.map { save(session, $0) }.allSatisfy { $0 }
 447        case .alertSecondButtonReturn: return true
 448        default: return false
 449        }
 450    }
 451
 452    /// Saves `path`. One held for its passphrase asks for it, or whether to leave without saving.
 453    static func save(_ session: DocumentSession, _ path: String) -> Bool {
 454        if session.save(path) { return true }
 455        let name = (path as NSString).lastPathComponent
 456        guard let hold = session.held[path], hold.takesPassphrase else {
 457            // A save that failed otherwise (a conflict, an error, an entry the passphrase can't
 458            // encrypt) still lets the file be left without saving.
 459            let alert = NSAlert()
 460            alert.messageText = String(localized: "Changes to \(name) aren't saved")
 461            alert.informativeText = session.held[path]?.notice(for: path) ?? session.conflict ?? session.lastError ?? ""
 462            alert.addButton(withTitle: String(localized: "Cancel"))
 463            alert.addButton(withTitle: String(localized: "Don't Save"))
 464            return alert.runModal() == .alertSecondButtonReturn
 465        }
 466        // A new passphrase is typed twice; one that must open what's encrypted already, once.
 467        let twice = hold == .file || OrgCrypt.firstMessage(session.document(of: path)?.text ?? "") == nil
 468        let fields = (twice ? [String(localized: "Passphrase"), String(localized: "Repeat passphrase")] : [String(localized: "Passphrase")]).map { placeholder in
 469            let field = NSSecureTextField(frame: NSRect(x: 0, y: 0, width: 260, height: 22))
 470            field.placeholderString = placeholder
 471            return field
 472        }
 473        let stack = NSStackView(views: fields)
 474        stack.orientation = .vertical
 475        stack.spacing = 6
 476        stack.frame = NSRect(x: 0, y: 0, width: 260, height: CGFloat(fields.count) * 28)
 477        var problem: String?
 478        while true {
 479            let alert = NSAlert()
 480            alert.messageText = String(localized: "Changes to \(name) aren't saved")
 481            alert.informativeText = (problem.map { $0 + "\n\n" } ?? "") + hold.notice(for: path) + " "
 482                + String(localized: "Enter the passphrase to encrypt and save them, or leave without saving.")
 483            alert.accessoryView = stack
 484            alert.addButton(withTitle: String(localized: "Encrypt and Save"))
 485            alert.addButton(withTitle: String(localized: "Don't Save"))
 486            alert.addButton(withTitle: String(localized: "Cancel"))
 487            alert.window.initialFirstResponder = fields[0]
 488            switch alert.runModal() {
 489            case .alertFirstButtonReturn:
 490                let passphrase = fields[0].stringValue
 491                if passphrase.isEmpty {
 492                    problem = String(localized: "Enter a passphrase.")
 493                } else if twice, fields[1].stringValue != passphrase {
 494                    problem = String(localized: "The passphrases differ")
 495                } else if let failure = session.unlock(passphrase, for: path) {
 496                    problem = failure
 497                } else {
 498                    session.passphrases.keep(passphrase, for: path, text: session.document(of: path)?.text ?? "")
 499                    return !session.dirtyPaths.contains(path)
 500                }
 501            case .alertSecondButtonReturn: return true
 502            default: return false
 503            }
 504        }
 505    }
 506}
 507
 508/// The open buffers, their order and carets, kept for the next launch.
 509@MainActor
 510enum BufferRestore {
 511    private static let key = "openBuffers"
 512
 513    struct State: Codable {
 514        var paths: [String]
 515        var current: String?
 516        var carets: [String: Int]
 517        /// In the Mac App Store build, bookmarks of the files outside every folder, which the
 518        /// sandbox would otherwise keep orgstar out of after relaunch.
 519        var bookmarks: [String: Data]?
 520    }
 521
 522    /// `bookmarking` says which paths get a bookmark. A path still open keeps the bookmark it
 523    /// has when no new one is made.
 524    static func save(_ session: DocumentSession, bookmarking: (String) -> Bool = { _ in false }, defaults: UserDefaults = .standard) {
 525        var carets: [String: Int] = [:]
 526        for path in session.openPaths { carets[path] = session.caret(of: path) }
 527        let previous = defaults.data(forKey: key).flatMap { try? JSONDecoder().decode(State.self, from: $0) }?.bookmarks ?? [:]
 528        var bookmarks: [String: Data] = [:]
 529        for path in session.openPaths {
 530            bookmarks[path] = (bookmarking(path) ? SecurityBookmark.make(URL(fileURLWithPath: path)) : nil) ?? previous[path]
 531        }
 532        let state = State(paths: session.openPaths, current: session.path, carets: carets, bookmarks: bookmarks.isEmpty ? nil : bookmarks)
 533        if let data = try? JSONEncoder().encode(state) { defaults.set(data, forKey: key) }
 534    }
 535
 536    #if APPSTORE
 537    /// Saves with bookmarks for the files outside `workspace`'s folders and grants.
 538    static func save(_ session: DocumentSession, workspace: WorkspaceModel?) {
 539        save(session, bookmarking: { workspace?.contains(URL(fileURLWithPath: $0)) != true })
 540    }
 541    #endif
 542
 543    /// Opens the buffers that were open, in order, and returns the carets to show them at.
 544    static func restore(_ session: DocumentSession, defaults: UserDefaults = .standard) -> [String: Int] {
 545        guard let data = defaults.data(forKey: key), var state = try? JSONDecoder().decode(State.self, from: data) else { return [:] }
 546        // A bookmarked file comes back with access, at the path it has now.
 547        for (path, bookmark) in state.bookmarks ?? [:] {
 548            guard let moved = SecurityBookmark.resolve(bookmark)?.url.path, moved != path else { continue }
 549            state.paths = state.paths.map { $0 == path ? moved : $0 }
 550            if state.current == path { state.current = moved }
 551            state.carets[moved] = state.carets.removeValue(forKey: path)
 552        }
 553        let existing = state.paths.filter { FileManager.default.fileExists(atPath: $0) }
 554        for path in existing { session.open(path) }
 555        if let current = state.current, existing.contains(current) { session.open(current) }
 556        return state.carets
 557    }
 558}
 559
 560@main
 561struct OrgstarApp: App {
 562    @NSApplicationDelegateAdaptor private var delegate: AppDelegate
 563    @State private var workspace = Result {
 564        try WorkspaceModel(directory: WorkspaceModel.defaultDirectory, settings: .with(todoKeywords: Preferences.orgSettings))
 565    }
 566    @State private var commands = AppCommands()
 567    @State private var clock = ClockModel()
 568    @State private var scheduler = SystemReminderCenter.isAvailable ? ReminderScheduler(center: SystemReminderCenter()) : nil
 569    @State private var session: DocumentSession = {
 570        #if APPSTORE
 571        ClockTask.titleKey = ClockTitleKey.loadOrCreate()
 572        #else
 573        // A snapshot run is a renamed, ad hoc signed copy, which the Keychain would stop at a prompt.
 574        ClockTask.titleKey = DevelopmentHooks.snapshotting ? nil : ClockTitleKey.loadOrCreate()
 575        #endif
 576        let session = DocumentSession()
 577        session.defaults = Preferences.orgSettings
 578        // Before any window: capture and agenda edits can save before the main window opens.
 579        session.encryptsTaggedEntries = OrgPreferences.cryptBeforeSave()
 580        session.cryptTag = OrgPreferences.cryptTag()
 581        return session
 582    }()
 583
 584    init() {
 585        PDFExport.mathJaxURL = OrgMathJax.script
 586        RevealExport.library = OrgMathJax.reveal
 587        RevealExport.mathJax = OrgMathJax.script
 588        #if !APPSTORE
 589        Printing.saveTo = DevelopmentHooks.printTo
 590        #endif
 591        DiagramBlocks.vizURL = OrgMathJax.viz
 592        DiagramBlocks.mermaidURL = OrgMathJax.mermaid
 593        #if APPSTORE
 594        PythonBlocks.folder = OrgMathJax.pyodide
 595        AgendaSnapshot.useGroupContainer = true
 596        EmacsFallback.offered = false
 597        _ = FolderGrants.shared
 598        ProStore.shared.start()
 599        #else
 600        DocumentSession.programs = Programs()
 601        MacPro.resolve()
 602        MacPro.renewInBackground()
 603        #endif
 604        // `org-sbe` in table formulas runs blocks, so it needs Babel as source blocks do.
 605        TableBlocks.allowed = { ProAccess.isUnlockedNow }
 606        // Debug builds, and runs with ORGSTAR_PERF set: main-thread stalls in the console.
 607        #if DEBUG
 608        Perf.watchMainThread()
 609        #else
 610        if ProcessInfo.processInfo.environment["ORGSTAR_PERF"] != nil { Perf.watchMainThread() }
 611        #endif
 612    }
 613
 614    var body: some Scene {
 615        Window("orgstar", id: "main") {
 616            switch workspace {
 617            case .success(let model):
 618                ContentView(workspace: model, session: session, commands: commands, scheduler: scheduler, clock: clock)
 619                    .environment(\.orgTheme, ConfigSync.shared.theme)
 620                    .textScaled()
 621                    .tint(ConfigSync.shared.theme.color("accent"))
 622                    .onAppear {
 623                        delegate.session = session
 624                        delegate.commands = commands
 625                        #if APPSTORE
 626                        delegate.workspace = model
 627                        #else
 628                        GitAutoCommit.shared.roots = { model.rootPaths }
 629                        GitAutoCommit.shared.report = { commands.show($0) }
 630                        session.fileWritten = { GitAutoCommit.shared.fileWritten($0) }
 631                        #endif
 632                        CaptureIntent.environment = (model, session, clock, commands)
 633                        var runner = XCallbackRunner(workspace: model, session: session, clock: clock)
 634                        runner.clipboard = { NSPasteboard.general.string(forType: .string) ?? "" }
 635                        runner.userName = NSFullUserName()
 636                        commands.xCallbackRunner = runner
 637                    }
 638            case .failure(let error):
 639                ContentUnavailableView("Can't Open the Index", systemImage: "exclamationmark.triangle", description: Text(error.localizedDescription))
 640            }
 641        }
 642        .defaultSize(width: 1280, height: 860)
 643        WindowGroup("Editor", id: "editor") {
 644            if case .success = workspace {
 645                EditorWindowView(session: session, commands: commands)
 646                    .environment(\.orgTheme, ConfigSync.shared.theme)
 647                    .tint(ConfigSync.shared.theme.color("accent"))
 648            }
 649        }
 650        .defaultSize(width: 900, height: 700)
 651        .commandsRemoved()
 652        Window("Agenda", id: "agenda") {
 653            if case .success(let model) = workspace {
 654                AgendaView(workspace: model, session: session, commands: commands, scheduler: scheduler, clock: clock)
 655                    .environment(\.orgTheme, ConfigSync.shared.theme)
 656                    .textScaled()
 657                    .tint(ConfigSync.shared.theme.color("accent"))
 658            }
 659        }
 660        .defaultSize(width: 760, height: 720)
 661        Window("Board", id: "board") {
 662            if case .success(let model) = workspace {
 663                BoardView(workspace: model, session: session, commands: commands)
 664                    .environment(\.orgTheme, ConfigSync.shared.theme)
 665                    .tint(ConfigSync.shared.theme.color("accent"))
 666            }
 667        }
 668        .defaultSize(width: 1100, height: 700)
 669        Window("Node Graph", id: "graph") {
 670            if case .success(let model) = workspace {
 671                RoamGraphWindow(workspace: model, session: session, commands: commands)
 672                    .tint(ConfigSync.shared.theme.color("accent"))
 673            }
 674        }
 675        .defaultSize(width: 900, height: 700)
 676        Window("Review Flashcards", id: "flashcards") {
 677            if case .success(let model) = workspace {
 678                FlashcardWindow(workspace: model, session: session, commands: commands)
 679                    .tint(ConfigSync.shared.theme.color("accent"))
 680            }
 681        }
 682        .defaultSize(width: 640, height: 560)
 683        Window("Lint All Folders", id: "lint-folders") {
 684            if case .success(let model) = workspace {
 685                FolderLintWindow(workspace: model, session: session, commands: commands)
 686                    .tint(ConfigSync.shared.theme.color("accent"))
 687            }
 688        }
 689        .defaultSize(width: 760, height: 520)
 690        Window("Clock Report", id: "clock-report") {
 691            if case .success(let model) = workspace {
 692                ClockReportView(workspace: model, session: session)
 693                    .environment(\.orgTheme, ConfigSync.shared.theme)
 694                    .tint(ConfigSync.shared.theme.color("accent"))
 695            }
 696        }
 697        .defaultSize(width: 860, height: 560)
 698        Window("Capture", id: "capture") {
 699            if case .success(let model) = workspace {
 700                CaptureView(workspace: model, session: session, commands: commands, clock: clock)
 701                    .environment(\.orgTheme, ConfigSync.shared.theme)
 702                    .tint(ConfigSync.shared.theme.color("accent"))
 703            }
 704        }
 705        .windowResizability(.contentSize)
 706        .windowLevel(.floating)
 707        .commands {
 708            CommandGroup(after: .newItem) {
 709                Button("Add Folder…") { commands.showingFolderPicker = true }
 710                    .keyboardShortcut("o", modifiers: [.command, .shift])
 711                Button("Quick Open…") { commands.showingQuickOpen = true }
 712                    .keyboardShortcut("p")
 713                Button("Command Palette…") { commands.showingPalette = true }
 714                    .keyboardShortcut("p", modifiers: [.command, .shift])
 715            }
 716            CommandGroup(after: .saveItem) {
 717                Menu("Export") {
 718                    ForEach(EditorCommands.all.filter { $0.id.hasPrefix("app.export.") && !hiddenCommandIDs.contains($0.id) }, id: \.id) { command in
 719                        Button(command.localizedTitle) { commands.run(command.id) }
 720                    }
 721                }
 722                .disabled(session.path == nil)
 723                Button("Share Subtree…") { commands.run("app.share-subtree") }
 724                    .disabled(!session.isOrg)
 725                Menu("Publish") {
 726                    ForEach(EditorCommands.all.filter { $0.id.hasPrefix("app.publish") }, id: \.id) { command in
 727                        Button(command.localizedTitle) { commands.run(command.id) }
 728                    }
 729                }
 730                Menu("Import") {
 731                    Button("Markdown Files…") { commands.run("app.import-markdown") }
 732                    Button("Obsidian Vault…") { commands.run("app.import-obsidian") }
 733                }
 734                Divider()
 735                Button("Revert to File on Disk") { commands.run("app.revert") }
 736                    .disabled(session.path == nil)
 737                Button("Resolve Sync Conflicts…") { commands.run("app.sync-conflicts") }
 738                    .disabled(session.path == nil)
 739                Button("History…") { commands.run("app.recovery") }
 740                    .disabled(session.path == nil)
 741                Button("Lint File") { commands.run("app.lint") }
 742                    .disabled(!FileLint.applies(to: session.path))
 743                Button("Lint All Folders") { commands.run("app.lint-folders") }
 744            }
 745            CommandGroup(replacing: .saveItem) {
 746                Button("Close Buffer") {
 747                    // ⌘W closes the buffer in the main window, and other windows themselves.
 748                    if let key = NSApp.keyWindow, key.identifier?.rawValue.contains("main") != true {
 749                        key.performClose(nil)
 750                    } else {
 751                        commands.run("app.buffer.kill")
 752                    }
 753                }
 754                .keyboardShortcut("w")
 755                Button("Close Window") { NSApp.keyWindow?.performClose(nil) }
 756                    .keyboardShortcut("w", modifiers: [.command, .shift])
 757                Divider()
 758                Button("Save") {
 759                    if !session.save(), session.conflict != nil { commands.showingConflict = true }
 760                }
 761                .keyboardShortcut("s")
 762                .disabled(session.path == nil || session.isReadOnly)
 763                Button("Save All") { commands.run("app.save-all") }
 764                    .keyboardShortcut("s", modifiers: [.command, .option])
 765                    .disabled(session.dirtyPaths.isEmpty)
 766            }
 767            CommandGroup(replacing: .printItem) {
 768                Button("Page Setup…") { NSPageLayout().runModal() }
 769                // ⌘P is Quick Open.
 770                Button("Print…") {
 771                    if NSApp.keyWindow?.identifier?.rawValue.contains("agenda") == true {
 772                        commands.agendaPrintRequested = true
 773                    } else {
 774                        commands.run("app.print")
 775                    }
 776                }
 777                .keyboardShortcut("p", modifiers: [.command, .option])
 778                Button("Print Subtree…") { commands.run("app.print-subtree") }
 779                    .disabled(!session.isOrg)
 780                Button("Print Selection…") { commands.run("app.print-selection") }
 781                    .disabled(!session.isOrg)
 782            }
 783            CommandGroup(after: .sidebar) {
 784                Button("Split Pane Below") { commands.run("app.split-below") }
 785                    .keyboardShortcut("2", modifiers: [.command, .control])
 786                Button("Split Pane Right") { commands.run("app.split-right") }
 787                    .keyboardShortcut("3", modifiers: [.command, .control])
 788                Button("Close Pane") { commands.run("app.pane-close") }
 789                    .keyboardShortcut("0", modifiers: [.command, .control])
 790                Button("Close Other Panes") { commands.run("app.pane-only") }
 791                    .keyboardShortcut("1", modifiers: [.command, .control])
 792                Button("Next Pane") { commands.run("app.pane-next") }
 793                    .keyboardShortcut("`", modifiers: [.command, .option])
 794                Divider()
 795                Button("Present") { commands.run("app.present") }
 796                    .keyboardShortcut("p", modifiers: [.command, .control])
 797                    .disabled(!session.isOrg)
 798                Divider()
 799                ViewMenuToggles(commands: commands)
 800                Divider()
 801                Button("Messages") { commands.run("app.messages") }
 802            }
 803            CommandGroup(after: .pasteboard) {
 804                Divider()
 805                FindMenu(commands: commands)
 806                MacroMenu(commands: commands)
 807            }
 808            CommandGroup(after: .textEditing) {
 809                Button("Cancel Running Task") { commands.run("app.babel.cancel") }
 810                    .keyboardShortcut(".")
 811                    .disabled(!session.isRunningBabel && !session.isRunningUserCommand && commands.emacsTask == nil)
 812                Button("Search Notes") { commands.focusSearch = true }
 813                    .keyboardShortcut("f", modifiers: [.command, .shift])
 814            }
 815            CommandGroup(before: .windowList) {
 816                AgendaMenuItem()
 817                Divider()
 818                Button("Switch to Buffer…") { commands.run("app.buffer.switch") }
 819                Button("Next Buffer") { commands.run("app.buffer.next") }
 820                    .keyboardShortcut("]", modifiers: [.command, .shift])
 821                Button("Previous Buffer") { commands.run("app.buffer.previous") }
 822                    .keyboardShortcut("[", modifiers: [.command, .shift])
 823                Divider()
 824            }
 825            CommandGroup(after: .newItem) {
 826                Button("Capture…") { commands.run("app.capture") }
 827                    .keyboardShortcut("n", modifiers: [.command, .shift])
 828                Button("New File from Template…") { commands.run("app.new-file-from-template") }
 829                Button("New Window") { commands.run("app.window-new") }
 830                    .keyboardShortcut("n", modifiers: [.command, .option])
 831            }
 832        }
 833        .commands {
 834            CommandMenu("Org") {
 835                ClockMenu(commands: commands, clock: clock)
 836                Divider()
 837                OrgMenuItems(commands: commands)
 838            }
 839        }
 840        .commands {
 841            CommandGroup(after: .appSettings) {
 842                Button("Edit Config File") { commands.jump(path: UserConfig.configFile.path, offset: 0) }
 843                    .keyboardShortcut(",", modifiers: [.command, .option])
 844            }
 845            #if !APPSTORE
 846            CommandGroup(after: .appInfo) {
 847                CheckForUpdatesItem(updates: delegate.updates)
 848            }
 849            #endif
 850            CommandGroup(replacing: .help) {
 851                Button("orgstar Manual") { NSWorkspace.shared.open(Manual.home) }
 852                Button("Keys") { NSWorkspace.shared.open(Manual.keys) }
 853                Divider()
 854                Button("What's New in orgstar") { commands.whatsNew = WhatsNew.releases.first }
 855                    .disabled(!commands.mainWindowOpen)
 856            }
 857        }
 858        Settings {
 859            #if APPSTORE
 860            SettingsView(commands: commands, workspace: try? workspace.get())
 861            #else
 862            SettingsView(commands: commands, workspace: try? workspace.get(), updates: delegate.updates)
 863            #endif
 864        }
 865    }
 866}
 867
 868/// The Org menu: every org command and the app's commands for entries and notes, in submenus by
 869/// subject, with the keys that run them in the current keymap.
 870struct OrgMenuItems: View {
 871    let commands: AppCommands
 872
 873    /// Submenus and the command id prefixes they hold, in menu order. A command goes in the
 874    /// first submenu with a prefix it starts with.
 875    static let groups: [(title: LocalizedStringKey, prefixes: [String])] = [
 876        ("Visibility", ["org.cycle", "org.fold.", "org.narrow.", "org.widen", "org.sparse-tree", "org.toggle-inline-images", "org.latex-preview"]),
 877        ("Headings", ["org.heading.", "org.subtree.", "org.element.", "org.goto", "org.sort", "org.archive.", "app.refile", "app.archive"]),
 878        ("TODO and Tags", ["org.todo.", "org.priority.", "org.tags.", "org.effort.", "app.rename-"]),
 879        ("Properties and Columns", ["org.property.", "org.columns", "org.drawer."]),
 880        ("Dates and Timers", ["org.schedule", "org.deadline", "org.timestamp.", "org.timer."]),
 881        ("Lists", ["org.item.", "org.checkbox."]),
 882        ("Tables", ["org.table", "app.table-", "app.plot"]),
 883        ("Links and Footnotes", ["org.link.", "org.id.", "org.footnote.", "app.cite."]),
 884        ("Blocks", ["org.babel.", "org.structure-template", "org.edit-special", "org.dblock.", "org.clock.report", "org.denote."]),
 885        ("Text", ["org.emphasize", "org.fill-"]),
 886        ("Attachments", ["app.attach."]),
 887        ("Notes", ["app.dailies.", "app.node."]),
 888        ("Encryption", ["app.crypt."]),
 889    ]
 890
 891    private static func group(of id: String) -> Int? {
 892        groups.firstIndex { $0.prefixes.contains { id.hasPrefix($0) } }
 893    }
 894
 895    private static let shown = EditorCommands.all.filter { ($0.id.hasPrefix("org.") || group(of: $0.id) != nil) && !hiddenCommandIDs.contains($0.id) }
 896
 897    var body: some View {
 898        // Commands that fit no subject, such as Act at Point, come first.
 899        ForEach(Self.shown.filter { Self.group(of: $0.id) == nil }, id: \.id) { item($0) }
 900        Divider()
 901        ForEach(Self.groups.indices, id: \.self) { index in
 902            Menu(Self.groups[index].title) {
 903                ForEach(Self.shown.filter { Self.group(of: $0.id) == index }, id: \.id) { item($0) }
 904            }
 905        }
 906    }
 907
 908    private func item(_ command: EditorCommand) -> some View {
 909        Button {
 910            if command.id.hasPrefix("org.") { commands.editor?.run(command.id) } else { commands.run(command.id) }
 911        } label: {
 912            Text(command.localizedTitle)
 913            if let keys = commands.keyLabel(for: command.id) { Text(keys) }
 914        }
 915        .disabled(command.id.hasPrefix("org.") && commands.editor == nil)
 916    }
 917}
 918
 919/// The user manual, as `scripts/publish-docs.sh` publishes it.
 920enum Manual {
 921    static let home = URL(string: "https://files.krz.sh/orgstar/")!
 922    /// The key reference, with every preset's keys.
 923    static let keys = URL(string: "https://files.krz.sh/orgstar/guide/03-keys.html#key-reference")!
 924}
 925
 926/// View ▸ the panes and the focused editor's modes, checked while on.
 927struct ViewMenuToggles: View {
 928    let commands: AppCommands
 929    @AppStorage("backlinksShown") private var backlinksShown = true
 930    @AppStorage("inspectorShown") private var inspectorShown = false
 931
 932    var body: some View {
 933        let outline = commands.outlineShown
 934        let editor = commands.editor
 935        // A key that switches an editor mode shows a message, so the checks follow it.
 936        let _ = commands.message
 937        Toggle("Show Outline", isOn: Binding(get: { outline }, set: { _ in commands.run("app.toggle-outline") }))
 938            .keyboardShortcut("o", modifiers: [.command, .option])
 939        Toggle("Show Backlinks", isOn: $backlinksShown)
 940        Toggle("Show Inspector", isOn: $inspectorShown)
 941            .keyboardShortcut("i", modifiers: [.command, .option])
 942        MarkupToggle()
 943        editorToggle("Truncate Long Lines", "editor.toggle-truncate-lines", editor?.truncatesLines)
 944        editorToggle("Auto Fill", "editor.toggle-auto-fill", editor?.autoFills)
 945        editorToggle("Check Spelling While Typing", "editor.toggle-spell-check", editor?.spellChecking)
 946    }
 947
 948    private func editorToggle(_ title: LocalizedStringKey, _ id: String, _ on: Bool?) -> some View {
 949        Toggle(title, isOn: Binding(get: { on ?? false }, set: { _ in commands.editor?.run(id) }))
 950            .disabled(on == nil)
 951    }
 952}
 953
 954/// View ▸ Show Markup (link brackets and targets, emphasis markers) and Show Line Numbers.
 955struct MarkupToggle: View {
 956    @AppStorage("showTabBar") private var showTabBar = false
 957    @AppStorage("showMarkup") private var showMarkup = false
 958    @AppStorage("showLineNumbers") private var showLineNumbers = false
 959    @AppStorage("lineNumbersType") private var lineNumbersType = "t"
 960
 961    var body: some View {
 962        Toggle("Show Markup", isOn: $showMarkup)
 963            .keyboardShortcut("m", modifiers: [.command, .shift])
 964        Toggle("Show Line Numbers", isOn: $showLineNumbers)
 965            .keyboardShortcut("l", modifiers: [.command, .shift])
 966        Picker("Line Numbers", selection: $lineNumbersType) {
 967            Text("Absolute").tag("t")
 968            Text("Relative").tag("relative")
 969            Text("Visual").tag("visual")
 970        }
 971        Toggle("Show Tab Bar", isOn: $showTabBar)
 972    }
 973}
 974
 975/// Edit ▸ Find: the editor's find bar.
 976struct FindMenu: View {
 977    let commands: AppCommands
 978
 979    var body: some View {
 980        Menu("Find") {
 981            item("Find…", "edit.find", "f")
 982            item("Find and Replace…", "edit.replace", "f", [.command, .option])
 983            item("Find Next", "edit.find-next", "g")
 984            item("Find Previous", "edit.find-previous", "g", [.command, .shift])
 985            item("Use Selection for Find", "edit.use-selection-for-find", "e")
 986            Divider()
 987            Button("Replace in Files…") { commands.run("app.replace-in-files") }
 988                .keyboardShortcut("f", modifiers: [.command, .option, .shift])
 989        }
 990    }
 991
 992    private func item(_ title: String, _ id: String, _ key: KeyEquivalent, _ modifiers: EventModifiers = .command) -> some View {
 993        Button(title) { commands.editor?.run(id) }
 994            .keyboardShortcut(key, modifiers: modifiers)
 995            .disabled(commands.editor == nil)
 996    }
 997}
 998
 999/// Edit ▸ Macros: keyboard macros, with the keys that run them in the current keymap.
1000struct MacroMenu: View {
1001    let commands: AppCommands
1002
1003    var body: some View {
1004        Menu("Macros") {
1005            item("Start Recording", "macro.start")
1006            item("Stop Recording", "macro.end")
1007            item("Run Last Macro", "macro.call")
1008            Divider()
1009            item("Name Last Macro…", "macro.name")
1010            item("Run Macro…", "macro.run")
1011        }
1012    }
1013
1014    private func item(_ title: LocalizedStringKey, _ id: String) -> some View {
1015        Button {
1016            commands.editor?.run(id)
1017        } label: {
1018            Text(title)
1019            if let keys = commands.keyLabel(for: id) { Text(keys) }
1020        }
1021        .disabled(commands.editor == nil)
1022    }
1023}
1024
1025/// Window ▸ Agenda.
1026struct AgendaMenuItem: View {
1027    @Environment(\.openWindow) private var openWindow
1028
1029    var body: some View {
1030        Button("Agenda") { openWindow(id: "agenda") }
1031            .keyboardShortcut("a", modifiers: [.command, .shift])
1032        Button("Board") { openWindow(id: "board") }
1033            .keyboardShortcut("b", modifiers: [.command, .shift])
1034        Button("Graph") { if ProAccess.shared.allows(.roam) { openWindow(id: "graph") } }
1035        Button("Review Flashcards") { openWindow(id: "flashcards") }
1036    }
1037}
1038
1039struct SettingsView: View {
1040    let commands: AppCommands
1041    let workspace: WorkspaceModel?
1042    #if !APPSTORE
1043    let updates: Updates
1044    #endif
1045    @State private var importing = false
1046    #if APPSTORE
1047    @State private var configFolder = UserConfig.directoryOverride
1048    #endif
1049    @Environment(\.openWindow) private var openWindow
1050    @AppStorage("saveMode") private var saveMode = SaveMode.automatic
1051    @AppStorage("keymap") private var preset = KeymapPreset.emacs
1052    @AppStorage("optionAsMeta") private var optionAsMeta = OptionAsMeta.left.rawValue
1053    @AppStorage("tagsColumn") private var tagsColumn = -77
1054    @AppStorage("headingAfterSubtree") private var headingAfterSubtree = false
1055    @AppStorage("splitLine") private var splitLine = false
1056    @AppStorage("alphabeticalLists") private var alphabeticalLists = true
1057    @AppStorage("fillColumn") private var fillColumn = 80
1058    @AppStorage("hiddenMarkers") private var hiddenMarkers = true
1059    @AppStorage("prettyEntities") private var prettyEntities = true
1060    @AppStorage("startupTruncated") private var startupTruncated = false
1061    @AppStorage("todoKeywords") private var todoKeywords = Preferences.defaultTodoKeywords
1062    @AppStorage("logDone") private var logDone = "nil"
1063    @AppStorage("logIntoDrawer") private var logIntoDrawer = ""
1064    @AppStorage("useSpeedCommands") private var useSpeedCommands = false
1065    @AppStorage("spellCheck") private var spellCheck = false
1066    @AppStorage("completionAuto") private var completionAuto = "preset"
1067    @AppStorage("completionAutoDelay") private var completionAutoDelay = 400
1068    @AppStorage("completionAutoPrefix") private var completionAutoPrefix = 2
1069    @AppStorage("completionStyle") private var completionStyle = "preset"
1070    @AppStorage("completionWords") private var completionWords = false
1071    @AppStorage("enforceTodoDependencies") private var enforceTodoDependencies = false
1072    @AppStorage("enforceTodoCheckboxDependencies") private var enforceTodoCheckboxDependencies = false
1073    @AppStorage("agendaSpan") private var agendaSpan = 10
1074    @AppStorage("agendaStartOffset") private var agendaStartOffset = 0
1075    @AppStorage("agendaSubfolders") private var agendaSubfolders = false
1076    @AppStorage("agendaShowAllDates") private var agendaShowAllDates = false
1077    @AppStorage("habitsOnlyForToday") private var habitsOnlyForToday = true
1078    @AppStorage("agendaDimBlockedTasks") private var agendaDimBlockedTasks = "t"
1079    @AppStorage("calendarEvents") private var calendarEvents = false
1080    @AppStorage("calendarEventCalendars") private var calendarEventCalendars = ""
1081    @State private var calendars: [(id: String, title: String, color: RGBA?)] = []
1082    @AppStorage("agendaReminders") private var agendaReminders = false
1083    @AppStorage("agendaReminderLists") private var agendaReminderLists = ""
1084    @State private var reminderLists: [(id: String, title: String, color: RGBA?)] = []
1085    @AppStorage("reminders") private var reminders = true
1086    @AppStorage("reminderLead") private var reminderLead = 12
1087    @AppStorage("clockIdleTime") private var clockIdleTime = 0
1088    @AppStorage("clockHistoryLength") private var clockHistoryLength = 5
1089    @AppStorage("globalCapture") private var globalCapture = true
1090    @AppStorage("menuBarItem") private var menuBarItem = false
1091    @AppStorage("settingsTab") private var tab = "general"
1092    @AppStorage("showHiddenFiles") private var showHiddenFiles = true
1093    @AppStorage("themeFont") private var themeFont = ""
1094    @AppStorage("themeBodyFont") private var themeBodyFont = ""
1095    @AppStorage("themeFontSize") private var themeFontSize = 13
1096    @AppStorage("themeLineSpacing") private var themeLineSpacing = 2
1097    @AppStorage("themeTextWidth") private var themeTextWidth = 0
1098    @AppStorage("themeHeadingStep") private var themeHeadingStep = 1
1099
1100    /// Installed font families that aren't monospaced, for body text.
1101    private static let proportionalFamilies: [String] = NSFontManager.shared.availableFontFamilies.filter { family in
1102        NSFontManager.shared.font(withFamily: family, traits: [], weight: 5, size: 13)?.isFixedPitch == false
1103    }
1104
1105    /// Installed monospaced font families.
1106    private static let monospacedFamilies: [String] = NSFontManager.shared.availableFontFamilies.filter { family in
1107        NSFontManager.shared.font(withFamily: family, traits: [], weight: 5, size: 13)?.isFixedPitch == true
1108    }
1109
1110    var body: some View {
1111        TabView(selection: $tab) {
1112            Tab("General", systemImage: "gearshape", value: "general") { general }
1113            Tab("Editing", systemImage: "text.alignleft", value: "editing") { editing }
1114            Tab("Appearance", systemImage: "paintpalette", value: "appearance") { appearance }
1115            Tab("Agenda", systemImage: "calendar", value: "agenda") { agenda }
1116            Tab("Capture", systemImage: "tray.and.arrow.down", value: "capture") { capture }
1117            Tab("Encryption", systemImage: "lock", value: "encryption") {
1118                Form { DecryptSettings() }.formStyle(.grouped).frame(height: 330)
1119            }
1120            #if !APPSTORE
1121            Tab(value: "git") { GitSettingsForm(workspace: workspace) } label: {
1122                Label { Text("Git", tableName: "DeveloperID") } icon: { Image(systemName: "arrow.triangle.branch") }
1123            }
1124            #endif
1125            #if APPSTORE
1126            Tab("orgstar+", systemImage: "star", value: "pro") { StoreForm() }
1127            #else
1128            Tab("orgstar+", systemImage: "star", value: "pro") { LicenseForm() }
1129            #endif
1130        }
1131        .frame(width: 600)
1132    }
1133
1134    private func editConfig() {
1135        ConfigSync.shared.start()
1136        openWindow(id: "main")
1137        commands.jump(path: UserConfig.configFile.path, offset: 0)
1138    }
1139
1140    #if APPSTORE
1141    /// A folder outside the app's container, such as `~/.config/orgstar` kept with dotfiles.
1142    private func chooseConfigFolder() {
1143        let panel = NSOpenPanel()
1144        panel.canChooseFiles = false
1145        panel.canChooseDirectories = true
1146        panel.canCreateDirectories = true
1147        panel.directoryURL = configFolder ?? ConfigFolder.suggested
1148        panel.message = String(localized: "Choose the folder for config.toml and orgstar's other configuration files.", comment: "Choose Configuration Folder panel")
1149        guard panel.runModal() == .OK, let url = panel.url else { return }
1150        if !ConfigFolder.set(url) {
1151            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"),
1152                             String(localized: "Access lasts until orgstar quits.", comment: "Alert when a folder grant or the configuration folder can't be saved"))
1153        }
1154        useConfigFolder(url)
1155    }
1156
1157    /// Reads and writes the configuration in `url`, or with nil in the default folder.
1158    private func useConfigFolder(_ url: URL?) {
1159        if url == nil { ConfigFolder.clear() }
1160        UserConfig.directoryOverride = url
1161        configFolder = url
1162        ConfigSync.shared.move(to: UserConfig.configFile)
1163    }
1164    #endif
1165
1166    #if !APPSTORE
1167    /// Links the `orgstar` command into a folder chosen in an open panel.
1168    private func installCommandLineTool() {
1169        let panel = NSOpenPanel()
1170        panel.canChooseFiles = false
1171        panel.canChooseDirectories = true
1172        panel.canCreateDirectories = true
1173        panel.showsHiddenFiles = true
1174        panel.directoryURL = CommandLineTool.suggestedFolder()
1175        panel.prompt = String(localized: "Install", table: "DeveloperID")
1176        panel.message = String(localized: "Choose a folder on your PATH for the orgstar command, such as ~/.local/bin or /usr/local/bin.", table: "DeveloperID")
1177        guard panel.runModal() == .OK, let folder = panel.url else { return }
1178        let helper = CommandLineTool.helper()
1179        let alert = NSAlert()
1180        alert.messageText = String(localized: "Couldn't Install orgstar", table: "DeveloperID")
1181        do {
1182            let link = try CommandLineTool.install(helper, in: folder)
1183            alert.messageText = String(localized: "Installed orgstar", table: "DeveloperID")
1184            alert.informativeText = String(localized: "\(OrgPaths.abbreviatingWithTilde(link.path)) runs the command in this app. Type orgstar --help in Terminal.", table: "DeveloperID")
1185        } catch {
1186            switch error {
1187            case .missing:
1188                alert.informativeText = String(localized: "This copy of orgstar has no command-line tool.", table: "DeveloperID")
1189            case .occupied(let path):
1190                alert.informativeText = String(localized: "\(path) is already there and isn't a link. Move it away or choose another folder.", table: "DeveloperID")
1191            case .unwritable(let path, let reason):
1192                alert.informativeText = String(localized: "orgstar can't write in \(path): \(reason). Choose a folder of your own, such as ~/.local/bin, or make the link in Terminal: sudo ln -sf '\(helper.path)' '\(path)/orgstar'", table: "DeveloperID")
1193            }
1194        }
1195        alert.runModal()
1196    }
1197    #endif
1198
1199    private var general: some View {
1200        Form {
1201            Section {
1202                LabeledContent("config.toml") {
1203                    HStack {
1204                        Button("Edit in orgstar") { editConfig() }
1205                        Button("Open with Default App") { NSWorkspace.shared.open(UserConfig.configFile) }
1206                        Button("Show in Finder") { NSWorkspace.shared.activateFileViewerSelecting([UserConfig.configFile]) }
1207                    }
1208                }
1209                #if APPSTORE
1210                LabeledContent("Folder") {
1211                    HStack {
1212                        Button("Choose Configuration Folder…") { chooseConfigFolder() }
1213                        if configFolder != nil { Button("Use Default Folder") { useConfigFolder(nil) } }
1214                    }
1215                }
1216                #endif
1217                LabeledContent("Emacs") {
1218                    Button("Import from Emacs…") { importing = true }
1219                }
1220            } footer: {
1221                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.")
1222                    .settingsFooter()
1223            }
1224            #if !APPSTORE
1225            Section {
1226                LabeledContent {
1227                    Button { installCommandLineTool() } label: { Text("Install Command-Line Tool…", tableName: "DeveloperID") }
1228                } label: {
1229                    Text("Command line", tableName: "DeveloperID")
1230                }
1231            } footer: {
1232                Text("Links the orgstar command into a folder on your PATH, to print the agenda, capture, clock in and out, and export from Terminal.", tableName: "DeveloperID")
1233                    .settingsFooter()
1234            }
1235            if updates.canCheck {
1236                Section {
1237                    Toggle(isOn: Binding(get: { updates.automatically }, set: { updates.automatically = $0 })) { Text("Check for updates automatically", tableName: "DeveloperID") }
1238                } footer: {
1239                    Text("Once a day, from the app's own feed. orgstar ▸ Check for Updates… checks now.", tableName: "DeveloperID")
1240                        .settingsFooter()
1241                }
1242            }
1243            #endif
1244            Section {
1245                Picker("Save files", selection: $saveMode) {
1246                    Text("Automatically, when typing stops").tag(SaveMode.automatic)
1247                    Text("Only with File ▸ Save (⌘S)").tag(SaveMode.explicit)
1248                }
1249                .pickerStyle(.radioGroup)
1250            }
1251            Section {
1252                Picker("Keys", selection: $preset) {
1253                    ForEach(KeymapPreset.allCases, id: \.self) { Text($0.title).tag($0) }
1254                }
1255                Toggle("Show hidden files and folders", isOn: $showHiddenFiles)
1256                Toggle("Keep orgstar in the menu bar", isOn: $menuBarItem)
1257                    .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.")
1258                Picker("Option as Meta", selection: $optionAsMeta) {
1259                    Text("Left Option").tag(OptionAsMeta.left.rawValue)
1260                    Text("Right Option").tag(OptionAsMeta.right.rawValue)
1261                    Text("Both").tag(OptionAsMeta([.left, .right]).rawValue)
1262                    Text("Neither").tag(0)
1263                }
1264            } footer: {
1265                Text("Your own bindings go in \(KeymapLoader.userFile.path), on top of the preset.")
1266                    .settingsFooter()
1267            }
1268        }
1269        .formStyle(.grouped)
1270        .frame(height: 330)
1271        .sheet(isPresented: $importing) { EmacsImportView(workspace: workspace) }
1272    }
1273
1274    private var editing: some View {
1275        Form {
1276            Section {
1277                Picker("Tags", selection: $tagsColumn) {
1278                    Text("Aligned to end at column 77").tag(-77)
1279                    Text("One space after the title").tag(0)
1280                }
1281                .help(Text(verbatim: "org-tags-column"))
1282                Toggle(isOn: $headingAfterSubtree) { keyed("New headings go after the subtree", "org.heading.insert") }
1283                    .help(Text(verbatim: "org-insert-heading-respect-content"))
1284                Toggle(isOn: $splitLine) { keyed("New headings and items split the line at the caret", "org.heading.insert") }
1285                    .help(Text(verbatim: "org-M-RET-may-split-line"))
1286                Toggle("Lists can use letters (a. b. c.)", isOn: $alphabeticalLists)
1287                    .help(Text(verbatim: "org-list-allow-alphabetical"))
1288                Stepper(value: $fillColumn, in: 40...200) { keyed("Fill Paragraph wraps lines at column \(fillColumn)", "org.fill-paragraph") }
1289                    .help(Text(verbatim: "fill-column"))
1290            }
1291            Section {
1292                Toggle("Long lines run off the edge instead of wrapping", isOn: $startupTruncated)
1293                    .help(Text(verbatim: "org-startup-truncated"))
1294            } footer: {
1295                Text("Applies to files as they open. View ▸ Truncate Long Lines switches the current file.")
1296                    .settingsFooter()
1297            }
1298            Section {
1299                Toggle("Emacs hides emphasis markers", isOn: $hiddenMarkers)
1300                    .help(Text(verbatim: "org-hide-emphasis-markers"))
1301                Toggle("Emacs shows entities as characters", isOn: $prettyEntities)
1302                    .help(Text(verbatim: "org-pretty-entities"))
1303            } footer: {
1304                Text("Tags, tables and Fill Paragraph measure text as your Emacs displays it, so both write the same file.")
1305                    .settingsFooter()
1306            }
1307            Section {
1308                TextField("Default TODO keywords", text: $todoKeywords, axis: .vertical)
1309            } footer: {
1310                Text("For files without #+TODO, in #+TODO syntax, one sequence per line. Takes effect when orgstar restarts.")
1311                    .settingsFooter()
1312            }
1313            Section {
1314                Toggle("Entries can't be done before their TODO children", isOn: $enforceTodoDependencies)
1315                    .help(Text(verbatim: "org-enforce-todo-dependencies"))
1316                Toggle("Entries can't be done with unchecked boxes", isOn: $enforceTodoCheckboxDependencies)
1317                    .help(Text(verbatim: "org-enforce-todo-checkbox-dependencies"))
1318            } footer: {
1319                Text("Under a parent with the ORDERED property (Org ▸ Properties and Columns ▸ Toggle ORDERED Property), TODO children are also done in order.")
1320                    .settingsFooter()
1321            }
1322            Section {
1323                Picker("When an entry is done", selection: $logDone) {
1324                    Text("Record nothing").tag("nil")
1325                    Text("Record the time, as CLOSED").tag("time")
1326                    Text("Record the time and ask for a note").tag("note")
1327                }
1328                .help(Text(verbatim: "org-log-done"))
1329                Toggle("State notes go in a LOGBOOK drawer", isOn: logIntoDrawerOn)
1330                    .help(Text(verbatim: "org-log-into-drawer"))
1331            } footer: {
1332                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.")
1333                    .settingsFooter()
1334            }
1335            Section {
1336                Toggle("Speed keys: single letters at the start of a heading line run commands", isOn: $useSpeedCommands)
1337                    .help(Text(verbatim: "org-use-speed-commands"))
1338                Toggle("Check spelling while typing", isOn: $spellCheck)
1339                    .help(Text(verbatim: "spell-check"))
1340            } footer: {
1341                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.")
1342                    .settingsFooter()
1343            }
1344            Section {
1345                Picker("Completion list opens", selection: $completionAuto) {
1346                    Text("As the keys do (by itself with Doom)").tag("preset")
1347                    Text("By itself as you type").tag("on")
1348                    Text("Only with a key").tag("off")
1349                }
1350                .help(Text(verbatim: "completion-auto"))
1351                Stepper("After a pause of \(completionAutoDelay) ms", value: $completionAutoDelay, in: 0...2000, step: 50)
1352                    .help(Text(verbatim: "completion-auto-delay"))
1353                Stepper("Once \(completionAutoPrefix) characters are typed", value: $completionAutoPrefix, in: 1...10)
1354                    .help(Text(verbatim: "completion-auto-prefix"))
1355                Picker("Candidates", selection: $completionStyle) {
1356                    Text("As the keys do (letters in order with Doom)").tag("preset")
1357                    Text("Start with what's typed").tag("prefix")
1358                    Text("Have its letters in order, best first").tag("fuzzy")
1359                }
1360                .help(Text(verbatim: "completion-style"))
1361                Toggle("The list offers words from open files and folders", isOn: $completionWords)
1362                    .help(Text(verbatim: "completion-words"))
1363            } header: {
1364                Text("Completion")
1365            } footer: {
1366                Text("Doom's keys open the list by itself and match letters in order, as Doom's corfu does; the Emacs and Mac keys do neither unless set here. Expand Word completes the word before the caret from your files whatever is set.")
1367                    .settingsFooter()
1368            }
1369        }
1370        .formStyle(.grouped)
1371        .frame(height: 860)
1372    }
1373
1374    /// `label`, then the keys that run `command` in the current preset, if any.
1375    private func keyed(_ label: LocalizedStringKey, _ command: String) -> some View {
1376        HStack(spacing: 6) {
1377            Text(label)
1378            if let keys = commands.keyLabel(for: command) {
1379                Text(verbatim: keys).font(.system(.body, design: .monospaced)).foregroundStyle(.secondary)
1380            }
1381        }
1382    }
1383
1384    /// `org-log-into-drawer` as a switch: on is "LOGBOOK" (Emacs's t); a drawer name of its own counts as on.
1385    private var logIntoDrawerOn: Binding<Bool> {
1386        Binding(get: { !logIntoDrawer.isEmpty }, set: { logIntoDrawer = $0 ? "LOGBOOK" : "" })
1387    }
1388
1389    private var appearance: some View {
1390        Form {
1391            ThemePickerSection()
1392            AppIconSection()
1393            Section {
1394                Picker("Font", selection: $themeFont) {
1395                    Text("System monospaced").tag("")
1396                    Divider()
1397                    ForEach(Self.monospacedFamilies, id: \.self) { Text($0).tag($0) }
1398                    if !themeFont.isEmpty, !Self.monospacedFamilies.contains(themeFont) { Text(themeFont).tag(themeFont) }
1399                }
1400                Picker("Body font", selection: $themeBodyFont) {
1401                    Text("Same as Font").tag("")
1402                    Text("System").tag("system")
1403                    Divider()
1404                    ForEach(Self.proportionalFamilies, id: \.self) { Text($0).tag($0) }
1405                    if !["", "system"].contains(themeBodyFont), !Self.proportionalFamilies.contains(themeBodyFont) { Text(themeBodyFont).tag(themeBodyFont) }
1406                }
1407                Stepper("Size: \(themeFontSize) pt", value: $themeFontSize, in: 8...36)
1408                Stepper("Line spacing: \(themeLineSpacing) pt", value: $themeLineSpacing, in: 0...16)
1409                Picker("Text width", selection: $themeTextWidth) {
1410                    Text("Whole editor").tag(0)
1411                    ForEach([60, 70, 80, 90, 100, 120], id: \.self) { Text("\($0) columns").tag($0) }
1412                    if ![0, 60, 70, 80, 90, 100, 120].contains(themeTextWidth) { Text("\(themeTextWidth) columns").tag(themeTextWidth) }
1413                }
1414                Stepper("Headings grow by \(themeHeadingStep) pt a level", value: $themeHeadingStep, in: 0...8)
1415            } footer: {
1416                Text("Tags and tables line up in columns, so Font should be monospaced. With a body font, prose uses it while tables, code, dates, tags and drawers keep Font.")
1417                    .settingsFooter()
1418            }
1419            Section {
1420                LabeledContent("Colors") {
1421                    HStack {
1422                        Button("Edit in config.toml") { editConfig() }
1423                        Button("Show Default Theme") {
1424                            openWindow(id: "main")
1425                            commands.jump(path: UserConfig.directory.appendingPathComponent("default-theme.toml").path, offset: 0)
1426                        }
1427                    }
1428                }
1429            } footer: {
1430                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.")
1431                    .settingsFooter()
1432            }
1433        }
1434        .formStyle(.grouped)
1435        .frame(height: 620)
1436    }
1437
1438    private var agenda: some View {
1439        Form {
1440            Section {
1441                Stepper("Agenda shows \(agendaSpan) days", value: $agendaSpan, in: 1...366)
1442                Stepper(agendaStartOffset == 0 ? "Agenda starts today" : "Agenda starts \(-agendaStartOffset) days before today", value: $agendaStartOffset, in: -14...0)
1443                Toggle("Include files in subfolders", isOn: $agendaSubfolders)
1444                Toggle("Show days without entries", isOn: $agendaShowAllDates)
1445                Toggle("Habits only today", isOn: $habitsOnlyForToday)
1446                Picker("Blocked entries", selection: $agendaDimBlockedTasks) {
1447                    Text("Dimmed").tag("t")
1448                    Text("Hidden").tag("invisible")
1449                    Text("Shown as usual").tag("nil")
1450                }
1451            }
1452            Section {
1453                Toggle("Show events from Calendar", isOn: $calendarEvents)
1454                    .disabled(!ProAccess.shared.isUnlocked && !calendarEvents)
1455                    .help(ProAccess.shared.isUnlocked ? "" : "Needs orgstar+")
1456                if calendarEvents {
1457                    choices(calendars, empty: CalendarEvents.isAuthorized ? "No calendars." : "Allow orgstar to read your calendars in System Settings ▸ Privacy & Security ▸ Calendars.", setting: $calendarEventCalendars)
1458                }
1459            } footer: {
1460                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.")
1461                    .settingsFooter()
1462            }
1463            .task(id: calendarEvents) {
1464                let allowed = calendarEvents ? await CalendarAccess.events.requestAccess() : false
1465                calendars = allowed ? CalendarAccess.events.calendars() : []
1466            }
1467            Section {
1468                Toggle("Show reminders from Reminders", isOn: $agendaReminders)
1469                    .disabled(!ProAccess.shared.isUnlocked && !agendaReminders)
1470                    .help(ProAccess.shared.isUnlocked ? "" : "Needs orgstar+")
1471                if agendaReminders {
1472                    choices(reminderLists, empty: ReminderLists.isAuthorized ? "No lists." : "Allow orgstar to read your reminders in System Settings ▸ Privacy & Security ▸ Reminders.", setting: $agendaReminderLists)
1473                }
1474            } footer: {
1475                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.")
1476                    .settingsFooter()
1477            }
1478            .task(id: agendaReminders) {
1479                let allowed = agendaReminders ? await CalendarAccess.reminders.requestAccess() : false
1480                reminderLists = allowed ? CalendarAccess.reminders.lists() : []
1481            }
1482            Section {
1483                Toggle("Notify before timed agenda entries", isOn: $reminders)
1484                Stepper("\(reminderLead) minutes before", value: $reminderLead, in: 0...120)
1485                    .disabled(!reminders)
1486            } footer: {
1487                Text("An entry's APPT_WARNTIME property overrides the lead time.")
1488                    .settingsFooter()
1489            }
1490            Section {
1491                Toggle("Ask what to do with idle time while clocked in", isOn: Binding {
1492                    clockIdleTime > 0
1493                } set: { on in
1494                    clockIdleTime = on ? 15 : 0
1495                })
1496                Stepper("After \(max(clockIdleTime, 1)) minutes without keyboard or mouse input", value: $clockIdleTime, in: 1...240)
1497                    .disabled(clockIdleTime == 0)
1498                Stepper("Remember \(clockHistoryLength) recently clocked entries", value: $clockHistoryLength, in: 1...35)
1499            } footer: {
1500                Text("org-clock-idle-time and org-clock-history-length. Org ▸ Clock lists the recent entries.")
1501                    .settingsFooter()
1502            }
1503        }
1504        .formStyle(.grouped)
1505        .frame(height: 560)
1506    }
1507
1508    /// A toggle per calendar or reminder list, with its color; `empty` when there are none.
1509    @ViewBuilder
1510    private func choices(_ calendars: [(id: String, title: String, color: RGBA?)], empty: LocalizedStringKey, setting: Binding<String>) -> some View {
1511        if calendars.isEmpty {
1512            Text(empty)
1513                .foregroundStyle(.secondary)
1514        }
1515        ForEach(calendars, id: \.id) { calendar in
1516            Toggle(isOn: chosen(calendar, among: calendars, setting: setting)) {
1517                HStack(spacing: 6) {
1518                    Circle()
1519                        .fill(calendar.color.map { Color(.sRGB, red: $0.red, green: $0.green, blue: $0.blue, opacity: $0.alpha) } ?? .secondary)
1520                        .frame(width: 8, height: 8)
1521                    Text(calendar.title)
1522                }
1523            }
1524        }
1525    }
1526
1527    /// `calendar-event-calendars` and `agenda-reminder-lists`: empty for every calendar or
1528    /// list, else the titles checked.
1529    private func chosen(
1530        _ calendar: (id: String, title: String, color: RGBA?), among calendars: [(id: String, title: String, color: RGBA?)], setting: Binding<String>
1531    ) -> Binding<Bool> {
1532        let chosen = setting.wrappedValue.split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
1533        return Binding {
1534            CalendarEvents.chooses(id: calendar.id, title: calendar.title, chosen: chosen)
1535        } set: { on in
1536            var titles = calendars.map(\.title).filter { title in
1537                chosen.isEmpty || chosen.contains(title) || chosen.contains(calendars.first { $0.title == title }?.id ?? "")
1538            }
1539            titles.removeAll { $0 == calendar.title }
1540            if on { titles.append(calendar.title) }
1541            // An empty list means every calendar; turning events off hides them all.
1542            guard !titles.isEmpty else { return }
1543            setting.wrappedValue = Set(titles) == Set(calendars.map(\.title)) ? "" : titles.joined(separator: ", ")
1544        }
1545    }
1546
1547    private var capture: some View {
1548        Form {
1549            Section {
1550                Toggle("⌃⌥Space opens Capture from any app", isOn: $globalCapture)
1551            } footer: {
1552                Text("Templates go in \(CaptureTemplates.userFile.path).")
1553                    .settingsFooter()
1554            }
1555            XCallbackSettings()
1556        }
1557        .formStyle(.grouped)
1558        .frame(height: 360)
1559    }
1560}
1561
1562extension Text {
1563    func settingsFooter() -> some View {
1564        font(.caption)
1565            .foregroundStyle(.secondary)
1566            .textSelection(.enabled)
1567            .frame(maxWidth: .infinity, alignment: .leading)
1568    }
1569}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form