Sources/Orgstar/OrgstarApp.swift

0dbf01d3bc8b68b775dfc3a8385b84bd682b85dd
orgstar/Sources/Orgstar/OrgstarApp.swift

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