Sources/Orgstar/OrgstarApp.swift

c14bb709281f24e063705eed4979a235abdb4967
orgstar/Sources/Orgstar/OrgstarApp.swift

1026 lines · 48236 bytes

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