Sources/Orgstar/OrgstarApp.swift

bd275bd1a81b85a03549d5435d6a0bd32c2cbd66
orgstar/Sources/Orgstar/OrgstarApp.swift

1567 lines · 77388 bytes

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