import Foundation import HelderCore import HelderServices import Observation /// A highlight on the line a jump landed on; `id` restarts it for a repeat jump. public struct LineFlash: Equatable { public var path: String public var line: Int public var id = UUID() } /// The answer to "close a file with unsaved edits?". public enum UnsavedCloseChoice: Equatable, Sendable { case save case discard case cancel } /// A file that never opens (`composer.lock`): the column flashes "Too big." instead. public struct TooBigNotice: Equatable { public var path: String public var id = UUID() } /// Everything the editor keeps for one path, so a rename or a delete moves or drops it in one step. /// Only the open file holds a buffer: opening a file asks about unsaved edits first, then reads disk. struct FileState: Equatable { /// The mode the file asked for; `presentation(for:)` resolves it against the file. var mode: ViewMode? /// Which git row opened the file; only the Diff overlay follows it. var side: DiffSide? /// Unsaved edits; nil means the buffer equals disk. var buffer: String? /// The last text read from disk. var disk: String? /// Moves whenever the shown text changes from outside the text view; unique across paths. var revision = 0 var image: Data? var imageUnreadable = false /// The contents turned out binary; the pane shows the "cannot display" placeholder. var isBinary = false /// The file vanished from disk while open; its last text is kept as unsaved edits. var isDeleted = false } @Observable @MainActor public final class EditorStore { /// The one open file; nil shows the empty state. public internal(set) var activePath: String? var states: [String: FileState] = [:] public var cursor: Cursor? /// The lines of the live text selection in the active pane. public var selection: LineSelection? /// The selected text itself, for "Pass on selection". public private(set) var selectedCode: String? public private(set) var flash: LineFlash? public private(set) var tooBig: TooBigNotice? /// Recently opened files, newest first; persisted per project. public internal(set) var history: [String] = [] /// The config's `git.defaultDiffMode`, as a view mode. public var defaultMode = ViewMode.actual public var editorConfig = HelderConfig.Editor() /// The mode to return to when the Diff overlay closes. public private(set) var modeBeforeDiff = ViewMode.actual /// The code pane's text view takes keyboard focus whenever this moves. public private(set) var textFocusRequest = 0 /// ⌘A outside a text field: the code pane selects everything when this moves. public private(set) var selectAllRequest = 0 /// Declared PHP class names; decides which tokens ⌘-click may follow. public private(set) var knownSymbols: Set = [] /// Moves whenever `knownSymbols` changes, so views can compare an Int instead of the set. public private(set) var knownSymbolsVersion = 0 public private(set) var symbolName: String? /// nil while the lookup for `symbolName` runs. public private(set) var symbolLookup: SymbolLookup? // MARK: Hooks WorkspaceModel (or the editor column) wires to the other stores. @ObservationIgnored public var presentOverlay: ((Overlay) -> Void)? /// Closes the overlay only while it is the Diff. @ObservationIgnored public var dismissDiffOverlay: (() -> Void)? @ObservationIgnored public var showToast: ((String, String?) -> Void)? /// After a write: git should re-read. @ObservationIgnored public var fileSaved: ((String) -> Void)? /// Asked before a dirty file closes; without it a dirty file stays open. @ObservationIgnored public var confirmUnsavedClose: ((String) -> UnsavedCloseChoice)? @ObservationIgnored public var symbols: SymbolServicing? /// The Diff overlay's own menu or pass-on prompt is open; the window's shortcuts then stand back. @ObservationIgnored public var diffOverlayBusy = false @ObservationIgnored public let root: String @ObservationIgnored let files: FileServicing @ObservationIgnored private let gitState: @MainActor () -> GitWorkingState @ObservationIgnored let session: SessionStoring @ObservationIgnored let recentFiles: RecentFilesStoring @ObservationIgnored private var pending: [UUID: Task] = [:] @ObservationIgnored var autoSaves: [String: (id: UUID, task: Task)] = [:] /// Bumped per path by every read and save, so an older read that lands late is dropped. @ObservationIgnored var loadGeneration: [String: Int] = [:] @ObservationIgnored private var revisionCounter = 0 @ObservationIgnored private var flashTask: Task? /// Nothing is written back until the saved state was read, so an early write never clobbers it. @ObservationIgnored var hasRestored = false @ObservationIgnored var sessionEnabled = false public convenience init(root: String, files: FileServicing, sourceControl: SourceControlStore, session: SessionStoring, recentFiles: RecentFilesStoring) { self.init(root: root, files: files, gitState: { sourceControl.state }, session: session, recentFiles: recentFiles) } /// `gitState` is read, never written: the editor only follows git. public init(root: String, files: FileServicing, gitState: @escaping @MainActor () -> GitWorkingState, session: SessionStoring, recentFiles: RecentFilesStoring) { self.root = root self.files = files self.gitState = gitState self.session = session self.recentFiles = recentFiles } // MARK: Reading public var modes: [String: ViewMode] { states.compactMapValues(\.mode) } public var sides: [String: DiffSide] { states.compactMapValues(\.side) } public var buffers: [String: String] { states.compactMapValues(\.buffer) } public var diskText: [String: String] { states.compactMapValues(\.disk) } public var images: [String: Data] { states.compactMapValues(\.image) } public var unreadableImages: Set { Set(states.filter(\.value.imageUnreadable).keys) } public var binaryPaths: Set { Set(states.filter(\.value.isBinary).keys) } public func side(for path: String) -> DiffSide? { states[path]?.side } public func revision(for path: String) -> Int { states[path]?.revision ?? 0 } public func image(for path: String) -> Data? { states[path]?.image } public func isUnreadableImage(_ path: String) -> Bool { states[path]?.imageUnreadable ?? false } public func isDeleted(_ path: String) -> Bool { states[path]?.isDeleted ?? false } /// HEAD vs disk for a changed file; nil for an unchanged one. public func diff(for path: String) -> Diff? { gitState().fileDiffs[path] } /// The pair the Diff overlay compares: the git row that opened the file, else HEAD vs disk. public func overlayDiff(for path: String, side: DiffSide?) -> Diff? { let state = gitState() if let side, let row = state.rowDiffs[Change.rowID(path: path, staged: side == .staged)] { return row } return state.fileDiffs[path] } /// True when a file is both staged and edited again, so the Diff must say which half it shows. public func hasBothSides(_ path: String) -> Bool { let rows = gitState().rowDiffs return rows[Change.rowID(path: path, staged: true)] != nil && rows[Change.rowID(path: path, staged: false)] != nil } public func presentation(for path: String) -> EditorPresentation { EditorPresentation(path: path, requested: states[path]?.mode, diff: diff(for: path), defaultMode: defaultMode, isBinary: states[path]?.isBinary ?? false) } /// The effective mode of a file. public func mode(for path: String) -> ViewMode { presentation(for: path).mode } /// What the editable view shows: the unsaved buffer, else the disk text. public func text(for path: String) -> String { states[path]?.buffer ?? states[path]?.disk ?? "" } /// A vanished file is dirty while it holds any text, so closing it asks and saving it is a choice. public func isDirty(_ path: String) -> Bool { guard let state = states[path], let buffer = state.buffer else { return false } return state.isDeleted || buffer != (state.disk ?? "") } public func isLoaded(_ path: String) -> Bool { states[path]?.disk != nil } /// Every path holding unsaved edits, the open file first. public var dirtyPaths: [String] { let others = states.keys.filter { $0 != activePath && isDirty($0) }.sorted() return (activePath.map { isDirty($0) ? [$0] : [] } ?? []) + others } // MARK: Status bar and breadcrumb public var activeMode: ViewMode? { activePath.map(mode(for:)) } public var activeLanguage: String? { activePath.map { EditorFileKind.of($0) == .image ? "Image" : FileType.languageLabel(for: $0) } } public var indentationLabel: String { "Spaces: \(editorConfig.tabSize)" } public var cursorLine: Int { cursorOnActive?.line ?? 1 } public var cursorColumn: Int { cursorOnActive?.column ?? 1 } public var activeIsDirty: Bool { activePath.map(isDirty) ?? false } private var cursorOnActive: Cursor? { guard let cursor, cursor.path == activePath else { return nil } return cursor } // MARK: Editing /// Records an edit to the active buffer; with `editor.autoSave` it is written 600ms after the last keystroke. public func edit(_ text: String) { guard let path = activePath else { return } var state = states[path] ?? FileState() state.buffer = (text == state.disk && !state.isDeleted) ? nil : text states[path] = state if editorConfig.autoSave && !state.isDeleted { scheduleAutoSave(path) } } public func updateCursor(line: Int, column: Int) { guard let path = activePath else { return } let next = Cursor(path: path, line: line, column: column) if cursor != next { cursor = next } } /// The live selection of the active pane; nil lines or empty code clears it. public func updateSelection(lines: ClosedRange?, code: String?) { guard let path = activePath, let lines, let code, !code.isEmpty else { if selection != nil { selection = nil } selectedCode = nil return } let next = LineSelection(path: path, start: lines.lowerBound, end: lines.upperBound, anchor: lines.lowerBound) if selection != next { selection = next } selectedCode = code } /// Hands keyboard focus to the code pane's text view. public func requestTextFocus() { textFocusRequest += 1 } /// Selects the whole open file in its pane; false when no file is open. @discardableResult public func selectAll() -> Bool { guard activePath != nil else { return false } selectAllRequest += 1 return true } // MARK: Modes public func setMode(_ mode: ViewMode, for path: String) { let current = self.mode(for: path) if mode == .diff { guard diff(for: path) != nil else { return } if current != .diff { modeBeforeDiff = current } states[path, default: FileState()].mode = .diff presentOverlay?(.diff(DiffOverlayRequest(path: path, side: states[path]?.side))) } else { states[path, default: FileState()].mode = mode if current == .diff { dismissDiffOverlay?() requestTextFocus() } } persistSoon() } /// ⌘M and the bar's Preview button: Markdown flips between its code view and the rendered preview. /// Any other file has nothing to flip. public func togglePreview() { guard let path = activePath, presentation(for: path).barButtons.contains(.preview) else { return } setMode(mode(for: path) == .preview ? .code : .preview, for: path) track { await $0.load(path, discardEdits: false) } } /// Show diff on a marked line in Actual: the Diff opens on HEAD vs disk, centred on that line. public func openDiff(atLine line: Int) { guard let path = activePath, diff(for: path) != nil else { return } let current = mode(for: path) if current != .diff { modeBeforeDiff = current } states[path, default: FileState()].mode = .diff presentOverlay?(.diff(DiffOverlayRequest(path: path, side: nil, focusLine: line))) } /// The Diff overlay went away (Esc, Collapse, or another overlay took its place): back to the mode it covered. public func closeDiff() { guard let path = activePath, states[path]?.mode == .diff else { return } states[path]?.mode = modeBeforeDiff == .diff ? .actual : modeBeforeDiff requestTextFocus() persistSoon() } /// The Collapse button: restore the mode and close the overlay. public func collapseDiff() { closeDiff() dismissDiffOverlay?() } // MARK: References and pass-on /// The reference for the current selection, else the caret line. public func currentReference() -> AgentReference? { guard let path = activePath else { return nil } if let selection, selection.path == path { return selection.reference } return AgentReference(path: path, startLine: cursorOnActive?.line ?? 1) } /// ⌘→: the pass-on prompt for the selected code; nil without a selection, so the key keeps its native meaning. public func passOnSelectionRequest(anchor: CGPoint) -> PassOnRequest? { guard let path = activePath, let selection, selection.path == path, let code = selectedCode, !code.isEmpty else { return nil } return PassOnRequest(reference: selection.reference.description, code: code, anchor: anchor) } /// The right-click menu for a line or selection in the code: Pass on and Copy reference, plus Show diff /// when `showDiffLine` names a marked line. public func contextMenuRequest(reference: AgentReference, code: String?, showDiffLine: Int? = nil, anchor: CGPoint) -> ContextMenuRequest { let target = ContextTarget.editor(reference: reference, code: code, showDiffLine: showDiffLine) return ContextMenuRequest(target: target, header: ContextActions.header(for: target, projectName: PathUtils.basename(root)), entries: ContextActions.entries(for: target), anchor: anchor) } // MARK: Symbols public func loadKnownSymbols() async { guard let symbols else { return } let names = await symbols.names() guard names != knownSymbols else { return } knownSymbols = names knownSymbolsVersion += 1 } /// ⌘-click on a class name: the popup opens at once with "Searching…", the lookup fills it. public func lookupSymbol(_ name: String) { symbolName = name symbolLookup = nil presentOverlay?(.symbol(name: name)) guard let symbols else { return } track { store in let result = await symbols.lookup(name) if store.symbolName == name { store.symbolLookup = result } } } // MARK: The open file /// Opens a file in place of the current one, always reading it fresh from disk. Unsaved edits in the open /// file (the same path too) are auto-saved, or ask save, discard or cancel; `accepted` runs once the open /// goes ahead, at once or after the save. Returns true when it went ahead at once. @discardableResult public func open(_ path: String, _ options: OpenOptions = OpenOptions(), accepted: (@MainActor () -> Void)? = nil) -> Bool { if FileType.tooBigNames.contains(PathUtils.basename(path)) { tooBig = TooBigNotice(path: path) accepted?() return true } if let active = activePath, isDirty(active) { let silent = editorConfig.autoSave && !isDeleted(active) switch silent ? .save : confirmUnsavedClose?(active) ?? .cancel { case .cancel: return false case .discard: dropBuffer(active) case .save: track { store in do { try await store.save(path: active, announce: !silent) } catch { return } store.show(path, options) accepted?() } return false } } show(path, options) accepted?() return true } /// History, mode, side, a read from disk that wins over any buffer, and a line jump with a flash. /// A changed file lands in Actual unless `showDiff`; `defaultMode` only covers a file without a stored mode. private func show(_ path: String, _ options: OpenOptions) { history = RecentLists.pushing(path, onto: history) activePath = path selection = nil selectedCode = nil let changed = diff(for: path) != nil && EditorFileKind.of(path) == .text var state = states[path] ?? FileState() state.mode = changed ? .actual : .code state.side = options.side states[path] = state if let line = options.line { cursor = Cursor(path: path, line: line, column: 1) flashLine(path: path, line: line) } if options.showDiff && changed { setMode(.diff, for: path) } track { await $0.load(path, discardEdits: true) } persistSoon() } private func dropBuffer(_ path: String) { cancelAutoSave(path) if states[path]?.buffer != nil { states[path]?.buffer = nil bumpRevision(path) } if states[path]?.isDeleted == true { states[path] = nil } } /// Drops a file's unsaved edits without asking and, when it is the open file, shows the empty state. /// `requestCloseActive` asks first. public func close(_ path: String) { dropBuffer(path) if cursor?.path == path { cursor = nil } if selection?.path == path { selection = nil; selectedCode = nil } if activePath == path { activePath = nil } persistSoon() } /// ⌘W and the context menu's Close: a dirty file asks save, discard or cancel. Returns true when the file closed. @discardableResult public func requestCloseActive() async -> Bool { guard let path = activePath else { return false } if isDirty(path) { switch confirmUnsavedClose?(path) ?? .cancel { case .cancel: return false case .save: do { try await save(path: path) } catch { return false } case .discard: break } } close(path) return true } /// Carries every path-keyed piece of state over a rename; a read still in flight for the old name is dropped. public func remap(from old: String, to new: String, isDirectory: Bool) { let move = { (p: String) in PathUtils.remap(p, from: old, to: new, isDirectory: isDirectory) } activePath = activePath.map(move) history = history.map(move) states = Dictionary(states.map { (move($0.key), $0.value) }, uniquingKeysWith: { $1 }) for path in Array(loadGeneration.keys) where move(path) != path { loadGeneration[path] = nil } for path in Array(autoSaves.keys) where move(path) != path { cancelAutoSave(path) scheduleAutoSave(move(path)) } if let c = cursor { cursor = Cursor(path: move(c.path), line: c.line, column: c.column) } if let s = selection { selection = LineSelection(path: move(s.path), start: s.start, end: s.end, anchor: s.anchor) } persistSoon() } /// Drops every piece of state for a deleted file or folder. public func forget(_ path: String, isDirectory: Bool) { let gone = { (p: String) in PathUtils.isInside(p, path, isDirectory: isDirectory) } if activePath.map(gone) == true { activePath = nil } history.removeAll(where: gone) for key in states.keys where gone(key) { states[key] = nil } for key in loadGeneration.keys where gone(key) { loadGeneration[key] = nil } for key in autoSaves.keys where gone(key) { cancelAutoSave(key) } if let c = cursor, gone(c.path) { cursor = nil } if let s = selection, gone(s.path) { selection = nil; selectedCode = nil } persistSoon() } /// Waits for every read and lookup this store started; tests use it to settle. public func settle() async { while let task = pending.values.first ?? autoSaves.values.first?.task { await task.value } } func bumpRevision(_ path: String) { revisionCounter += 1 states[path, default: FileState()].revision = revisionCounter } private func flashLine(path: String, line: Int) { flash = LineFlash(path: path, line: line) let id = flash?.id flashTask?.cancel() flashTask = Task { [weak self] in try? await Task.sleep(for: .seconds(1)) guard let self, !Task.isCancelled, self.flash?.id == id else { return } self.flash = nil } } func track(_ work: @escaping @MainActor (EditorStore) async -> Void) { let id = UUID() pending[id] = Task { [weak self] in guard let self else { return } await work(self) self.pending[id] = nil } } }