Sources/Orgstar/OrgstarApp.swift
377 lines · 15365 bytes
1import AppKit
2import OrgApp
3import OrgCore
4import OrgEditorAppKit
5import SwiftUI
6import UserNotifications
7
8/// Window-level requests the menu bar makes.
9@MainActor
10@Observable
11final class AppCommands {
12 var showingQuickOpen = false
13 var showingFolderPicker = false
14 var focusSearch = false
15 var showingConflict = false
16 var showingPalette = false
17 /// A location another window asked the main window to show.
18 private(set) var jumpRequest: (path: String, offset: Int, id: Int)?
19 private var jumpID = 0
20 /// The editor showing the open file, for menus and the palette.
21 var editor: OrgEditor?
22 /// The pending key prefix, and what can follow it.
23 var pendingKeys: String?
24 /// The editor's evil state in the Doom preset.
25 var editorState: String?
26 var keyHints: [KeyHint] = []
27 /// A question a command asked, answered in the echo area.
28 private(set) var prompt: PromptRequest?
29 /// The last message from a command or the keymap, cleared after a few seconds.
30 private(set) var message: String?
31 private var messageID = 0
32
33 func ask(_ prompt: Prompt, reply: @escaping (String?) -> Void) {
34 self.prompt = PromptRequest(prompt: prompt, reply: reply)
35 }
36
37 /// Ends the prompt with an answer, or nil to cancel, and gives the editor the keys back.
38 func answer(_ text: String?) {
39 guard let request = prompt else { return }
40 prompt = nil
41 if let textView = editor?.textView { textView.window?.makeFirstResponder(textView) }
42 request.reply(text)
43 }
44
45 /// An app command from a menu, run by the main window.
46 private(set) var runRequest: (id: String, serial: Int)?
47 private var runSerial = 0
48
49 func run(_ id: String) {
50 runSerial += 1
51 runRequest = (id, runSerial)
52 }
53
54 func jump(path: String, offset: Int) {
55 jumpID += 1
56 jumpRequest = (path, offset, jumpID)
57 }
58
59 func show(_ text: String) {
60 messageID += 1
61 let id = messageID
62 message = text
63 Task {
64 try? await Task.sleep(for: .seconds(4))
65 if messageID == id { message = nil }
66 }
67 }
68}
69
70struct PromptRequest: Identifiable {
71 let id = UUID()
72 let prompt: Prompt
73 let reply: (String?) -> Void
74}
75
76@MainActor
77final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCenterDelegate {
78 var session: DocumentSession?
79 var commands: AppCommands?
80
81 func applicationDidFinishLaunching(_ notification: Notification) {
82 if SystemReminderCenter.isAvailable { UNUserNotificationCenter.current().delegate = self }
83 }
84
85 /// Reminders show while Orgstar is in front too.
86 nonisolated func userNotificationCenter(
87 _ center: UNUserNotificationCenter, willPresent notification: UNNotification
88 ) async -> UNNotificationPresentationOptions {
89 [.banner, .sound, .list]
90 }
91
92 /// Clicking a reminder shows its entry.
93 nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {
94 let info = response.notification.request.content.userInfo
95 guard let path = info["path"] as? String, let offset = info["offset"] as? Int else { return }
96 await MainActor.run {
97 NSApp.activate()
98 commands?.jump(path: path, offset: offset)
99 }
100 }
101
102 func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { true }
103
104 func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {
105 guard let session else { return .terminateNow }
106 return UnsavedChanges.resolve(session) ? .terminateNow : .terminateCancel
107 }
108}
109
110/// Unsaved edits when leaving a file or quitting.
111@MainActor
112enum UnsavedChanges {
113 /// Whether the open file can be left: saved in automatic mode, or as the user chooses in
114 /// explicit mode. A save that fails or conflicts keeps the file open.
115 static func resolve(_ session: DocumentSession) -> Bool {
116 guard session.isDirty else { return true }
117 if session.saveMode == .automatic { return session.save() }
118 let alert = NSAlert()
119 alert.messageText = "Save changes to \(session.path.map { ($0 as NSString).lastPathComponent } ?? "this file")?"
120 alert.informativeText = "Your changes will be lost if you don't save them."
121 alert.addButton(withTitle: "Save")
122 alert.addButton(withTitle: "Don't Save")
123 alert.addButton(withTitle: "Cancel")
124 switch alert.runModal() {
125 case .alertFirstButtonReturn: return session.save()
126 case .alertSecondButtonReturn: return true
127 default: return false
128 }
129 }
130}
131
132@main
133struct OrgstarApp: App {
134 @NSApplicationDelegateAdaptor private var delegate: AppDelegate
135 @State private var workspace = Result {
136 try WorkspaceModel(directory: WorkspaceModel.defaultDirectory, settings: .with(todoKeywords: Preferences.orgSettings))
137 }
138 @State private var commands = AppCommands()
139 @State private var clock = ClockModel()
140 @State private var scheduler = SystemReminderCenter.isAvailable ? ReminderScheduler(center: SystemReminderCenter()) : nil
141 @State private var session: DocumentSession = {
142 let session = DocumentSession()
143 session.defaults = Preferences.orgSettings
144 return session
145 }()
146
147 var body: some Scene {
148 Window("Orgstar", id: "main") {
149 switch workspace {
150 case .success(let model):
151 ContentView(workspace: model, session: session, commands: commands, scheduler: scheduler, clock: clock)
152 .onAppear {
153 delegate.session = session
154 delegate.commands = commands
155 }
156 case .failure(let error):
157 ContentUnavailableView("Can't open the index", systemImage: "exclamationmark.triangle", description: Text(error.localizedDescription))
158 }
159 }
160 .defaultSize(width: 1280, height: 860)
161 Window("Agenda", id: "agenda") {
162 if case .success(let model) = workspace {
163 AgendaView(workspace: model, session: session, commands: commands, scheduler: scheduler)
164 }
165 }
166 .defaultSize(width: 760, height: 720)
167 Window("Board", id: "board") {
168 if case .success(let model) = workspace {
169 BoardView(workspace: model, session: session, commands: commands)
170 }
171 }
172 .defaultSize(width: 1100, height: 700)
173 Window("Clock Report", id: "clock-report") {
174 if case .success(let model) = workspace {
175 ClockReportView(workspace: model)
176 }
177 }
178 .defaultSize(width: 860, height: 560)
179 Window("Capture", id: "capture") {
180 if case .success(let model) = workspace {
181 CaptureView(workspace: model, session: session, commands: commands)
182 }
183 }
184 .windowResizability(.contentSize)
185 .windowLevel(.floating)
186 .commands {
187 CommandGroup(after: .newItem) {
188 Button("Add Folder…") { commands.showingFolderPicker = true }
189 .keyboardShortcut("o", modifiers: [.command, .shift])
190 Button("Quick Open…") { commands.showingQuickOpen = true }
191 .keyboardShortcut("p")
192 Button("Command Palette…") { commands.showingPalette = true }
193 .keyboardShortcut("p", modifiers: [.command, .shift])
194 }
195 CommandGroup(after: .saveItem) {
196 Menu("Export") {
197 ForEach(EditorCommands.all.filter { $0.id.hasPrefix("app.export.") }, id: \.id) { command in
198 Button(command.title) { commands.run(command.id) }
199 }
200 }
201 .disabled(session.path == nil)
202 }
203 CommandGroup(replacing: .saveItem) {
204 Button("Save") {
205 if !session.save(), session.conflict != nil { commands.showingConflict = true }
206 }
207 .keyboardShortcut("s")
208 .disabled(session.path == nil || session.isReadOnly)
209 }
210 CommandGroup(after: .textEditing) {
211 Button("Search Notes") { commands.focusSearch = true }
212 .keyboardShortcut("f", modifiers: [.command, .shift])
213 }
214 CommandGroup(before: .windowList) {
215 AgendaMenuItem()
216 }
217 CommandGroup(after: .newItem) {
218 Button("Capture…") { commands.run("app.capture") }
219 .keyboardShortcut("n", modifiers: [.command, .shift])
220 }
221 }
222 .commands {
223 CommandMenu("Org") {
224 ForEach(EditorCommands.all.filter { $0.id.hasPrefix("org.") }, id: \.id) { command in
225 Button(command.title) { commands.editor?.run(command.id) }
226 .disabled(commands.editor == nil)
227 }
228 }
229 }
230 Settings {
231 SettingsView()
232 }
233 }
234}
235
236/// Window ▸ Agenda.
237struct AgendaMenuItem: View {
238 @Environment(\.openWindow) private var openWindow
239
240 var body: some View {
241 Button("Agenda") { openWindow(id: "agenda") }
242 .keyboardShortcut("a", modifiers: [.command, .shift])
243 Button("Board") { openWindow(id: "board") }
244 .keyboardShortcut("b", modifiers: [.command, .shift])
245 }
246}
247
248struct SettingsView: View {
249 @AppStorage("saveMode") private var saveMode = SaveMode.automatic
250 @AppStorage("keymap") private var preset = KeymapPreset.emacs
251 @AppStorage("optionAsMeta") private var optionAsMeta = OptionAsMeta.left.rawValue
252 @AppStorage("tagsColumn") private var tagsColumn = -77
253 @AppStorage("headingAfterSubtree") private var headingAfterSubtree = true
254 @AppStorage("splitLine") private var splitLine = false
255 @AppStorage("alphabeticalLists") private var alphabeticalLists = true
256 @AppStorage("fillColumn") private var fillColumn = 80
257 @AppStorage("hiddenMarkers") private var hiddenMarkers = true
258 @AppStorage("prettyEntities") private var prettyEntities = true
259 @AppStorage("todoKeywords") private var todoKeywords = Preferences.defaultTodoKeywords
260 @AppStorage("agendaSpan") private var agendaSpan = 10
261 @AppStorage("agendaStartOffset") private var agendaStartOffset = -3
262 @AppStorage("agendaSubfolders") private var agendaSubfolders = false
263 @AppStorage("reminders") private var reminders = true
264 @AppStorage("reminderLead") private var reminderLead = 12
265 @AppStorage("globalCapture") private var globalCapture = true
266 @AppStorage("settingsTab") private var tab = "general"
267
268 var body: some View {
269 TabView(selection: $tab) {
270 Tab("General", systemImage: "gearshape", value: "general") { general }
271 Tab("Editing", systemImage: "text.alignleft", value: "editing") { editing }
272 Tab("Agenda", systemImage: "calendar", value: "agenda") { agenda }
273 Tab("Capture", systemImage: "tray.and.arrow.down", value: "capture") { capture }
274 }
275 .frame(width: 600)
276 }
277
278 private var general: some View {
279 Form {
280 Section {
281 Picker("Save files", selection: $saveMode) {
282 Text("Automatically, when typing stops").tag(SaveMode.automatic)
283 Text("Only with File ▸ Save (⌘S)").tag(SaveMode.explicit)
284 }
285 .pickerStyle(.radioGroup)
286 }
287 Section {
288 Picker("Keys", selection: $preset) {
289 ForEach(KeymapPreset.allCases, id: \.self) { Text($0.title).tag($0) }
290 }
291 Picker("Option as Meta", selection: $optionAsMeta) {
292 Text("Left Option").tag(OptionAsMeta.left.rawValue)
293 Text("Right Option").tag(OptionAsMeta.right.rawValue)
294 Text("Both").tag(OptionAsMeta([.left, .right]).rawValue)
295 Text("Neither").tag(0)
296 }
297 } footer: {
298 Text("Your own bindings go in \(KeymapLoader.userFile.path), on top of the preset.")
299 .settingsFooter()
300 }
301 }
302 .formStyle(.grouped)
303 .frame(height: 250)
304 }
305
306 private var editing: some View {
307 Form {
308 Section {
309 Picker("Tags", selection: $tagsColumn) {
310 Text("Aligned to end at column 77").tag(-77)
311 Text("One space after the title").tag(0)
312 }
313 Toggle("M-RET adds the new heading after the subtree", isOn: $headingAfterSubtree)
314 Toggle("M-RET splits the line at the caret", isOn: $splitLine)
315 Toggle("Lists can use letters (a. b. c.)", isOn: $alphabeticalLists)
316 Stepper("M-q fills to column \(fillColumn)", value: $fillColumn, in: 40...200)
317 }
318 Section {
319 Toggle("Emacs hides emphasis markers (org-hide-emphasis-markers)", isOn: $hiddenMarkers)
320 Toggle("Emacs shows entities as characters (org-pretty-entities)", isOn: $prettyEntities)
321 } footer: {
322 Text("Tags, tables and M-q measure text as your Emacs displays it, so both write the same file.")
323 .settingsFooter()
324 }
325 Section {
326 TextField("Default TODO keywords", text: $todoKeywords)
327 } footer: {
328 Text("For files without #+TODO, in #+TODO syntax. Takes effect when Orgstar restarts.")
329 .settingsFooter()
330 }
331 }
332 .formStyle(.grouped)
333 .frame(height: 450)
334 }
335
336 private var agenda: some View {
337 Form {
338 Section {
339 Stepper("Agenda shows \(agendaSpan) days", value: $agendaSpan, in: 1...31)
340 Stepper(agendaStartOffset == 0 ? "Agenda starts today" : "Agenda starts \(-agendaStartOffset) days before today", value: $agendaStartOffset, in: -14...0)
341 Toggle("Include files in subfolders", isOn: $agendaSubfolders)
342 }
343 Section {
344 Toggle("Notify before timed agenda entries", isOn: $reminders)
345 Stepper("\(reminderLead) minutes before", value: $reminderLead, in: 0...120)
346 .disabled(!reminders)
347 } footer: {
348 Text("An entry's APPT_WARNTIME property overrides the lead time.")
349 .settingsFooter()
350 }
351 }
352 .formStyle(.grouped)
353 .frame(height: 290)
354 }
355
356 private var capture: some View {
357 Form {
358 Section {
359 Toggle("⌃⌥Space opens Capture from any app", isOn: $globalCapture)
360 } footer: {
361 Text("Templates go in \(CaptureTemplates.userFile.path).")
362 .settingsFooter()
363 }
364 }
365 .formStyle(.grouped)
366 .frame(height: 160)
367 }
368}
369
370private extension Text {
371 func settingsFooter() -> some View {
372 font(.caption)
373 .foregroundStyle(.secondary)
374 .textSelection(.enabled)
375 .frame(maxWidth: .infinity, alignment: .leading)
376 }
377}