Branchwell

Textley / app · textley.ai / Sources / Textley / TextleyApplication.swift

Raw 20.0 KB on 63b71f34cfe61bc6553e8463e803a45424bff4d3
1import AppKit
2import SwiftUI
3import TextleyCore
4
5@main
6struct TextleyMain {
7 @MainActor static func main() {
8 if CommandLine.arguments.contains(TextleyMCPDesktopSetup.argument) {
9 Task.detached {
10 await TextleyMCPStdioBridge.run()
11 exit(0)
12 }
13 dispatchMain()
14 }
15 let app = NSApplication.shared
16 let delegate = TextleyApplication()
17 app.setActivationPolicy(.regular)
18 app.delegate = delegate
19 withExtendedLifetime(delegate) { app.run() }
20 }
21}
22
23@MainActor
24final class TextleyApplication: NSObject, NSApplicationDelegate, NSMenuItemValidation {
25 let preferences: Preferences
26 let mcp: TextleyMCPService
27 private let defaults: UserDefaults
28 private var windows: [EditorWindow] = []
29 private var settings: NSWindowController?
30 private let recentMenu = NSMenu(title: "Open Recent")
31
32 init(defaults: UserDefaults = .standard) {
33 self.defaults = defaults
34 preferences = Preferences(defaults: defaults)
35 mcp = TextleyMCPService(defaults: defaults)
36 super.init()
37 }
38
39 var activeWindow: EditorWindow? {
40 (NSApp.keyWindow?.windowController as? EditorWindow)
41 ?? (NSApp.mainWindow?.windowController as? EditorWindow)
42 ?? windows.last
43 }
44
45 func applicationWillFinishLaunching(_ notification: Notification) {
46 installMenu()
47 }
48
49 func applicationDidFinishLaunching(_ notification: Notification) {
50 if windows.isEmpty { _ = try? makeNewTab(isLaunchStarter: true) }
51 if let controller = windows.first {
52 for path in defaults.stringArray(forKey: "vaultPaths") ?? [] {
53 controller.addVault(URL(fileURLWithPath: path, isDirectory: true))
54 }
55 }
56 NSApp.activate(ignoringOtherApps: true)
57 Task { await mcp.attach(store: self) }
58 #if TEXTLEY_SPARKLE
59 TextleyUpdates.shared.start()
60 #endif
61 }
62
63 func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
64 if !flag {
65 if let activeWindow { activeWindow.showWindow(nil) } else { newTab() }
66 }
67 return true
68 }
69
70 func application(_ application: NSApplication, open urls: [URL]) { openFiles(urls) }
71
72 func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {
73 for controller in windows where !controller.approveClosingWindow() { return .terminateCancel }
74 return .terminateNow
75 }
76
77 @discardableResult
78 func newWindow(with documents: [EditorDocument] = []) -> EditorWindow {
79 let controller = EditorWindow(application: self, documents: documents)
80 windows.append(controller)
81 controller.showWindow(nil)
82 controller.window?.makeKeyAndOrderFront(nil)
83 controller.focusActive()
84 return controller
85 }
86
87 func removeWindow(_ controller: EditorWindow) {
88 for vault in controller.documents.vaults { vault.stop() }
89 windows.removeAll { $0 === controller }
90 }
91
92 @objc func newTab() { _ = try? makeNewTab() }
93
94 func makeNewTab(isLaunchStarter: Bool = false) throws -> EditorDocument {
95 let document = try EditorDocument(isLaunchStarter: isLaunchStarter)
96 if let activeWindow {
97 activeWindow.documents.add(document)
98 activeWindow.showWindow(nil)
99 activeWindow.focusActive()
100 } else {
101 newWindow(with: [document])
102 }
103 return document
104 }
105
106 @objc private func newWindowAction() {
107 if let document = try? EditorDocument() { newWindow(with: [document]) }
108 }
109
110 @objc func openPanel() {
111 let panel = NSOpenPanel()
112 panel.allowsMultipleSelection = true
113 panel.canChooseDirectories = false
114 panel.title = "Open Files"
115 if panel.runModal() == .OK { openFiles(panel.urls) }
116 }
117
118 @objc func openFolderPanel() {
119 let panel = NSOpenPanel()
120 panel.allowsMultipleSelection = true
121 panel.canChooseDirectories = true
122 panel.canChooseFiles = false
123 panel.prompt = "Open"
124 panel.title = "Open Folders"
125 guard panel.runModal() == .OK else { return }
126 let controller = activeWindow ?? newWindow()
127 for url in panel.urls { controller.addVault(canonical(url)) }
128 controller.documents.showsSidebar = true
129 rememberVaults(panel.urls)
130 }
131
132 func rememberVaults(_ urls: [URL]) {
133 let remembered = Set(defaults.stringArray(forKey: "vaultPaths") ?? [])
134 let selected = urls.map { canonical($0).path }
135 defaults.set(Array(remembered.union(selected)).sorted(), forKey: "vaultPaths")
136 }
137
138 func forgetVault(_ url: URL) {
139 let paths = defaults.stringArray(forKey: "vaultPaths") ?? []
140 defaults.set(paths.filter { $0 != url.path }, forKey: "vaultPaths")
141 }
142
143 func refreshDocuments(in root: URL) {
144 let prefix = root.path.hasSuffix("/") ? root.path : root.path + "/"
145 for controller in windows {
146 for document in controller.documents.tabs where document.url?.path.hasPrefix(prefix) == true {
147 document.refreshFromFolder()
148 }
149 }
150 }
151
152 func openFiles(_ inputs: [URL], in preferred: EditorWindow? = nil) {
153 var target = preferred ?? activeWindow
154 for input in inputs where input.isFileURL {
155 let url = canonical(input)
156 if let (controller, existing) = owner(of: url) {
157 controller.showWindow(nil)
158 controller.window?.makeKeyAndOrderFront(nil)
159 controller.select(existing)
160 target = controller
161 continue
162 }
163 do {
164 let document = try readDocument(url)
165 if let target {
166 if target.documents.tabs.count == 1, let draft = target.documents.active,
167 draft.url == nil, !draft.isDirty, draft.change == 0 {
168 target.documents.remove(draft)
169 }
170 target.documents.add(document)
171 target.showWindow(nil)
172 target.window?.makeKeyAndOrderFront(nil)
173 target.focusActive()
174 } else {
175 target = newWindow(with: [document])
176 }
177 noteRecent(url)
178 } catch { NSApp.presentError(error) }
179 }
180 }
181
182 func openFileForMCP(_ url: URL) throws -> EditorDocument {
183 if let (controller, document) = owner(of: url) {
184 controller.showWindow(nil)
185 controller.window?.makeKeyAndOrderFront(nil)
186 controller.select(document)
187 return document
188 }
189 let document = try readDocument(url)
190 if let controller = activeWindow {
191 controller.documents.add(document)
192 controller.showWindow(nil)
193 controller.window?.makeKeyAndOrderFront(nil)
194 controller.focusActive()
195 } else {
196 newWindow(with: [document])
197 }
198 noteRecent(url)
199 return document
200 }
201
202 private func readDocument(_ url: URL) throws -> EditorDocument {
203 if FolderEntry.isImage(url) { return try EditorDocument(imageURL: url) }
204 return try EditorDocument(url: url, data: TextFileAccess.read(url))
205 }
206
207 var mcpTabs: [(EditorWindow, EditorDocument)] {
208 windows.flatMap { controller in controller.documents.tabs.map { (controller, $0) } }
209 }
210
211 var mcpVaults: [FolderVault] {
212 var found = Set<URL>()
213 return windows.flatMap { $0.documents.vaults }.filter { found.insert($0.url).inserted }
214 }
215
216 func owner(of url: URL, excluding excluded: EditorDocument? = nil) -> (EditorWindow, EditorDocument)? {
217 let url = canonical(url)
218 for controller in windows {
219 if let document = controller.documents.tabs.first(where: { $0 !== excluded && $0.url == url }) {
220 return (controller, document)
221 }
222 }
223 return nil
224 }
225
226 private func canonical(_ url: URL) -> URL { url.standardizedFileURL.resolvingSymlinksInPath() }
227
228 func noteRecent(_ url: URL) {
229 NSDocumentController.shared.noteNewRecentDocumentURL(url)
230 var paths = (defaults.stringArray(forKey: "recentPaths") ?? []).filter { $0 != url.path }
231 paths.insert(url.path, at: 0)
232 defaults.set(Array(paths.prefix(12)), forKey: "recentPaths")
233 populateRecent()
234 }
235
236 private func populateRecent() {
237 recentMenu.removeAllItems()
238 let paths = defaults.stringArray(forKey: "recentPaths") ?? []
239 for path in paths {
240 let url = URL(fileURLWithPath: path)
241 let menuItem = item(url.lastPathComponent, #selector(openRecent(_:)))
242 menuItem.representedObject = url
243 menuItem.toolTip = path
244 recentMenu.addItem(menuItem)
245 }
246 if paths.isEmpty {
247 let empty = NSMenuItem(title: "No Recent Files", action: nil, keyEquivalent: "")
248 recentMenu.addItem(empty)
249 } else {
250 recentMenu.addItem(.separator())
251 recentMenu.addItem(item("Clear Menu", #selector(clearRecent)))
252 }
253 }
254
255 @objc private func openRecent(_ sender: NSMenuItem) {
256 if let url = sender.representedObject as? URL { openFiles([url]) }
257 }
258
259 @objc private func clearRecent() {
260 defaults.removeObject(forKey: "recentPaths")
261 NSDocumentController.shared.clearRecentDocuments(nil)
262 populateRecent()
263 }
264
265 @objc private func save() {
266 if let controller = activeWindow, let document = controller.documents.active { _ = controller.save(document) }
267 }
268
269 @objc private func saveCopy() {
270 if let controller = activeWindow, let document = controller.documents.active { _ = controller.save(document, copy: true) }
271 }
272
273 @objc private func closeTab() {
274 if let controller = activeWindow {
275 if let document = controller.documents.active { controller.closeTab(document) }
276 else { controller.window?.performClose(nil) }
277 }
278 }
279
280 @objc private func nextTab() { activeWindow?.documents.cycle(direction: 1); activeWindow?.focusActive() }
281 @objc private func previousTab() { activeWindow?.documents.cycle(direction: -1); activeWindow?.focusActive() }
282 @objc private func moveTab() {
283 if let controller = activeWindow, let document = controller.documents.active { controller.moveToNewWindow(document) }
284 }
285
286 @objc private func find() { activeWindow?.documents.active?.openFind() }
287 @objc private func findNext() { activeWindow?.documents.active?.findNext() }
288 @objc private func findPrevious() { activeWindow?.documents.active?.findNext(backward: true) }
289
290 @objc private func goToLine() {
291 guard let document = activeWindow?.documents.active else { return }
292 let alert = NSAlert()
293 alert.messageText = "Go to Line"
294 alert.addButton(withTitle: "Go")
295 alert.addButton(withTitle: "Cancel")
296 let field = NSTextField(frame: NSRect(x: 0, y: 0, width: 180, height: 24))
297 field.placeholderString = "Line number"
298 field.setAccessibilityLabel("Line number")
299 alert.accessoryView = field
300 alert.window.initialFirstResponder = field
301 if alert.runModal() == .alertFirstButtonReturn {
302 if let number = Int(field.stringValue.trimmingCharacters(in: .whitespaces)), document.goToLine(number) { return }
303 let invalid = NSAlert()
304 invalid.messageText = "That line isn’t in this document"
305 invalid.runModal()
306 }
307 }
308
309 @objc private func cleanup(_ sender: NSMenuItem) {
310 if let operation = Cleanup(rawValue: sender.title) { activeWindow?.documents.active?.apply(operation) }
311 }
312
313 @objc private func toggleSidebar() { activeWindow?.documents.showsSidebar.toggle() }
314 @objc private func toggleWrap() { preferences.editor.wrap.toggle() }
315 @objc private func toggleLineNumbers() { preferences.editor.lineNumbers.toggle() }
316 @objc private func togglePreview() {
317 guard let document = activeWindow?.documents.active, document.language == .markdown else { return }
318 document.showsPreview.toggle()
319 }
320
321 @objc private func showSettings() { openSettings(page: .editor) }
322
323 private func openSettings(page: SettingsView.Page) {
324 if settings == nil {
325 let window = NSWindow(contentRect: NSRect(origin: .zero, size: SettingsView.contentSize),
326 styleMask: [.titled, .closable], backing: .buffered, defer: false)
327 window.title = "Text Editor Settings"
328 window.isReleasedWhenClosed = false
329 let view = SettingsView(preferences: preferences, mcp: mcp, initialPage: page)
330 window.contentViewController = NSHostingController(rootView: view)
331 window.center()
332 settings = NSWindowController(window: window)
333 }
334 settings?.showWindow(nil)
335 }
336
337 #if TEXTLEY_SPARKLE
338 @objc private func checkForUpdates() { TextleyUpdates.shared.check() }
339 #endif
340
341 @objc private func toggleFinderColor(_ sender: NSMenuItem) {
342 guard let url = activeWindow?.documents.active?.url,
343 let color = FinderColorLabel(rawValue: sender.tag) else { return }
344 do { try color.toggle(at: url) } catch { NSApp.presentError(error) }
345 }
346
347 func validateMenuItem(_ item: NSMenuItem) -> Bool {
348 let document = activeWindow?.documents.active
349 switch item.action {
350 case #selector(toggleFinderColor(_:)):
351 guard let url = document?.url, let color = FinderColorLabel(rawValue: item.tag) else { return false }
352 item.state = FinderColorLabel.standardColors(at: url).contains(color) ? .on : .off
353 return true
354 case #selector(save), #selector(saveCopy), #selector(find), #selector(findNext), #selector(findPrevious),
355 #selector(cleanup(_:)), #selector(goToLine):
356 return document?.isImage == false
357 case #selector(togglePreview):
358 item.state = document?.showsPreview == true ? .on : .off
359 return document?.language == .markdown
360 case #selector(toggleSidebar):
361 item.state = activeWindow?.documents.showsSidebar == true ? .on : .off
362 return activeWindow != nil
363 case #selector(toggleWrap):
364 item.state = preferences.editor.wrap ? .on : .off
365 return true
366 case #selector(toggleLineNumbers):
367 item.state = preferences.editor.lineNumbers ? .on : .off
368 return true
369 #if TEXTLEY_SPARKLE
370 case #selector(checkForUpdates): return TextleyUpdates.shared.canCheck
371 #endif
372 case #selector(moveTab): return document != nil
373 case #selector(closeTab): return activeWindow != nil
374 case #selector(nextTab), #selector(previousTab): return (activeWindow?.documents.tabs.count ?? 0) > 1
375 default: return true
376 }
377 }
378
379 private func item(_ title: String, _ action: Selector, _ key: String = "",
380 modifiers: NSEvent.ModifierFlags = .command) -> NSMenuItem {
381 let item = NSMenuItem(title: title, action: action, keyEquivalent: key)
382 item.target = self
383 item.keyEquivalentModifierMask = modifiers
384 return item
385 }
386
387 private func standard(_ title: String, _ action: Selector, _ key: String,
388 modifiers: NSEvent.ModifierFlags = .command) -> NSMenuItem {
389 let item = NSMenuItem(title: title, action: action, keyEquivalent: key)
390 item.keyEquivalentModifierMask = modifiers
391 return item
392 }
393
394 private func installMenu() {
395 let root = NSMenu()
396 func add(_ title: String, _ items: [NSMenuItem]) -> NSMenu {
397 let menu = NSMenu(title: title)
398 let parent = NSMenuItem(title: title, action: nil, keyEquivalent: "")
399 parent.submenu = menu
400 root.addItem(parent)
401 for item in items { menu.addItem(item) }
402 return menu
403 }
404
405 let services = NSMenu(title: "Services")
406 let servicesItem = NSMenuItem(title: "Services", action: nil, keyEquivalent: "")
407 servicesItem.submenu = services
408 var appItems: [NSMenuItem] = [
409 standard("About Text Editor", #selector(NSApplication.orderFrontStandardAboutPanel(_:)), "")
410 ]
411 #if TEXTLEY_SPARKLE
412 let updates = NSMenuItem(title: "Check for Updates…", action: #selector(checkForUpdates), keyEquivalent: "")
413 updates.target = self
414 appItems.append(updates)
415 #endif
416 _ = add("Text Editor", appItems + [
417 .separator(), item("Settings…", #selector(showSettings), ","), .separator(), servicesItem, .separator(),
418 standard("Hide Text Editor", #selector(NSApplication.hide(_:)), "h"),
419 standard("Hide Others", #selector(NSApplication.hideOtherApplications(_:)), "h", modifiers: [.command, .option]),
420 standard("Show All", #selector(NSApplication.unhideAllApplications(_:)), ""),
421 .separator(), standard("Quit Text Editor", #selector(NSApplication.terminate(_:)), "q")
422 ])
423 NSApp.servicesMenu = services
424
425 let recentItem = NSMenuItem(title: "Open Recent", action: nil, keyEquivalent: "")
426 recentItem.submenu = recentMenu
427 let colorsItem = NSMenuItem(title: "Finder Color Labels", action: nil, keyEquivalent: "")
428 let colorsMenu = NSMenu(title: colorsItem.title)
429 for color in FinderColorLabel.allCases {
430 let labelItem = item(color.name, #selector(toggleFinderColor(_:)))
431 labelItem.tag = color.rawValue
432 colorsMenu.addItem(labelItem)
433 }
434 colorsItem.submenu = colorsMenu
435 populateRecent()
436 _ = add("File", [
437 item("New Document", #selector(newTab), "n"),
438 item("New Window", #selector(newWindowAction), "n", modifiers: [.command, .shift]),
439 item("Open…", #selector(openPanel), "o"),
440 item("Open Folder…", #selector(openFolderPanel), "o", modifiers: [.command, .shift]), recentItem, .separator(),
441 item("Close Tab", #selector(closeTab), "w"),
442 standard("Close Window", #selector(NSWindow.performClose(_:)), "w", modifiers: [.command, .shift]),
443 item("Save", #selector(save), "s"),
444 item("Save a Copy…", #selector(saveCopy), "s", modifiers: [.command, .shift]),
445 .separator(), colorsItem
446 ])
447 _ = add("Edit", [
448 standard("Undo", Selector(("undo:")), "z"),
449 standard("Redo", Selector(("redo:")), "z", modifiers: [.command, .shift]), .separator(),
450 standard("Cut", #selector(NSText.cut(_:)), "x"),
451 standard("Copy", #selector(NSText.copy(_:)), "c"),
452 standard("Paste", #selector(NSText.paste(_:)), "v"),
453 standard("Select All", #selector(NSText.selectAll(_:)), "a"), .separator(),
454 item("Find…", #selector(find), "f"),
455 item("Find Next", #selector(findNext), "g"),
456 item("Find Previous", #selector(findPrevious), "g", modifiers: [.command, .shift]),
457 item("Go to Line…", #selector(goToLine), "l")
458 ])
459 _ = add("Text", Cleanup.allCases.map { item($0.rawValue, #selector(cleanup(_:))) })
460 _ = add("View", [
461 item("Show Sidebar", #selector(toggleSidebar), "s", modifiers: [.command, .control]),
462 item("Show Line Numbers", #selector(toggleLineNumbers)),
463 item("Soft Wrap", #selector(toggleWrap)),
464 item("Markdown Preview", #selector(togglePreview), "p", modifiers: [.command, .option])
465 ])
466 let windowMenu = add("Window", [
467 standard("Minimize", #selector(NSWindow.performMiniaturize(_:)), "m"),
468 standard("Zoom", #selector(NSWindow.performZoom(_:)), ""),
469 .separator(), item("Next Tab", #selector(nextTab), "]", modifiers: [.command, .shift]),
470 item("Previous Tab", #selector(previousTab), "[", modifiers: [.command, .shift]),
471 item("Move Tab to New Window", #selector(moveTab)), .separator(),
472 standard("Bring All to Front", #selector(NSApplication.arrangeInFront(_:)), "")
473 ])
474 NSApp.windowsMenu = windowMenu
475 NSApp.mainMenu = root
476 }
477}