Sources/Orgstar/OrgstarApp.swift

d5d689119906f897a828c3446b186ad97c0a37ea
orgstar/Sources/Orgstar/OrgstarApp.swift

238 lines · 10076 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    /// A location another window asked the main window to show.
 17    private(set) var jumpRequest: (path: String, offset: Int, id: Int)?
 18    private var jumpID = 0
 19    /// The editor showing the open file, for menus and the palette.
 20    var editor: OrgEditor?
 21    /// The pending key prefix, and what can follow it.
 22    var pendingKeys: String?
 23    var keyHints: [KeyHint] = []
 24    /// A question a command asked, answered in the echo area.
 25    private(set) var prompt: PromptRequest?
 26    /// The last message from a command or the keymap, cleared after a few seconds.
 27    private(set) var message: String?
 28    private var messageID = 0
 29
 30    func ask(_ prompt: Prompt, reply: @escaping (String?) -> Void) {
 31        self.prompt = PromptRequest(prompt: prompt, reply: reply)
 32    }
 33
 34    /// Ends the prompt with an answer, or nil to cancel, and gives the editor the keys back.
 35    func answer(_ text: String?) {
 36        guard let request = prompt else { return }
 37        prompt = nil
 38        if let textView = editor?.textView { textView.window?.makeFirstResponder(textView) }
 39        request.reply(text)
 40    }
 41
 42    func jump(path: String, offset: Int) {
 43        jumpID += 1
 44        jumpRequest = (path, offset, jumpID)
 45    }
 46
 47    func show(_ text: String) {
 48        messageID += 1
 49        let id = messageID
 50        message = text
 51        Task {
 52            try? await Task.sleep(for: .seconds(4))
 53            if messageID == id { message = nil }
 54        }
 55    }
 56}
 57
 58struct PromptRequest: Identifiable {
 59    let id = UUID()
 60    let prompt: Prompt
 61    let reply: (String?) -> Void
 62}
 63
 64@MainActor
 65final class AppDelegate: NSObject, NSApplicationDelegate {
 66    var session: DocumentSession?
 67
 68    func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { true }
 69
 70    func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {
 71        guard let session else { return .terminateNow }
 72        return UnsavedChanges.resolve(session) ? .terminateNow : .terminateCancel
 73    }
 74}
 75
 76/// Unsaved edits when leaving a file or quitting.
 77@MainActor
 78enum UnsavedChanges {
 79    /// Whether the open file can be left: saved in automatic mode, or as the user chooses in
 80    /// explicit mode. A save that fails or conflicts keeps the file open.
 81    static func resolve(_ session: DocumentSession) -> Bool {
 82        guard session.isDirty else { return true }
 83        if session.saveMode == .automatic { return session.save() }
 84        let alert = NSAlert()
 85        alert.messageText = "Save changes to \(session.path.map { ($0 as NSString).lastPathComponent } ?? "this file")?"
 86        alert.informativeText = "Your changes will be lost if you don't save them."
 87        alert.addButton(withTitle: "Save")
 88        alert.addButton(withTitle: "Don't Save")
 89        alert.addButton(withTitle: "Cancel")
 90        switch alert.runModal() {
 91        case .alertFirstButtonReturn: return session.save()
 92        case .alertSecondButtonReturn: return true
 93        default: return false
 94        }
 95    }
 96}
 97
 98@main
 99struct OrgstarApp: App {
100    @NSApplicationDelegateAdaptor private var delegate: AppDelegate
101    @State private var workspace = Result {
102        try WorkspaceModel(directory: WorkspaceModel.defaultDirectory, settings: .with(todoKeywords: Preferences.orgSettings))
103    }
104    @State private var commands = AppCommands()
105    @State private var session: DocumentSession = {
106        let session = DocumentSession()
107        session.defaults = Preferences.orgSettings
108        return session
109    }()
110
111    var body: some Scene {
112        Window("Orgstar", id: "main") {
113            switch workspace {
114            case .success(let model):
115                ContentView(workspace: model, session: session, commands: commands)
116                    .onAppear { delegate.session = session }
117            case .failure(let error):
118                ContentUnavailableView("Can't open the index", systemImage: "exclamationmark.triangle", description: Text(error.localizedDescription))
119            }
120        }
121        .defaultSize(width: 1280, height: 860)
122        Window("Agenda", id: "agenda") {
123            if case .success(let model) = workspace {
124                AgendaView(workspace: model, session: session, commands: commands)
125            }
126        }
127        .defaultSize(width: 760, height: 720)
128        .commands {
129            CommandGroup(after: .newItem) {
130                Button("Add Folder…") { commands.showingFolderPicker = true }
131                    .keyboardShortcut("o", modifiers: [.command, .shift])
132                Button("Quick Open…") { commands.showingQuickOpen = true }
133                    .keyboardShortcut("p")
134                Button("Command Palette…") { commands.showingPalette = true }
135                    .keyboardShortcut("p", modifiers: [.command, .shift])
136            }
137            CommandGroup(replacing: .saveItem) {
138                Button("Save") {
139                    if !session.save(), session.conflict != nil { commands.showingConflict = true }
140                }
141                .keyboardShortcut("s")
142                .disabled(session.path == nil || session.isReadOnly)
143            }
144            CommandGroup(after: .textEditing) {
145                Button("Search Notes") { commands.focusSearch = true }
146                    .keyboardShortcut("f", modifiers: [.command, .shift])
147            }
148            CommandGroup(before: .windowList) {
149                AgendaMenuItem()
150            }
151        }
152        .commands {
153            CommandMenu("Org") {
154                ForEach(EditorCommands.all.filter { $0.id.hasPrefix("org.") }, id: \.id) { command in
155                    Button(command.title) { commands.editor?.run(command.id) }
156                        .disabled(commands.editor == nil)
157                }
158            }
159        }
160        Settings {
161            SettingsView()
162        }
163    }
164}
165
166/// Window ▸ Agenda.
167struct AgendaMenuItem: View {
168    @Environment(\.openWindow) private var openWindow
169
170    var body: some View {
171        Button("Agenda") { openWindow(id: "agenda") }
172            .keyboardShortcut("a", modifiers: [.command, .shift])
173    }
174}
175
176struct SettingsView: View {
177    @AppStorage("saveMode") private var saveMode = SaveMode.automatic
178    @AppStorage("keymap") private var preset = KeymapPreset.emacs
179    @AppStorage("optionAsMeta") private var optionAsMeta = OptionAsMeta.left.rawValue
180    @AppStorage("tagsColumn") private var tagsColumn = -77
181    @AppStorage("headingAfterSubtree") private var headingAfterSubtree = true
182    @AppStorage("splitLine") private var splitLine = false
183    @AppStorage("alphabeticalLists") private var alphabeticalLists = true
184    @AppStorage("fillColumn") private var fillColumn = 80
185    @AppStorage("hiddenMarkers") private var hiddenMarkers = true
186    @AppStorage("prettyEntities") private var prettyEntities = true
187    @AppStorage("todoKeywords") private var todoKeywords = Preferences.defaultTodoKeywords
188    @AppStorage("agendaSpan") private var agendaSpan = 10
189    @AppStorage("agendaStartOffset") private var agendaStartOffset = -3
190    @AppStorage("agendaSubfolders") private var agendaSubfolders = false
191
192    var body: some View {
193        Form {
194            Picker("Save files:", selection: $saveMode) {
195                Text("Automatically, when typing stops").tag(SaveMode.automatic)
196                Text("Only with File ▸ Save (⌘S)").tag(SaveMode.explicit)
197            }
198            .pickerStyle(.radioGroup)
199            Picker("Keys:", selection: $preset) {
200                ForEach(KeymapPreset.allCases, id: \.self) { Text($0.title).tag($0) }
201            }
202            Picker("Option as Meta:", selection: $optionAsMeta) {
203                Text("Left Option").tag(OptionAsMeta.left.rawValue)
204                Text("Right Option").tag(OptionAsMeta.right.rawValue)
205                Text("Both").tag(OptionAsMeta([.left, .right]).rawValue)
206                Text("Neither").tag(0)
207            }
208            Text("Your own bindings go in \(KeymapLoader.userFile.path), on top of the preset.")
209                .font(.caption)
210                .foregroundStyle(.secondary)
211                .textSelection(.enabled)
212            Divider()
213            Picker("Tags:", selection: $tagsColumn) {
214                Text("Aligned to end at column 77").tag(-77)
215                Text("One space after the title").tag(0)
216            }
217            Toggle("M-RET adds the new heading after the subtree", isOn: $headingAfterSubtree)
218            Toggle("M-RET splits the line at the caret", isOn: $splitLine)
219            Toggle("Lists can use letters (a. b. c.)", isOn: $alphabeticalLists)
220            Stepper("M-q fills to column \(fillColumn)", value: $fillColumn, in: 40...200)
221            Toggle("Emacs hides emphasis markers (org-hide-emphasis-markers)", isOn: $hiddenMarkers)
222            Toggle("Emacs shows entities as characters (org-pretty-entities)", isOn: $prettyEntities)
223            Text("Tags, tables and M-q measure text as your Emacs displays it, so both write the same file.")
224                .font(.caption)
225                .foregroundStyle(.secondary)
226            TextField("Default TODO keywords:", text: $todoKeywords)
227            Text("For files without #+TODO, in #+TODO syntax. Takes effect when Orgstar restarts.")
228                .font(.caption)
229                .foregroundStyle(.secondary)
230            Divider()
231            Stepper("Agenda shows \(agendaSpan) days", value: $agendaSpan, in: 1...31)
232            Stepper(agendaStartOffset == 0 ? "Agenda starts today" : "Agenda starts \(-agendaStartOffset) days before today", value: $agendaStartOffset, in: -14...0)
233            Toggle("Agenda includes files in subfolders", isOn: $agendaSubfolders)
234        }
235        .padding(20)
236        .frame(width: 480)
237    }
238}
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