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