restores Helder in all its glory
This commit is contained in:
@@ -0,0 +1,227 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
import HelderServices
|
||||
|
||||
extension EditorStore {
|
||||
// MARK: Reading from disk
|
||||
|
||||
/// ⌘R: re-reads a file; disk wins over an unsaved buffer, because the agent may have rewritten it.
|
||||
public func reloadFromDisk(_ path: String) async {
|
||||
await load(path, discardEdits: true)
|
||||
}
|
||||
|
||||
public func reloadActiveFromDisk() async {
|
||||
guard let path = activePath else { return }
|
||||
await reloadFromDisk(path)
|
||||
}
|
||||
|
||||
/// The watcher saw files change (nil: anything may have). The open file and every unsaved buffer pick up
|
||||
/// the new disk text; a dirty buffer is kept, so a background write never eats the user's typing.
|
||||
public func filesChanged(_ paths: [String]?) async {
|
||||
let watched = (activePath.map { [$0] } ?? []) + dirtyPaths.filter { $0 != activePath }
|
||||
let targets = watched.filter { path in
|
||||
guard let state = states[path], state.disk != nil || state.image != nil || state.isBinary else { return false }
|
||||
return paths.map { $0.contains(path) } ?? true
|
||||
}
|
||||
for path in targets { await load(path, discardEdits: false) }
|
||||
}
|
||||
|
||||
/// Bytes of an image a Markdown document shows; project-relative, read through the file service.
|
||||
public func readImage(_ path: String) async -> Data? {
|
||||
await files.readImage(path)
|
||||
}
|
||||
|
||||
func load(_ path: String, discardEdits: Bool) async {
|
||||
let generation = nextGeneration(path)
|
||||
switch EditorFileKind.of(path) {
|
||||
case .image:
|
||||
let data = await files.readImage(path)
|
||||
guard loadGeneration[path] == generation else { return }
|
||||
states[path, default: FileState()].image = data
|
||||
states[path]?.imageUnreadable = data == nil
|
||||
case .binary:
|
||||
return
|
||||
case .text:
|
||||
let contents: FileContents
|
||||
do {
|
||||
contents = try await files.readText(path)
|
||||
} catch {
|
||||
guard loadGeneration[path] == generation else { return }
|
||||
Log.warn("editor", "read failed for \(path): \(error.localizedDescription)")
|
||||
if Self.isMissing(error) {
|
||||
markDeleted(path, discardEdits: discardEdits)
|
||||
} else if states[path]?.disk == nil {
|
||||
states[path, default: FileState()].disk = ""
|
||||
}
|
||||
return
|
||||
}
|
||||
guard loadGeneration[path] == generation else { return }
|
||||
switch contents {
|
||||
case let .text(text):
|
||||
states[path, default: FileState()].isBinary = false
|
||||
applyDisk(text, for: path, discardEdits: discardEdits)
|
||||
case .binary:
|
||||
states[path, default: FileState()].isBinary = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func nextGeneration(_ path: String) -> Int {
|
||||
let next = (loadGeneration[path] ?? 0) + 1
|
||||
loadGeneration[path] = next
|
||||
return next
|
||||
}
|
||||
|
||||
private func applyDisk(_ text: String, for path: String, discardEdits: Bool) {
|
||||
var state = states[path] ?? FileState()
|
||||
let previous = state.disk
|
||||
let wasDeleted = state.isDeleted
|
||||
state.disk = text
|
||||
state.isDeleted = false
|
||||
states[path] = state
|
||||
if let buffer = state.buffer {
|
||||
if discardEdits {
|
||||
states[path]?.buffer = nil
|
||||
bumpRevision(path)
|
||||
} else if buffer == text {
|
||||
states[path]?.buffer = nil
|
||||
}
|
||||
} else if previous != text || wasDeleted {
|
||||
bumpRevision(path)
|
||||
}
|
||||
}
|
||||
|
||||
/// The file is gone: its last text stays on screen as unsaved edits, so nothing is lost and
|
||||
/// only an explicit save writes it back. A forced reload lets the empty disk win.
|
||||
private func markDeleted(_ path: String, discardEdits: Bool) {
|
||||
var state = states[path] ?? FileState()
|
||||
cancelAutoSave(path)
|
||||
if discardEdits {
|
||||
state.buffer = nil
|
||||
state.disk = ""
|
||||
state.isDeleted = false
|
||||
states[path] = state
|
||||
bumpRevision(path)
|
||||
return
|
||||
}
|
||||
guard !state.isDeleted else { return }
|
||||
state.isDeleted = true
|
||||
if state.buffer == nil { state.buffer = state.disk ?? "" }
|
||||
if state.disk == nil { state.disk = "" }
|
||||
states[path] = state
|
||||
}
|
||||
|
||||
static func isMissing(_ error: Error) -> Bool {
|
||||
if let cocoa = error as? CocoaError {
|
||||
return cocoa.code == .fileReadNoSuchFile || cocoa.code == .fileNoSuchFile
|
||||
}
|
||||
let ns = error as NSError
|
||||
return ns.domain == NSPOSIXErrorDomain && ns.code == Int(ENOENT)
|
||||
}
|
||||
|
||||
// MARK: Saving
|
||||
|
||||
/// ⌘S: writes the active buffer when it differs from disk, then re-reads the disk copy.
|
||||
public func save() async throws {
|
||||
guard let path = activePath else { return }
|
||||
try await save(path: path)
|
||||
}
|
||||
|
||||
/// `announce` is off for auto-save, which would otherwise toast on every pause in typing.
|
||||
public func save(path: String, announce: Bool = true) async throws {
|
||||
guard let text = states[path]?.buffer, isDirty(path) else { return }
|
||||
cancelAutoSave(path)
|
||||
let generation = nextGeneration(path)
|
||||
do {
|
||||
try await files.write(path, contents: text)
|
||||
} catch {
|
||||
Log.error("save", "write failed for \(path): \(error.localizedDescription)")
|
||||
showToast?("Save failed", path)
|
||||
throw error
|
||||
}
|
||||
let disk = (try? await files.read(path)) ?? text
|
||||
if loadGeneration[path] == generation, states[path] != nil {
|
||||
states[path]?.disk = disk
|
||||
states[path]?.isDeleted = false
|
||||
if states[path]?.buffer == disk { states[path]?.buffer = nil }
|
||||
}
|
||||
if announce { showToast?("Saved", path) }
|
||||
fileSaved?(path)
|
||||
}
|
||||
|
||||
func scheduleAutoSave(_ path: String) {
|
||||
cancelAutoSave(path)
|
||||
let id = UUID()
|
||||
let task = Task { [weak self] in
|
||||
try? await Task.sleep(for: .milliseconds(600))
|
||||
guard let self, !Task.isCancelled, self.autoSaves[path]?.id == id else { return }
|
||||
self.autoSaves[path] = nil
|
||||
try? await self.save(path: path, announce: false)
|
||||
}
|
||||
autoSaves[path] = (id, task)
|
||||
}
|
||||
|
||||
func cancelAutoSave(_ path: String) {
|
||||
autoSaves.removeValue(forKey: path)?.task.cancel()
|
||||
}
|
||||
|
||||
/// Writes every auto-save still waiting on its pause, so nothing typed is left behind.
|
||||
public func flushAutoSaves() async {
|
||||
for path in Array(autoSaves.keys) {
|
||||
cancelAutoSave(path)
|
||||
try? await save(path: path, announce: false)
|
||||
}
|
||||
}
|
||||
|
||||
/// Before a window closes or switches project: each dirty file asks save, discard or cancel.
|
||||
/// Returns false on cancel, and then no discard is applied.
|
||||
public func resolveUnsaved() async -> Bool {
|
||||
await flushAutoSaves()
|
||||
var discarded: [String] = []
|
||||
for path in dirtyPaths {
|
||||
switch confirmUnsavedClose?(path) ?? .cancel {
|
||||
case .cancel:
|
||||
return false
|
||||
case .save:
|
||||
do { try await save(path: path) } catch { return false }
|
||||
case .discard:
|
||||
discarded.append(path)
|
||||
}
|
||||
}
|
||||
for path in discarded where states[path]?.buffer != nil {
|
||||
states[path]?.buffer = nil
|
||||
bumpRevision(path)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// MARK: Session
|
||||
|
||||
/// Restores the last session and the recent-files list for this project.
|
||||
public func restore(restoreSession: Bool) async {
|
||||
history = await recentFiles.load()
|
||||
sessionEnabled = restoreSession
|
||||
defer { hasRestored = true }
|
||||
guard restoreSession, let saved = session.loadSession(root: root) else { return }
|
||||
let usable = { (p: String) in !FileType.tooBigNames.contains(PathUtils.basename(p)) }
|
||||
for (path, mode) in saved.modes { states[path, default: FileState()].mode = mode == .diff ? .actual : mode }
|
||||
for (path, side) in saved.sides { states[path, default: FileState()].side = side }
|
||||
activePath = saved.active.flatMap { usable($0) ? $0 : nil }
|
||||
if let active = activePath { await load(active, discardEdits: true) }
|
||||
}
|
||||
|
||||
/// Writes the session and the recent-files list.
|
||||
public func persist() async {
|
||||
if sessionEnabled {
|
||||
let state = SessionState(active: activePath, modes: modes.filter { $0.key == activePath },
|
||||
sides: sides.filter { $0.key == activePath })
|
||||
session.saveSession(state, root: root)
|
||||
}
|
||||
await recentFiles.save(history)
|
||||
}
|
||||
|
||||
func persistSoon() {
|
||||
guard hasRestored else { return }
|
||||
track { await $0.persist() }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,460 @@
|
||||
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.
|
||||
/// It outlives the file being open, so switching back finds unsaved edits where they were.
|
||||
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<String> = []
|
||||
/// 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: the git column 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<Void, Never>] = [:]
|
||||
@ObservationIgnored var autoSaves: [String: (id: UUID, task: Task<Void, Never>)] = [:]
|
||||
/// 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<Void, Never>?
|
||||
/// 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 the git column.
|
||||
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<String> { Set(states.filter(\.value.imageUnreadable).keys) }
|
||||
public var binaryPaths: Set<String> { 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<Int>?, 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) }
|
||||
}
|
||||
|
||||
/// A click 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: exactly Pass on and Copy reference.
|
||||
public func contextMenuRequest(reference: AgentReference, code: String?, anchor: CGPoint) -> ContextMenuRequest {
|
||||
let target = ContextTarget.editor(reference: reference, code: code)
|
||||
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: history, mode, side, a read from disk, and a line jump with a flash.
|
||||
/// A changed file lands in Actual unless `showDiff`; `defaultMode` only covers a file without a stored mode.
|
||||
public func open(_ path: String, _ options: OpenOptions = OpenOptions()) {
|
||||
if FileType.tooBigNames.contains(PathUtils.basename(path)) {
|
||||
tooBig = TooBigNotice(path: path)
|
||||
return
|
||||
}
|
||||
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: false) }
|
||||
persistSoon()
|
||||
}
|
||||
|
||||
/// 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) {
|
||||
cancelAutoSave(path)
|
||||
if states[path]?.buffer != nil {
|
||||
states[path]?.buffer = nil
|
||||
bumpRevision(path)
|
||||
}
|
||||
if states[path]?.isDeleted == true { states[path] = nil }
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
import HelderServices
|
||||
import Observation
|
||||
|
||||
@Observable
|
||||
@MainActor
|
||||
public final class ExplorerStore {
|
||||
public private(set) var tree: FileNode?
|
||||
/// Expanded folders; a newly opened project starts fully collapsed.
|
||||
public private(set) var expanded: Set<String> = []
|
||||
/// The keyboard cursor, by path.
|
||||
public var selectedPath: String?
|
||||
|
||||
/// Receives a toast title and its mono detail line; `WorkspaceModel` wires it to `ToastStore`.
|
||||
@ObservationIgnored public var notify: (_ title: String, _ detail: String?) -> Void = { _, _ in }
|
||||
|
||||
@ObservationIgnored private let files: FileServicing
|
||||
@ObservationIgnored private let system: SystemActing
|
||||
@ObservationIgnored private var reloadGeneration = 0
|
||||
|
||||
public init(files: FileServicing, system: SystemActing) {
|
||||
self.files = files
|
||||
self.system = system
|
||||
}
|
||||
|
||||
public func rows(showHidden: Bool) -> [TreeRow] {
|
||||
tree.map { FileTree.visibleRows($0, expanded: expanded, showHidden: showHidden) } ?? []
|
||||
}
|
||||
|
||||
/// Expands or collapses a folder and re-reads its children, so files the agent added show up.
|
||||
@discardableResult
|
||||
public func toggle(_ directory: String) -> Task<Void, Never> {
|
||||
if expanded.contains(directory) { expanded.remove(directory) } else { expanded.insert(directory) }
|
||||
return Task { await refreshChildren(of: directory) }
|
||||
}
|
||||
|
||||
/// Expands every ancestor of a path so its row is visible.
|
||||
public func reveal(_ path: String) {
|
||||
expanded.formUnion(PathUtils.ancestors(path))
|
||||
}
|
||||
|
||||
/// Reveals a path and puts the cursor on it: what opening a file does to the tree.
|
||||
public func select(_ path: String) {
|
||||
reveal(path)
|
||||
selectedPath = path
|
||||
}
|
||||
|
||||
public func moveSelection(by step: Int, showHidden: Bool) {
|
||||
let list = rows(showHidden: showHidden)
|
||||
guard !list.isEmpty else { return }
|
||||
guard let index = list.firstIndex(where: { $0.path == selectedPath }) else {
|
||||
selectedPath = list[0].path
|
||||
return
|
||||
}
|
||||
selectedPath = list[min(max(index + step, 0), list.count - 1)].path
|
||||
}
|
||||
|
||||
/// Carries expanded folders and the cursor over a rename.
|
||||
public func remap(from old: String, to new: String, isDirectory: Bool) {
|
||||
expanded = Set(expanded.map { PathUtils.remap($0, from: old, to: new, isDirectory: isDirectory) })
|
||||
selectedPath = selectedPath.map { PathUtils.remap($0, from: old, to: new, isDirectory: isDirectory) }
|
||||
}
|
||||
|
||||
// MARK: Loading
|
||||
|
||||
/// Reloads the whole tree, keeping the expansion.
|
||||
public func reload() async {
|
||||
reloadGeneration += 1
|
||||
let generation = reloadGeneration
|
||||
let fresh = await files.tree()
|
||||
guard generation == reloadGeneration else { return }
|
||||
tree = fresh
|
||||
}
|
||||
|
||||
/// Loads once for a column that appears before `WorkspaceModel` loaded the tree.
|
||||
public func loadIfNeeded() async {
|
||||
if tree == nil { await reload() }
|
||||
}
|
||||
|
||||
public func refreshChildren(of directory: String) async {
|
||||
let generation = reloadGeneration
|
||||
let children = await files.children(of: directory)
|
||||
// A full reload that started meanwhile already carries these children.
|
||||
guard generation == reloadGeneration, let tree else { return }
|
||||
self.tree = FileTree.replacingChildren(of: directory, with: children, in: tree)
|
||||
}
|
||||
|
||||
// MARK: Disk changes
|
||||
|
||||
/// Creates an empty file and returns its path; expands the parent folder.
|
||||
public func createFile(in directory: String, name: String) async throws -> String {
|
||||
let path = try newEntryPath(in: directory, name: name)
|
||||
try await files.createFile(path)
|
||||
reveal(path)
|
||||
await reload()
|
||||
return path
|
||||
}
|
||||
|
||||
/// Creates a folder and returns its path; expands the parent and the new folder.
|
||||
public func createFolder(in directory: String, name: String) async throws -> String {
|
||||
let path = try newEntryPath(in: directory, name: name)
|
||||
try await files.createDirectory(path)
|
||||
reveal(path)
|
||||
expanded.insert(path)
|
||||
await reload()
|
||||
return path
|
||||
}
|
||||
|
||||
/// Renames on disk and returns the new path; callers must also remap the editor.
|
||||
public func rename(_ path: String, to name: String, isDirectory: Bool) async throws -> String {
|
||||
guard let clean = PathUtils.validatedName(name) else { throw FileServiceError.invalidName(name) }
|
||||
let next = try await files.rename(path, to: clean)
|
||||
guard next != path else { return path }
|
||||
remap(from: path, to: next, isDirectory: isDirectory)
|
||||
await reload()
|
||||
return next
|
||||
}
|
||||
|
||||
public func delete(_ path: String) async throws {
|
||||
let isDirectory = tree.flatMap { FileTree.find(path, in: $0) }?.isDirectory ?? false
|
||||
try await files.delete(path)
|
||||
expanded = expanded.filter { !PathUtils.isInside($0, path, isDirectory: true) }
|
||||
if let selected = selectedPath, PathUtils.isInside(selected, path, isDirectory: isDirectory) { selectedPath = nil }
|
||||
await reload()
|
||||
}
|
||||
|
||||
// MARK: Prompt and menu flows
|
||||
|
||||
/// Finishes the name prompt: creates or renames, toasts, and returns the resulting path (nil on failure or no-op).
|
||||
public func submitName(_ name: String, for purpose: NamePromptRequest.Purpose) async -> String? {
|
||||
do {
|
||||
switch purpose {
|
||||
case let .newFile(directory):
|
||||
let path = try await createFile(in: directory, name: name)
|
||||
notify("Created file", path)
|
||||
return path
|
||||
case let .newFolder(directory):
|
||||
let path = try await createFolder(in: directory, name: name)
|
||||
notify("Created folder", path)
|
||||
return path
|
||||
case let .rename(path, isDirectory):
|
||||
let next = try await rename(path, to: name, isDirectory: isDirectory)
|
||||
guard next != path else { return nil }
|
||||
notify(isDirectory ? "Renamed folder" : "Renamed file", next)
|
||||
return next
|
||||
}
|
||||
} catch {
|
||||
Log.error("fs", "\(purpose) failed: \(error)")
|
||||
switch purpose {
|
||||
case .rename: notify("Rename failed", name)
|
||||
case let .newFile(directory), let .newFolder(directory):
|
||||
notify("Create failed", PathUtils.newEntryPath(inDirectory: directory, name: name.trimmingCharacters(in: .whitespaces)))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
/// The prompt's preview line: the path a submit would create or rename to, or nil while the name is unusable.
|
||||
nonisolated public static func promptTarget(for purpose: NamePromptRequest.Purpose, name: String) -> String? {
|
||||
let trimmed = name.trimmingCharacters(in: .whitespaces)
|
||||
guard !trimmed.isEmpty else { return nil }
|
||||
switch purpose {
|
||||
case let .newFile(directory):
|
||||
return PathUtils.newEntryPath(inDirectory: directory, name: trimmed)
|
||||
case let .newFolder(directory):
|
||||
return PathUtils.newEntryPath(inDirectory: directory, name: trimmed) + "/"
|
||||
case let .rename(path, isDirectory):
|
||||
guard let clean = PathUtils.validatedName(trimmed), clean != PathUtils.basename(path) else { return nil }
|
||||
return PathUtils.reference(PathUtils.join(PathUtils.dirname(path), clean), isDirectory: isDirectory)
|
||||
}
|
||||
}
|
||||
|
||||
/// Deletes after the confirm dialog, toasts, and returns whether it worked; callers must also drop editor state.
|
||||
public func deleteEntry(_ path: String, isDirectory: Bool) async -> Bool {
|
||||
do {
|
||||
try await delete(path)
|
||||
} catch {
|
||||
Log.error("fs", "delete failed: \(error)")
|
||||
notify("Delete failed", path)
|
||||
return false
|
||||
}
|
||||
notify(isDirectory ? "Deleted folder" : "Deleted file", path)
|
||||
return true
|
||||
}
|
||||
|
||||
/// Delete always asks first; nothing else in the Explorer menu does.
|
||||
public func confirmation(for action: ContextAction) -> ConfirmRequest? {
|
||||
guard case let .delete(path, isDirectory) = action else { return nil }
|
||||
return ConfirmRequest(
|
||||
title: isDirectory ? "Delete folder?" : "Delete file?",
|
||||
body: isDirectory ? "\(path)/ and everything inside it will be permanently deleted."
|
||||
: "\(path) will be permanently deleted.",
|
||||
confirmLabel: "Delete", action: action)
|
||||
}
|
||||
|
||||
/// Runs the actions that need no prompt: copy, Show in Finder, and an already confirmed delete.
|
||||
/// False for actions this store does not own (pass on, new, rename, git).
|
||||
@discardableResult
|
||||
public func perform(_ action: ContextAction) async -> Bool {
|
||||
switch action {
|
||||
case let .copyReference(text):
|
||||
system.copy(text)
|
||||
notify("Copied reference", text)
|
||||
case let .copyFileName(name):
|
||||
system.copy(name)
|
||||
notify("Copied", name)
|
||||
case let .revealInFinder(path):
|
||||
guard let url = files.absoluteURL(for: path) else { return true }
|
||||
system.revealInFinder(url)
|
||||
case let .delete(path, isDirectory):
|
||||
_ = await deleteEntry(path, isDirectory: isDirectory)
|
||||
default:
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/// The menu target for a visible row.
|
||||
public static func target(for row: TreeRow) -> ContextTarget {
|
||||
row.kind == .directory ? .directory(path: row.path) : .file(path: row.path)
|
||||
}
|
||||
|
||||
private func newEntryPath(in directory: String, name: String) throws -> String {
|
||||
let trimmed = name.trimmingCharacters(in: .whitespaces)
|
||||
let path = PathUtils.newEntryPath(inDirectory: directory, name: trimmed)
|
||||
guard !trimmed.isEmpty, path != directory else { throw FileServiceError.invalidName(name) }
|
||||
return path
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
import HelderServices
|
||||
import Observation
|
||||
|
||||
/// Which column has keyboard focus: drives the active-panel tint and arrow-key navigation.
|
||||
public enum Panel: String, Sendable, CaseIterable {
|
||||
case sourceControl
|
||||
case explorer
|
||||
case editor
|
||||
case terminal
|
||||
}
|
||||
|
||||
/// The column layout one project remembers between launches.
|
||||
public struct ColumnLayoutSnapshot: Codable, Sendable, Equatable {
|
||||
public var sourceControlWidth: Double
|
||||
public var explorerWidth: Double
|
||||
public var agentWidth: Double
|
||||
public var fluid: Bool
|
||||
public var gitVisible: Bool
|
||||
|
||||
public init(sourceControlWidth: Double, explorerWidth: Double, agentWidth: Double, fluid: Bool, gitVisible: Bool) {
|
||||
self.sourceControlWidth = sourceControlWidth
|
||||
self.explorerWidth = explorerWidth
|
||||
self.agentWidth = agentWidth
|
||||
self.fluid = fluid
|
||||
self.gitVisible = gitVisible
|
||||
}
|
||||
|
||||
public static func key(root: String) -> String { "helder.layout:" + root }
|
||||
}
|
||||
|
||||
/// Where column layouts are kept, one per project root.
|
||||
public protocol LayoutPersisting: Sendable {
|
||||
func load(root: String) -> ColumnLayoutSnapshot?
|
||||
func save(_ snapshot: ColumnLayoutSnapshot, root: String)
|
||||
/// View → Zoom, shared by every project.
|
||||
func loadZoom() -> Double
|
||||
func saveZoom(_ level: Double)
|
||||
}
|
||||
|
||||
extension LayoutPersisting {
|
||||
public func loadZoom() -> Double { 0 }
|
||||
public func saveZoom(_ level: Double) {}
|
||||
}
|
||||
|
||||
/// UserDefaults-backed layouts, next to the session and the agent split.
|
||||
public struct UserDefaultsLayoutStore: LayoutPersisting, @unchecked Sendable {
|
||||
private let defaults: UserDefaults
|
||||
|
||||
public init(defaults: UserDefaults = .standard) {
|
||||
self.defaults = defaults
|
||||
}
|
||||
|
||||
public func load(root: String) -> ColumnLayoutSnapshot? {
|
||||
defaults.data(forKey: ColumnLayoutSnapshot.key(root: root)).flatMap { try? JSONDecoder().decode(ColumnLayoutSnapshot.self, from: $0) }
|
||||
}
|
||||
|
||||
public func save(_ snapshot: ColumnLayoutSnapshot, root: String) {
|
||||
if let data = try? JSONEncoder().encode(snapshot) { defaults.set(data, forKey: ColumnLayoutSnapshot.key(root: root)) }
|
||||
}
|
||||
|
||||
public func loadZoom() -> Double { defaults.double(forKey: "helder.zoom") }
|
||||
public func saveZoom(_ level: Double) { defaults.set(level, forKey: "helder.zoom") }
|
||||
}
|
||||
|
||||
@Observable
|
||||
@MainActor
|
||||
public final class LayoutStore {
|
||||
public private(set) var widths = ColumnWidths(sourceControl: 236, explorer: 288, agent: 480)
|
||||
/// The agent pane's share of the right column; persisted across launches.
|
||||
public private(set) var agentFraction: Double
|
||||
public private(set) var windowWidth: Double = 1680
|
||||
/// ⌘G: the Source Control column is shown.
|
||||
public private(set) var gitVisible = true
|
||||
/// ⌘L: columns re-fit on resize and focus. A manual splitter drag turns this off.
|
||||
public private(set) var fluid = true
|
||||
/// ⌘.: dotfiles show in the tree and the search.
|
||||
public private(set) var showHidden = false
|
||||
public private(set) var focusZone = FocusZone.neutral
|
||||
public private(set) var activePanel: Panel?
|
||||
/// macOS hides the traffic lights in full screen, so the title bar reclaims their inset.
|
||||
public var isFullScreen = false
|
||||
/// View → Zoom: half steps, each whole step 20% larger, as Chromium zooms.
|
||||
public private(set) var zoomLevel: Double = 0
|
||||
|
||||
@ObservationIgnored private let session: SessionStoring
|
||||
@ObservationIgnored private let persistence: LayoutPersisting?
|
||||
@ObservationIgnored private var root: String?
|
||||
|
||||
public init(session: SessionStoring, persistence: LayoutPersisting? = nil) {
|
||||
self.session = session
|
||||
self.persistence = persistence
|
||||
agentFraction = session.loadLayout().agentFraction
|
||||
zoomLevel = Self.clampZoom(persistence?.loadZoom() ?? 0)
|
||||
}
|
||||
|
||||
public static let zoomRange: ClosedRange<Double> = -3...5
|
||||
|
||||
/// The factor the code and terminal text sizes are multiplied by.
|
||||
public var textScale: Double { pow(1.2, zoomLevel) }
|
||||
|
||||
public func zoom(_ step: ZoomStep) {
|
||||
let next: Double = switch step {
|
||||
case .reset: 0
|
||||
case .bigger: zoomLevel + 0.5
|
||||
case .smaller: zoomLevel - 0.5
|
||||
}
|
||||
let clamped = Self.clampZoom(next)
|
||||
guard clamped != zoomLevel else { return }
|
||||
zoomLevel = clamped
|
||||
persistence?.saveZoom(clamped)
|
||||
}
|
||||
|
||||
private static func clampZoom(_ level: Double) -> Double {
|
||||
min(max(level, zoomRange.lowerBound), zoomRange.upperBound)
|
||||
}
|
||||
|
||||
/// Loads the project's saved columns; a project without one starts fluid with every column shown.
|
||||
public func restore(root: String) {
|
||||
self.root = root
|
||||
activePanel = nil
|
||||
focusZone = .neutral
|
||||
let saved = persistence?.load(root: root)
|
||||
gitVisible = saved?.gitVisible ?? true
|
||||
fluid = saved?.fluid ?? true
|
||||
if let saved, !saved.fluid {
|
||||
widths = ColumnWidths(sourceControl: clamp(saved.sourceControlWidth, ColumnLayout.sourceControlRange),
|
||||
explorer: clamp(saved.explorerWidth, ColumnLayout.explorerRange),
|
||||
agent: max(saved.agentWidth, ColumnLayout.minEditorWidth))
|
||||
}
|
||||
refit()
|
||||
}
|
||||
|
||||
public var snapshot: ColumnLayoutSnapshot {
|
||||
ColumnLayoutSnapshot(sourceControlWidth: widths.sourceControl, explorerWidth: widths.explorer,
|
||||
agentWidth: widths.agent, fluid: fluid, gitVisible: gitVisible)
|
||||
}
|
||||
|
||||
public func toggleGit() {
|
||||
gitVisible.toggle()
|
||||
if !gitVisible && activePanel == .sourceControl { activePanel = nil }
|
||||
refit()
|
||||
save()
|
||||
}
|
||||
|
||||
public func toggleFluid() {
|
||||
fluid.toggle()
|
||||
refit()
|
||||
save()
|
||||
}
|
||||
|
||||
public func toggleHidden() {
|
||||
showHidden.toggle()
|
||||
}
|
||||
|
||||
public func windowResized(width: Double) {
|
||||
windowWidth = width
|
||||
refit()
|
||||
}
|
||||
|
||||
/// Focus moves the fluid widths below 1600pt: the editor or the terminals get more room.
|
||||
public func focus(_ panel: Panel) {
|
||||
if panel == .sourceControl && !gitVisible { return }
|
||||
activePanel = panel
|
||||
switch panel {
|
||||
case .editor: focusZone = .editor
|
||||
case .terminal: focusZone = .terminal
|
||||
default: break
|
||||
}
|
||||
refit()
|
||||
}
|
||||
|
||||
/// Opening a file widens the editor without moving the keyboard cursor out of the list it came from.
|
||||
public func setFocusZone(_ zone: FocusZone) {
|
||||
focusZone = zone
|
||||
refit()
|
||||
}
|
||||
|
||||
public func dragSourceControl(by delta: Double) {
|
||||
fluid = false
|
||||
widths.sourceControl = clamp(widths.sourceControl + delta, ColumnLayout.sourceControlRange)
|
||||
}
|
||||
|
||||
public func dragExplorer(by delta: Double) {
|
||||
fluid = false
|
||||
widths.explorer = clamp(widths.explorer + delta, ColumnLayout.explorerRange)
|
||||
}
|
||||
|
||||
/// The agent splitter sits on the column's left edge, so dragging right shrinks it.
|
||||
public func dragAgent(by delta: Double) {
|
||||
fluid = false
|
||||
let maxWidth = ColumnLayout.maxAgentWidth(windowWidth: windowWidth, widths: widths, sourceControlVisible: gitVisible)
|
||||
widths.agent = clamp(widths.agent - delta, ColumnLayout.minEditorWidth...maxWidth)
|
||||
}
|
||||
|
||||
/// Call when a splitter drag ends: the locked widths are saved for this project.
|
||||
public func endDrag() {
|
||||
save()
|
||||
}
|
||||
|
||||
public func setAgentFraction(_ fraction: Double) {
|
||||
agentFraction = LayoutState.clampAgentFraction(fraction)
|
||||
session.saveLayout(LayoutState(agentFraction: agentFraction))
|
||||
}
|
||||
|
||||
/// Moves the agent/shell divider by `delta` points in a right column `height` points tall.
|
||||
public func dragAgentSplit(by delta: Double, height: Double) {
|
||||
guard height > 0 else { return }
|
||||
setAgentFraction((agentFraction * height + delta) / height)
|
||||
}
|
||||
|
||||
// MARK: Column geometry
|
||||
|
||||
/// The visible columns, left to right.
|
||||
public var columns: [Panel] {
|
||||
gitVisible ? Panel.allCases : [.explorer, .editor, .terminal]
|
||||
}
|
||||
|
||||
/// The horizontal extent of a column in window coordinates; nil for a hidden column.
|
||||
public func span(of panel: Panel) -> ClosedRange<Double>? {
|
||||
let splitter = ColumnLayout.splitterWidth
|
||||
let sc = gitVisible ? widths.sourceControl + splitter : 0
|
||||
let editorStart = sc + widths.explorer + splitter
|
||||
let agentStart = max(editorStart, windowWidth - widths.agent)
|
||||
switch panel {
|
||||
case .sourceControl: return gitVisible ? 0...widths.sourceControl : nil
|
||||
case .explorer: return sc...(sc + widths.explorer)
|
||||
case .editor: return editorStart...max(editorStart, agentStart - splitter)
|
||||
case .terminal: return agentStart...max(agentStart, windowWidth)
|
||||
}
|
||||
}
|
||||
|
||||
/// The column under a window x; nil within `splitterMargin` of a divider, so a splitter drag never refocuses.
|
||||
public func panel(atX x: Double, splitterMargin: Double = 0) -> Panel? {
|
||||
columns.first { panel in
|
||||
guard let span = span(of: panel) else { return false }
|
||||
return x >= span.lowerBound + splitterMargin && x <= span.upperBound - splitterMargin
|
||||
}
|
||||
}
|
||||
|
||||
/// The column `step` places left (−1) or right (+1) of `panel`, clamped at the ends. No focus counts as the editor.
|
||||
public func neighbour(of panel: Panel?, step: Int) -> Panel {
|
||||
let list = columns
|
||||
let index = list.firstIndex(of: panel ?? .editor) ?? list.firstIndex(of: .editor) ?? 0
|
||||
return list[min(max(index + step, 0), list.count - 1)]
|
||||
}
|
||||
|
||||
private func refit() {
|
||||
var next = fluid ? ColumnLayout.fluid(windowWidth: windowWidth, focus: focusZone) : widths
|
||||
next = ColumnLayout.fitted(next, windowWidth: windowWidth, sourceControlVisible: gitVisible)
|
||||
if next != widths { widths = next }
|
||||
}
|
||||
|
||||
private func save() {
|
||||
guard let root else { return }
|
||||
persistence?.save(snapshot, root: root)
|
||||
}
|
||||
|
||||
private func clamp(_ value: Double, _ range: ClosedRange<Double>) -> Double {
|
||||
min(max(value, range.lowerBound), range.upperBound)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import Foundation
|
||||
import HelderServices
|
||||
import Observation
|
||||
|
||||
@Observable
|
||||
@MainActor
|
||||
public final class NoteStore {
|
||||
public static let fileName = NotesService.fileName
|
||||
|
||||
public var text = ""
|
||||
/// What is on disk, so a save without edits does not touch the file and wake the watcher.
|
||||
public private(set) var savedText = ""
|
||||
|
||||
/// Raises a toast; the model wires it to `ToastStore`.
|
||||
@ObservationIgnored public var notify: ((String, String?) -> Void)?
|
||||
@ObservationIgnored private let notes: NotesServicing
|
||||
|
||||
public init(notes: NotesServicing) {
|
||||
self.notes = notes
|
||||
}
|
||||
|
||||
public var isDirty: Bool { text != savedText }
|
||||
|
||||
public var characterCount: Int { text.count }
|
||||
|
||||
public func load() async {
|
||||
let loaded = await notes.read()
|
||||
text = loaded
|
||||
savedText = loaded
|
||||
}
|
||||
|
||||
/// Picks up an outside edit of the note file; unsaved typing always wins.
|
||||
public func reloadIfClean() async {
|
||||
guard !isDirty else { return }
|
||||
let loaded = await notes.read()
|
||||
guard !isDirty, loaded != savedText else { return }
|
||||
text = loaded
|
||||
savedText = loaded
|
||||
}
|
||||
|
||||
/// Saves when the text changed; called on window blur, on close and when the overlay closes.
|
||||
/// Returns false when the write failed.
|
||||
@discardableResult
|
||||
public func save() async -> Bool {
|
||||
guard isDirty else { return true }
|
||||
let snapshot = text
|
||||
// Marked saved before the write, so a second blur during the write does not write again.
|
||||
let previous = savedText
|
||||
savedText = snapshot
|
||||
do {
|
||||
try await notes.write(snapshot)
|
||||
return true
|
||||
} catch {
|
||||
if savedText == snapshot { savedText = previous }
|
||||
Log.error("notes", "save failed: \(error.localizedDescription)")
|
||||
notify?("Save failed", Self.fileName)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/// The trimmed note for ⌘P, or nil when it is empty.
|
||||
public var passableText: String? {
|
||||
let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
return trimmed.isEmpty ? nil : trimmed
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
import CoreGraphics
|
||||
import Foundation
|
||||
import HelderCore
|
||||
import Observation
|
||||
|
||||
/// The full-screen side-by-side diff: which file, which git half, and an optional line to centre.
|
||||
public struct DiffOverlayRequest: Equatable {
|
||||
public var path: String
|
||||
/// nil compares HEAD with disk; a click in Actual always does that.
|
||||
public var side: DiffSide?
|
||||
public var focusLine: Int?
|
||||
|
||||
public init(path: String, side: DiffSide?, focusLine: Int? = nil) {
|
||||
self.path = path
|
||||
self.side = side
|
||||
self.focusLine = focusLine
|
||||
}
|
||||
}
|
||||
|
||||
/// The pass-on prompt: a note field over the reference it will insert.
|
||||
public struct PassOnRequest: Equatable {
|
||||
public var reference: String
|
||||
/// Selected code, sent as a fenced block under the reference.
|
||||
public var code: String?
|
||||
/// Window coordinates the prompt anchors to.
|
||||
public var anchor: CGPoint
|
||||
|
||||
public init(reference: String, code: String? = nil, anchor: CGPoint) {
|
||||
self.reference = reference
|
||||
self.code = code
|
||||
self.anchor = anchor
|
||||
}
|
||||
}
|
||||
|
||||
public struct ContextMenuRequest: Equatable {
|
||||
public var target: ContextTarget
|
||||
public var header: String
|
||||
public var entries: [ContextMenuEntry]
|
||||
/// Row menus anchor to the column's right edge so they never cover the rows.
|
||||
public var anchor: CGPoint
|
||||
|
||||
public init(target: ContextTarget, header: String, entries: [ContextMenuEntry], anchor: CGPoint) {
|
||||
self.target = target
|
||||
self.header = header
|
||||
self.entries = entries
|
||||
self.anchor = anchor
|
||||
}
|
||||
}
|
||||
|
||||
/// The new-file, new-folder and rename prompt.
|
||||
public struct NamePromptRequest: Equatable {
|
||||
public enum Purpose: Equatable {
|
||||
case newFile(inDirectory: String)
|
||||
case newFolder(inDirectory: String)
|
||||
case rename(path: String, isDirectory: Bool)
|
||||
}
|
||||
|
||||
public var purpose: Purpose
|
||||
public var initialName: String
|
||||
public var anchor: CGPoint
|
||||
|
||||
public init(purpose: Purpose, initialName: String = "", anchor: CGPoint) {
|
||||
self.purpose = purpose
|
||||
self.initialName = initialName
|
||||
self.anchor = anchor
|
||||
}
|
||||
}
|
||||
|
||||
/// A destructive action waiting for a yes.
|
||||
public struct ConfirmRequest: Equatable {
|
||||
public var title: String
|
||||
public var body: String?
|
||||
public var confirmLabel: String
|
||||
public var action: ContextAction
|
||||
|
||||
public init(title: String, body: String? = nil, confirmLabel: String, action: ContextAction) {
|
||||
self.title = title
|
||||
self.body = body
|
||||
self.confirmLabel = confirmLabel
|
||||
self.action = action
|
||||
}
|
||||
}
|
||||
|
||||
/// Everything that floats over the workspace. Exactly one at a time: presenting one replaces the other.
|
||||
public enum Overlay: Equatable {
|
||||
case none
|
||||
/// ⌘F; the seed is the editor selection's first line.
|
||||
case search(seed: String)
|
||||
/// `?`: the keyboard reference.
|
||||
case shortcuts
|
||||
/// ⌘N: the project note.
|
||||
case note
|
||||
case diff(DiffOverlayRequest)
|
||||
/// ⇧⌘O: the other recent projects. The bare window's launcher is not an overlay.
|
||||
case launcher
|
||||
/// ⌘↑/⌘↓ from the editor: the recent-files navigator.
|
||||
case recentFiles(initialSelection: Int)
|
||||
case passOn(PassOnRequest)
|
||||
/// ⌘-click on a PHP class name.
|
||||
case symbol(name: String)
|
||||
case contextMenu(ContextMenuRequest)
|
||||
case namePrompt(NamePromptRequest)
|
||||
case confirm(ConfirmRequest)
|
||||
}
|
||||
|
||||
@Observable
|
||||
@MainActor
|
||||
public final class OverlayStore {
|
||||
public private(set) var current = Overlay.none
|
||||
/// Called with the old and new overlay on every change, however it happened, so closing
|
||||
/// behaviour (the note saves, the Diff restores the mode) runs even when another overlay takes over.
|
||||
@ObservationIgnored public var onChange: ((_ old: Overlay, _ new: Overlay) -> Void)?
|
||||
|
||||
public init() {}
|
||||
|
||||
public var isPresented: Bool { current != .none }
|
||||
|
||||
/// Shows an overlay, closing whatever was open.
|
||||
public func present(_ overlay: Overlay) {
|
||||
set(overlay)
|
||||
}
|
||||
|
||||
/// Esc: closes the one open overlay.
|
||||
public func dismiss() {
|
||||
set(.none)
|
||||
}
|
||||
|
||||
private func set(_ next: Overlay) {
|
||||
let old = current
|
||||
guard old != next else { return }
|
||||
current = next
|
||||
onChange?(old, next)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
import HelderServices
|
||||
import Observation
|
||||
|
||||
@Observable
|
||||
@MainActor
|
||||
public final class SourceControlStore {
|
||||
public private(set) var state = GitWorkingState.empty
|
||||
/// False until the first read landed, so the column can tell "loading" from "clean".
|
||||
public private(set) var hasLoaded = false
|
||||
/// The commit box draft; always one lowercase line (see `setCommitMessage`).
|
||||
public private(set) var commitMessage = ""
|
||||
/// The keyboard cursor, kept as a row id because the list reorders under it.
|
||||
public var selectedRowID: String?
|
||||
public private(set) var isPushing = false
|
||||
/// The `git` config section: confirmations and the poll interval.
|
||||
public var config = HelderConfig.Git() {
|
||||
didSet {
|
||||
if pollTask != nil && config.refreshInterval != oldValue.refreshInterval { startPolling() }
|
||||
}
|
||||
}
|
||||
|
||||
/// Receives a toast title and its mono detail line; `WorkspaceModel` wires it to `ToastStore`.
|
||||
@ObservationIgnored public var notify: (_ title: String, _ detail: String?) -> Void = { _, _ in }
|
||||
|
||||
@ObservationIgnored private let git: GitServicing
|
||||
@ObservationIgnored private let derive: @Sendable (GitSnapshot?) -> GitWorkingState
|
||||
@ObservationIgnored private var refreshGeneration = 0
|
||||
@ObservationIgnored private var pollTask: Task<Void, Never>?
|
||||
|
||||
/// `derive` runs off the main actor, since it diffs every changed file.
|
||||
public init(git: GitServicing, derive: @escaping @Sendable (GitSnapshot?) -> GitWorkingState = { GitDerivation.derive($0) }) {
|
||||
self.git = git
|
||||
self.derive = derive
|
||||
}
|
||||
|
||||
// MARK: Rows
|
||||
|
||||
/// Rows in list order: staged folder groups, then unstaged ones.
|
||||
public var rows: [Change] { SourceControlText.navigationOrder(state.changes) }
|
||||
|
||||
public var stagedGroups: [ChangeGroup] { SourceControlText.groupByDir(state.changes.filter(\.staged)) }
|
||||
public var unstagedGroups: [ChangeGroup] { SourceControlText.groupByDir(state.changes.filter { !$0.staged }) }
|
||||
|
||||
public var selectedRow: Change? { state.changes.first { $0.id == selectedRowID } }
|
||||
|
||||
/// Paths with a staged row, in row order: what "unstage all" sends to git.
|
||||
public var stagedPaths: [String] {
|
||||
var seen = Set<String>()
|
||||
return state.changes.filter { $0.staged && seen.insert($0.path).inserted }.map(\.path)
|
||||
}
|
||||
|
||||
/// The status letter the Explorer shows per file; the unstaged row wins, as in the file-level diff.
|
||||
public var fileStatuses: [String: GitStatus] {
|
||||
var out: [String: GitStatus] = [:]
|
||||
for change in state.changes where out[change.path] == nil || !change.staged {
|
||||
out[change.path] = change.status
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/// Moves the cursor; a cursor whose row vanished starts over at the top.
|
||||
public func moveSelection(by step: Int) {
|
||||
let list = rows
|
||||
guard !list.isEmpty else { return }
|
||||
guard let index = list.firstIndex(where: { $0.id == selectedRowID }) else {
|
||||
selectedRowID = list[0].id
|
||||
return
|
||||
}
|
||||
selectedRowID = list[min(max(index + step, 0), list.count - 1)].id
|
||||
}
|
||||
|
||||
// MARK: Commit box
|
||||
|
||||
public var canCommit: Bool {
|
||||
state.stagedCount > 0 && !commitMessage.trimmingCharacters(in: .whitespaces).isEmpty
|
||||
}
|
||||
|
||||
public func setCommitMessage(_ value: String) {
|
||||
commitMessage = SourceControlText.normalizeCommitMessage(value)
|
||||
}
|
||||
|
||||
// MARK: Git
|
||||
|
||||
/// Re-reads git and derives rows and diffs; a result that a newer refresh overtook is dropped.
|
||||
public func refresh() async {
|
||||
refreshGeneration += 1
|
||||
let generation = refreshGeneration
|
||||
let snapshot: GitSnapshot?
|
||||
do {
|
||||
snapshot = try await git.load()
|
||||
} catch {
|
||||
Log.warn("git", "status failed: \(error)")
|
||||
return
|
||||
}
|
||||
guard generation == refreshGeneration else { return }
|
||||
let derive = self.derive
|
||||
let derived = await Task.detached(priority: .userInitiated) { derive(snapshot) }.value
|
||||
guard generation == refreshGeneration else { return }
|
||||
state = derived
|
||||
hasLoaded = true
|
||||
}
|
||||
|
||||
/// Loads once for a column that appears before `WorkspaceModel` refreshed.
|
||||
public func loadIfNeeded() async {
|
||||
if !hasLoaded { await refresh() }
|
||||
}
|
||||
|
||||
public func stage(_ path: String) async {
|
||||
await run("Stage failed", detail: path) { try await self.git.stage([path]) }
|
||||
}
|
||||
|
||||
public func unstage(_ path: String) async {
|
||||
await run("Unstage failed", detail: path) { try await self.git.unstage([path]) }
|
||||
}
|
||||
|
||||
/// Stages every path with an unstaged row, including ones that also have a staged row.
|
||||
public func stageAll() async {
|
||||
let paths = state.unstagedPaths
|
||||
guard !paths.isEmpty else { return }
|
||||
await run("Stage failed", detail: nil) { try await self.git.stage(paths) }
|
||||
}
|
||||
|
||||
public func unstageAll() async {
|
||||
let paths = stagedPaths
|
||||
guard !paths.isEmpty else { return }
|
||||
await run("Unstage failed", detail: nil) { try await self.git.unstage(paths) }
|
||||
}
|
||||
|
||||
/// Commits the staged files with the draft, clears it, and returns how many files went in (0 when nothing did).
|
||||
public func commit() async -> Int {
|
||||
let message = commitMessage.trimmingCharacters(in: .whitespaces)
|
||||
guard !message.isEmpty, state.stagedCount > 0 else { return 0 }
|
||||
let count = Set(state.changes.filter(\.staged).map(\.path)).count
|
||||
commitMessage = ""
|
||||
do {
|
||||
try await git.commit(message: message)
|
||||
} catch {
|
||||
Log.error("git", "commit failed: \(error)")
|
||||
if commitMessage.isEmpty { commitMessage = message }
|
||||
notify("Commit failed", Self.failureDetail(error))
|
||||
return 0
|
||||
}
|
||||
await refresh()
|
||||
let subject = message.count > 34 ? String(message.prefix(34)) + "…" : message
|
||||
notify("Committed \(count) file\(count == 1 ? "" : "s")", subject)
|
||||
return count
|
||||
}
|
||||
|
||||
public func push() async -> PushResult {
|
||||
guard !isPushing else { return PushResult(ok: false, message: "A push is already running") }
|
||||
isPushing = true
|
||||
notify("Pushing…", nil)
|
||||
let result = await git.push()
|
||||
isPushing = false
|
||||
await refresh()
|
||||
notify(result.ok ? "Pushed" : "Push failed", result.message)
|
||||
return result
|
||||
}
|
||||
|
||||
public func discard(_ path: String) async {
|
||||
do {
|
||||
try await git.discard([path])
|
||||
} catch {
|
||||
Log.error("git", "discard failed: \(error)")
|
||||
notify("Discard failed", path)
|
||||
await refresh()
|
||||
return
|
||||
}
|
||||
await refresh()
|
||||
notify("Discarded changes", path)
|
||||
}
|
||||
|
||||
// MARK: Actions
|
||||
|
||||
/// The confirm dialog an action needs first under the config, or nil to run it straight away.
|
||||
public func confirmation(for action: ContextAction) -> ConfirmRequest? {
|
||||
switch action {
|
||||
case let .discard(path) where config.confirmDiscard:
|
||||
ConfirmRequest(title: "Discard changes to \(path)?",
|
||||
body: "This reverts the file to the last commit and cannot be undone.",
|
||||
confirmLabel: "Discard", action: action)
|
||||
case let .stage(path) where config.confirmStage:
|
||||
ConfirmRequest(title: "Stage \(path)?", confirmLabel: "Stage", action: action)
|
||||
case let .unstage(path) where config.confirmUnstage:
|
||||
ConfirmRequest(title: "Unstage \(path)?", confirmLabel: "Unstage", action: action)
|
||||
default:
|
||||
nil
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs a git action that is already confirmed; false for actions this store does not own.
|
||||
@discardableResult
|
||||
public func perform(_ action: ContextAction) async -> Bool {
|
||||
switch action {
|
||||
case let .stage(path): await stage(path)
|
||||
case let .unstage(path): await unstage(path)
|
||||
case let .discard(path): await discard(path)
|
||||
default: return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// MARK: Polling
|
||||
|
||||
/// Re-reads git every `config.refreshInterval` ms as a backstop for a missed watcher event; 0 disables it.
|
||||
public func startPolling() {
|
||||
pollTask?.cancel()
|
||||
pollTask = nil
|
||||
let interval = config.refreshInterval
|
||||
guard interval > 0 else { return }
|
||||
pollTask = Task { [weak self] in
|
||||
while !Task.isCancelled {
|
||||
try? await Task.sleep(for: .milliseconds(interval))
|
||||
guard !Task.isCancelled, let self else { return }
|
||||
await self.refresh()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public func stopPolling() {
|
||||
pollTask?.cancel()
|
||||
pollTask = nil
|
||||
}
|
||||
|
||||
public var isPolling: Bool { pollTask != nil }
|
||||
|
||||
private func run(_ failure: String, detail: String?, _ operation: () async throws -> Void) async {
|
||||
do {
|
||||
try await operation()
|
||||
} catch {
|
||||
Log.error("git", "\(failure): \(error)")
|
||||
notify(failure, detail ?? Self.failureDetail(error))
|
||||
}
|
||||
await refresh()
|
||||
}
|
||||
|
||||
private static func failureDetail(_ error: Error) -> String {
|
||||
if case let GitError.commandFailed(_, _, stderr) = error, !stderr.isEmpty { return stderr }
|
||||
return String(describing: error)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
import CoreGraphics
|
||||
import Foundation
|
||||
import HelderCore
|
||||
import HelderServices
|
||||
import Observation
|
||||
import SwiftTerm
|
||||
|
||||
/// A live terminal pane, as the store talks to it. The Terminal views implement this over SwiftTerm.
|
||||
@MainActor
|
||||
public protocol TerminalSessionHandle: AnyObject {
|
||||
/// Writes raw bytes to the child process, as if typed.
|
||||
func send(_ text: String)
|
||||
func terminate()
|
||||
/// Spawns the child process in a pseudo-terminal.
|
||||
func start(_ launch: TerminalLaunch, argv0: String)
|
||||
/// The child's pid once spawned; the store reaps it after `terminate()`, which only signals it.
|
||||
var processID: pid_t? { get }
|
||||
/// The selected text, if any.
|
||||
var selectedText: String? { get }
|
||||
/// Pastes as the terminal would from the clipboard, then takes the keyboard.
|
||||
func paste(_ text: String)
|
||||
}
|
||||
|
||||
/// Handles that never spawn a process, such as test doubles, need not implement `start` or `processID`.
|
||||
extension TerminalSessionHandle {
|
||||
public func start(_ launch: TerminalLaunch, argv0: String) {}
|
||||
public var processID: pid_t? { nil }
|
||||
public var selectedText: String? { nil }
|
||||
public func paste(_ text: String) { send(BracketedPaste.wrap(text, composerHasText: false)) }
|
||||
}
|
||||
|
||||
extension HelderTerminalView {
|
||||
var processID: pid_t? {
|
||||
let pid = process?.shellPid ?? 0
|
||||
return pid > 0 ? pid : nil
|
||||
}
|
||||
}
|
||||
|
||||
@Observable
|
||||
@MainActor
|
||||
public final class TerminalStore {
|
||||
/// Set by the workspace once the project config is resolved; panes wait for it before spawning.
|
||||
public var config = HelderConfig.defaults {
|
||||
didSet { isConfigured = true }
|
||||
}
|
||||
public private(set) var isConfigured = false
|
||||
public private(set) var agentExited = false
|
||||
public private(set) var shellExited = false
|
||||
/// True while the agent's composer holds typed or pasted text, so the next paste starts on a new line.
|
||||
public private(set) var agentComposerHasText = false
|
||||
|
||||
@ObservationIgnored public let projectRoot: String?
|
||||
@ObservationIgnored public private(set) var agent: TerminalSessionHandle?
|
||||
@ObservationIgnored public private(set) var shell: TerminalSessionHandle?
|
||||
@ObservationIgnored private let environment: [String: String]
|
||||
/// A right-click in a pane: its kind, whether it holds a selection, the click in window coordinates.
|
||||
@ObservationIgnored public var contextMenuRequested: ((TerminalKind, Bool, CGPoint) -> Void)?
|
||||
|
||||
public init(projectRoot: String? = nil, environment: [String: String] = ProcessInfo.processInfo.environment) {
|
||||
self.projectRoot = projectRoot
|
||||
self.environment = environment
|
||||
}
|
||||
|
||||
/// Executable, arguments, environment and cwd for a pane.
|
||||
public func launch(for kind: TerminalKind) -> TerminalLaunch {
|
||||
TerminalLaunch.make(kind: kind, config: config, projectRoot: projectRoot, environment: environment)
|
||||
}
|
||||
|
||||
/// argv[0] with a leading dash, which makes the shell a login shell: a Finder-launched app
|
||||
/// inherits launchd's bare PATH, and only the login profile (Homebrew, nvm) repairs it.
|
||||
public static func loginArgv0(for executable: String) -> String {
|
||||
"-" + ((executable as NSString).lastPathComponent)
|
||||
}
|
||||
|
||||
public func session(_ kind: TerminalKind) -> TerminalSessionHandle? {
|
||||
switch kind {
|
||||
case .agent: agent
|
||||
case .shell: shell
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes observed flags only when they change: panes attach during a SwiftUI update pass.
|
||||
public func attach(_ handle: TerminalSessionHandle, as kind: TerminalKind) {
|
||||
switch kind {
|
||||
case .agent:
|
||||
agent = handle
|
||||
if agentExited { agentExited = false }
|
||||
if agentComposerHasText { agentComposerHasText = false }
|
||||
case .shell:
|
||||
shell = handle
|
||||
if shellExited { shellExited = false }
|
||||
}
|
||||
}
|
||||
|
||||
/// Attaches a pane and spawns its process.
|
||||
public func start(_ kind: TerminalKind, on handle: TerminalSessionHandle) {
|
||||
attach(handle, as: kind)
|
||||
let launch = launch(for: kind)
|
||||
Log.info("pty", "spawn \(kind.rawValue): \(launch.executable) \(launch.arguments.joined(separator: " ")) in \(launch.workingDirectory)")
|
||||
handle.start(launch, argv0: Self.loginArgv0(for: launch.executable))
|
||||
}
|
||||
|
||||
/// Kills whatever runs in the pane and spawns it again with the current config.
|
||||
public func restart(_ kind: TerminalKind) {
|
||||
guard let handle = session(kind) else { return }
|
||||
Self.terminate(handle)
|
||||
start(kind, on: handle)
|
||||
}
|
||||
|
||||
/// The process ended on its own; an exit we asked for never reports here.
|
||||
public func processExited(_ kind: TerminalKind, exitCode: Int32? = nil) {
|
||||
switch kind {
|
||||
case .agent: agentExited = true
|
||||
case .shell: shellExited = true
|
||||
}
|
||||
if let exitCode, exitCode != 0 {
|
||||
Log.warn("pty", "\(kind.rawValue) exited unexpectedly with code \(exitCode)")
|
||||
} else {
|
||||
Log.info("pty", "\(kind.rawValue) exited")
|
||||
}
|
||||
}
|
||||
|
||||
public func hasExited(_ kind: TerminalKind) -> Bool {
|
||||
kind == .agent ? agentExited : shellExited
|
||||
}
|
||||
|
||||
/// Feed every keystroke the user sends to the agent: Enter empties the composer, printable text fills it.
|
||||
public func agentReceivedInput(_ data: String) {
|
||||
if data.contains("\r") {
|
||||
agentComposerHasText = false
|
||||
} else if let scalar = data.unicodeScalars.first, scalar.value >= 0x20 {
|
||||
agentComposerHasText = true
|
||||
}
|
||||
}
|
||||
|
||||
/// Pastes into the agent's composer as a bracketed paste, so the CLI does not submit it.
|
||||
public func insertIntoAgent(text: String) {
|
||||
guard let agent else { return }
|
||||
agent.send(BracketedPaste.wrap(text, composerHasText: agentComposerHasText))
|
||||
agentComposerHasText = true
|
||||
}
|
||||
|
||||
public func selection(_ kind: TerminalKind) -> String? {
|
||||
guard let text = session(kind)?.selectedText, !text.isEmpty else { return nil }
|
||||
return text
|
||||
}
|
||||
|
||||
public func paste(_ text: String, into kind: TerminalKind) {
|
||||
guard !text.isEmpty, let handle = session(kind) else { return }
|
||||
handle.paste(text)
|
||||
if kind == .agent { agentComposerHasText = true }
|
||||
}
|
||||
|
||||
/// A pane's window closed: ends its process once, unless `terminateAll` already did.
|
||||
public func release(_ handle: TerminalSessionHandle) {
|
||||
if agent === handle {
|
||||
agent = nil
|
||||
} else if shell === handle {
|
||||
shell = nil
|
||||
} else {
|
||||
return
|
||||
}
|
||||
Self.terminate(handle)
|
||||
}
|
||||
|
||||
/// Kills both processes; call it before the window closes or the store is replaced.
|
||||
public func terminateAll() {
|
||||
agent.map(Self.terminate)
|
||||
shell.map(Self.terminate)
|
||||
agent = nil
|
||||
shell = nil
|
||||
}
|
||||
|
||||
private static func terminate(_ handle: TerminalSessionHandle) {
|
||||
let pid = handle.processID
|
||||
handle.terminate()
|
||||
if let pid {
|
||||
Task.detached(priority: .utility) { await ChildReaper.reap(pid) }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import Foundation
|
||||
import Observation
|
||||
|
||||
public struct Toast: Identifiable, Equatable {
|
||||
public let id = UUID()
|
||||
public var title: String
|
||||
/// A path or reference, shown in mono under the title.
|
||||
public var detail: String?
|
||||
}
|
||||
|
||||
/// Short confirmations in a corner. They may sit over an overlay; they are not one.
|
||||
@Observable
|
||||
@MainActor
|
||||
public final class ToastStore {
|
||||
public static let lifetime: Duration = .milliseconds(2300)
|
||||
public private(set) var toasts: [Toast] = []
|
||||
|
||||
public init() {}
|
||||
|
||||
public func show(_ title: String, detail: String? = nil) {
|
||||
let toast = Toast(title: title, detail: detail)
|
||||
toasts.append(toast)
|
||||
Task { [weak self] in
|
||||
try? await Task.sleep(for: Self.lifetime)
|
||||
self?.toasts.removeAll { $0.id == toast.id }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import CoreGraphics
|
||||
import Foundation
|
||||
import HelderCore
|
||||
import HelderServices
|
||||
|
||||
extension WorkspaceModel {
|
||||
// MARK: Overlays
|
||||
|
||||
func overlayChanged(from old: Overlay, to new: Overlay) {
|
||||
switch old {
|
||||
case .note:
|
||||
if let note { track { await note.save() } }
|
||||
case .diff:
|
||||
editor?.closeDiff()
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
/// The recent projects other than this one, for ⇧⌘O.
|
||||
public var otherRecentProjects: [RecentProject] {
|
||||
recentProjects.filter { $0.path != root?.path }
|
||||
}
|
||||
|
||||
/// ⇧⌘O: the recent-project list; the recents are re-read, since another window may have added one.
|
||||
func showRecentProjects() {
|
||||
overlay.present(.launcher)
|
||||
track {
|
||||
self.recentProjects = await self.app.recentProjects.list()
|
||||
}
|
||||
}
|
||||
|
||||
func activateLauncher() {
|
||||
switch launcher.selectedChoice {
|
||||
case .chooseFolder: perform(.openFolder)
|
||||
case let .open(path): perform(.openRecentProject(path))
|
||||
case nil: break
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Focus and the row cursor
|
||||
|
||||
func focus(_ panel: Panel) {
|
||||
let previous = layout.activePanel
|
||||
layout.focus(panel)
|
||||
guard layout.activePanel == panel else { return }
|
||||
focusRequest = FocusRequest(.panel(panel))
|
||||
if panel == .editor { editor?.requestTextFocus() }
|
||||
if panel == .sourceControl && previous != .sourceControl { scheduleRefresh(.git) }
|
||||
}
|
||||
|
||||
func moveRowCursor(by step: Int) {
|
||||
switch layout.activePanel {
|
||||
case .sourceControl: sourceControl?.moveSelection(by: step)
|
||||
case .explorer: explorer?.moveSelection(by: step, showHidden: layout.showHidden)
|
||||
default: break
|
||||
}
|
||||
}
|
||||
|
||||
func openSelectedRow() {
|
||||
switch layout.activePanel {
|
||||
case .sourceControl:
|
||||
guard let row = selectedGitRow() else { return }
|
||||
open(row.change.path, OpenOptions(side: row.change.staged ? .staged : .unstaged))
|
||||
case .explorer:
|
||||
guard let explorer, let row = selectedTreeRow() else { return }
|
||||
if row.row.kind == .directory { explorer.toggle(row.row.path) } else { open(row.row.path) }
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Editor and the note
|
||||
|
||||
func passSelection(_ info: TextSelectionInfo?) {
|
||||
guard let editor, let path = editor.activePath else { return }
|
||||
if let info {
|
||||
let reference = AgentReference(path: path, lines: info.startLine...max(info.startLine, info.endLine))
|
||||
overlay.present(.passOn(PassOnRequest(reference: reference.description, code: info.text, anchor: defaultAnchor)))
|
||||
} else if let request = editor.passOnSelectionRequest(anchor: defaultAnchor) {
|
||||
overlay.present(.passOn(request))
|
||||
}
|
||||
}
|
||||
|
||||
/// ⌘P with the note open: the whole note goes to the agent, and the note closes so the text is seen landing.
|
||||
func passNote() {
|
||||
guard let note, let text = note.passableText else { return }
|
||||
terminal.insertIntoAgent(text: text)
|
||||
overlay.dismiss()
|
||||
toasts.show("Note passed to agent", detail: NoteStore.fileName)
|
||||
}
|
||||
|
||||
func editorSelectionFirstLine() -> String {
|
||||
guard let editor, let path = editor.activePath, let selection = editor.selection, selection.path == path else { return "" }
|
||||
let lines = editor.text(for: path).split(separator: "\n", omittingEmptySubsequences: false)
|
||||
guard selection.start >= 1, selection.start <= lines.count else { return "" }
|
||||
return lines[selection.start - 1].trimmingCharacters(in: .whitespaces)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
import CoreGraphics
|
||||
import Foundation
|
||||
import HelderCore
|
||||
import HelderServices
|
||||
|
||||
extension WorkspaceModel {
|
||||
/// Runs a context-menu action; one the config or the Explorer guards asks first through the confirm overlay.
|
||||
public func perform(_ action: ContextAction) {
|
||||
let anchor = takeMenuAnchor()
|
||||
if let request = sourceControl?.confirmation(for: action) ?? explorer?.confirmation(for: action) {
|
||||
overlay.present(.confirm(request))
|
||||
} else {
|
||||
execute(action, anchor: anchor)
|
||||
}
|
||||
}
|
||||
|
||||
func showContextMenu(_ target: ContextTarget, anchor: CGPoint) {
|
||||
overlay.present(.contextMenu(ContextMenuRequest(
|
||||
target: target,
|
||||
header: ContextActions.header(for: target, projectName: name),
|
||||
entries: ContextActions.entries(for: target),
|
||||
anchor: anchor
|
||||
)))
|
||||
}
|
||||
|
||||
/// Closes an open context menu and returns where it stood, so a prompt it opens appears in the same place.
|
||||
private func takeMenuAnchor() -> CGPoint {
|
||||
guard case let .contextMenu(menu) = overlay.current else { return defaultAnchor }
|
||||
overlay.dismiss()
|
||||
return menu.anchor
|
||||
}
|
||||
|
||||
var defaultAnchor: CGPoint {
|
||||
CGPoint(x: (layout.span(of: .editor)?.lowerBound ?? 0) + 60, y: 150)
|
||||
}
|
||||
|
||||
func confirmPending() {
|
||||
guard case let .confirm(request) = overlay.current else { return }
|
||||
overlay.dismiss()
|
||||
execute(request.action, anchor: defaultAnchor)
|
||||
}
|
||||
|
||||
// MARK: Row menus
|
||||
|
||||
/// ⌘→ in Source Control or Explorer: the selected row's menu, beside the column at the row's height.
|
||||
func openRowMenu() {
|
||||
switch layout.activePanel {
|
||||
case .sourceControl:
|
||||
guard let row = selectedGitRow() else { return }
|
||||
showContextMenu(.gitRow(path: row.change.path, staged: row.change.staged),
|
||||
anchor: rowMenuAnchor(.sourceControl, frame: rowFrames[.git(row.change.id)],
|
||||
estimate: row.index, rowHeight: Metrics.sourceControlRow))
|
||||
case .explorer:
|
||||
guard let row = selectedTreeRow() else { return }
|
||||
showContextMenu(ExplorerStore.target(for: row.row),
|
||||
anchor: rowMenuAnchor(.explorer, frame: rowFrames[.tree(row.row.path)],
|
||||
estimate: row.index, rowHeight: Metrics.explorerRow))
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
func selectedGitRow() -> (change: Change, index: Int)? {
|
||||
guard let sourceControl else { return nil }
|
||||
let rows = sourceControl.rows
|
||||
guard let index = rows.firstIndex(where: { $0.id == sourceControl.selectedRowID }) else { return nil }
|
||||
return (rows[index], index)
|
||||
}
|
||||
|
||||
func selectedTreeRow() -> (row: TreeRow, index: Int)? {
|
||||
guard let explorer else { return nil }
|
||||
let rows = explorer.rows(showHidden: layout.showHidden)
|
||||
guard let index = rows.firstIndex(where: { $0.path == explorer.selectedPath }) else { return nil }
|
||||
return (rows[index], index)
|
||||
}
|
||||
|
||||
/// Row menus open beside the column, never over its rows, level with the row; a row that never
|
||||
/// reported its frame is placed by its index, which is off once the list scrolls.
|
||||
func rowMenuAnchor(_ panel: Panel, frame: CGRect?, estimate index: Int, rowHeight: CGFloat) -> CGPoint {
|
||||
let x = layout.span(of: panel)?.upperBound ?? 220
|
||||
let y = frame.map { $0.minY + 4 } ?? Metrics.titleBar + Metrics.panelHeader + CGFloat(index) * rowHeight + 4
|
||||
return CGPoint(x: x, y: y)
|
||||
}
|
||||
|
||||
// MARK: Running actions
|
||||
|
||||
/// Runs an action that needs no (more) confirmation. The stores are read before any await,
|
||||
/// so an action still running after a project switch never lands in the new project.
|
||||
func execute(_ action: ContextAction, anchor: CGPoint) {
|
||||
let sourceControl = sourceControl, explorer = explorer, editor = editor
|
||||
switch action {
|
||||
case let .passOnReference(reference, code):
|
||||
overlay.present(.passOn(PassOnRequest(reference: reference, code: code, anchor: anchor)))
|
||||
case let .passOnFileName(name):
|
||||
overlay.present(.passOn(PassOnRequest(reference: name, anchor: anchor)))
|
||||
case let .newFile(directory):
|
||||
overlay.present(.namePrompt(NamePromptRequest(purpose: .newFile(inDirectory: directory), anchor: anchor)))
|
||||
case let .newFolder(directory):
|
||||
overlay.present(.namePrompt(NamePromptRequest(purpose: .newFolder(inDirectory: directory), anchor: anchor)))
|
||||
case let .rename(path, isDirectory):
|
||||
overlay.present(.namePrompt(NamePromptRequest(purpose: .rename(path: path, isDirectory: isDirectory),
|
||||
initialName: PathUtils.basename(path), anchor: anchor)))
|
||||
case let .openDiff(path):
|
||||
open(path, OpenOptions(showDiff: true))
|
||||
case let .copyTerminalSelection(kind):
|
||||
if let text = terminal.selection(kind) { app.system.copy(text) }
|
||||
case let .pasteIntoTerminal(kind):
|
||||
if let text = app.system.pasteboardText() { terminal.paste(text, into: kind) }
|
||||
case let .discard(path):
|
||||
track {
|
||||
await sourceControl?.discard(path)
|
||||
await editor?.reloadFromDisk(path)
|
||||
}
|
||||
case let .delete(path, isDirectory):
|
||||
track {
|
||||
guard await explorer?.deleteEntry(path, isDirectory: isDirectory) == true else { return }
|
||||
editor?.forget(path, isDirectory: isDirectory)
|
||||
await sourceControl?.refresh()
|
||||
}
|
||||
default:
|
||||
track {
|
||||
if await sourceControl?.perform(action) == true { return }
|
||||
await explorer?.perform(action)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func submitName(_ name: String) {
|
||||
guard case let .namePrompt(request) = overlay.current else { return }
|
||||
overlay.dismiss()
|
||||
guard let explorer else { return }
|
||||
let sourceControl = sourceControl, editor = editor
|
||||
track {
|
||||
guard let path = await explorer.submitName(name, for: request.purpose) else { return }
|
||||
switch request.purpose {
|
||||
case .newFile: if self.editor === editor { self.open(path) }
|
||||
case .newFolder: break
|
||||
case let .rename(old, isDirectory): editor?.remap(from: old, to: path, isDirectory: isDirectory)
|
||||
}
|
||||
await sourceControl?.refresh()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
import HelderServices
|
||||
|
||||
extension WorkspaceModel {
|
||||
/// Switches this window to another project folder and remembers it in the recents.
|
||||
/// Unsaved edits are asked about first; a cancel keeps the current project.
|
||||
public func openProject(_ url: URL) async {
|
||||
let url = url.standardizedFileURL
|
||||
overlay.dismiss()
|
||||
if url == root { return }
|
||||
guard await prepareToClose() else { return }
|
||||
await closeProject()
|
||||
root = url
|
||||
attach(url)
|
||||
await loadProject()
|
||||
isReady = true
|
||||
}
|
||||
|
||||
/// Asks about every unsaved file, then writes the note and the session.
|
||||
/// False when the user cancelled: the window or project must stay.
|
||||
public func prepareToClose() async -> Bool {
|
||||
if let editor, !(await editor.resolveUnsaved()) { return false }
|
||||
await note?.save()
|
||||
await editor?.persist()
|
||||
return true
|
||||
}
|
||||
|
||||
/// The window is closing: the unsaved prompt already ran, so this only winds the project down.
|
||||
public func windowWillClose() {
|
||||
guard lifecycleTask == nil else { return }
|
||||
lifecycleTask = Task { [weak self] in
|
||||
await self?.closeProject()
|
||||
self?.lifecycleTask = nil
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs a project switch outside `work`, since the switch waits for `work` to drain.
|
||||
func switchProject(_ operation: @escaping @MainActor () async -> Void) {
|
||||
guard lifecycleTask == nil else { return }
|
||||
lifecycleTask = Task { [weak self] in
|
||||
await operation()
|
||||
self?.lifecycleTask = nil
|
||||
}
|
||||
}
|
||||
|
||||
func attach(_ root: URL) {
|
||||
generation += 1
|
||||
let services = app.makeWorkspace(root)
|
||||
self.services = services
|
||||
name = ProjectLocator.name(of: root)
|
||||
title = ProjectLocator.title(of: root)
|
||||
rowFrames = [:]
|
||||
let notify: (String, String?) -> Void = { [weak self] title, detail in self?.toasts.show(title, detail: detail) }
|
||||
|
||||
let sourceControl = SourceControlStore(git: services.git)
|
||||
sourceControl.notify = notify
|
||||
self.sourceControl = sourceControl
|
||||
|
||||
let explorer = ExplorerStore(files: services.files, system: app.system)
|
||||
explorer.notify = notify
|
||||
self.explorer = explorer
|
||||
|
||||
let editor = EditorStore(root: root.path, files: services.files, sourceControl: sourceControl,
|
||||
session: app.session, recentFiles: services.recentFiles)
|
||||
wire(editor, symbols: services.symbols)
|
||||
self.editor = editor
|
||||
|
||||
let note = NoteStore(notes: services.notes)
|
||||
note.notify = notify
|
||||
self.note = note
|
||||
terminal = TerminalStore(projectRoot: root.path)
|
||||
wireTerminal()
|
||||
launcher = LauncherList(recents: recentProjects, excluding: root.path)
|
||||
}
|
||||
|
||||
private func wire(_ editor: EditorStore, symbols: SymbolServicing) {
|
||||
editor.presentOverlay = { [weak self] in self?.overlay.present($0) }
|
||||
editor.dismissDiffOverlay = { [weak self] in
|
||||
guard let self, case .diff = self.overlay.current else { return }
|
||||
self.overlay.dismiss()
|
||||
}
|
||||
editor.showToast = { [weak self] title, detail in self?.toasts.show(title, detail: detail) }
|
||||
editor.fileSaved = { [weak self, weak editor] _ in
|
||||
guard let self, self.editor === editor else { return }
|
||||
self.scheduleRefresh(.git)
|
||||
}
|
||||
editor.confirmUnsavedClose = { [weak self] path in self?.app.system.confirmUnsavedClose(path) ?? .cancel }
|
||||
editor.symbols = symbols
|
||||
}
|
||||
|
||||
func loadProject() async {
|
||||
guard let root, let services else { return }
|
||||
let current = generation
|
||||
layout.restore(root: root.path)
|
||||
config = await services.config.resolve()
|
||||
guard generation == current else { return }
|
||||
applyConfig()
|
||||
await app.recentProjects.add(root.path)
|
||||
recentProjects = await app.recentProjects.list()
|
||||
guard generation == current else { return }
|
||||
launcher = LauncherList(recents: recentProjects, excluding: root.path)
|
||||
let sourceControl = sourceControl, explorer = explorer, note = note, editor = editor
|
||||
async let git: Void = sourceControl?.refresh() ?? ()
|
||||
async let tree: Void = explorer?.reload() ?? ()
|
||||
async let loaded: Void = note?.load() ?? ()
|
||||
_ = await (git, tree, loaded)
|
||||
await editor?.restore(restoreSession: config.session.restoreOnLaunch)
|
||||
guard generation == current else { return }
|
||||
startWatcher(root)
|
||||
sourceControl?.startPolling()
|
||||
scheduleSymbolLoad(after: timings.symbolsAfterLaunch)
|
||||
}
|
||||
|
||||
/// Stops the watchers and polling, waits for the work still running against this project,
|
||||
/// then saves the note and the session and ends the terminals.
|
||||
func closeProject() async {
|
||||
watcher?.stop()
|
||||
watcher = nil
|
||||
sourceControl?.stopPolling()
|
||||
pendingRefresh = []
|
||||
let refresh = refreshTask, symbols = symbolsTask
|
||||
refreshTask = nil
|
||||
symbolsTask = nil
|
||||
refreshID = UUID()
|
||||
refresh?.cancel()
|
||||
symbols?.cancel()
|
||||
let running = Array(work.values)
|
||||
running.forEach { $0.cancel() }
|
||||
await refresh?.value
|
||||
await symbols?.value
|
||||
for task in running { await task.value }
|
||||
await editor?.flushAutoSaves()
|
||||
await note?.save()
|
||||
await editor?.persist()
|
||||
terminal.terminateAll()
|
||||
}
|
||||
|
||||
/// Pushes the config into every store that reads it; runs on load and whenever `.helder/config.json` changes.
|
||||
func applyConfig() {
|
||||
terminal.config = config
|
||||
sourceControl?.config = config.git
|
||||
guard let editor else { return }
|
||||
if editor.editorConfig != config.editor { editor.editorConfig = config.editor }
|
||||
let mode = ViewMode(config.git.defaultDiffMode)
|
||||
if editor.defaultMode != mode { editor.defaultMode = mode }
|
||||
}
|
||||
|
||||
func reloadConfig() async {
|
||||
guard let services else { return }
|
||||
let current = generation
|
||||
let resolved = await services.config.resolve()
|
||||
guard generation == current else { return }
|
||||
config = resolved
|
||||
applyConfig()
|
||||
}
|
||||
|
||||
private func startWatcher(_ root: URL) {
|
||||
watcher?.stop()
|
||||
let watcher = app.makeWatcher()
|
||||
watcher.start(root: root) { [weak self] event in
|
||||
Task { @MainActor in await self?.handle(event) }
|
||||
}
|
||||
self.watcher = watcher
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
import HelderServices
|
||||
|
||||
extension WorkspaceModel {
|
||||
/// ⌘R: reloads git, the tree and the open file from disk (disk wins over unsaved edits), and flashes the columns.
|
||||
public func refresh() async {
|
||||
refreshTick += 1
|
||||
let editor = editor
|
||||
async let reread: Void = run([.git, .tree])
|
||||
async let active: Void = editor?.reloadActiveFromDisk() ?? ()
|
||||
_ = await (reread, active)
|
||||
}
|
||||
|
||||
/// Reacts to a disk change from the watcher: project and git events gather into one debounced refresh.
|
||||
public func handle(_ event: WatchEvent) async {
|
||||
switch event {
|
||||
case .project: scheduleRefresh([.git, .tree, .symbols, .openFiles, .note])
|
||||
case .git: scheduleRefresh(.git)
|
||||
case .config: await reloadConfig()
|
||||
}
|
||||
}
|
||||
|
||||
/// Waits until every scheduled refresh, symbol load, command and project switch has finished; tests use it to settle.
|
||||
public func settle() async {
|
||||
while true {
|
||||
if let task = lifecycleTask {
|
||||
await task.value
|
||||
} else if let task = refreshTask {
|
||||
await task.value
|
||||
} else if let task = symbolsTask {
|
||||
await task.value
|
||||
if symbolsTask == task { symbolsTask = nil }
|
||||
} else if let task = work.values.first {
|
||||
await task.value
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
await editor?.settle()
|
||||
}
|
||||
|
||||
func scheduleRefresh(_ scope: RefreshScope) {
|
||||
pendingRefresh.formUnion(scope)
|
||||
guard refreshTask == nil, !pendingRefresh.isEmpty else { return }
|
||||
let id = UUID()
|
||||
refreshID = id
|
||||
refreshTask = Task { [weak self] in
|
||||
guard let self else { return }
|
||||
try? await Task.sleep(for: self.timings.refreshDebounce)
|
||||
guard !Task.isCancelled, self.refreshID == id else { return }
|
||||
let scope = self.pendingRefresh
|
||||
self.pendingRefresh = []
|
||||
await self.run(scope)
|
||||
guard self.refreshID == id else { return }
|
||||
self.refreshTask = nil
|
||||
self.scheduleRefresh([])
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the stores once up front, so a pass that outlives a project switch only touches the old project.
|
||||
func run(_ scope: RefreshScope) async {
|
||||
let sourceControl = sourceControl, explorer = explorer, editor = editor, note = note
|
||||
let current = generation
|
||||
if scope.contains(.symbols) {
|
||||
await services?.symbols.invalidate()
|
||||
if generation == current { scheduleSymbolLoad(after: timings.symbolsAfterChange) }
|
||||
}
|
||||
async let git: Void = scope.contains(.git) ? (sourceControl?.refresh() ?? ()) : ()
|
||||
async let tree: Void = scope.contains(.tree) ? (explorer?.reload() ?? ()) : ()
|
||||
async let files: Void = scope.contains(.openFiles) ? (editor?.filesChanged(nil) ?? ()) : ()
|
||||
async let notes: Void = scope.contains(.note) ? (note?.reloadIfClean() ?? ()) : ()
|
||||
_ = await (git, tree, files, notes)
|
||||
}
|
||||
|
||||
/// Restarts the countdown on every change, so a burst of writes loads the class list once.
|
||||
func scheduleSymbolLoad(after delay: Duration) {
|
||||
symbolsTask?.cancel()
|
||||
let editor = editor
|
||||
symbolsTask = Task {
|
||||
try? await Task.sleep(for: delay)
|
||||
guard !Task.isCancelled else { return }
|
||||
await editor?.loadKnownSymbols()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
import CoreGraphics
|
||||
import Foundation
|
||||
import HelderCore
|
||||
import HelderServices
|
||||
import Observation
|
||||
|
||||
/// What the model asks of the window it lives in; the shell fills these in.
|
||||
public struct WindowHooks {
|
||||
public var closeWindow: () -> Void = {}
|
||||
|
||||
public init() {}
|
||||
}
|
||||
|
||||
/// Timings the model waits on; tests shorten them.
|
||||
public struct WorkspaceTimings: Sendable {
|
||||
/// How long watcher events are gathered into one refresh.
|
||||
public var refreshDebounce: Duration = .milliseconds(100)
|
||||
/// The declared-class list loads late on purpose: it only decides which tokens may underline.
|
||||
public var symbolsAfterLaunch: Duration = .milliseconds(1500)
|
||||
public var symbolsAfterChange: Duration = .milliseconds(2000)
|
||||
|
||||
public init() {}
|
||||
|
||||
public static let immediate: WorkspaceTimings = {
|
||||
var timings = WorkspaceTimings()
|
||||
timings.refreshDebounce = .zero
|
||||
timings.symbolsAfterLaunch = .zero
|
||||
timings.symbolsAfterChange = .zero
|
||||
return timings
|
||||
}()
|
||||
}
|
||||
|
||||
/// What one refresh pass re-reads.
|
||||
public struct RefreshScope: OptionSet, Sendable {
|
||||
public let rawValue: Int
|
||||
public init(rawValue: Int) { self.rawValue = rawValue }
|
||||
|
||||
public static let git = RefreshScope(rawValue: 1)
|
||||
public static let tree = RefreshScope(rawValue: 2)
|
||||
/// A changed file may add or remove a PHP class.
|
||||
public static let symbols = RefreshScope(rawValue: 4)
|
||||
/// The open file and every unsaved buffer pick up the disk text; unsaved edits are kept.
|
||||
public static let openFiles = RefreshScope(rawValue: 8)
|
||||
/// The project note picks up an outside edit when it has no unsaved typing.
|
||||
public static let note = RefreshScope(rawValue: 16)
|
||||
}
|
||||
|
||||
/// A list row whose on-screen frame the ⌘→ menu anchors to.
|
||||
public enum RowKey: Hashable, Sendable {
|
||||
/// A Source Control row, by `Change.id`.
|
||||
case git(String)
|
||||
/// An Explorer row, by path.
|
||||
case tree(String)
|
||||
}
|
||||
|
||||
/// One window, one project. Composes the stores and runs the actions that span several of them.
|
||||
/// Views read the stores directly; anything that changes more than one store goes through `perform`.
|
||||
@Observable
|
||||
@MainActor
|
||||
public final class WorkspaceModel {
|
||||
/// nil until a project is opened; the window then shows the launcher.
|
||||
public internal(set) var root: URL?
|
||||
public internal(set) var name = ""
|
||||
/// `APP_NAME` from the project's `.env`, else the folder name.
|
||||
public internal(set) var title = "Helder"
|
||||
public internal(set) var config = HelderConfig.defaults
|
||||
public internal(set) var recentProjects: [RecentProject] = []
|
||||
/// True once the first load finished, so the window never flashes the launcher on a slow disk.
|
||||
public internal(set) var isReady = false
|
||||
/// The bare window's launcher rows and cursor.
|
||||
public internal(set) var launcher = LauncherList()
|
||||
/// The latest request to move keyboard focus; views take first responder when it names them.
|
||||
public internal(set) var focusRequest: FocusRequest?
|
||||
/// Bumped by ⌘R; the columns flash once per bump so a refresh that changed nothing still reads.
|
||||
public internal(set) var refreshTick = 0
|
||||
/// The branch · project card shown briefly when the window becomes key again.
|
||||
public internal(set) var isFocusFlashVisible = false
|
||||
|
||||
public let layout: LayoutStore
|
||||
public let overlay: OverlayStore
|
||||
public let toasts: ToastStore
|
||||
public internal(set) var sourceControl: SourceControlStore?
|
||||
public internal(set) var explorer: ExplorerStore?
|
||||
public internal(set) var editor: EditorStore?
|
||||
public internal(set) var terminal: TerminalStore
|
||||
public internal(set) var note: NoteStore?
|
||||
|
||||
@ObservationIgnored public let app: AppServices
|
||||
@ObservationIgnored public internal(set) var services: WorkspaceServices?
|
||||
@ObservationIgnored public var hooks = WindowHooks()
|
||||
@ObservationIgnored public var timings: WorkspaceTimings
|
||||
@ObservationIgnored var watcher: FileWatching?
|
||||
@ObservationIgnored var pendingRefresh: RefreshScope = []
|
||||
@ObservationIgnored var refreshTask: Task<Void, Never>?
|
||||
@ObservationIgnored var refreshID = UUID()
|
||||
@ObservationIgnored var symbolsTask: Task<Void, Never>?
|
||||
@ObservationIgnored var flashTask: Task<Void, Never>?
|
||||
/// Fire-and-forget work started by commands; `settle()` waits for it and a project switch drains it.
|
||||
@ObservationIgnored var work: [UUID: Task<Void, Never>] = [:]
|
||||
/// A project switch or window close; kept apart from `work` because it drains `work`.
|
||||
@ObservationIgnored var lifecycleTask: Task<Void, Never>?
|
||||
/// Moves on every project switch, so work that awaited across one can tell its project is gone.
|
||||
@ObservationIgnored var generation = 0
|
||||
/// Where the Source Control and Explorer rows sit on screen, in top-left window coordinates.
|
||||
@ObservationIgnored var rowFrames: [RowKey: CGRect] = [:]
|
||||
@ObservationIgnored var hasStarted = false
|
||||
@ObservationIgnored var resignedKey = false
|
||||
|
||||
public init(root: URL?, app: AppServices, timings: WorkspaceTimings = WorkspaceTimings()) {
|
||||
self.app = app
|
||||
self.timings = timings
|
||||
self.root = root?.standardizedFileURL
|
||||
layout = LayoutStore(session: app.session, persistence: app.layouts)
|
||||
overlay = OverlayStore()
|
||||
toasts = ToastStore()
|
||||
terminal = TerminalStore()
|
||||
wireTerminal()
|
||||
overlay.onChange = { [weak self] old, new in self?.overlayChanged(from: old, to: new) }
|
||||
if let root = self.root { attach(root) }
|
||||
}
|
||||
|
||||
/// Loads the recents and, with a project, its config, git, tree, note and session; then starts the watchers.
|
||||
public func start() async {
|
||||
guard !hasStarted else { return }
|
||||
hasStarted = true
|
||||
recentProjects = await app.recentProjects.list()
|
||||
launcher = LauncherList(recents: recentProjects, excluding: root?.path)
|
||||
if root != nil { await loadProject() }
|
||||
isReady = true
|
||||
}
|
||||
|
||||
/// Runs any command: the one entry point for views, menus and the keyboard.
|
||||
public func perform(_ command: Command) {
|
||||
switch command {
|
||||
case let .showSearch(seed): overlay.present(.search(seed: seed.isEmpty ? editorSelectionFirstLine() : seed))
|
||||
case .showNote: overlay.present(.note)
|
||||
case .showShortcuts: overlay.present(.shortcuts)
|
||||
case .showRecentProjects: showRecentProjects()
|
||||
case let .showRecentFiles(index): overlay.present(.recentFiles(initialSelection: index))
|
||||
case let .showContextMenu(target, anchor): showContextMenu(target, anchor: anchor)
|
||||
case .dismissOverlay: overlay.dismiss()
|
||||
case .confirmPending: confirmPending()
|
||||
case let .submitName(name): submitName(name)
|
||||
case let .passToAgent(text, reference):
|
||||
overlay.dismiss()
|
||||
passToAgent(text, toast: reference)
|
||||
|
||||
case let .launcherMove(step): launcher.move(by: step)
|
||||
case let .launcherSelect(index): launcher.select(index)
|
||||
case .launcherActivate: activateLauncher()
|
||||
|
||||
case .toggleGit: layout.toggleGit()
|
||||
case .toggleAutoFit: layout.toggleFluid()
|
||||
case .toggleHidden: layout.toggleHidden()
|
||||
case let .focus(panel): focus(panel)
|
||||
case let .focusNeighbour(step): focus(layout.neighbour(of: layout.activePanel, step: step))
|
||||
|
||||
case let .moveRowCursor(step): moveRowCursor(by: step)
|
||||
case .openSelectedRow: openSelectedRow()
|
||||
case .openRowMenu: openRowMenu()
|
||||
|
||||
case let .open(path, options): open(path, options)
|
||||
case .save:
|
||||
guard let editor, editor.activeIsDirty else { return }
|
||||
track { try? await editor.save() }
|
||||
case .closeFileOrWindow:
|
||||
if let editor, editor.activePath != nil {
|
||||
track { await editor.requestCloseActive() }
|
||||
} else {
|
||||
hooks.closeWindow()
|
||||
}
|
||||
case .cycleMode: editor?.togglePreview()
|
||||
case let .passSelection(info): passSelection(info)
|
||||
case .selectAllInFile: editor?.selectAll()
|
||||
|
||||
case .commit:
|
||||
guard let sourceControl, sourceControl.canCommit else { return }
|
||||
track { _ = await sourceControl.commit() }
|
||||
case .push:
|
||||
guard let sourceControl else { return }
|
||||
track { _ = await sourceControl.push() }
|
||||
case .focusCommitMessage:
|
||||
if !layout.gitVisible { layout.toggleGit() }
|
||||
layout.focus(.sourceControl)
|
||||
focusRequest = FocusRequest(.commitMessage)
|
||||
|
||||
case .passNote: passNote()
|
||||
|
||||
case .openFolder:
|
||||
switchProject {
|
||||
guard let url = await self.app.system.chooseFolder() else { return }
|
||||
await self.openProject(url)
|
||||
}
|
||||
case let .openRecentProject(path): switchProject { await self.openProject(URL(fileURLWithPath: path)) }
|
||||
case .refresh: track { await self.refresh() }
|
||||
case .newWindow: app.system.openNewInstance(nil)
|
||||
case let .zoom(step): layout.zoom(step)
|
||||
|
||||
case let .context(action): perform(action)
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens a file in the editor, reveals it in the Explorer and gives the editor the wide columns.
|
||||
public func open(_ path: String, _ options: OpenOptions = OpenOptions()) {
|
||||
guard let editor else { return }
|
||||
explorer?.select(path)
|
||||
editor.open(path, options)
|
||||
layout.setFocusZone(.editor)
|
||||
}
|
||||
|
||||
/// Inserts text into the agent's composer without submitting it, and confirms with a toast.
|
||||
public func passToAgent(_ text: String, toast reference: String? = nil) {
|
||||
terminal.insertIntoAgent(text: text)
|
||||
toasts.show("Passed to agent", detail: reference)
|
||||
}
|
||||
|
||||
/// Paths with a git change; the file lists mark them with a dot.
|
||||
public var changedPaths: Set<String> {
|
||||
Set(sourceControl?.state.changes.map(\.path) ?? [])
|
||||
}
|
||||
|
||||
/// A view took the keyboard: the request is spent, so a view rebuilt later never grabs focus for it again.
|
||||
public func focusTaken(_ target: FocusTarget) {
|
||||
if focusRequest?.target == target { focusRequest = nil }
|
||||
}
|
||||
|
||||
/// A click inside a column: it becomes the active panel without taking first responder.
|
||||
public func pointerFocused(_ panel: Panel) {
|
||||
let previous = layout.activePanel
|
||||
layout.focus(panel)
|
||||
if panel == .sourceControl && previous != .sourceControl { scheduleRefresh(.git) }
|
||||
}
|
||||
|
||||
func wireTerminal() {
|
||||
terminal.contextMenuRequested = { [weak self] kind, hasSelection, point in
|
||||
self?.showContextMenu(.terminal(kind, hasSelection: hasSelection), anchor: point)
|
||||
}
|
||||
}
|
||||
|
||||
/// A Source Control or Explorer row reports where it sits (nil when it leaves the screen).
|
||||
public func rowFrameChanged(_ key: RowKey, _ frame: CGRect?) {
|
||||
rowFrames[key] = frame
|
||||
}
|
||||
|
||||
/// Saves the note when the window loses focus.
|
||||
public func windowDidResignKey() {
|
||||
resignedKey = true
|
||||
guard let note else { return }
|
||||
track { await note.save() }
|
||||
}
|
||||
|
||||
/// Coming back to a window flashes branch · project, so the right window is obvious; launch never does.
|
||||
public func windowDidBecomeKey() {
|
||||
guard resignedKey else { return }
|
||||
resignedKey = false
|
||||
guard root != nil else { return }
|
||||
flashTask?.cancel()
|
||||
isFocusFlashVisible = true
|
||||
flashTask = Task { [weak self] in
|
||||
try? await Task.sleep(for: Metrics.focusFlashDuration)
|
||||
guard !Task.isCancelled else { return }
|
||||
self?.isFocusFlashVisible = false
|
||||
}
|
||||
}
|
||||
|
||||
func track(_ operation: @escaping @MainActor () async -> Void) {
|
||||
let id = UUID()
|
||||
work[id] = Task { [weak self] in
|
||||
await operation()
|
||||
self?.work[id] = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
import HelderServices
|
||||
|
||||
/// Every service one project window needs. Tests pass fakes; the app uses `live(root:)`.
|
||||
public struct WorkspaceServices {
|
||||
public var git: GitServicing
|
||||
public var files: FileServicing
|
||||
public var search: SearchServicing
|
||||
public var symbols: SymbolServicing
|
||||
public var config: ConfigServicing
|
||||
public var notes: NotesServicing
|
||||
public var recentFiles: RecentFilesStoring
|
||||
|
||||
public init(git: GitServicing, files: FileServicing, search: SearchServicing, symbols: SymbolServicing,
|
||||
config: ConfigServicing, notes: NotesServicing, recentFiles: RecentFilesStoring) {
|
||||
self.git = git
|
||||
self.files = files
|
||||
self.search = search
|
||||
self.symbols = symbols
|
||||
self.config = config
|
||||
self.notes = notes
|
||||
self.recentFiles = recentFiles
|
||||
}
|
||||
|
||||
public static func live(root: URL) -> WorkspaceServices {
|
||||
let config = ConfigService(root: root)
|
||||
let search = RipgrepSearchService(root: root, config: config)
|
||||
return WorkspaceServices(
|
||||
git: GitService(root: root),
|
||||
files: FileService(root: root, search: search),
|
||||
search: search,
|
||||
symbols: SymbolService(root: root, config: config),
|
||||
config: config,
|
||||
notes: NotesService(root: root),
|
||||
recentFiles: RecentFilesStore(root: root)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Services shared by every window: what outlives one project.
|
||||
public struct AppServices {
|
||||
public var recentProjects: RecentProjectsStoring
|
||||
public var session: SessionStoring
|
||||
/// Column widths and toggles, per project.
|
||||
public var layouts: LayoutPersisting
|
||||
/// Dialogs, pasteboard, Finder.
|
||||
public var system: SystemActing
|
||||
/// Builds the services for a project folder.
|
||||
public var makeWorkspace: (URL) -> WorkspaceServices
|
||||
public var makeWatcher: () -> FileWatching
|
||||
|
||||
/// Every store is passed in, so a test can never reach the user's real recents, sessions or layouts.
|
||||
public init(recentProjects: RecentProjectsStoring, session: SessionStoring, layouts: LayoutPersisting, system: SystemActing,
|
||||
makeWorkspace: @escaping (URL) -> WorkspaceServices, makeWatcher: @escaping () -> FileWatching) {
|
||||
self.recentProjects = recentProjects
|
||||
self.session = session
|
||||
self.layouts = layouts
|
||||
self.system = system
|
||||
self.makeWorkspace = makeWorkspace
|
||||
self.makeWatcher = makeWatcher
|
||||
}
|
||||
|
||||
public static let live = AppServices(
|
||||
recentProjects: RecentProjectsStore(),
|
||||
session: SessionStore(),
|
||||
layouts: UserDefaultsLayoutStore(),
|
||||
system: LiveSystemActions(),
|
||||
makeWorkspace: WorkspaceServices.live(root:),
|
||||
makeWatcher: { FSEventsWatcher() }
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user