Sources/Orgstar/OrgstarApp.swift

71cfd8421de8b3d3c1fbdc9f394e56b267ec23e1
orgstar/Sources/Orgstar/OrgstarApp.swift

1085 lines · 51492 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        #if APPSTORE
 382        AgendaSnapshot.useGroupContainer = true
 383        EmacsFallback.offered = false
 384        _ = FolderGrants.shared
 385        ProStore.shared.start()
 386        #else
 387        DocumentSession.programs = Programs()
 388        MacPro.resolve()
 389        MacPro.renewInBackground()
 390        #endif
 391        // `org-sbe` in table formulas runs blocks, so it needs Babel as source blocks do.
 392        TableBlocks.allowed = { ProAccess.isUnlockedNow }
 393        // Debug builds, and runs with ORGSTAR_PERF set: main-thread stalls in the console.
 394        #if DEBUG
 395        Perf.watchMainThread()
 396        #else
 397        if ProcessInfo.processInfo.environment["ORGSTAR_PERF"] != nil { Perf.watchMainThread() }
 398        #endif
 399    }
 400
 401    var body: some Scene {
 402        Window("orgstar", id: "main") {
 403            switch workspace {
 404            case .success(let model):
 405                ContentView(workspace: model, session: session, commands: commands, scheduler: scheduler, clock: clock)
 406                    .environment(\.orgTheme, ConfigSync.shared.theme)
 407                    .tint(ConfigSync.shared.theme.color("accent"))
 408                    .onAppear {
 409                        delegate.session = session
 410                        delegate.commands = commands
 411                        #if APPSTORE
 412                        delegate.workspace = model
 413                        #endif
 414                        CaptureIntent.environment = (model, session, clock, commands)
 415                    }
 416            case .failure(let error):
 417                ContentUnavailableView("Can't open the index", systemImage: "exclamationmark.triangle", description: Text(error.localizedDescription))
 418            }
 419        }
 420        .defaultSize(width: 1280, height: 860)
 421        WindowGroup("Editor", id: "editor") {
 422            if case .success = workspace {
 423                EditorWindowView(session: session, commands: commands, clock: clock)
 424                    .environment(\.orgTheme, ConfigSync.shared.theme)
 425                    .tint(ConfigSync.shared.theme.color("accent"))
 426            }
 427        }
 428        .defaultSize(width: 900, height: 700)
 429        .commandsRemoved()
 430        Window("Agenda", id: "agenda") {
 431            if case .success(let model) = workspace {
 432                AgendaView(workspace: model, session: session, commands: commands, scheduler: scheduler, clock: clock)
 433                    .environment(\.orgTheme, ConfigSync.shared.theme)
 434                    .tint(ConfigSync.shared.theme.color("accent"))
 435            }
 436        }
 437        .defaultSize(width: 760, height: 720)
 438        Window("Board", id: "board") {
 439            if case .success(let model) = workspace {
 440                BoardView(workspace: model, session: session, commands: commands)
 441                    .environment(\.orgTheme, ConfigSync.shared.theme)
 442                    .tint(ConfigSync.shared.theme.color("accent"))
 443            }
 444        }
 445        .defaultSize(width: 1100, height: 700)
 446        Window("Clock Report", id: "clock-report") {
 447            if case .success(let model) = workspace {
 448                ClockReportView(workspace: model, session: session)
 449            }
 450        }
 451        .defaultSize(width: 860, height: 560)
 452        Window("Capture", id: "capture") {
 453            if case .success(let model) = workspace {
 454                CaptureView(workspace: model, session: session, commands: commands, clock: clock)
 455            }
 456        }
 457        .windowResizability(.contentSize)
 458        .windowLevel(.floating)
 459        .commands {
 460            CommandGroup(after: .newItem) {
 461                Button("Add Folder…") { commands.showingFolderPicker = true }
 462                    .keyboardShortcut("o", modifiers: [.command, .shift])
 463                Button("Quick Open…") { commands.showingQuickOpen = true }
 464                    .keyboardShortcut("p")
 465                Button("Command Palette…") { commands.showingPalette = true }
 466                    .keyboardShortcut("p", modifiers: [.command, .shift])
 467            }
 468            CommandGroup(after: .saveItem) {
 469                Menu("Export") {
 470                    ForEach(EditorCommands.all.filter { $0.id.hasPrefix("app.export.") && !hiddenCommandIDs.contains($0.id) }, id: \.id) { command in
 471                        Button(command.localizedTitle) { commands.run(command.id) }
 472                    }
 473                }
 474                .disabled(session.path == nil)
 475                Menu("Publish") {
 476                    ForEach(EditorCommands.all.filter { $0.id.hasPrefix("app.publish") }, id: \.id) { command in
 477                        Button(command.localizedTitle) { commands.run(command.id) }
 478                    }
 479                }
 480                Divider()
 481                Button("Revert to File on Disk") { commands.run("app.revert") }
 482                    .disabled(session.path == nil)
 483                Button("Resolve Sync Conflicts…") { commands.run("app.sync-conflicts") }
 484                    .disabled(session.path == nil)
 485                Button("Recovery Versions…") { commands.run("app.recovery") }
 486                    .disabled(session.path == nil)
 487            }
 488            CommandGroup(replacing: .saveItem) {
 489                Button("Close Buffer") {
 490                    // ⌘W closes the buffer in the main window, and other windows themselves.
 491                    if let key = NSApp.keyWindow, key.identifier?.rawValue.contains("main") != true {
 492                        key.performClose(nil)
 493                    } else {
 494                        commands.run("app.buffer.kill")
 495                    }
 496                }
 497                .keyboardShortcut("w")
 498                Button("Close Window") { NSApp.keyWindow?.performClose(nil) }
 499                    .keyboardShortcut("w", modifiers: [.command, .shift])
 500                Divider()
 501                Button("Save") {
 502                    if !session.save(), session.conflict != nil { commands.showingConflict = true }
 503                }
 504                .keyboardShortcut("s")
 505                .disabled(session.path == nil || session.isReadOnly)
 506                Button("Save All") { commands.run("app.save-all") }
 507                    .keyboardShortcut("s", modifiers: [.command, .option])
 508                    .disabled(session.dirtyPaths.isEmpty)
 509            }
 510            CommandGroup(after: .sidebar) {
 511                Button("Split Pane Below") { commands.run("app.split-below") }
 512                    .keyboardShortcut("2", modifiers: [.command, .control])
 513                Button("Split Pane Right") { commands.run("app.split-right") }
 514                    .keyboardShortcut("3", modifiers: [.command, .control])
 515                Button("Close Pane") { commands.run("app.pane-close") }
 516                    .keyboardShortcut("0", modifiers: [.command, .control])
 517                Button("Close Other Panes") { commands.run("app.pane-only") }
 518                    .keyboardShortcut("1", modifiers: [.command, .control])
 519                Button("Next Pane") { commands.run("app.pane-next") }
 520                    .keyboardShortcut("`", modifiers: [.command, .option])
 521                Divider()
 522                Button("Show or Hide Outline") { commands.run("app.toggle-outline") }
 523                    .keyboardShortcut("o", modifiers: [.command, .option])
 524                Button("Show or Hide Backlinks") { commands.run("app.toggle-backlinks") }
 525                Button("Show or Hide Columns and Clock") { commands.run("app.toggle-inspector") }
 526                    .keyboardShortcut("i", modifiers: [.command, .option])
 527                MarkupToggle()
 528                Button("Truncate or Wrap Long Lines") { commands.run("editor.toggle-truncate-lines") }
 529                Button("Turn Auto Fill On or Off") { commands.run("editor.toggle-auto-fill") }
 530                Button("Check Spelling While Typing") { commands.editor?.run("editor.toggle-spell-check") }
 531                    .disabled(commands.editor == nil)
 532            }
 533            CommandGroup(after: .pasteboard) {
 534                Divider()
 535                FindMenu(commands: commands)
 536            }
 537            CommandGroup(after: .textEditing) {
 538                Button("Cancel Running Task") { commands.run("app.babel.cancel") }
 539                    .keyboardShortcut(".")
 540                    .disabled(!session.isRunningBabel && commands.emacsTask == nil)
 541                Button("Search Notes") { commands.focusSearch = true }
 542                    .keyboardShortcut("f", modifiers: [.command, .shift])
 543            }
 544            CommandGroup(before: .windowList) {
 545                AgendaMenuItem()
 546                Divider()
 547                Button("Switch to Buffer…") { commands.run("app.buffer.switch") }
 548                Button("Next Buffer") { commands.run("app.buffer.next") }
 549                    .keyboardShortcut("]", modifiers: [.command, .shift])
 550                Button("Previous Buffer") { commands.run("app.buffer.previous") }
 551                    .keyboardShortcut("[", modifiers: [.command, .shift])
 552                Divider()
 553            }
 554            CommandGroup(after: .newItem) {
 555                Button("Capture…") { commands.run("app.capture") }
 556                    .keyboardShortcut("n", modifiers: [.command, .shift])
 557                Button("New Window") { commands.run("app.window-new") }
 558                    .keyboardShortcut("n", modifiers: [.command, .option])
 559            }
 560        }
 561        .commands {
 562            CommandMenu("Org") {
 563                ClockMenu(commands: commands, clock: clock)
 564                Divider()
 565                OrgMenuItems(commands: commands)
 566            }
 567        }
 568        .commands {
 569            CommandGroup(after: .appSettings) {
 570                Button("Edit Config File") { commands.jump(path: UserConfig.configFile.path, offset: 0) }
 571                    .keyboardShortcut(",", modifiers: [.command, .option])
 572            }
 573            #if !APPSTORE
 574            CommandGroup(after: .appInfo) {
 575                CheckForUpdatesItem(updates: delegate.updates)
 576            }
 577            #endif
 578            CommandGroup(before: .help) {
 579                Button("What's New in orgstar") { commands.whatsNew = WhatsNew.releases.first }
 580                    .disabled(!commands.mainWindowOpen)
 581            }
 582        }
 583        Settings {
 584            #if APPSTORE
 585            SettingsView(commands: commands, workspace: try? workspace.get())
 586            #else
 587            SettingsView(commands: commands, workspace: try? workspace.get(), updates: delegate.updates)
 588            #endif
 589        }
 590    }
 591}
 592
 593/// The Org menu: every org command, with the keys that run it in the current keymap.
 594struct OrgMenuItems: View {
 595    let commands: AppCommands
 596
 597    var body: some View {
 598        ForEach(EditorCommands.all.filter { $0.id.hasPrefix("org.") }, id: \.id) { command in
 599            Button {
 600                commands.editor?.run(command.id)
 601            } label: {
 602                Text(command.localizedTitle)
 603                if let keys = commands.keyLabel(for: command.id) { Text(keys) }
 604            }
 605            .disabled(commands.editor == nil)
 606        }
 607    }
 608}
 609
 610/// View ▸ Show Markup (link brackets and targets, emphasis markers) and Show Line Numbers.
 611struct MarkupToggle: View {
 612    @AppStorage("showTabBar") private var showTabBar = false
 613    @AppStorage("showMarkup") private var showMarkup = false
 614    @AppStorage("showLineNumbers") private var showLineNumbers = false
 615    @AppStorage("lineNumbersType") private var lineNumbersType = "t"
 616
 617    var body: some View {
 618        Toggle("Show Markup", isOn: $showMarkup)
 619            .keyboardShortcut("m", modifiers: [.command, .shift])
 620        Toggle("Show Line Numbers", isOn: $showLineNumbers)
 621            .keyboardShortcut("l", modifiers: [.command, .shift])
 622        Picker("Line Numbers", selection: $lineNumbersType) {
 623            Text("Absolute").tag("t")
 624            Text("Relative").tag("relative")
 625            Text("Visual").tag("visual")
 626        }
 627        Toggle("Show Tab Bar", isOn: $showTabBar)
 628    }
 629}
 630
 631/// Edit ▸ Find: the editor's find bar.
 632struct FindMenu: View {
 633    let commands: AppCommands
 634
 635    var body: some View {
 636        Menu("Find") {
 637            item("Find…", "edit.find", "f")
 638            item("Find and Replace…", "edit.replace", "f", [.command, .option])
 639            item("Find Next", "edit.find-next", "g")
 640            item("Find Previous", "edit.find-previous", "g", [.command, .shift])
 641            item("Use Selection for Find", "edit.use-selection-for-find", "e")
 642        }
 643    }
 644
 645    private func item(_ title: String, _ id: String, _ key: KeyEquivalent, _ modifiers: EventModifiers = .command) -> some View {
 646        Button(title) { commands.editor?.run(id) }
 647            .keyboardShortcut(key, modifiers: modifiers)
 648            .disabled(commands.editor == nil)
 649    }
 650}
 651
 652/// Window ▸ Agenda.
 653struct AgendaMenuItem: View {
 654    @Environment(\.openWindow) private var openWindow
 655
 656    var body: some View {
 657        Button("Agenda") { openWindow(id: "agenda") }
 658            .keyboardShortcut("a", modifiers: [.command, .shift])
 659        Button("Board") { openWindow(id: "board") }
 660            .keyboardShortcut("b", modifiers: [.command, .shift])
 661    }
 662}
 663
 664struct SettingsView: View {
 665    let commands: AppCommands
 666    let workspace: WorkspaceModel?
 667    #if !APPSTORE
 668    let updates: Updates
 669    #endif
 670    @State private var importing = false
 671    #if APPSTORE
 672    @State private var configFolder = UserConfig.directoryOverride
 673    #endif
 674    @Environment(\.openWindow) private var openWindow
 675    @AppStorage("saveMode") private var saveMode = SaveMode.automatic
 676    @AppStorage("keymap") private var preset = KeymapPreset.emacs
 677    @AppStorage("optionAsMeta") private var optionAsMeta = OptionAsMeta.left.rawValue
 678    @AppStorage("tagsColumn") private var tagsColumn = -77
 679    @AppStorage("headingAfterSubtree") private var headingAfterSubtree = false
 680    @AppStorage("splitLine") private var splitLine = false
 681    @AppStorage("alphabeticalLists") private var alphabeticalLists = true
 682    @AppStorage("fillColumn") private var fillColumn = 80
 683    @AppStorage("hiddenMarkers") private var hiddenMarkers = true
 684    @AppStorage("prettyEntities") private var prettyEntities = true
 685    @AppStorage("startupTruncated") private var startupTruncated = false
 686    @AppStorage("todoKeywords") private var todoKeywords = Preferences.defaultTodoKeywords
 687    @AppStorage("logDone") private var logDone = "nil"
 688    @AppStorage("logIntoDrawer") private var logIntoDrawer = ""
 689    @AppStorage("useSpeedCommands") private var useSpeedCommands = false
 690    @AppStorage("spellCheck") private var spellCheck = false
 691    @AppStorage("enforceTodoDependencies") private var enforceTodoDependencies = false
 692    @AppStorage("enforceTodoCheckboxDependencies") private var enforceTodoCheckboxDependencies = false
 693    @AppStorage("agendaSpan") private var agendaSpan = 10
 694    @AppStorage("agendaStartOffset") private var agendaStartOffset = 0
 695    @AppStorage("agendaSubfolders") private var agendaSubfolders = false
 696    @AppStorage("agendaShowAllDates") private var agendaShowAllDates = false
 697    @AppStorage("habitsOnlyForToday") private var habitsOnlyForToday = true
 698    @AppStorage("agendaDimBlockedTasks") private var agendaDimBlockedTasks = "t"
 699    @AppStorage("calendarEvents") private var calendarEvents = false
 700    @AppStorage("calendarEventCalendars") private var calendarEventCalendars = ""
 701    @State private var calendars: [(id: String, title: String, color: RGBA?)] = []
 702    @AppStorage("agendaReminders") private var agendaReminders = false
 703    @AppStorage("agendaReminderLists") private var agendaReminderLists = ""
 704    @State private var reminderLists: [(id: String, title: String, color: RGBA?)] = []
 705    @AppStorage("reminders") private var reminders = true
 706    @AppStorage("reminderLead") private var reminderLead = 12
 707    @AppStorage("clockIdleTime") private var clockIdleTime = 0
 708    @AppStorage("clockHistoryLength") private var clockHistoryLength = 5
 709    @AppStorage("globalCapture") private var globalCapture = true
 710    @AppStorage("settingsTab") private var tab = "general"
 711    @AppStorage("showHiddenFiles") private var showHiddenFiles = true
 712    @AppStorage("themeFont") private var themeFont = ""
 713    @AppStorage("themeBodyFont") private var themeBodyFont = ""
 714    @AppStorage("themeFontSize") private var themeFontSize = 13
 715    @AppStorage("themeLineSpacing") private var themeLineSpacing = 2
 716    @AppStorage("themeTextWidth") private var themeTextWidth = 0
 717    @AppStorage("themeHeadingStep") private var themeHeadingStep = 1
 718
 719    /// Installed font families that aren't monospaced, for body text.
 720    private static let proportionalFamilies: [String] = NSFontManager.shared.availableFontFamilies.filter { family in
 721        NSFontManager.shared.font(withFamily: family, traits: [], weight: 5, size: 13)?.isFixedPitch == false
 722    }
 723
 724    /// Installed monospaced font families.
 725    private static let monospacedFamilies: [String] = NSFontManager.shared.availableFontFamilies.filter { family in
 726        NSFontManager.shared.font(withFamily: family, traits: [], weight: 5, size: 13)?.isFixedPitch == true
 727    }
 728
 729    var body: some View {
 730        TabView(selection: $tab) {
 731            Tab("General", systemImage: "gearshape", value: "general") { general }
 732            Tab("Editing", systemImage: "text.alignleft", value: "editing") { editing }
 733            Tab("Appearance", systemImage: "paintpalette", value: "appearance") { appearance }
 734            Tab("Agenda", systemImage: "calendar", value: "agenda") { agenda }
 735            Tab("Capture", systemImage: "tray.and.arrow.down", value: "capture") { capture }
 736            #if APPSTORE
 737            Tab("orgstar+", systemImage: "star", value: "pro") { StoreForm() }
 738            #else
 739            Tab("orgstar+", systemImage: "star", value: "pro") { LicenseForm() }
 740            #endif
 741        }
 742        .frame(width: 600)
 743    }
 744
 745    private func editConfig() {
 746        ConfigSync.shared.start()
 747        openWindow(id: "main")
 748        commands.jump(path: UserConfig.configFile.path, offset: 0)
 749    }
 750
 751    #if APPSTORE
 752    /// A folder outside the app's container, such as `~/.config/orgstar` kept with dotfiles.
 753    private func chooseConfigFolder() {
 754        let panel = NSOpenPanel()
 755        panel.canChooseFiles = false
 756        panel.canChooseDirectories = true
 757        panel.canCreateDirectories = true
 758        panel.directoryURL = configFolder ?? ConfigFolder.suggested
 759        panel.message = String(localized: "Choose the folder for config.toml and orgstar's other configuration files.", comment: "Choose Configuration Folder panel")
 760        guard panel.runModal() == .OK, let url = panel.url else { return }
 761        if !ConfigFolder.set(url) {
 762            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"),
 763                             String(localized: "Access lasts until orgstar quits.", comment: "Alert when a folder grant or the configuration folder can't be saved"))
 764        }
 765        useConfigFolder(url)
 766    }
 767
 768    /// Reads and writes the configuration in `url`, or with nil in the default folder.
 769    private func useConfigFolder(_ url: URL?) {
 770        if url == nil { ConfigFolder.clear() }
 771        UserConfig.directoryOverride = url
 772        configFolder = url
 773        ConfigSync.shared.move(to: UserConfig.configFile)
 774    }
 775    #endif
 776
 777    private var general: some View {
 778        Form {
 779            Section {
 780                LabeledContent("config.toml") {
 781                    HStack {
 782                        Button("Edit in orgstar") { editConfig() }
 783                        Button("Open with Default App") { NSWorkspace.shared.open(UserConfig.configFile) }
 784                        Button("Show in Finder") { NSWorkspace.shared.activateFileViewerSelecting([UserConfig.configFile]) }
 785                    }
 786                }
 787                #if APPSTORE
 788                LabeledContent("Folder") {
 789                    HStack {
 790                        Button("Choose Configuration Folder…") { chooseConfigFolder() }
 791                        if configFolder != nil { Button("Use Default Folder") { useConfigFolder(nil) } }
 792                    }
 793                }
 794                #endif
 795                LabeledContent("Emacs") {
 796                    Button("Import from Emacs…") { importing = true }
 797                }
 798            } footer: {
 799                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.")
 800                    .settingsFooter()
 801            }
 802            #if !APPSTORE
 803            if updates.canCheck {
 804                Section {
 805                    Toggle(isOn: Binding(get: { updates.automatically }, set: { updates.automatically = $0 })) { Text("Check for updates automatically", tableName: "DeveloperID") }
 806                } footer: {
 807                    Text("Once a day, from the app's own feed. orgstar ▸ Check for Updates… checks now.", tableName: "DeveloperID")
 808                        .settingsFooter()
 809                }
 810            }
 811            #endif
 812            Section {
 813                Picker("Save files", selection: $saveMode) {
 814                    Text("Automatically, when typing stops").tag(SaveMode.automatic)
 815                    Text("Only with File ▸ Save (⌘S)").tag(SaveMode.explicit)
 816                }
 817                .pickerStyle(.radioGroup)
 818            }
 819            Section {
 820                Picker("Keys", selection: $preset) {
 821                    ForEach(KeymapPreset.allCases, id: \.self) { Text($0.title).tag($0) }
 822                }
 823                Toggle("Show hidden files and folders", isOn: $showHiddenFiles)
 824                Picker("Option as Meta", selection: $optionAsMeta) {
 825                    Text("Left Option").tag(OptionAsMeta.left.rawValue)
 826                    Text("Right Option").tag(OptionAsMeta.right.rawValue)
 827                    Text("Both").tag(OptionAsMeta([.left, .right]).rawValue)
 828                    Text("Neither").tag(0)
 829                }
 830            } footer: {
 831                Text("Your own bindings go in \(KeymapLoader.userFile.path), on top of the preset.")
 832                    .settingsFooter()
 833            }
 834        }
 835        .formStyle(.grouped)
 836        .frame(height: 330)
 837        .sheet(isPresented: $importing) { EmacsImportView(workspace: workspace) }
 838    }
 839
 840    private var editing: some View {
 841        Form {
 842            Section {
 843                Picker("Tags", selection: $tagsColumn) {
 844                    Text("Aligned to end at column 77").tag(-77)
 845                    Text("One space after the title").tag(0)
 846                }
 847                Toggle("M-RET adds the new heading after the subtree", isOn: $headingAfterSubtree)
 848                Toggle("M-RET splits the line at the caret", isOn: $splitLine)
 849                Toggle("Lists can use letters (a. b. c.)", isOn: $alphabeticalLists)
 850                Stepper("M-q fills to column \(fillColumn)", value: $fillColumn, in: 40...200)
 851            }
 852            Section {
 853                Toggle("Long lines run off the edge instead of wrapping (org-startup-truncated)", isOn: $startupTruncated)
 854            } footer: {
 855                Text("Applies to files as they open. View ▸ Truncate or Wrap Long Lines switches the current file.")
 856                    .settingsFooter()
 857            }
 858            Section {
 859                Toggle("Emacs hides emphasis markers (org-hide-emphasis-markers)", isOn: $hiddenMarkers)
 860                Toggle("Emacs shows entities as characters (org-pretty-entities)", isOn: $prettyEntities)
 861            } footer: {
 862                Text("Tags, tables and M-q measure text as your Emacs displays it, so both write the same file.")
 863                    .settingsFooter()
 864            }
 865            Section {
 866                TextField("Default TODO keywords", text: $todoKeywords, axis: .vertical)
 867            } footer: {
 868                Text("For files without #+TODO, in #+TODO syntax, one sequence per line. Takes effect when orgstar restarts.")
 869                    .settingsFooter()
 870            }
 871            Section {
 872                Toggle("Entries can't be done before their TODO children (org-enforce-todo-dependencies)", isOn: $enforceTodoDependencies)
 873                Toggle("Entries can't be done with unchecked boxes (org-enforce-todo-checkbox-dependencies)", isOn: $enforceTodoCheckboxDependencies)
 874            } footer: {
 875                Text("Under a parent with the ORDERED property (Toggle ORDERED Property, C-c C-x o), TODO children are also done in order.")
 876                    .settingsFooter()
 877            }
 878            Section {
 879                Picker("When an entry is done (org-log-done)", selection: $logDone) {
 880                    Text("Record nothing").tag("nil")
 881                    Text("Record the time, as CLOSED").tag("time")
 882                    Text("Record the time and ask for a note").tag("note")
 883                }
 884                Toggle("State notes go in a LOGBOOK drawer (org-log-into-drawer)", isOn: logIntoDrawerOn)
 885            } footer: {
 886                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.")
 887                    .settingsFooter()
 888            }
 889            Section {
 890                Toggle("Speed keys: single letters at the start of a heading line run commands (org-use-speed-commands)", isOn: $useSpeedCommands)
 891                Toggle("Check spelling while typing (spell-check)", isOn: $spellCheck)
 892            } footer: {
 893                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.")
 894                    .settingsFooter()
 895            }
 896        }
 897        .formStyle(.grouped)
 898        .frame(height: 860)
 899    }
 900
 901    /// `org-log-into-drawer` as a switch: on is "LOGBOOK" (Emacs's t); a drawer name of its own counts as on.
 902    private var logIntoDrawerOn: Binding<Bool> {
 903        Binding(get: { !logIntoDrawer.isEmpty }, set: { logIntoDrawer = $0 ? "LOGBOOK" : "" })
 904    }
 905
 906    private var appearance: some View {
 907        Form {
 908            ThemePickerSection()
 909            AppIconSection()
 910            Section {
 911                Picker("Font", selection: $themeFont) {
 912                    Text("System monospaced").tag("")
 913                    Divider()
 914                    ForEach(Self.monospacedFamilies, id: \.self) { Text($0).tag($0) }
 915                    if !themeFont.isEmpty, !Self.monospacedFamilies.contains(themeFont) { Text(themeFont).tag(themeFont) }
 916                }
 917                Picker("Body text", selection: $themeBodyFont) {
 918                    Text("Same as Font").tag("")
 919                    Text("System").tag("system")
 920                    Divider()
 921                    ForEach(Self.proportionalFamilies, id: \.self) { Text($0).tag($0) }
 922                    if !["", "system"].contains(themeBodyFont), !Self.proportionalFamilies.contains(themeBodyFont) { Text(themeBodyFont).tag(themeBodyFont) }
 923                }
 924                Stepper("Size: \(themeFontSize) pt", value: $themeFontSize, in: 8...36)
 925                Stepper("Line spacing: \(themeLineSpacing) pt", value: $themeLineSpacing, in: 0...16)
 926                Picker("Text width", selection: $themeTextWidth) {
 927                    Text("Whole editor").tag(0)
 928                    ForEach([60, 70, 80, 90, 100, 120], id: \.self) { Text("\($0) columns").tag($0) }
 929                    if ![0, 60, 70, 80, 90, 100, 120].contains(themeTextWidth) { Text("\(themeTextWidth) columns").tag(themeTextWidth) }
 930                }
 931                Stepper("Headings grow by \(themeHeadingStep) pt a level", value: $themeHeadingStep, in: 0...8)
 932            } footer: {
 933                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.")
 934                    .settingsFooter()
 935            }
 936            Section {
 937                LabeledContent("Colors") {
 938                    HStack {
 939                        Button("Edit in config.toml") { editConfig() }
 940                        Button("Show Default Theme") {
 941                            openWindow(id: "main")
 942                            commands.jump(path: UserConfig.directory.appendingPathComponent("default-theme.toml").path, offset: 0)
 943                        }
 944                    }
 945                }
 946            } footer: {
 947                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.")
 948                    .settingsFooter()
 949            }
 950        }
 951        .formStyle(.grouped)
 952        .frame(height: 620)
 953    }
 954
 955    private var agenda: some View {
 956        Form {
 957            Section {
 958                Stepper("Agenda shows \(agendaSpan) days", value: $agendaSpan, in: 1...366)
 959                Stepper(agendaStartOffset == 0 ? "Agenda starts today" : "Agenda starts \(-agendaStartOffset) days before today", value: $agendaStartOffset, in: -14...0)
 960                Toggle("Include files in subfolders", isOn: $agendaSubfolders)
 961                Toggle("Show days without entries", isOn: $agendaShowAllDates)
 962                Toggle("Habits only today", isOn: $habitsOnlyForToday)
 963                Picker("Blocked entries", selection: $agendaDimBlockedTasks) {
 964                    Text("Dimmed").tag("t")
 965                    Text("Hidden").tag("invisible")
 966                    Text("Shown as usual").tag("nil")
 967                }
 968            }
 969            Section {
 970                Toggle("Show events from Calendar", isOn: $calendarEvents)
 971                    .disabled(!ProAccess.shared.isUnlocked && !calendarEvents)
 972                    .help(ProAccess.shared.isUnlocked ? "" : "Needs orgstar+")
 973                if calendarEvents {
 974                    choices(calendars, empty: CalendarEvents.isAuthorized ? "No calendars." : "Allow orgstar to read your calendars in System Settings ▸ Privacy & Security ▸ Calendars.", setting: $calendarEventCalendars)
 975                }
 976            } footer: {
 977                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.")
 978                    .settingsFooter()
 979            }
 980            .task(id: calendarEvents) {
 981                let allowed = calendarEvents ? await CalendarAccess.events.requestAccess() : false
 982                calendars = allowed ? CalendarAccess.events.calendars() : []
 983            }
 984            Section {
 985                Toggle("Show reminders from Reminders", isOn: $agendaReminders)
 986                    .disabled(!ProAccess.shared.isUnlocked && !agendaReminders)
 987                    .help(ProAccess.shared.isUnlocked ? "" : "Needs orgstar+")
 988                if agendaReminders {
 989                    choices(reminderLists, empty: ReminderLists.isAuthorized ? "No lists." : "Allow orgstar to read your reminders in System Settings ▸ Privacy & Security ▸ Reminders.", setting: $agendaReminderLists)
 990                }
 991            } footer: {
 992                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.")
 993                    .settingsFooter()
 994            }
 995            .task(id: agendaReminders) {
 996                let allowed = agendaReminders ? await CalendarAccess.reminders.requestAccess() : false
 997                reminderLists = allowed ? CalendarAccess.reminders.lists() : []
 998            }
 999            Section {
1000                Toggle("Notify before timed agenda entries", isOn: $reminders)
1001                Stepper("\(reminderLead) minutes before", value: $reminderLead, in: 0...120)
1002                    .disabled(!reminders)
1003            } footer: {
1004                Text("An entry's APPT_WARNTIME property overrides the lead time.")
1005                    .settingsFooter()
1006            }
1007            Section {
1008                Toggle("Ask what to do with idle time while clocked in", isOn: Binding {
1009                    clockIdleTime > 0
1010                } set: { on in
1011                    clockIdleTime = on ? 15 : 0
1012                })
1013                Stepper("After \(max(clockIdleTime, 1)) minutes without keyboard or mouse input", value: $clockIdleTime, in: 1...240)
1014                    .disabled(clockIdleTime == 0)
1015                Stepper("Remember \(clockHistoryLength) recently clocked entries", value: $clockHistoryLength, in: 1...35)
1016            } footer: {
1017                Text("org-clock-idle-time and org-clock-history-length. Org ▸ Clock lists the recent entries.")
1018                    .settingsFooter()
1019            }
1020        }
1021        .formStyle(.grouped)
1022        .frame(height: 560)
1023    }
1024
1025    /// A toggle per calendar or reminder list, with its color; `empty` when there are none.
1026    @ViewBuilder
1027    private func choices(_ calendars: [(id: String, title: String, color: RGBA?)], empty: LocalizedStringKey, setting: Binding<String>) -> some View {
1028        if calendars.isEmpty {
1029            Text(empty)
1030                .foregroundStyle(.secondary)
1031        }
1032        ForEach(calendars, id: \.id) { calendar in
1033            Toggle(isOn: chosen(calendar, among: calendars, setting: setting)) {
1034                HStack(spacing: 6) {
1035                    Circle()
1036                        .fill(calendar.color.map { Color(.sRGB, red: $0.red, green: $0.green, blue: $0.blue, opacity: $0.alpha) } ?? .secondary)
1037                        .frame(width: 8, height: 8)
1038                    Text(calendar.title)
1039                }
1040            }
1041        }
1042    }
1043
1044    /// `calendar-event-calendars` and `agenda-reminder-lists`: empty for every calendar or
1045    /// list, else the titles checked.
1046    private func chosen(
1047        _ calendar: (id: String, title: String, color: RGBA?), among calendars: [(id: String, title: String, color: RGBA?)], setting: Binding<String>
1048    ) -> Binding<Bool> {
1049        let chosen = setting.wrappedValue.split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
1050        return Binding {
1051            CalendarEvents.chooses(id: calendar.id, title: calendar.title, chosen: chosen)
1052        } set: { on in
1053            var titles = calendars.map(\.title).filter { title in
1054                chosen.isEmpty || chosen.contains(title) || chosen.contains(calendars.first { $0.title == title }?.id ?? "")
1055            }
1056            titles.removeAll { $0 == calendar.title }
1057            if on { titles.append(calendar.title) }
1058            // An empty list means every calendar; turning events off hides them all.
1059            guard !titles.isEmpty else { return }
1060            setting.wrappedValue = Set(titles) == Set(calendars.map(\.title)) ? "" : titles.joined(separator: ", ")
1061        }
1062    }
1063
1064    private var capture: some View {
1065        Form {
1066            Section {
1067                Toggle("⌃⌥Space opens Capture from any app", isOn: $globalCapture)
1068            } footer: {
1069                Text("Templates go in \(CaptureTemplates.userFile.path).")
1070                    .settingsFooter()
1071            }
1072        }
1073        .formStyle(.grouped)
1074        .frame(height: 160)
1075    }
1076}
1077
1078extension Text {
1079    func settingsFooter() -> some View {
1080        font(.caption)
1081            .foregroundStyle(.secondary)
1082            .textSelection(.enabled)
1083            .frame(maxWidth: .infinity, alignment: .leading)
1084    }
1085}
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