Sources/Orgstar/OrgstarApp.swift

2e50d150645045338c8026719a350801b4edfc44
orgstar/Sources/Orgstar/OrgstarApp.swift history · blame · raw

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