Sources/Orgstar/OrgstarApp.swift

ed22b081d67b5b581163acfdbf816cc75d80ef27
orgstar/Sources/Orgstar/OrgstarApp.swift

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