Sources/Orgstar/OrgstarApp.swift

179a5811b2572a291069756654682ed095210c9d
orgstar/Sources/Orgstar/OrgstarApp.swift

1090 lines · 51887 bytes

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