Sources/Orgstar/OrgstarApp.swift

ea7e7fd2a0d65a2fb2df882c3ceeabcf86d3bd02
orgstar/Sources/Orgstar/OrgstarApp.swift

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