Sources/Orgstar/OrgstarApp.swift

397c9ad69a596cfff75844141c5e537217661eb3
orgstar/Sources/Orgstar/OrgstarApp.swift history · blame · raw

152 lines · 6006 bytes

  1import AppKit
  2import OrgApp
  3import OrgCore
  4import OrgEditorAppKit
  5import SwiftUI
  6
  7/// Window-level requests the menu bar makes.
  8@MainActor
  9@Observable
 10final class AppCommands {
 11    var showingQuickOpen = false
 12    var showingFolderPicker = false
 13    var focusSearch = false
 14    var showingConflict = false
 15    var showingPalette = false
 16    /// The editor showing the open file, for menus and the palette.
 17    var editor: OrgEditor?
 18    /// The pending key prefix, and what can follow it.
 19    var pendingKeys: String?
 20    var keyHints: [KeyHint] = []
 21    /// The last message from a command or the keymap, cleared after a few seconds.
 22    private(set) var message: String?
 23    private var messageID = 0
 24
 25    func show(_ text: String) {
 26        messageID += 1
 27        let id = messageID
 28        message = text
 29        Task {
 30            try? await Task.sleep(for: .seconds(4))
 31            if messageID == id { message = nil }
 32        }
 33    }
 34}
 35
 36@MainActor
 37final class AppDelegate: NSObject, NSApplicationDelegate {
 38    var session: DocumentSession?
 39
 40    func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { true }
 41
 42    func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {
 43        guard let session else { return .terminateNow }
 44        return UnsavedChanges.resolve(session) ? .terminateNow : .terminateCancel
 45    }
 46}
 47
 48/// Unsaved edits when leaving a file or quitting.
 49@MainActor
 50enum UnsavedChanges {
 51    /// Whether the open file can be left: saved in automatic mode, or as the user chooses in
 52    /// explicit mode. A save that fails or conflicts keeps the file open.
 53    static func resolve(_ session: DocumentSession) -> Bool {
 54        guard session.isDirty else { return true }
 55        if session.saveMode == .automatic { return session.save() }
 56        let alert = NSAlert()
 57        alert.messageText = "Save changes to \(session.path.map { ($0 as NSString).lastPathComponent } ?? "this file")?"
 58        alert.informativeText = "Your changes will be lost if you don't save them."
 59        alert.addButton(withTitle: "Save")
 60        alert.addButton(withTitle: "Don't Save")
 61        alert.addButton(withTitle: "Cancel")
 62        switch alert.runModal() {
 63        case .alertFirstButtonReturn: return session.save()
 64        case .alertSecondButtonReturn: return true
 65        default: return false
 66        }
 67    }
 68}
 69
 70@main
 71struct OrgstarApp: App {
 72    @NSApplicationDelegateAdaptor private var delegate: AppDelegate
 73    @State private var workspace = Result { try WorkspaceModel(directory: WorkspaceModel.defaultDirectory) }
 74    @State private var commands = AppCommands()
 75    @State private var session = DocumentSession()
 76
 77    var body: some Scene {
 78        Window("Orgstar", id: "main") {
 79            switch workspace {
 80            case .success(let model):
 81                ContentView(workspace: model, session: session, commands: commands)
 82                    .onAppear { delegate.session = session }
 83            case .failure(let error):
 84                ContentUnavailableView("Can't open the index", systemImage: "exclamationmark.triangle", description: Text(error.localizedDescription))
 85            }
 86        }
 87        .defaultSize(width: 1280, height: 860)
 88        .commands {
 89            CommandGroup(after: .newItem) {
 90                Button("Add Folder…") { commands.showingFolderPicker = true }
 91                    .keyboardShortcut("o", modifiers: [.command, .shift])
 92                Button("Quick Open…") { commands.showingQuickOpen = true }
 93                    .keyboardShortcut("p")
 94                Button("Command Palette…") { commands.showingPalette = true }
 95                    .keyboardShortcut("p", modifiers: [.command, .shift])
 96            }
 97            CommandGroup(replacing: .saveItem) {
 98                Button("Save") {
 99                    if !session.save(), session.conflict != nil { commands.showingConflict = true }
100                }
101                .keyboardShortcut("s")
102                .disabled(session.path == nil || session.isReadOnly)
103            }
104            CommandGroup(after: .textEditing) {
105                Button("Search Notes") { commands.focusSearch = true }
106                    .keyboardShortcut("f", modifiers: [.command, .shift])
107            }
108        }
109        .commands {
110            CommandMenu("Org") {
111                ForEach(EditorCommands.all.filter { $0.id.hasPrefix("org.") }, id: \.id) { command in
112                    Button(command.title) { commands.editor?.run(command.id) }
113                        .disabled(commands.editor == nil)
114                }
115            }
116        }
117        Settings {
118            SettingsView()
119        }
120    }
121}
122
123struct SettingsView: View {
124    @AppStorage("saveMode") private var saveMode = SaveMode.automatic
125    @AppStorage("keymap") private var preset = KeymapPreset.emacs
126    @AppStorage("optionAsMeta") private var optionAsMeta = OptionAsMeta.left.rawValue
127
128    var body: some View {
129        Form {
130            Picker("Save files:", selection: $saveMode) {
131                Text("Automatically, when typing stops").tag(SaveMode.automatic)
132                Text("Only with File ▸ Save (⌘S)").tag(SaveMode.explicit)
133            }
134            .pickerStyle(.radioGroup)
135            Picker("Keys:", selection: $preset) {
136                ForEach(KeymapPreset.allCases, id: \.self) { Text($0.title).tag($0) }
137            }
138            Picker("Option as Meta:", selection: $optionAsMeta) {
139                Text("Left Option").tag(OptionAsMeta.left.rawValue)
140                Text("Right Option").tag(OptionAsMeta.right.rawValue)
141                Text("Both").tag(OptionAsMeta([.left, .right]).rawValue)
142                Text("Neither").tag(0)
143            }
144            Text("Your own bindings go in \(KeymapLoader.userFile.path), on top of the preset.")
145                .font(.caption)
146                .foregroundStyle(.secondary)
147                .textSelection(.enabled)
148        }
149        .padding(20)
150        .frame(width: 420)
151    }
152}