Sources/Orgstar/OrgstarApp.swift

19641366e5de9103a7d88bf80436ab2aebc03cf5
orgstar/Sources/Orgstar/OrgstarApp.swift

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