Textley / app · textley.ai / Sources / Textley / EditorWindow.swift
| 1 | import AppKit |
| 2 | import Observation |
| 3 | import SwiftUI |
| 4 | import TextleyCore |
| 5 | |
| 6 | @MainActor @Observable |
| 7 | final class WindowDocuments { |
| 8 | var tabs: [EditorDocument] |
| 9 | var selectedID: UUID? |
| 10 | var showsSidebar = true |
| 11 | var vaults: [FolderVault] = [] |
| 12 | |
| 13 | init(documents: [EditorDocument]) { |
| 14 | tabs = documents |
| 15 | selectedID = documents.first?.id |
| 16 | } |
| 17 | |
| 18 | var active: EditorDocument? { tabs.first { $0.id == selectedID } } |
| 19 | |
| 20 | func select(_ id: UUID?) { |
| 21 | selectedID = id |
| 22 | } |
| 23 | |
| 24 | func add(_ document: EditorDocument) { |
| 25 | tabs.append(document) |
| 26 | select(document.id) |
| 27 | } |
| 28 | |
| 29 | func remove(_ document: EditorDocument) { |
| 30 | guard let index = tabs.firstIndex(where: { $0.id == document.id }) else { return } |
| 31 | let wasSelected = document.id == selectedID |
| 32 | tabs.remove(at: index) |
| 33 | if wasSelected { |
| 34 | select(tabs.isEmpty ? nil : tabs[min(index, tabs.count - 1)].id) |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | func cycle(direction: Int) { |
| 39 | guard tabs.count > 1, let index = tabs.firstIndex(where: { $0.id == selectedID }) else { return } |
| 40 | select(tabs[(index + direction + tabs.count) % tabs.count].id) |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | @MainActor |
| 45 | final class EditorWindow: NSWindowController, NSWindowDelegate { |
| 46 | let documents: WindowDocuments |
| 47 | unowned let application: TextleyApplication |
| 48 | |
| 49 | init(application: TextleyApplication, documents: [EditorDocument]) { |
| 50 | self.application = application |
| 51 | self.documents = WindowDocuments(documents: documents) |
| 52 | let window = NSWindow( |
| 53 | contentRect: NSRect(x: 0, y: 0, width: 1000, height: 650), |
| 54 | styleMask: [.titled, .closable, .miniaturizable, .resizable], |
| 55 | backing: .buffered, defer: false |
| 56 | ) |
| 57 | super.init(window: window) |
| 58 | window.title = "Text Editor" |
| 59 | window.minSize = NSSize(width: 590, height: 350) |
| 60 | window.tabbingMode = .disallowed |
| 61 | window.isReleasedWhenClosed = false |
| 62 | window.delegate = self |
| 63 | let content = NSHostingController(rootView: WorkspaceView(controller: self)) |
| 64 | content.sizingOptions = [] |
| 65 | window.contentViewController = content |
| 66 | window.setContentSize(NSSize(width: 1000, height: 650)) |
| 67 | window.center() |
| 68 | syncWindow() |
| 69 | } |
| 70 | |
| 71 | required init?(coder: NSCoder) { fatalError("init(coder:) is unavailable") } |
| 72 | |
| 73 | func syncWindow() { |
| 74 | let document = documents.active |
| 75 | window?.title = document?.title ?? "Text Editor" |
| 76 | window?.representedURL = document?.url |
| 77 | window?.isDocumentEdited = document?.isDirty ?? false |
| 78 | } |
| 79 | |
| 80 | func focusActive() { |
| 81 | Task { @MainActor [weak self] in |
| 82 | await Task.yield() |
| 83 | guard let document = self?.documents.active, !document.isShowingMarkdownPreview else { return } |
| 84 | document.focusEditor() |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | func select(_ document: EditorDocument) { |
| 89 | documents.select(document.id) |
| 90 | focusActive() |
| 91 | } |
| 92 | |
| 93 | func closeTab(_ document: EditorDocument) { |
| 94 | guard approveClosing(document) else { return } |
| 95 | documents.remove(document) |
| 96 | focusActive() |
| 97 | } |
| 98 | |
| 99 | func moveToNewWindow(_ document: EditorDocument) { |
| 100 | documents.remove(document) |
| 101 | document.scroll.removeFromSuperview() |
| 102 | application.newWindow(with: [document]) |
| 103 | syncWindow() |
| 104 | } |
| 105 | |
| 106 | func addVault(_ url: URL) { |
| 107 | guard !documents.vaults.contains(where: { $0.url == url }) else { return } |
| 108 | documents.vaults.append(FolderVault(url: url) { [weak self] root in |
| 109 | self?.application.refreshDocuments(in: root) |
| 110 | }) |
| 111 | } |
| 112 | |
| 113 | func removeVault(_ vault: FolderVault) { |
| 114 | vault.stop() |
| 115 | documents.vaults.removeAll { $0 === vault } |
| 116 | application.forgetVault(vault.url) |
| 117 | } |
| 118 | |
| 119 | func save(_ document: EditorDocument, copy: Bool = false) -> Bool { |
| 120 | var destination = document.url |
| 121 | if destination == nil || copy { |
| 122 | destination = chooseDestination(for: document, copy: copy) |
| 123 | } |
| 124 | guard let url = destination else { return false } |
| 125 | if application.owner(of: url, excluding: copy ? nil : document) != nil { |
| 126 | showError(TextFileError.openDestination) |
| 127 | return false |
| 128 | } |
| 129 | do { |
| 130 | try document.save(to: url, copy: copy) |
| 131 | } catch TextFileError.diskChanged { |
| 132 | let alert = NSAlert() |
| 133 | alert.alertStyle = .warning |
| 134 | alert.messageText = "“\(document.title)” changed on disk" |
| 135 | alert.informativeText = "Save a copy to keep both versions, or replace the file with your edits." |
| 136 | alert.addButton(withTitle: "Save a Copy…") |
| 137 | alert.addButton(withTitle: "Cancel") |
| 138 | let replace = alert.addButton(withTitle: "Replace File") |
| 139 | replace.hasDestructiveAction = true |
| 140 | switch alert.runModal() { |
| 141 | case .alertFirstButtonReturn: |
| 142 | guard let newURL = chooseDestination(for: document, copy: true) else { return false } |
| 143 | guard application.owner(of: newURL) == nil else { |
| 144 | showError(TextFileError.openDestination) |
| 145 | return false |
| 146 | } |
| 147 | do { |
| 148 | try document.save(to: newURL) |
| 149 | destination = newURL |
| 150 | } catch { showError(error); return false } |
| 151 | case .alertThirdButtonReturn: |
| 152 | do { try document.save(to: url, force: true) } catch { showError(error); return false } |
| 153 | default: return false |
| 154 | } |
| 155 | } catch { |
| 156 | showError(error) |
| 157 | return false |
| 158 | } |
| 159 | if let destination { application.noteRecent(destination) } |
| 160 | syncWindow() |
| 161 | return true |
| 162 | } |
| 163 | |
| 164 | private func chooseDestination(for document: EditorDocument, copy: Bool) -> URL? { |
| 165 | let panel = NSSavePanel() |
| 166 | panel.title = copy ? "Save a Copy" : "Save Document" |
| 167 | panel.canCreateDirectories = true |
| 168 | if let url = document.url { |
| 169 | panel.directoryURL = url.deletingLastPathComponent() |
| 170 | if copy { |
| 171 | let name = url.deletingPathExtension().lastPathComponent + " copy" |
| 172 | panel.nameFieldStringValue = url.pathExtension.isEmpty ? name : name + "." + url.pathExtension |
| 173 | } else { |
| 174 | panel.nameFieldStringValue = url.lastPathComponent |
| 175 | } |
| 176 | } else { |
| 177 | panel.nameFieldStringValue = document.language == .markdown ? "Untitled.md" : "Untitled.txt" |
| 178 | } |
| 179 | return panel.runModal() == .OK ? panel.url?.standardizedFileURL.resolvingSymlinksInPath() : nil |
| 180 | } |
| 181 | |
| 182 | private func showError(_ error: Error) { NSApp.presentError(error) } |
| 183 | |
| 184 | private func approveClosing(_ document: EditorDocument) -> Bool { |
| 185 | guard document.isDirty else { return true } |
| 186 | let alert = NSAlert() |
| 187 | alert.alertStyle = .warning |
| 188 | alert.messageText = "Save changes to “\(document.title)”?" |
| 189 | alert.informativeText = "Save your changes before closing this document." |
| 190 | alert.addButton(withTitle: "Save") |
| 191 | alert.addButton(withTitle: "Cancel") |
| 192 | let discard = alert.addButton(withTitle: "Discard") |
| 193 | discard.hasDestructiveAction = true |
| 194 | switch alert.runModal() { |
| 195 | case .alertFirstButtonReturn: return save(document) |
| 196 | case .alertThirdButtonReturn: return true |
| 197 | default: return false |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | func approveClosingWindow() -> Bool { |
| 202 | for document in documents.tabs where document.isDirty { |
| 203 | select(document) |
| 204 | if !approveClosing(document) { return false } |
| 205 | } |
| 206 | return true |
| 207 | } |
| 208 | |
| 209 | func windowShouldClose(_ sender: NSWindow) -> Bool { approveClosingWindow() } |
| 210 | func windowWillClose(_ notification: Notification) { application.removeWindow(self) } |
| 211 | func windowWillReturnUndoManager(_ window: NSWindow) -> UndoManager? { documents.active?.history } |
| 212 | } |