Sources/Orgstar/OrgstarApp.swift

9300add1d8a7e33f0fc51a6e9a6cf4969be05032
orgstar/Sources/Orgstar/OrgstarApp.swift

1375 lines · 67332 bytes

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