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? @ObservationIgnored var refreshID = UUID() @ObservationIgnored var symbolsTask: Task? @ObservationIgnored var flashTask: Task? /// Fire-and-forget work started by commands; `settle()` waits for it and a project switch drains it. @ObservationIgnored var work: [UUID: Task] = [:] /// A project switch or window close; kept apart from `work` because it drains `work`. @ObservationIgnored var lifecycleTask: Task? /// 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. /// Nothing moves when the editor's unsaved-edits prompt is cancelled or its save fails. public func open(_ path: String, _ options: OpenOptions = OpenOptions()) { guard let editor else { return } editor.open(path, options) { [weak self] in self?.explorer?.select(path) self?.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 { 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 } } }