use anyhow::{Context, Result};
use crossterm::{
event::{
self, DisableBracketedPaste, DisableMouseCapture, EnableBracketedPaste, EnableMouseCapture,
Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers, KeyboardEnhancementFlags,
MouseButton, MouseEvent, MouseEventKind, PopKeyboardEnhancementFlags,
PushKeyboardEnhancementFlags,
},
execute,
terminal::{EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode},
};
use ratatui::{
Terminal,
backend::CrosstermBackend,
layout::{Constraint, Direction, Layout, Rect},
style::{Color, Modifier, Style},
text::{Line, Span},
widgets::Paragraph,
};
use std::collections::BTreeSet;
use std::io::{Stdout, stdout};
use std::path::{Path, PathBuf};
use std::time::Duration;
mod click;
mod cursor_blink;
mod editor_layout;
mod fs_watch;
mod git_worker;
mod hover;
mod nav;
mod overlay;
mod perf_hud;
pub(crate) mod sidebar_dwell;
mod welcome;
use click::{ClickTracker, ModifiedClickTracker};
use cursor_blink::CursorBlink;
use fs_watch::FsWatch;
use git_worker::GitWorker;
use hover::{HOVER_DELAY, HoverDwell};
use nav::{NavHistory, NavLoc};
use overlay::OverlayManager;
use perf_hud::PerfHud;
use sidebar_dwell::{AUTO_HIDE_DWELL, SidebarDwell};
use welcome::WelcomeState;
use crate::widgets::terminal::cwd_of_pid;
use crate::widgets::{
dependencies::{DependenciesPanel, Dependency, Ecosystem},
editor::{Editor, EditorTabs},
file_tree::FileTree,
open_editors::{OpenEditorItem, OpenEditorsPanel},
outline::OutlinePanel,
remote::RemotePanel,
run_debug::RunDebugPanel,
search::{SearchPanel, SearchRequest},
source_control::SourceControlPanel,
terminal::{MouseAction, MouseButtonKind, MouseMods, PtyTerminal},
timeline::TimelinePanel,
};
/// Which sidebar view is active in the left side panel.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum SidebarView {
Explorer,
Search,
SourceControl,
Remote,
RunDebug,
Extensions,
Testing,
}
/// The toggleable sub-views stacked inside the Explorer side panel, mirroring
/// VS Code's "Views and More Actions" (⋯) menu on the EXPLORER header. Ordered
/// top-to-bottom exactly as they stack in the panel.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum ExplorerView {
OpenEditors,
Folders,
Outline,
Timeline,
Dependencies,
}
impl ExplorerView {
/// Every view, in stacking order — the order the ⋯ menu lists them.
pub const ALL: [ExplorerView; 5] = [
ExplorerView::OpenEditors,
ExplorerView::Folders,
ExplorerView::Outline,
ExplorerView::Timeline,
ExplorerView::Dependencies,
];
/// Menu / section-header label, matching VS Code's wording. Dependencies is
/// a static fallback only — its real label is language-aware and computed
/// from the detected ecosystems (see [`crate::widgets::dependencies`]).
pub fn label(self) -> &'static str {
match self {
ExplorerView::OpenEditors => "Open Editors",
ExplorerView::Folders => "Folders",
ExplorerView::Outline => "Outline",
ExplorerView::Timeline => "Timeline",
ExplorerView::Dependencies => "Dependencies",
}
}
}
/// Which Explorer sub-views are shown, toggled from the ⋯ menu. Wraps the
/// persisted [`crate::prefs::ExplorerViewsPrefs`] so the app can query/flip a
/// view by its [`ExplorerView`] without touching the serde struct's fields
/// directly.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub struct ExplorerViewVisibility {
flags: crate::prefs::ExplorerViewsPrefs,
}
impl ExplorerViewVisibility {
fn from_prefs(flags: crate::prefs::ExplorerViewsPrefs) -> Self {
Self { flags }
}
fn as_prefs(self) -> crate::prefs::ExplorerViewsPrefs {
self.flags
}
pub fn is_visible(&self, view: ExplorerView) -> bool {
match view {
ExplorerView::OpenEditors => self.flags.open_editors,
ExplorerView::Folders => self.flags.folders,
ExplorerView::Outline => self.flags.outline,
ExplorerView::Timeline => self.flags.timeline,
ExplorerView::Dependencies => self.flags.dependencies,
}
}
/// Flip one view's visibility, returning the new state.
pub fn toggle(&mut self, view: ExplorerView) -> bool {
let slot = match view {
ExplorerView::OpenEditors => &mut self.flags.open_editors,
ExplorerView::Folders => &mut self.flags.folders,
ExplorerView::Outline => &mut self.flags.outline,
ExplorerView::Timeline => &mut self.flags.timeline,
ExplorerView::Dependencies => &mut self.flags.dependencies,
};
*slot = !*slot;
*slot
}
}
/// The clickable icons on the activity bar, used to track which one the
/// pointer is hovering. Mirrors `SidebarView` plus the bottom-anchored
/// settings gear, which is not a sidebar view but is still a hoverable
/// button.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum ActivityIcon {
Explorer,
Search,
SourceControl,
Remote,
RunDebug,
Extensions,
Testing,
Settings,
}
/// How many commits the history scrubber loads up front (#371).
///
/// A ceiling rather than the whole history: the issue's own criterion is
/// that scrubbing 200 commits stays interactive, and a repo with 50,000 of
/// them should not pay for all of them to answer a question about the last
/// few hundred. Lazy loading around the cursor is the follow-up; this bounds
/// the first version so it cannot be slow on a large repo.
const SCRUB_COMMIT_LIMIT: usize = 500;
/// How long one host gets in a fleet run (#363).
///
/// A ceiling on the CONNECT and a wall-clock bound on the whole thing: the
/// issue's criterion is that a host which times out shows red without
/// delaying the others, and only the second bound delivers that for a host
/// that connects and then hangs.
const FLEET_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
const ACTIVITY_BAR_WIDTH: u16 = 4;
const ACTIVITY_ICON_HEIGHT: u16 = 2;
const ACTIVITY_ICON_GAP: u16 = 0;
const FALLBACK_CELL_PIXEL: (u32, u32) = (10, 20);
/// Fixed width of the secondary side bar (hosts the active file's Outline),
/// on the edge opposite the primary side bar. VS Code's auxiliary bar.
const SECONDARY_SIDEBAR_WIDTH: u16 = 30;
/// Cell box for each Customize Layout toolbar icon: 2 cells wide × 1 tall —
/// exactly HALF an activity-bar icon's `ACTIVITY_BAR_WIDTH`×`ACTIVITY_ICON_HEIGHT`
/// (4×2) box, so the toolbar reads as a smaller chrome control than the far-left
/// Explorer / Search icons, as intended. With the usual ~1:2 cell aspect this is
/// a crisp ~square ≈20×20px image. Baked OPAQUE on the editor background so it
/// paints in FRONT of the tab-strip / welcome top line (the line sits behind
/// it), and stays within the single top row (no overlap with editor content).
const LAYOUT_ICON_CELLS_W: u16 = 2;
const LAYOUT_ICON_CELLS_H: u16 = 1;
/// Which edge the primary side bar (and the activity bar that flanks it) dock
/// to. VS Code's "Primary Side Bar Position". Persisted via `crate::prefs`.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
pub(crate) enum SideBarPosition {
#[default]
Left,
Right,
}
/// Horizontal span of the bottom panel (the terminal stack). Mirrors VS
/// Code's "Panel Alignment": `Center` (default) spans the editor column;
/// `Left`/`Right` hug that half of the editor column; `Justify` stretches the
/// panel across the full content width, under the side bar. Persisted.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
pub(crate) enum PanelAlignment {
Left,
#[default]
Center,
Right,
Justify,
}
/// Where the quick input (command palette / Go to File) anchors vertically.
/// VS Code's "Quick Input Position". Persisted.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
pub(crate) enum QuickInputPosition {
#[default]
Top,
Center,
}
/// One in-flight `textDocument/selectionRange` request (#254): the
/// Expand Selection gesture waiting on its chains. `positions` snapshots
/// the exact cursors the request was fired for, so a reply (or a reuse
/// attempt) after ANY caret movement is recognised as stale even though
/// `edit_seq` did not move.
struct PendingSelectionRanges {
id: u64,
path: PathBuf,
seq: u64,
presses: usize,
positions: Vec<(u32, u32)>,
}
/// Pre-Zen visibility snapshot, restored verbatim when Zen Mode is toggled
/// off so the workspace returns to exactly the chrome it had before.
#[derive(Clone, Copy, Debug)]
struct PreZenLayout {
activity_bar: bool,
status_bar: bool,
side_bar: bool,
secondary_side_bar: bool,
panel: bool,
}
/// Hit-test rects for the three layout-control icons (Toggle Primary Side
/// Bar, Toggle Panel, Customize Layout) rendered at the top-right of the
/// editor tab strip and the welcome screen — croft's analog of VS Code's
/// title-bar layout controls.
#[derive(Clone, Copy, Default)]
struct LayoutIconAreas {
toggle_side_bar: Rect,
toggle_panel: Rect,
customize: Rect,
}
/// Result of [`compute_chrome_layout`]: the rectangles for each workspace
/// region within the horizontal `main` band. Hidden regions are `None` and
/// consume no width.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
struct ChromeLayout {
activity: Option<Rect>,
primary_side: Option<Rect>,
secondary_side: Option<Rect>,
/// The editor + terminal column (always present).
right: Rect,
/// Column of the seam between the editor and the primary side bar, where a
/// resize drag starts. `None` when the primary side bar is hidden.
sidebar_splitter_x: Option<u16>,
}
/// Pure horizontal layout of the workspace chrome within `main`. Column order
/// follows the primary side bar's position (the activity bar always flanks the
/// primary side bar on its outer edge, like VS Code):
/// `Left`: `[activity][primary][right......][secondary]`
/// `Right`: `[secondary][right......][primary][activity]`
/// The `right` column is guaranteed at least `RIGHT_PANE_MIN` cells; the
/// primary side bar is shrunk to make room when the frame is narrow.
fn compute_chrome_layout(
main: Rect,
activity_visible: bool,
primary_visible: bool,
secondary_visible: bool,
side_bar_position: SideBarPosition,
sidebar_w: u16,
secondary_w: u16,
) -> ChromeLayout {
let activity_w = if activity_visible {
ACTIVITY_BAR_WIDTH
} else {
0
};
let secondary_w = if secondary_visible { secondary_w } else { 0 };
// Reserve activity + secondary first, then fit the primary side bar in
// what's left while keeping RIGHT_PANE_MIN for the editor column.
let reserved = activity_w.saturating_add(secondary_w);
let after_reserved = main.width.saturating_sub(reserved);
let max_primary = after_reserved.saturating_sub(RIGHT_PANE_MIN);
let primary_w = if primary_visible {
sidebar_w.min(max_primary)
} else {
0
};
let right_w = after_reserved.saturating_sub(primary_w);
let row = |x: u16, w: u16| Rect {
x,
y: main.y,
width: w,
height: main.height,
};
let mut x = main.x;
let (activity, primary_side, right, secondary_side, splitter);
match side_bar_position {
SideBarPosition::Left => {
activity = (activity_w > 0).then(|| row(x, activity_w));
x += activity_w;
primary_side = (primary_w > 0).then(|| row(x, primary_w));
x += primary_w;
let right_rect = row(x, right_w);
// Seam = editor's left edge.
splitter = (primary_w > 0).then_some(right_rect.x);
right = right_rect;
x += right_w;
secondary_side = (secondary_w > 0).then(|| row(x, secondary_w));
}
SideBarPosition::Right => {
secondary_side = (secondary_w > 0).then(|| row(x, secondary_w));
x += secondary_w;
let right_rect = row(x, right_w);
right = right_rect;
x += right_w;
// Seam = sidebar's left edge (= editor's right edge).
splitter = (primary_w > 0).then_some(x);
primary_side = (primary_w > 0).then(|| row(x, primary_w));
x += primary_w;
activity = (activity_w > 0).then(|| row(x, activity_w));
}
}
ChromeLayout {
activity,
primary_side,
secondary_side,
right,
sidebar_splitter_x: splitter,
}
}
/// Pure horizontal placement of the bottom panel within its `band`. `Center`
/// and `Justify` fill the band; `Left`/`Right` hug that half (clamped to a
/// usable minimum). The leftover strip is painted with the editor background
/// by the caller so it never ghosts.
fn panel_band_rect(band: Rect, alignment: PanelAlignment) -> Rect {
match alignment {
PanelAlignment::Center | PanelAlignment::Justify => band,
PanelAlignment::Left => Rect {
width: (band.width / 2).max(RIGHT_PANE_MIN).min(band.width),
..band
},
PanelAlignment::Right => {
let w = (band.width / 2).max(RIGHT_PANE_MIN).min(band.width);
Rect {
x: band.x + band.width - w,
width: w,
..band
}
}
}
}
/// Centered popup geometry for frames of any size. Min bounds cap at the
/// frame because Ord::clamp panics on min > max, and a frame with no
/// cells on an axis gets no popup at all.
fn fallback_popup_rect(full: Rect, max_w_cap: u16) -> Rect {
if full.width == 0 || full.height == 0 {
return Rect {
width: 0,
height: 0,
..full
};
}
let max_w = max_w_cap.min(full.width);
let max_h = full.height;
let width = (full.width.saturating_mul(7) / 10).clamp(40.min(max_w), max_w);
let height = (full.height.saturating_mul(6) / 10).clamp(10.min(max_h), max_h);
Rect {
x: full.x + (full.width.saturating_sub(width)) / 2,
y: full.y + (full.height.saturating_sub(height)) / 4,
width,
height,
}
}
fn activity_icon_glyph_x(bar: Rect) -> u16 {
bar.x + bar.width / 2
}
/// Rank an executable basename as an lldb-dap candidate, or `None` if it is not
/// one. LLVM ships the adapter under several names: the bare `lldb-dap`, the
/// versioned `lldb-dap-18` that Debian/Ubuntu install (often with no
/// unversioned symlink), and the legacy `lldb-vscode[-NN]` name from older
/// releases. Higher rank wins: an unversioned binary (tracks the system
/// default) beats any versioned one, a newer LLVM release beats an older one,
/// and at equal version the modern `lldb-dap` name beats legacy `lldb-vscode`.
fn lldb_dap_rank(name: &str) -> Option<i64> {
if name == "lldb-dap" {
return Some(i64::MAX);
}
if name == "lldb-vscode" {
return Some(i64::MAX - 1);
}
// `family` breaks ties at equal version: lldb-dap (1) over lldb-vscode (0).
let (version, family) = name
.strip_prefix("lldb-dap-")
.map(|v| (v, 1))
.or_else(|| name.strip_prefix("lldb-vscode-").map(|v| (v, 0)))?;
let version: i64 = version.parse().ok()?;
Some(version * 2 + family)
}
/// Resolve the `lldb-dap` adapter binary: the Xcode Command Line Tools copy
/// first (always present on a dev Mac), then the best-ranked match found by
/// scanning `PATH` for `lldb-dap`/`lldb-dap-NN`/`lldb-vscode[-NN]`. `None` if
/// none is installed.
fn lldb_dap_path() -> Option<String> {
let xcode = "/Library/Developer/CommandLineTools/usr/bin/lldb-dap";
if std::path::Path::new(xcode).is_file() {
return Some(xcode.to_string());
}
let path_var = std::env::var_os("PATH")?;
let mut best: Option<(i64, String)> = None;
for dir in std::env::split_paths(&path_var) {
let Ok(entries) = std::fs::read_dir(&dir) else {
continue;
};
for entry in entries.flatten() {
let Some(name) = entry.file_name().to_str().map(str::to_owned) else {
continue;
};
let Some(rank) = lldb_dap_rank(&name) else {
continue;
};
let full = entry.path();
if is_executable_file(&full) && best.as_ref().is_none_or(|(r, _)| rank > *r) {
best = Some((rank, full.to_string_lossy().into_owned()));
}
}
}
best.map(|(_, p)| p)
}
/// The error shown when no lldb-dap adapter is installed, with a host-correct
/// install hint: Xcode Command Line Tools on macOS, the LLVM package elsewhere.
fn lldb_dap_missing_message() -> String {
let hint = if cfg!(target_os = "macos") {
"install Xcode Command Line Tools"
} else {
"install LLVM, e.g. apt install lldb"
};
format!("lldb-dap not found ({hint})")
}
/// The interpreter that runs a Python project's own code: its `.venv` python
/// (where the project's deps, pytest included, are importable) or the system
/// python3. The debug venv's python is only the debugpy ADAPTER host — the
/// debuggee must be this one, or a pytest module launch can't import pytest.
fn project_python(root: &Path) -> PathBuf {
let venv = root.join(".venv").join("bin").join("python");
if venv.is_file() {
return venv;
}
if let Some(path_var) = std::env::var_os("PATH") {
for dir in std::env::split_paths(&path_var) {
let candidate = dir.join("python3");
if candidate.is_file() {
return candidate;
}
}
}
PathBuf::from("python3")
}
/// Whether `path` is a regular file with the executable bit set — i.e. a
/// compiled binary or script croft can run directly (`./file`) and debug via
/// lldb-dap without a build step. The honest signal for "directly executable",
/// since such files usually have no extension.
fn is_executable_file(path: &Path) -> bool {
use std::os::unix::fs::PermissionsExt;
std::fs::metadata(path)
.map(|m| m.is_file() && m.permissions().mode() & 0o111 != 0)
.unwrap_or(false)
}
/// Append variable rows to the debug tree, recursing into any expanded
/// (`variablesReference` in `expanded`) container whose children are loaded.
/// Pulled out as a free function so it can borrow the session immutably while
/// the caller mutates the row vector.
fn push_variable_rows(
rows: &mut Vec<crate::widgets::run_debug::DebugRow>,
session: &crate::dap::session::DapSession,
expanded: &std::collections::HashSet<i64>,
vars: &[crate::dap::session::Variable],
indent: u8,
) {
use crate::widgets::run_debug::{DebugRow, DebugRowKind};
for v in vars {
let expandable = v.variables_ref > 0;
let is_open = expandable && expanded.contains(&v.variables_ref);
rows.push(DebugRow {
indent,
kind: DebugRowKind::Variable {
reference: v.variables_ref,
expandable,
expanded: is_open,
name: v.name.clone(),
value: v.value.clone(),
type_name: v.type_name.clone(),
},
});
if is_open && let Some(children) = session.variables.get(&v.variables_ref) {
push_variable_rows(rows, session, expanded, children, indent.saturating_add(1));
}
}
}
fn activity_explorer_y(bar: Rect) -> u16 {
bar.y + 1
}
fn activity_search_y(bar: Rect) -> u16 {
activity_explorer_y(bar) + ACTIVITY_ICON_HEIGHT + ACTIVITY_ICON_GAP
}
fn activity_source_control_y(bar: Rect) -> u16 {
activity_search_y(bar) + ACTIVITY_ICON_HEIGHT + ACTIVITY_ICON_GAP
}
fn activity_run_debug_y(bar: Rect) -> u16 {
activity_source_control_y(bar) + ACTIVITY_ICON_HEIGHT + ACTIVITY_ICON_GAP
}
fn activity_remote_y(bar: Rect) -> u16 {
activity_run_debug_y(bar) + ACTIVITY_ICON_HEIGHT + ACTIVITY_ICON_GAP
}
fn activity_extensions_y(bar: Rect) -> u16 {
activity_remote_y(bar) + ACTIVITY_ICON_HEIGHT + ACTIVITY_ICON_GAP
}
fn activity_testing_y(bar: Rect) -> u16 {
activity_extensions_y(bar) + ACTIVITY_ICON_HEIGHT + ACTIVITY_ICON_GAP
}
fn activity_explorer_block(bar: Rect) -> Rect {
Rect {
x: bar.x,
y: activity_explorer_y(bar),
width: bar.width,
height: ACTIVITY_ICON_HEIGHT,
}
}
fn activity_search_block(bar: Rect) -> Rect {
Rect {
x: bar.x,
y: activity_search_y(bar),
width: bar.width,
height: ACTIVITY_ICON_HEIGHT,
}
}
fn activity_source_control_block(bar: Rect) -> Rect {
Rect {
x: bar.x,
y: activity_source_control_y(bar),
width: bar.width,
height: ACTIVITY_ICON_HEIGHT,
}
}
fn activity_remote_block(bar: Rect) -> Rect {
Rect {
x: bar.x,
y: activity_remote_y(bar),
width: bar.width,
height: ACTIVITY_ICON_HEIGHT,
}
}
fn activity_run_debug_block(bar: Rect) -> Rect {
Rect {
x: bar.x,
y: activity_run_debug_y(bar),
width: bar.width,
height: ACTIVITY_ICON_HEIGHT,
}
}
fn activity_extensions_block(bar: Rect) -> Rect {
Rect {
x: bar.x,
y: activity_extensions_y(bar),
width: bar.width,
height: ACTIVITY_ICON_HEIGHT,
}
}
fn activity_testing_block(bar: Rect) -> Rect {
Rect {
x: bar.x,
y: activity_testing_y(bar),
width: bar.width,
height: ACTIVITY_ICON_HEIGHT,
}
}
/// The settings gear, anchored to the BOTTOM of the activity bar (VS Code's
/// "Manage" gear), asymmetric to the view icons stacked from the top. Returns
/// an empty rect when the bar is too short to fit the gear below the last view
/// icon, so the caller skips rendering and hit-testing it rather than letting
/// it collide with Run-and-Debug on a tiny terminal.
///
/// Reserves a 1-cell bottom inset (`ACTIVITY_ICON_HEIGHT + 1`) so the gap below
/// the gear matches the 1-cell top inset the view icons get from
/// `activity_explorer_y`'s `bar.y + 1`. Without it the gear hugged the row
/// directly above the status bar, reading as lopsidedly low.
const ACTIVITY_BOTTOM_INSET: u16 = 1;
fn activity_settings_block(bar: Rect) -> Rect {
let y = bar
.y
.saturating_add(bar.height)
.saturating_sub(ACTIVITY_ICON_HEIGHT + ACTIVITY_BOTTOM_INSET);
let last_view_bottom = activity_testing_y(bar) + ACTIVITY_ICON_HEIGHT;
if y < last_view_bottom {
return Rect::default();
}
Rect {
x: bar.x,
y,
width: bar.width,
height: ACTIVITY_ICON_HEIGHT,
}
}
#[derive(Default, Clone, Copy)]
struct SidebarAreas {
/// Block occupied by the Explorer activity-bar icon, in absolute coords.
/// Multi-row when image rendering is active; the hit-test still uses the
/// whole block.
explorer_icon: Rect,
/// Block occupied by the Search activity-bar icon, in absolute coords.
search_icon: Rect,
/// Block occupied by the Source Control activity-bar icon, in absolute coords.
source_control_icon: Rect,
/// Block occupied by the Remote Explorer activity-bar icon, in absolute coords.
remote_icon: Rect,
/// Block occupied by the Run and Debug activity-bar icon, in absolute coords.
run_debug_icon: Rect,
/// Block occupied by the Extensions activity-bar icon, in absolute coords.
extensions_icon: Rect,
/// Block occupied by the Testing (beaker) activity-bar icon, in absolute coords.
testing_icon: Rect,
/// Block occupied by the settings gear, bottom-anchored on the activity
/// bar (VS Code's "Manage" button). Asymmetric to the view icons up top;
/// clicking it opens the settings menu (Color Theme picker).
settings_icon: Rect,
}
/// Pre-encoded iTerm2 OSC-1337 inline-image escape sequences for each icon
/// state. Encoded once in `App::init_graphics` (no PNG re-encoding per
/// frame) and rewritten under the activity-bar block after every ratatui
/// frame draw, since ratatui's bg-clear overdraws the image.
pub struct ActivityBarImages {
explorer_active: String,
explorer_inactive: String,
explorer_hovered: String,
search_active: String,
search_inactive: String,
search_hovered: String,
source_control_active: String,
source_control_inactive: String,
source_control_hovered: String,
remote_active: String,
remote_inactive: String,
remote_hovered: String,
run_debug_active: String,
run_debug_inactive: String,
run_debug_hovered: String,
extensions_active: String,
extensions_inactive: String,
extensions_hovered: String,
testing_active: String,
testing_inactive: String,
testing_hovered: String,
/// The settings gear. `active` is shown while its menu is open so the
/// button reads as pressed, mirroring the view icons' selected state;
/// `hovered` brightens it while the pointer rests on it.
settings_active: String,
settings_inactive: String,
settings_hovered: String,
/// Customize Layout toolbar icons (top-right of the editor / welcome),
/// baked OPAQUE at the 4×2-cell toolbar box so they paint in front of the
/// container's top line. The side-bar / panel icons carry an on/off pair
/// (filled vs. hollow) matching their visibility; every icon also has a
/// brighter `_hover` variant emitted while the pointer rests on it, exactly
/// like the activity-bar icons.
layout_sidebar_on: String,
layout_sidebar_on_hover: String,
layout_sidebar_off: String,
layout_sidebar_off_hover: String,
layout_panel_on: String,
layout_panel_on_hover: String,
layout_panel_off: String,
layout_panel_off_hover: String,
layout_customize: String,
layout_customize_hover: String,
}
/// Single source of truth for the application's user-facing name.
pub const APP_NAME: &str = "croft";
/// Agnoster-style status colours: clean working tree is green, any dirtiness
/// (modified, staged, or untracked) flips the pill to yellow/orange.
const GIT_CLEAN_COLOR: Color = Color::Rgb(0xa3, 0xbe, 0x8c);
const GIT_DIRTY_COLOR: Color = Color::Rgb(0xeb, 0xcb, 0x8b);
/// Build the status-bar spans for the git pill: branch glyph, branch name,
/// optional ahead/behind counts. Colour alone carries clean/dirty state, in
/// the spirit of the Agnoster zsh theme. Returns an empty vec outside a git
/// repo so the bar shows nothing.
fn git_status_spans<'a>(status: &'a crate::git::GitStatus) -> Vec<Span<'a>> {
if !status.in_repo {
return Vec::new();
}
let pill_color = if status.dirty {
GIT_DIRTY_COLOR
} else {
GIT_CLEAN_COLOR
};
let mut spans: Vec<Span> = Vec::with_capacity(6);
spans.push(Span::raw(" "));
// Codicon `cod-source-control` (U+EA68): the Y-fork that matches the
// activity-bar Source Control icon, so the status-bar branch indicator
// and the SCM panel share the same visual mark.
spans.push(Span::styled("\u{ea68} ", Style::default().fg(pill_color)));
let label: &str = match (&status.branch, &status.detached_hash) {
(Some(b), _) => b.as_str(),
(None, Some(h)) => h.as_str(),
(None, None) => "(no head)",
};
spans.push(Span::styled(
label,
Style::default().fg(pill_color).add_modifier(Modifier::BOLD),
));
if status.ahead > 0 {
spans.push(Span::styled(
format!(" \u{2191}{}", status.ahead),
Style::default().fg(GIT_CLEAN_COLOR),
));
}
if status.behind > 0 {
spans.push(Span::styled(
format!(" \u{2193}{}", status.behind),
Style::default().fg(GIT_DIRTY_COLOR),
));
}
spans
}
/// Logo orange (#e97c41), sampled from `assets/logo.png`: the colour of the
/// `<>` angle brackets in the "cr<>ft" wordmark. Also the Extensions panel's
/// trash button — the warm complement to the teal brand gradient.
pub(crate) const BRAND_ORANGE: Color = Color::Rgb(0xe9, 0x7c, 0x41);
/// Spans for the "cr<>ft" wordmark at the left of the status bar, styled to
/// mirror the app logo: white letters with the `<>` (the stylised "o") in the
/// brand orange, sitting on the bar's own background rather than a pill.
fn brand_spans(theme: crate::theme::Theme) -> Vec<Span<'static>> {
let letter = Style::default()
.fg(theme.ui(Color::White))
.add_modifier(Modifier::BOLD);
vec![
Span::styled(" cr", letter),
Span::styled(
"<>",
Style::default()
.fg(BRAND_ORANGE)
.add_modifier(Modifier::BOLD),
),
Span::styled("ft ", letter),
]
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Pane {
Tree,
Editor,
Terminal,
}
/// Which tab the bottom panel group shows. The panel is the "terminal group"
/// VS Code-style: a tab strip over a shared region. `Terminal` shows the live
/// shell(s); `Problems` shows aggregated workspace diagnostics; `Output` is the
/// read-only per-channel log viewer.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum BottomPanelTab {
Terminal,
Problems,
Output,
Ports,
Captures,
}
/// A transient, click-only notification that a browsable port just appeared in
/// the terminal. It never captures keystrokes — the terminal owns those — so
/// the user clicks an action or lets it auto-dismiss. The forward actions only
/// apply on a remote session (a local port is already reachable).
struct PortToast {
port: u16,
process: Option<String>,
origin_remote: bool,
shown_at: std::time::Instant,
/// Action button hit rects, recomputed each render.
buttons: Vec<(Rect, PortToastAction)>,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum PortToastAction {
ForwardAndOpen,
ForwardOnly,
Open,
Dismiss,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum CreateKind {
File,
Folder,
}
/// Why the single-host lock was last refused, for announcing each reason
/// once (see `App::pair_lock_denied`).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum PairLockDenial {
Busy,
Io,
}
/// The bottom-left "a newer croft is available" popup (#333). Click-only
/// like the port toast: it never takes a keystroke from the editor or a
/// terminal. `ready` flips it from Update/Later to Relaunch once the staged
/// build has landed.
struct UpdateToast {
version: String,
ready: bool,
/// Action button hit rects, recomputed each render.
buttons: Vec<(Rect, UpdateToastAction)>,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum UpdateToastAction {
/// Stage the new version in the background; nothing on PATH changes.
Update,
/// Dismiss, and never offer this version again.
Later,
/// Swap the staged binary in and re-exec - the only path that updates.
Relaunch,
}
/// Which producer an [`crate::update_watch::UpdateEvent`] came from: the
/// remote install watcher, the drift rebuild, or the staged release build
/// (#333). They share one event type and one status-bar state machine.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum UpdateSource {
Watch,
SelfInstall,
Staged,
}
/// A fenced block about to run (#353), parked behind the confirm popup.
#[derive(Clone, Debug)]
struct PendingRunBlock {
pane_name: String,
cwd: PathBuf,
command: String,
/// The block as written, shown whole in the popup (the fence was
/// refused if it carried control characters, so it renders as typed).
code: String,
/// Turns the popup red: the block looks destructive or said `{confirm}`.
destructive: bool,
/// The document this block came from, for `{persist}`'s write-back.
doc: Option<PathBuf>,
/// The fence opener's SOURCE line, which keys the captured output.
block_line: usize,
/// `{persist}`: write the capture back into the document.
persist: bool,
/// `{timeout=N}`: stop CAPTURING after N seconds. Never stops the
/// process; the block keeps running in its pane.
capture_timeout: Option<std::time::Duration>,
}
/// A block whose output croft is waiting for (#354).
///
/// Armed when the block is typed into its pane and settled by
/// [`App::settle_block_captures`] when the shell reports the command
/// finished.
///
/// IDENTITY, NOT POSITION (#440, landed as #441). `after` is the id of the
/// last command the pane had already finished when the block was typed, so
/// this block's command is the first decoration whose id is greater. Ids
/// are monotonic and the collector never renumbers them, so an evicted
/// command reads as GONE rather than as its neighbour - which is what makes
/// the `{persist}` write safe rather than merely guarded.
///
/// The previous shape indexed the decoration list, which is a sliding
/// window: an eviction shifted every index down and index `seen` came to
/// name a stranger. That was narrowed with a high-water sample and could
/// not be closed by one, because any length-derived signal samples a value
/// that can move twice between observations. An id cannot move at all.
struct PendingCapture {
pane_name: String,
doc: Option<PathBuf>,
block_line: usize,
/// Ids at or below this belong to commands that finished BEFORE the
/// block was typed.
///
/// `None` is a sentinel, not a special case: ids start at 1, so `None`
/// and `Some(0)` select identically and a fresh pane needs no separate
/// handling.
///
/// THE RESIDUAL IS IN THE SELECTION, NOT HERE. Settling takes the
/// EARLIEST qualifying id, which is this block's command only if
/// nothing else finished in the gap between arming and the keystrokes
/// reaching the shell. A command completing in that gap is taken
/// instead, on a pane with a full history exactly as on a fresh one -
/// `after` does not enter into it. The window is much smaller than the
/// eviction one it replaced, since a foreign command must now COMPLETE
/// in the gap rather than merely exist, and the outcome self-corrects
/// on the next run. Closing it properly means arming after the
/// keystrokes are known to have landed, which is a different change.
after: Option<u64>,
started: std::time::Instant,
timeout: Option<std::time::Duration>,
persist: bool,
}
/// Canonicalise `path` even when it no longer exists.
///
/// `std::fs::canonicalize` stats the final component, so it fails on a path
/// that has been deleted — and a deletion event carries exactly such a path.
/// Resolving the deepest ancestor that still exists and re-attaching the tail
/// gives the same answer for a live path and a usable one for a dead path,
/// which is what lets a removal clear the row it created (#345).
///
/// `None` when nothing on the way to the filesystem root resolves, and also
/// for a path with no file name to strip — a bare root, or one ending in
/// `..` — which cannot be climbed any further.
fn canonicalize_existing_ancestor(path: &Path) -> Option<PathBuf> {
let mut tail: Vec<std::ffi::OsString> = Vec::new();
let mut probe = path.to_path_buf();
loop {
if let Ok(canon) = std::fs::canonicalize(&probe) {
let mut out = canon;
for part in tail.iter().rev() {
out.push(part);
}
return Some(out);
}
// `file_name` is None for a root or `..`; either way there is
// nothing further to climb.
tail.push(probe.file_name()?.to_os_string());
probe = probe.parent()?.to_path_buf();
}
}
/// State of a background self-update observed by a remote-launched croft.
/// `Idle` is the steady state; `InProgress` paints an "Updating" hint in
/// the status bar; `Ready` arms the re-exec into the freshly-shipped binary.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum UpdateStatus {
Idle,
InProgress,
Ready,
}
/// What to do with one on-type formatting reply (#254). `NotOurs` leaves the
/// armed request alone — a superseded reply must not disarm the newer one
/// still in flight — while `Stale` and `Apply` both consume it.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum OnTypeReply {
NotOurs,
Stale,
Apply,
}
/// Rotating-arc frames for the in-progress update glyph. Cycled to read as a
/// spinning circular arrow, the universal "working" indicator.
const UPDATE_SPINNER_FRAMES: [&str; 6] = [
"\u{25DC}", "\u{25E0}", "\u{25DD}", "\u{25DE}", "\u{25E1}", "\u{25DF}",
];
/// Milliseconds each spinner frame is held; ~10 frames/second reads as smooth
/// motion while keeping the status-bar-only redraws light over SSH.
const UPDATE_SPINNER_FRAME_MS: u128 = 100;
/// Grace before the post-teardown js-debug orphan sweep runs, letting a
/// just-killed server's detached watchdog reparent to init so the sweep can
/// recognise it as an orphan. See [`crate::dap::reaper`].
const REAPER_TEARDOWN_GRACE_MS: u64 = 250;
/// Pick the spinner frame for a given elapsed time. Pure so the wrap-around
/// is unit-testable without a clock.
fn update_spinner_frame(elapsed_ms: u128) -> &'static str {
let n = UPDATE_SPINNER_FRAMES.len() as u128;
UPDATE_SPINNER_FRAMES[((elapsed_ms / UPDATE_SPINNER_FRAME_MS) % n) as usize]
}
#[derive(Clone, PartialEq, Eq, Debug)]
enum MenuAction {
Create(CreateKind),
/// Move every path in `paths` to the OS trash (recoverable). One entry
/// for a single right-click, more when a multi-selection is active.
Delete {
paths: Vec<PathBuf>,
},
/// Open the rename prompt pre-filled with the entry's current name.
Rename(PathBuf),
/// Cut the listed paths to the explorer clipboard for later Paste.
Cut(Vec<PathBuf>),
/// Copy the listed paths to the explorer clipboard for later Paste.
Copy(Vec<PathBuf>),
/// Paste the explorer clipboard's payload into `target_dir`.
Paste(PathBuf),
/// Stash this path as the "compare anchor" so the next file the user
/// right-clicks can be diffed against it.
SelectForCompare(PathBuf),
/// Open a side-by-side diff between the previously-selected anchor and
/// the file the user just right-clicked.
CompareWithSelected {
anchor: PathBuf,
other: PathBuf,
},
/// Re-root the workspace at the right-clicked folder. Folder-only -
/// files can't be roots. Used to dive into a nested git repo without
/// relaunching croft.
MakeRoot(PathBuf),
/// Add another folder to the workspace (multi-root, #147): opens the
/// fuzzy directory picker in add-folder mode.
AddWorkspaceFolder,
/// Drop a SECONDARY workspace root from the folder set (#147).
RemoveWorkspaceFolder(PathBuf),
/// Copy the absolute path of the right-clicked editor tab to the system
/// clipboard (VS Code's "Copy Path"). Available wherever the tab is backed
/// by a real on-disk path, local or remote.
CopyTabPath(PathBuf),
/// Copy the right-clicked editor tab's path relative to the workspace root
/// (VS Code's "Copy Relative Path"). Falls back to the absolute path when
/// the file lives outside the workspace root. Local or remote.
CopyTabRelativePath(PathBuf),
/// Reveal the right-clicked editor tab's file in the Explorer tree:
/// expand its parent folders, select its row, and focus the Explorer.
/// Mirrors VS Code's "Reveal in Explorer View". Works local and remote.
RevealInExplorer(PathBuf),
/// Reveal the path in macOS Finder via `open -R`. Local-macOS only:
/// on a remote SSH session croft runs on the headless host where no
/// Finder exists, so the menu omits this entry entirely rather than
/// offering a no-op.
RevealInFinder(PathBuf),
/// Open the file in an extension-contributed viewer (#465): the viewer's
/// id and the file.
OpenInViewer(String, PathBuf),
/// Close the editor tab at `idx`. Mirrors clicking the tab's `×`
/// glyph; surfaces in the tab-strip right-click menu so the four
/// close actions (Close / Others / Right / All) live in one place.
CloseTab(usize),
/// Close every editor tab whose index ≠ `keep_idx`.
CloseOtherTabs(usize),
/// Close every editor tab whose index > `from_idx`.
CloseTabsToRight(usize),
/// Close every editor tab and reset the pane to a blank state.
CloseAllTabs,
/// Close every saved (non-dirty) editor tab, keeping any with unsaved
/// changes. Mirrors VS Code's "Close Saved".
CloseSavedTabs,
/// Promote the preview tab at `idx` to a permanent tab so a later
/// single-click open won't replace it (VS Code's "Keep Open"). Only
/// surfaced for a tab that is currently the replaceable preview slot.
KeepTabOpen(usize),
/// Toggle the pinned state of the tab at `idx` (VS Code's "Pin" / "Unpin").
/// Pinned tabs stay leftmost and survive Close Others / Close to the Right.
ToggleTabPin(usize),
/// Split the editor side by side, the new (focused) duplicate to the RIGHT
/// (VS Code "Split Right"). The default split.
SplitEditor,
/// Split side by side, the new focused duplicate to the LEFT ("Split Left").
SplitEditorLeft,
/// Split stacked, the new focused duplicate ABOVE ("Split Up").
SplitEditorUp,
/// Split stacked, the new focused duplicate BELOW ("Split Down").
SplitEditorDown,
/// Move the active editor into the group above ("Move Above").
MoveEditorUp,
/// Move the active editor into the group below ("Move Below").
MoveEditorDown,
/// Move the active editor into the group to the left ("Move Left").
MoveEditorLeft,
/// Move the active editor into the group to the right ("Move Right").
MoveEditorRight,
/// Open a second view of the active file beside it ("Split in Group").
SplitInGroup,
/// Move keyboard focus to the left editor group (while split).
FocusGroupLeft,
/// Move keyboard focus to the right editor group (while split).
FocusGroupRight,
/// VS Code "Move into New Window": detach the tab at `idx` into a
/// full-screen, chrome-free editor window (Esc returns it). The tab leaves
/// its group, which collapses if it was the group's last tab.
MoveIntoNewWindow(usize),
/// VS Code "Copy into New Window" (⌘K O): open a duplicate view of the tab
/// at `idx` in a full-screen editor window, leaving the original in place.
CopyIntoNewWindow(usize),
/// Editor body: LSP "Rename Symbol" of the identifier at buffer `(row,
/// col)`. Captured at right-click so the later dispatch targets the same
/// symbol the user clicked.
RenameSymbolAt {
row: usize,
col: usize,
},
/// Editor body: "Change All Occurrences" of the word at buffer `(row,
/// col)` (multi-cursor select within the current file).
ChangeAllOccurrencesAt {
row: usize,
col: usize,
},
/// Editor body: LSP "Go to Definition" of the identifier at buffer
/// `(row, col)`.
GoToDefinitionAt {
row: usize,
col: usize,
},
/// Editor body: LSP "Go to Declaration" of the identifier at buffer
/// `(row, col)`. Distinct from definition for languages that separate the
/// two (C/C++ header prototype vs `.c` body, TypeScript `.d.ts` vs source).
GoToDeclarationAt {
row: usize,
col: usize,
},
/// Editor body: LSP "Go to Type Definition" of the identifier at buffer
/// `(row, col)`. Jumps to where the *type* of the expression under the
/// cursor is defined (e.g. the `User` struct for `let u = get_user()`),
/// as opposed to where the symbol itself is defined.
GoToTypeDefinitionAt {
row: usize,
col: usize,
},
/// Editor body: LSP "Go to Implementations" of the abstraction at buffer
/// `(row, col)`. Walks down from a trait / interface / abstract method to
/// the concrete implementors; the server often returns many, in which case
/// the results are offered as a picker built from `GoToLocation` items.
GoToImplementationAt {
row: usize,
col: usize,
},
/// Editor body: LSP "Go to References" of the symbol at buffer `(row, col)`.
/// Finds every use of the symbol project-wide (declaration included, like VS
/// Code); the server almost always returns many, which are offered as a
/// picker built from `GoToLocation` items.
GoToReferencesAt {
row: usize,
col: usize,
},
/// Return to the location before the last navigation jump (#31).
NavigateBack,
NavigateForward,
/// Editor body: LSP "Quick Fix" of the position at buffer `(row, col)`.
QuickFixAt {
row: usize,
col: usize,
},
/// Jump straight to an already-resolved location (LSP line/character). Used
/// for the entries of the multi-result "Go to Implementations" / "Go to
/// References" pickers, where each row is one location; selecting it records
/// nav history and opens the file at that position.
GoToLocation {
path: PathBuf,
line: u32,
col: u32,
},
/// Editor gutter: toggle a breakpoint on 1-based `line`. Built from a
/// glyph-margin right-click; the label reads "Add Breakpoint" or "Remove
/// Breakpoint" depending on whether one already sits on that line, but both
/// resolve to the same toggle. Mirrors VS Code's glyph-margin menu.
ToggleBreakpointAt {
line: usize,
},
/// Editor gutter: open the breakpoint-condition editor for 1-based `line`,
/// creating the breakpoint if absent. VS Code's "Add Conditional
/// Breakpoint" / "Edit Condition".
EditBreakpointConditionAt {
line: usize,
},
/// Editor gutter: open the logpoint editor for 1-based `line`, creating
/// the breakpoint if absent. VS Code's "Add Logpoint" / "Edit Logpoint".
EditLogpointAt {
line: usize,
},
/// Editor gutter: ask the resident navigator about 0-based `line`
/// (opens the ask box scoped to that line).
AskNavigatorAt {
line: usize,
},
/// Editor body: ask the navigator about the selected 0-based inclusive
/// line span (the selection's text rides the turn).
AskNavigatorSelection {
start: usize,
end: usize,
},
/// CAPTURES row: ask the navigator about the selected captured line,
/// with the pane rows around it (#372).
AskNavigatorAboutCapture,
/// PROBLEMS row: have the navigator fix this diagnostic as a streamed,
/// cancellable edit (#374).
FixProblemWithNavigator {
path: PathBuf,
item: crate::widgets::problems::ProblemItem,
},
/// Editor body: one level of the call hierarchy for the symbol at buffer
/// `(row, col)` — callers when `incoming`, callees otherwise.
ShowCallsAt {
row: usize,
col: usize,
incoming: bool,
},
/// Settings gear → "Color Theme": replace the gear menu with the theme
/// picker (the list of themes with a check on the active one).
OpenThemePicker,
/// Theme picker entry: switch the IDE color theme to `theme`, persist it,
/// re-emit the session background, and re-bake the icon images.
SetTheme(crate::theme::Theme),
/// Explorer "Views and More Actions" (⋯) entry: flip the visibility of one
/// stacked sub-view (Open Editors / Folders / Outline / Timeline / Rust
/// Dependencies) and persist the choice.
ToggleExplorerView(ExplorerView),
/// Customize Layout: re-open the Customize Layout popup (so a toggle the
/// user just flipped stays visible for the next one, like VS Code).
OpenCustomizeLayout,
/// Customize Layout: show/hide the left activity bar.
ToggleActivityBar,
/// Customize Layout: show/hide the primary side bar (same as ⌘B).
ToggleSideBar,
ToggleAutoHideSideBar,
/// Customize Layout: show/hide the secondary side bar (the Outline).
ToggleSecondarySideBar,
/// Customize Layout: show/hide the bottom panel (the terminal, same as ⌃J).
TogglePanel,
/// Customize Layout: show/hide the bottom status bar.
ToggleStatusBar,
/// Customize Layout: dock the primary side bar to `position`.
SetSideBarPosition(SideBarPosition),
/// Customize Layout: set the bottom panel's horizontal alignment.
SetPanelAlignment(PanelAlignment),
/// Customize Layout: anchor the quick input at `position`.
SetQuickInputPosition(QuickInputPosition),
/// Customize Layout: toggle Zen Mode (hide all chrome / restore).
ToggleZenMode,
/// Terminal pane right-click: rename the pane at `idx`.
RenameTerminal(usize),
/// Terminal pane right-click: clear the pane at `idx`'s screen + scrollback.
ClearTerminal(usize),
/// Terminal pane right-click: maximize the pane at `idx` across the
/// panel (or restore the even split when already maximized).
ToggleMaximizeTerminal(usize),
/// Terminal pane right-click: collapse the pane at `idx` to a strip, or
/// expand it again (#313).
ToggleCollapseTerminal(usize),
/// Terminal pane right-click: copy the pane's selection to the clipboard.
/// Offered only while the pane HAS one, so the entry never copies nothing.
TerminalCopySelection,
/// Terminal pane right-click: paste the host clipboard into the pane.
TerminalPaste,
/// Terminal pane right-click: enter quick-select hint mode on the pane.
TerminalQuickSelect,
/// Terminal pane right-click: enter copy mode (keyboard selection with
/// vi motions) on the pane.
TerminalCopyMode,
/// Terminal pane right-click: open the durable command-history search.
TerminalCommandHistory,
/// Terminal pane right-click: dump the pane's scrollback into a scratch
/// editor tab.
OpenScrollbackInEditor,
/// Terminal pane right-click: toggle broadcast input (keystrokes go to
/// every pane at once; enabling routes through the confirm popup).
ToggleBroadcastInput,
/// Terminal pane right-click while broadcasting: toggle whether the
/// active pane receives the mirrored input.
ToggleBroadcastExclusion,
/// Terminal pane right-click: restore the most recently closed pane
/// while it is still inside the undo-close grace window.
UndoCloseTerminal,
/// Command decoration menu: copy the command's output span to the
/// clipboard (pane `idx`, the clicked decoration embedded).
CopyCommandOutput(usize, crate::widgets::terminal::CommandDecoration),
/// Command decoration menu: select the command's output span in the pane.
SelectCommandOutput(usize, crate::widgets::terminal::CommandDecoration),
/// Command decoration menu: type the command at the shell again.
RerunCommand(usize, crate::widgets::terminal::CommandDecoration),
/// Terminal profile dropdown (`⌄`): open a new pane running this shell path.
NewTerminalWithProfile(String),
/// Minimap right-click menu: show/hide the editor minimap.
ToggleMinimap,
/// Minimap right-click menu: move the strip to the given editor edge.
SetMinimapSide(MinimapSide),
/// Status-bar language picker: set the active buffer's language mode.
SetLanguage(Option<crate::highlight::LangKind>),
/// Status-bar EOL picker: switch the buffer's line-ending style.
SetLineEnding(crate::widgets::editor::LineEnding),
/// Status-bar encoding picker: reopen the file decoded with this encoding.
SetEncoding(&'static encoding_rs::Encoding),
/// Status-bar indentation picker: pin spaces-vs-tabs and width for newly
/// typed indentation.
SetIndentStyle(crate::widgets::editor::IndentStyle),
/// Status-bar indentation picker: rewrite existing leading indentation.
/// `true` converts tabs to spaces, `false` converts spaces to tabs.
ConvertIndentation(bool),
}
/// Return the macOS-style keyboard shortcut hint to display on the right
/// side of a context-menu row, when one exists. Mirrors the bindings in
/// `handle_tree_key` / `handle_explorer_shortcut` so the menu is a
/// discovery surface for the same accelerators the keyboard accepts.
fn shortcut_for(action: &MenuAction) -> Option<&'static str> {
match action {
MenuAction::Create(CreateKind::File) => Some("⌘F"),
MenuAction::Create(CreateKind::Folder) => Some("⌘⇧N"),
MenuAction::Cut(_) => Some("⌘X"),
MenuAction::Copy(_) => Some("⌘C"),
MenuAction::Paste(_) => Some("⌘V"),
MenuAction::Rename(_) => Some("⌘R"),
MenuAction::MakeRoot(_) => Some("⌘/"),
MenuAction::AddWorkspaceFolder => None,
MenuAction::RemoveWorkspaceFolder(_) => None,
MenuAction::RevealInFinder(_) => Some("⌥⌘R"),
MenuAction::CopyTabPath(_) => Some("⌥⌘C"),
MenuAction::CopyTabRelativePath(_) => Some("⌥⇧⌘C"),
MenuAction::RevealInExplorer(_) => Some("⌘K E"),
MenuAction::Delete { .. } => Some("⌫"),
MenuAction::CloseTab(_) => Some("⌘W"),
MenuAction::CloseOtherTabs(_) => Some("⌥⌘T"),
MenuAction::CloseAllTabs => Some("⌘K W"),
MenuAction::CloseSavedTabs => Some("⌘K U"),
MenuAction::KeepTabOpen(_) => Some("⌘K ⇧P"),
MenuAction::ToggleTabPin(_) => Some("⌘K P"),
MenuAction::SplitEditor => Some("⌘\\"),
MenuAction::SplitEditorUp => Some("⌘K ⌘\\"),
MenuAction::SplitInGroup => Some("⌘K ⇧⌘\\"),
MenuAction::FocusGroupLeft => Some("⌥⌘←"),
MenuAction::FocusGroupRight => Some("⌥⌘→"),
MenuAction::CopyIntoNewWindow(_) => Some("⌘K O"),
MenuAction::MoveIntoNewWindow(_) => Some("⌘K ⇧O"),
MenuAction::RenameSymbolAt { .. } => Some("F2"),
MenuAction::ChangeAllOccurrencesAt { .. } => Some("⌘F2"),
MenuAction::GoToDefinitionAt { .. } => Some("F12"),
MenuAction::GoToReferencesAt { .. } => Some("⇧F12"),
MenuAction::NavigateBack => Some("⌃-"),
MenuAction::NavigateForward => Some("⌃⇧-"),
MenuAction::QuickFixAt { .. } => Some("⌘."),
MenuAction::GoToDeclarationAt { .. } => Some("⌃⇧F12"),
MenuAction::GoToTypeDefinitionAt { .. } => Some("⌃F12"),
MenuAction::GoToImplementationAt { .. } => Some("⌘F12"),
MenuAction::ToggleBreakpointAt { .. } => Some("F9"),
MenuAction::EditBreakpointConditionAt { .. } => Some("⇧F9"),
MenuAction::EditLogpointAt { .. } => Some("⇧⌥F9"),
MenuAction::AskNavigatorAt { .. } => Some("⌘K Q"),
MenuAction::AskNavigatorSelection { .. } => Some("⌘K Q"),
MenuAction::AskNavigatorAboutCapture => Some("n"),
MenuAction::FixProblemWithNavigator { .. } => None,
MenuAction::ShowCallsAt { incoming: true, .. } => Some("⌘K H"),
MenuAction::ShowCallsAt {
incoming: false, ..
} => Some("⌘K ⇧H"),
MenuAction::OpenThemePicker => Some("⌘K ⌘T"),
MenuAction::ToggleSideBar => Some("⌘B"),
MenuAction::ToggleSecondarySideBar => Some("⌥⌘B"),
MenuAction::TogglePanel => Some("⌃J"),
MenuAction::ToggleMinimap => Some("⌥⌘M"),
MenuAction::ToggleZenMode => Some("⌘K Z"),
MenuAction::CloseTabsToRight(_) => Some("⌘K →"),
MenuAction::SelectForCompare(_) => Some("⌘K S"),
MenuAction::CompareWithSelected { .. } => Some("⌘K C"),
MenuAction::RenameTerminal(_) => Some("⌘K R"),
MenuAction::ClearTerminal(_) => Some("⌘K K"),
MenuAction::ToggleMaximizeTerminal(_) => Some("⌘K M"),
// No hint. The label alternates "Collapse Terminal" / "Expand
// Terminal", but `Cmd+K [` only ever COLLAPSES: it acts on
// `active_terminal`, which the focus invariant guarantees is never a
// folded pane, so the expand branch is unreachable from the chord. Its
// sibling `ToggleMaximizeTerminal` can carry `⌘K M` honestly because
// that chord really does toggle both ways. Advertising a shortcut
// beside a label it cannot perform is worse than showing none.
MenuAction::ToggleCollapseTerminal(_) => None,
MenuAction::TerminalCopySelection => Some("⌘C"),
MenuAction::TerminalPaste => Some("⌘V"),
MenuAction::TerminalQuickSelect => Some("⌃⇧Space"),
MenuAction::TerminalCopyMode => Some("⌃⇧Y"),
MenuAction::TerminalCommandHistory => Some("⌃⇧H"),
MenuAction::OpenScrollbackInEditor => Some("⌘K D"),
MenuAction::ToggleBroadcastInput => Some("⌘K I"),
MenuAction::ToggleBroadcastExclusion => Some("⌘K ⇧I"),
MenuAction::UndoCloseTerminal => Some("⌘K ⇧T"),
MenuAction::CopyCommandOutput(..) => Some("⌘K ⇧C"),
MenuAction::SelectCommandOutput(..) => Some("⌘K ⇧S"),
MenuAction::RerunCommand(..) => Some("⌘K ⇧R"),
_ => None,
}
}
/// Display width (in cells) a menu entry needs: its label plus the right-aligned
/// shortcut hint (items) or the `▸` submenu indicator. Dividers need none.
fn menu_entry_width(entry: &MenuEntry) -> usize {
match entry {
MenuEntry::Item { label, action } => {
let shortcut = shortcut_for(action)
.map(|s| s.chars().count() + 2)
.unwrap_or(0);
label.chars().count() + shortcut
}
MenuEntry::Submenu { label, .. } => label.chars().count() + 2,
MenuEntry::Header(label) => label.chars().count(),
MenuEntry::Separator => 0,
}
}
/// The end-of-session feedback line. When breakpoints were set but the program
/// exited without ever stopping, say so explicitly — that is the common "I set a
/// breakpoint and nothing happened" confusion (e.g. running a library module
/// whose breakpointed code is never called). Otherwise a plain end message.
/// What a parked launch does once its task exits 0.
///
/// Two shapes, because a compound's task and a config's task are different
/// steps (#318). A config's own task is the LAST thing before the adapter
/// starts, so the config is already resolved. A compound's task runs BEFORE
/// its member is considered at all, and the member may carry a task of its
/// own - VS Code runs both - so that continuation re-enters the normal launch
/// path rather than skipping to the adapter.
enum PendingLaunchStep {
/// The config's own task just finished: start it. Boxed like the other
/// variant so neither dominates the enum's size - a resolved config is
/// several hundred bytes, and this type is held in an `Option` on `App`.
Resolved(Box<crate::dap::configs::ResolvedConfig>),
/// A compound's task just finished: launch its member from the top, which
/// parks again if the member has a `preLaunchTask` too.
Member(Box<crate::dap::configs::DebugConfig>),
}
/// A launch.json config launch parked behind its `preLaunchTask` (#250): the
/// task runs in a terminal pane, and the FinishedCommand sweep decides.
struct PendingDebugLaunch {
/// Uid of the pane the task command was written to.
pane: u64,
/// The task's command line, matched against the pane's next finished
/// command (OSC 133 reports what actually ran).
command: String,
/// What to do once the task exits 0.
step: PendingLaunchStep,
/// When the task was written, for the no-command-mark fallback below.
started: std::time::Instant,
}
/// Whether a finished pane command settles the pending preLaunchTask: same
/// pane, and the captured command line is the task's (the shell may report
/// it with surrounding whitespace). Pure, for tests.
fn finished_settles_pending(pane: u64, cmd: &str, pending_pane: u64, pending_cmd: &str) -> bool {
pane == pending_pane && cmd.trim() == pending_cmd.trim()
}
/// How long a parked launch waits before concluding the pane will never
/// report a command mark. Only consulted while the pane's foreground is back
/// to a plain shell — a long build keeps a non-shell foreground and waits
/// indefinitely, exactly like the FinishedCommand path.
const PRELAUNCH_MARK_GRACE: std::time::Duration = std::time::Duration::from_secs(15);
/// An lldb launch's `program`, resolved against the session's cwd (VS Code's
/// contract for relative programs, and NOT croft's own working directory) and
/// checked for existence, so the validation and the adapter can never read a
/// relative path differently. Returns the absolute path to hand the adapter.
fn resolve_lldb_program(program: &str, cwd: &Path) -> Result<PathBuf, String> {
let resolved = crate::dap::configs::absolute_in(program, cwd);
if resolved.exists() {
Ok(resolved)
} else {
Err(format!(
"program {} does not exist — does the preLaunchTask build it?",
resolved.display()
))
}
}
/// The FinishedCommand match is the settling signal for a parked launch, but
/// it depends on OSC 133 shell-integration marks. This is the fallback for
/// panes that will never produce one: the pane vanished, or its foreground
/// returned to a plain shell (the task is over) and the grace period passed
/// without a mark. Returns the abort reason, or `None` to keep waiting. Pure.
fn pending_abort_reason(
pane_exists: bool,
foreground_is_shell: bool,
waited: std::time::Duration,
) -> Option<&'static str> {
if !pane_exists {
return Some("its terminal pane closed");
}
if foreground_is_shell && waited > PRELAUNCH_MARK_GRACE {
return Some("the task produced no command mark (shell integration missing in that pane?)");
}
None
}
fn debug_end_message(had_breakpoints: bool, ever_stopped: bool) -> &'static str {
if had_breakpoints && !ever_stopped {
"Program exited without hitting a breakpoint"
} else {
"Debug session ended"
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum ExplorerClipMode {
Copy,
Cut,
}
#[derive(Clone, Debug)]
struct ExplorerClipboard {
mode: ExplorerClipMode,
paths: Vec<PathBuf>,
}
/// Accumulated type-to-jump state for the Explorer. `prefix` lowercase
/// only; `last` is the instant of the most recent keystroke.
#[derive(Clone, Debug)]
struct TreeTypeahead {
prefix: String,
last: std::time::Instant,
}
/// Inter-keystroke gap that keeps the typeahead buffer alive. Anything
/// longer than this resets the prefix to a single character and cycles
/// past the current selection so repeating the same letter walks
/// through matches.
const TREE_TYPEAHEAD_WINDOW: std::time::Duration = std::time::Duration::from_millis(750);
/// State for an in-progress drag inside the explorer pane. The drag is only
/// "armed" once the pointer has actually moved off the original cell, so a
/// stationary mouse-down → mouse-up still behaves like a click.
#[derive(Clone, Debug)]
struct ExplorerDrag {
/// Paths the drag is moving (or copying, when Alt is held).
paths: Vec<PathBuf>,
/// Tree row of the drop target under the pointer. `None` means the
/// pointer is over empty space or outside the tree.
target_idx: Option<usize>,
/// True once we've seen a Drag event with a different cell from the
/// initial Down. Until then we treat the gesture as a still-pending click.
armed: bool,
/// (instant, x, y) of the initiating mouse-down.
started_at: (std::time::Instant, u16, u16),
/// Index of the row the user pressed on. Used as the toggle target if
/// the gesture turns out to be a stationary Alt-click rather than a drag.
start_idx: usize,
/// True when the initiating mouse-down was an Alt/Ctrl click. A
/// non-armed release toggles the start row's mark; an armed release
/// performs a copy-drop instead of the default move-drop.
toggle_on_release: bool,
}
/// Build the right-click context-menu items for an editor tab strip
/// click on tab `idx`. `tab_count` is the total number of open tabs;
/// used to gate "Close Others" / "Close to the Right" so they don't
/// surface when they would be no-ops.
fn build_tab_context_menu_items(
idx: usize,
tab_count: usize,
is_split: bool,
clicked: Option<&Path>,
reveal_enabled: bool,
clicked_is_preview: bool,
clicked_is_pinned: bool,
) -> Vec<MenuEntry> {
let mut items: Vec<MenuEntry> = Vec::new();
items.push(MenuEntry::item("Close", MenuAction::CloseTab(idx)));
if tab_count > 1 {
items.push(MenuEntry::item(
"Close Others",
MenuAction::CloseOtherTabs(idx),
));
}
if idx + 1 < tab_count {
items.push(MenuEntry::item(
"Close to the Right",
MenuAction::CloseTabsToRight(idx),
));
}
if tab_count > 1 {
items.push(MenuEntry::item("Close Saved", MenuAction::CloseSavedTabs));
}
items.push(MenuEntry::item("Close All", MenuAction::CloseAllTabs));
// Copy Path: any tab backed by a real on-disk path, local or remote (it's
// a clipboard write, not a host bridge). Sits between the close group and
// Reveal in Finder, mirroring VS Code's tab-menu order.
if let Some(path) = clicked {
items.push(MenuEntry::item(
"Copy Path",
MenuAction::CopyTabPath(path.to_path_buf()),
));
items.push(MenuEntry::item(
"Copy Relative Path",
MenuAction::CopyTabRelativePath(path.to_path_buf()),
));
}
// Reveal in Finder: local-macOS only, and only when the tab is backed by a
// real on-disk path (a blank/untitled buffer has nothing to reveal). On a
// remote SSH session the entry is withheld, matching the explorer menu.
if let Some(path) = clicked.filter(|_| reveal_enabled) {
items.push(MenuEntry::item(
"Reveal in Finder",
MenuAction::RevealInFinder(path.to_path_buf()),
));
}
// Reveal in Explorer View: select the file in croft's own tree. The tree
// exists local and remote, so this is gated only on a real path.
if let Some(path) = clicked {
items.push(MenuEntry::item(
"Reveal in Explorer View",
MenuAction::RevealInExplorer(path.to_path_buf()),
));
}
// Keep Open: only meaningful for the replaceable preview tab (italic).
// Promotes it so a subsequent single-click open won't replace it. VS Code
// omits the entry on an already-permanent tab, so we do too.
if clicked_is_preview {
items.push(MenuEntry::item("Keep Open", MenuAction::KeepTabOpen(idx)));
}
// Pin / Unpin: always offered. A pinned tab reads "Unpin"; pinning keeps it
// leftmost and shields it from Close Others / Close to the Right.
items.push(MenuEntry::item(
if clicked_is_pinned { "Unpin" } else { "Pin" },
MenuAction::ToggleTabPin(idx),
));
// A top-level "Split Right" (the common case), then a "Split & Move"
// submenu holding every directional split, the four directional moves, and
// Split in Group — mirroring VS Code's tab menu.
items.push(MenuEntry::item("Split Right", MenuAction::SplitEditor));
items.push(MenuEntry::Submenu {
label: String::from("Split & Move"),
items: vec![
MenuEntry::item("Split Up", MenuAction::SplitEditorUp),
MenuEntry::item("Split Down", MenuAction::SplitEditorDown),
MenuEntry::item("Split Left", MenuAction::SplitEditorLeft),
MenuEntry::item("Split Right", MenuAction::SplitEditor),
MenuEntry::Separator,
// VS Code's vertical labels: Above = Up, Below = Down.
MenuEntry::item("Move Above", MenuAction::MoveEditorUp),
MenuEntry::item("Move Below", MenuAction::MoveEditorDown),
MenuEntry::item("Move Left", MenuAction::MoveEditorLeft),
MenuEntry::item("Move Right", MenuAction::MoveEditorRight),
MenuEntry::Separator,
MenuEntry::item("Split in Group", MenuAction::SplitInGroup),
],
});
// VS Code's "Move into New Window" / "Copy into New Window". croft has no
// OS windows, so a "window" is a full-screen, chrome-free editor surface
// (Esc returns). Move works on any buffer (it carries the editor itself);
// Copy reopens the file, so it needs a real on-disk path.
items.push(MenuEntry::item(
"Move into New Window",
MenuAction::MoveIntoNewWindow(idx),
));
if clicked.is_some() {
items.push(MenuEntry::item(
"Copy into New Window",
MenuAction::CopyIntoNewWindow(idx),
));
}
// Focus-group navigation appears once a second group exists.
if is_split {
items.push(MenuEntry::item(
"Focus Left Group",
MenuAction::FocusGroupLeft,
));
items.push(MenuEntry::item(
"Focus Right Group",
MenuAction::FocusGroupRight,
));
}
items
}
/// Build the right-click context-menu items for the explorer.
///
/// * Right-click on an entry (file or non-root folder) → entry-scoped
/// actions: Cut, Copy, Paste, Rename, Delete. Multi-select promotes
/// Delete to a count and keeps Rename on a single entry only.
/// * Right-click on empty tree space, or on the workspace root row →
/// workspace-scoped actions: New File, New Folder, Paste.
///
/// Test-side entry with no viewer lookup, so a viewer installed on the host
/// can never reach the built-in rows these tests assert; the app itself goes
/// through [`build_tree_context_menu_items_in_dir`] with the dir it carries.
#[cfg(test)]
fn build_tree_context_menu_items(
node: Option<&crate::widgets::file_tree::Node>,
root: &Path,
selection: &[PathBuf],
target_dir: &Path,
clipboard: Option<&ExplorerClipboard>,
compare_anchor: Option<&Path>,
) -> Vec<(String, MenuAction)> {
// No viewer lookup at all: these tests assert the built-in rows, so the
// lookup must find nothing whatever the host has installed.
build_tree_context_menu_items_with(
node,
root,
selection,
target_dir,
clipboard,
compare_anchor,
|_| None,
)
}
/// [`build_tree_context_menu_items`] reading the viewers under an explicit
/// config dir: the app passes the dir it carries, so the row it builds and
/// the click that resolves the row read the same extensions.
fn build_tree_context_menu_items_in_dir(
config_dir: &Path,
node: Option<&crate::widgets::file_tree::Node>,
root: &Path,
selection: &[PathBuf],
target_dir: &Path,
clipboard: Option<&ExplorerClipboard>,
compare_anchor: Option<&Path>,
) -> Vec<(String, MenuAction)> {
build_tree_context_menu_items_with(
node,
root,
selection,
target_dir,
clipboard,
compare_anchor,
|file| {
crate::mcp::registry::viewer_for_path_in_dir(config_dir, file)
.map(|v| (v.label.clone(), v.key()))
},
)
}
/// [`build_tree_context_menu_items`] with the viewer lookup injected (#465):
/// `viewer_for` answers "which installed viewer handles this file", as
/// `(label, id)`, so a test can offer one without an extensions dir.
fn build_tree_context_menu_items_with(
node: Option<&crate::widgets::file_tree::Node>,
root: &Path,
selection: &[PathBuf],
target_dir: &Path,
clipboard: Option<&ExplorerClipboard>,
compare_anchor: Option<&Path>,
viewer_for: impl Fn(&Path) -> Option<(String, String)>,
) -> Vec<(String, MenuAction)> {
let entry_target = crate::widgets::file_tree::delete_target_for(node, root);
let mut items: Vec<(String, MenuAction)> = Vec::new();
if let Some(p) = entry_target {
// Right-click on any node (file or folder, nested or not):
// surface New File… / New Folder… at the top so the user can
// create a new entry next to / inside whatever they clicked,
// without having to scroll up to the workspace root first.
// `target_dir` is already routed by `create_target_dir_for`:
// a folder click resolves to the folder itself, a file click
// to the file's parent — same convention VS Code uses.
items.push((
String::from("New File"),
MenuAction::Create(CreateKind::File),
));
items.push((
String::from("New Folder"),
MenuAction::Create(CreateKind::Folder),
));
let paths_for_action: Vec<PathBuf> = if selection.iter().any(|sp| sp == &p) {
selection.to_vec()
} else {
vec![p.clone()]
};
items.push((
String::from("Cut"),
MenuAction::Cut(paths_for_action.clone()),
));
items.push((
String::from("Copy"),
MenuAction::Copy(paths_for_action.clone()),
));
if clipboard.is_some() {
items.push((
String::from("Paste"),
MenuAction::Paste(target_dir.to_path_buf()),
));
}
if paths_for_action.len() == 1 {
items.push((String::from("Rename"), MenuAction::Rename(p.clone())));
}
// Compare actions only make sense for a single regular file.
let single_file_target = paths_for_action
.first()
.filter(|_| paths_for_action.len() == 1)
.filter(|pp| pp.is_file());
if let Some(file) = single_file_target {
// An installed viewer for this file kind (#465): `Open in csvlens`
// on a .csv, once the csvlens extension has been added.
if let Some((label, id)) = viewer_for(file) {
items.push((label, MenuAction::OpenInViewer(id, file.clone())));
}
match compare_anchor {
Some(anchor) if anchor != file.as_path() => {
items.push((
format!(
"Compare with Selected ({})",
anchor
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| anchor.display().to_string()),
),
MenuAction::CompareWithSelected {
anchor: anchor.to_path_buf(),
other: file.clone(),
},
));
}
_ => {}
}
items.push((
String::from("Select for Compare"),
MenuAction::SelectForCompare(file.clone()),
));
}
// Two regular files selected: offer a direct diff between them,
// skipping the two-step Select-for-Compare anchor dance. Folders
// can't be diffed, so any folder in the selection suppresses it.
if paths_for_action.len() == 2 && paths_for_action.iter().all(|p| p.is_file()) {
items.push((
String::from("Compare Selected"),
MenuAction::CompareWithSelected {
anchor: paths_for_action[0].clone(),
other: paths_for_action[1].clone(),
},
));
}
// "Make root" appears only for non-root folders. Re-roots the
// workspace at the clicked folder so the user can dive into a
// nested git repo without relaunching croft.
let single_folder_target: Option<&PathBuf> = paths_for_action
.first()
.filter(|_| paths_for_action.len() == 1)
.filter(|_| node.map(|n| n.is_dir).unwrap_or(false))
.filter(|pp| pp.as_path() != root);
if let Some(folder) = single_folder_target {
items.push((
String::from("Make root"),
MenuAction::MakeRoot(folder.clone()),
));
}
let label = if paths_for_action.len() > 1 {
format!("Delete {} items", paths_for_action.len())
} else {
String::from("Delete")
};
items.push((
label,
MenuAction::Delete {
paths: paths_for_action,
},
));
} else {
items.push((
String::from("New File"),
MenuAction::Create(CreateKind::File),
));
items.push((
String::from("New Folder"),
MenuAction::Create(CreateKind::Folder),
));
// Root section rows (multi-root, #147): grow the folder set from
// any root row; drop a SECONDARY root from its own row. The
// primary is the launch identity — Make Root changes it, never a
// removal.
if let Some(n) = node.filter(|n| n.depth == 0) {
items.push((
String::from("Add Folder to Workspace"),
MenuAction::AddWorkspaceFolder,
));
if n.path != root {
items.push((
String::from("Remove Folder from Workspace"),
MenuAction::RemoveWorkspaceFolder(n.path.clone()),
));
}
}
if clipboard.is_some() {
items.push((
String::from("Paste"),
MenuAction::Paste(target_dir.to_path_buf()),
));
}
}
items
}
/// Insert "Reveal in Finder" into a freshly-built tree context menu, but only
/// when the action can actually do something: `enabled` is true (a local macOS
/// session) and a concrete entry was clicked (`clicked`). On a remote SSH
/// session croft runs on the headless host where there is no Finder, so the
/// item is omitted entirely rather than shown as a dead no-op, keeping the
/// local and remote menus honest. The entry lands directly beneath the New
/// File / New Folder block to mirror VS Code's top "reveal" placement.
fn maybe_add_reveal_in_finder(
items: &mut Vec<(String, MenuAction)>,
clicked: Option<&Path>,
enabled: bool,
) {
let Some(path) = clicked.filter(|_| enabled) else {
return;
};
// Insert directly after the leading New File / New Folder block: find the
// first non-Create entry and slot in ahead of it. Deriving the position
// this way (rather than a literal index) keeps the placement correct even
// if the Create block grows or the empty-area menu shape changes.
let pos = items
.iter()
.position(|(_, a)| !matches!(a, MenuAction::Create(_)))
.unwrap_or(items.len());
items.insert(
pos,
(
String::from("Reveal in Finder"),
MenuAction::RevealInFinder(path.to_path_buf()),
),
);
}
/// One row of a context menu: a clickable action, a parent that opens a nested
/// submenu, or a divider. Most menus are a flat list of `Item`s; the editor tab
/// menu uses a `Submenu` ("Split & Move") whose children include `Separator`s.
#[derive(Clone, Debug)]
enum MenuEntry {
Item {
label: String,
action: MenuAction,
},
Submenu {
label: String,
items: Vec<MenuEntry>,
},
Separator,
/// A dimmed, non-selectable section label (e.g. "Side Bar Position" in the
/// Customize Layout popup). The cursor skips it like a `Separator`.
Header(String),
}
impl MenuEntry {
fn item(label: impl Into<String>, action: MenuAction) -> Self {
Self::Item {
label: label.into(),
action,
}
}
fn header(label: impl Into<String>) -> Self {
Self::Header(label.into())
}
/// The action a click on this entry dispatches, if it is a plain item.
fn action(&self) -> Option<&MenuAction> {
match self {
Self::Item { action, .. } => Some(action),
_ => None,
}
}
/// True for a row the cursor may land on (items and submenu parents, not
/// dividers or section headers).
fn is_selectable(&self) -> bool {
!matches!(self, Self::Separator | Self::Header(_))
}
}
impl From<(String, MenuAction)> for MenuEntry {
fn from((label, action): (String, MenuAction)) -> Self {
Self::Item { label, action }
}
}
struct ContextMenu {
/// Top-left of the menu in absolute terminal coordinates.
origin: (u16, u16),
/// Items, in display order.
items: Vec<MenuEntry>,
/// Highlighted top-level row.
selected: usize,
/// Index into `items` of the currently open submenu (a `Submenu` entry), or
/// `None` when no submenu is open.
open_submenu: Option<usize>,
/// Highlighted row WITHIN the open submenu (only meaningful when
/// `open_submenu` is `Some`).
submenu_selected: usize,
/// Where any New File / New Folder should be created.
target_dir: PathBuf,
}
impl ContextMenu {
/// A flat menu from `(label, action)` tuples (the common case).
fn flat(origin: (u16, u16), items: Vec<(String, MenuAction)>, target_dir: PathBuf) -> Self {
Self {
origin,
items: items.into_iter().map(MenuEntry::from).collect(),
selected: 0,
open_submenu: None,
submenu_selected: 0,
target_dir,
}
}
/// The entries at the active level: the open submenu's children, or the
/// top-level items.
fn level_entries(&self) -> &[MenuEntry] {
match self.open_submenu {
Some(i) => match &self.items[i] {
MenuEntry::Submenu { items, .. } => items,
_ => &self.items,
},
None => &self.items,
}
}
fn level_selected(&self) -> usize {
if self.open_submenu.is_some() {
self.submenu_selected
} else {
self.selected
}
}
fn set_level_selected(&mut self, idx: usize) {
if self.open_submenu.is_some() {
self.submenu_selected = idx;
} else {
self.selected = idx;
}
}
/// Move the cursor up/down within the active level, skipping dividers and
/// stopping at the ends.
fn move_cursor(&mut self, down: bool) {
let entries = self.level_entries();
let n = entries.len();
let mut i = self.level_selected();
loop {
i = if down {
if i + 1 >= n {
return;
}
i + 1
} else {
if i == 0 {
return;
}
i - 1
};
if entries[i].is_selectable() {
self.set_level_selected(i);
return;
}
}
}
/// The entry currently under the cursor at the active level.
fn cursor_entry(&self) -> Option<&MenuEntry> {
self.level_entries().get(self.level_selected())
}
/// The action a cursor-on-item Enter/click dispatches (None on a submenu
/// parent or divider).
fn cursor_action(&self) -> Option<MenuAction> {
match self.cursor_entry() {
Some(MenuEntry::Item { action, .. }) => Some(action.clone()),
_ => None,
}
}
/// If the top-level cursor is on a submenu parent (and none is open yet),
/// open it, selecting its first selectable child. Returns true when opened.
fn open_cursor_submenu(&mut self) -> bool {
if self.open_submenu.is_some() {
return false;
}
if let Some(MenuEntry::Submenu { items, .. }) = self.items.get(self.selected) {
self.submenu_selected = items.iter().position(MenuEntry::is_selectable).unwrap_or(0);
self.open_submenu = Some(self.selected);
return true;
}
false
}
/// Close any open submenu, returning to the top level. Returns true when a
/// submenu was actually open.
fn close_submenu(&mut self) -> bool {
if self.open_submenu.take().is_some() {
self.submenu_selected = 0;
return true;
}
false
}
}
#[derive(Clone, PartialEq, Eq, Debug)]
enum PromptKind {
Create(CreateKind),
/// Rename the entry at `path`. The prompt's `target_dir` holds the
/// entry's parent; `buffer` is pre-filled with the current basename.
Rename(PathBuf),
/// LSP "Rename Symbol" (F2 in the editor): rename the identifier at
/// `(row, col)` in `path`. `buffer` is pre-filled with the symbol; on
/// commit the new name drives a `textDocument/rename` request.
RenameSymbol {
path: PathBuf,
row: usize,
col: usize,
},
/// Debugger "Add Conditional Breakpoint" / "Edit Condition": edit the
/// boolean condition for the breakpoint on 1-based `line` of `path`. The
/// buffer is pre-filled with any existing condition; on commit the
/// breakpoint is created (if absent) and the condition attached/cleared,
/// then pushed to a live session. A popup, never the status line.
BreakpointCondition {
path: PathBuf,
line: usize,
},
/// Debugger "Add Logpoint" / "Edit Logpoint": edit the log message for
/// the breakpoint on 1-based `line` of `path` (`{expr}` holes are
/// interpolated by the adapter, which prints instead of pausing). Same
/// commit shape as [`PromptKind::BreakpointCondition`].
Logpoint {
path: PathBuf,
line: usize,
},
/// Rename the terminal pane at `idx`. The buffer is pre-filled with its
/// current label; on commit the name overrides the auto label.
RenameTerminal(usize),
/// Annotate a span of terminal output on pane `pane` (Cmd+K N with a
/// selection). `existing` edits that annotation in place; otherwise
/// `line`/`start`/`len` pin a new one. A blank commit cancels (or, for
/// an existing note, deletes it).
AnnotateTerminal {
pane: usize,
line: i32,
/// Scroll-clock reading `line` was captured against when the prompt
/// OPENED. The commit anchors with this pair: sampling a fresh
/// baseline at commit would mis-pin the note by every row that
/// streamed while the user typed it.
clock: i64,
start: u16,
len: u16,
existing: Option<usize>,
},
}
struct Prompt {
label: String,
buffer: String,
kind: PromptKind,
target_dir: PathBuf,
error: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct PendingDiscard {
rel_path: String,
untracked: bool,
}
/// A revert-hunk request waiting on its confirm popup. Holds the
/// single-hunk patch built when the user pressed R, so the confirm
/// reverse-applies exactly what they were looking at.
#[derive(Clone, Debug, PartialEq, Eq)]
struct PendingRevertHunk {
rel_path: String,
patch: String,
}
/// Why the branch picker is open, deciding what its Enter does. `Checkout`
/// is the default (click the branch name / "Checkout to"); the others are
/// reached from the Branch submenu and act on the highlighted *existing*
/// branch (or, for `CreateFrom`, use it as the base for a new branch).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum BranchPurpose {
#[default]
Checkout,
CreateFrom,
Delete,
Merge,
Rebase,
}
/// The live ssh-pane workspace offer (#364): which pane's foreground became
/// `ssh <host>`, the resolved config alias, and when the offer appeared (it
/// expires on its own if neither accepted nor dismissed).
#[derive(Clone, Debug, PartialEq, Eq)]
struct SshOffer {
pane: u64,
host: String,
since: std::time::Instant,
}
/// A left press forwarded to a mouse-tracking child (#474): which pane got
/// it, the host cell it landed on, and whether the drag since has become
/// croft's own text selection (a child that asked only for clicks cannot use
/// a drag, so croft keeps it). See `App::terminal_pointer_forwarded`.
///
/// The pane is held by its stable `uid`, NOT its index in `App::terminals`:
/// a pane closed while the button is held (the close chord, the header
/// button) shifts every later pane one slot left, and an index would then
/// deliver the release to the neighbour while the child that got the press
/// keeps a button it thinks is still down.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct ForwardedPointer {
pane: u64,
press: (u16, u16),
selecting: bool,
}
/// State for edge auto-scroll during a terminal drag-selection. `dir` is
/// -1 (pointer above the top edge, scroll into history) or +1 (below the
/// bottom edge, scroll toward live); `col` is the last drag column so the
/// re-pinned selection head tracks the pointer horizontally; `last` rate-
/// limits the scroll so it advances at a readable speed rather than once
/// per main-loop wakeup.
#[derive(Clone, Copy)]
struct TerminalSelectAutoScroll {
dir: i32,
col: u16,
last: std::time::Instant,
}
/// Active quick-select session on the focused terminal pane: the labelled
/// matches overlaid on the viewport, the label prefix typed so far, and
/// whether any typed char was UPPERCASE (commit then pastes the match into
/// the shell as well as copying it, WezTerm's convention).
pub struct QuickSelectState {
/// Index into `App::terminals` of the pane the labels were scraped
/// from: hints, pastes and re-pushes are bound to it, and any gesture
/// that activates a sibling pane closes the mode (the copy-mode rule).
pane: usize,
/// Scroll-clock reading the hint lines were captured at (one snapshot
/// with the lines themselves); every re-push reuses it so the pane's
/// render-time translation keeps labels on their scrolled matches.
clock: i64,
hints: Vec<QuickHint>,
typed: String,
shifted: bool,
}
/// One labelled quick-select match: where it sits (absolute grid line plus
/// char span in the spacer-skipped row text), the text a committed label
/// copies, and the label itself.
#[derive(Clone)]
struct QuickHint {
line: i32,
start: usize,
len: usize,
text: String,
label: String,
/// Continuation segments `(absolute line, start, len)` when the match
/// wraps the pane edge: highlighted alongside the head span, but the
/// label glyph only ever paints on the head.
tail: Vec<(i32, usize, usize)>,
}
/// Active copy-mode session on the focused terminal pane (WezTerm / tmux
/// copy mode): a keyboard cursor over the grid plus the selection anchor
/// and kind once v / V / Ctrl+V arms one. The pane paints the cursor and
/// the selection; this state owns the motions.
pub struct CopyModeState {
/// Pane index the mode opened on. The coordinates and clock below are
/// meaningless against any other pane (each pane owns an independent
/// scroll clock), so a gesture that moves `active_terminal` while the
/// mode is up closes it instead of hijacking the new pane.
pane: usize,
/// Cursor cell: absolute grid line + grid column.
line: i32,
col: u16,
/// Selection anchor cell; `None` until v / V / Ctrl+V arms a selection.
anchor: Option<(i32, u16)>,
kind: CopySelKind,
/// Scroll-clock reading the coordinates above are valid against. The
/// pane re-anchors its painted selection to streaming content between
/// keypresses; every key handler folds the clock movement into these
/// coordinates first, or the keystroke would teleport the highlight
/// back to the stale absolute lines.
clock: i64,
}
/// Which shape the copy-mode selection takes: vim's v / V / Ctrl+V.
#[derive(Clone, Copy, PartialEq, Eq)]
enum CopySelKind {
Char,
Line,
Block,
}
/// How long a closed terminal pane stays parked (child alive, hidden)
/// before the tick drops it for real. Ghostty and iTerm2 default their
/// undo-close window to 5s; croft doubles it because the hint lives in a
/// TUI status line that is easier to miss than a native toast.
pub const UNDO_CLOSE_GRACE: std::time::Duration = std::time::Duration::from_secs(10);
/// How many closed editor tabs Cmd+K ⇧W can walk back through.
const CLOSED_TAB_STACK_CAP: usize = 20;
/// A closed editor tab, reopenable via Cmd+K ⇧W (VS Code "Reopen Closed
/// Editor"): the file plus the view state needed to restore the tab as the
/// user left it. Unlike [`ClosedTerminal`] there is no live process to
/// park, so entries never expire; the stack is just bounded.
pub struct ClosedTab {
pub path: PathBuf,
pub pinned: bool,
pub cursor: (usize, usize),
pub scroll: usize,
}
/// A terminal pane parked by close for the undo-close grace window: the
/// live pane, the slot it occupied (so restore puts it back where it was),
/// and when it was closed (for expiry).
pub struct ClosedTerminal {
pub term: crate::widgets::terminal::PtyTerminal,
pub idx: usize,
pub closed_at: std::time::Instant,
}
/// A `cargo test --no-run` running on a background thread: the receiver for
/// its result, the test's name, and the workspace root it builds for (so a
/// re-root mid-build discards the binary instead of debugging it in the
/// wrong workspace).
type PendingTestDebug = (
std::sync::mpsc::Receiver<Result<PathBuf, String>>,
String,
PathBuf,
);
/// A COMMITS graph reply: the root and revspec it answers, and the rows.
/// Tagged rather than bare so a reply for a since-left root or a superseded
/// view is discarded on drain (#348).
type GraphReply = (
PathBuf,
Option<String>,
Vec<crate::widgets::commit_graph::GraphRow>,
);
type GraphReplyRx = std::sync::mpsc::Receiver<GraphReply>;
type GraphReplyTx = std::sync::mpsc::Sender<GraphReply>;
pub struct App {
pub tree: FileTree,
pub search: SearchPanel,
pub remote: RemotePanel,
pub source_control: SourceControlPanel,
/// The Source Control COMMITS section: the repo-wide commit graph with
/// lane rails, stacked under the change list. See [`CommitGraphPanel`].
pub commit_graph: crate::widgets::commit_graph::CommitGraphPanel,
/// Background `git log --topo-order` + lane layout for the COMMITS
/// section, tagged by the root it describes so a stale reply after a
/// Make Root is ignored on drain.
graph_rx: GraphReplyRx,
graph_tx: GraphReplyTx,
/// What the COMMITS panel is currently showing: `None` for the root's
/// own history, `Some("base..lane")` for a worktree lane's diff (#348).
///
/// The reply tag carries this too, so a history refresh landing while a
/// lane diff is up is discarded rather than replacing it - the panel
/// already discarded replies for a since-left ROOT, and this is the same
/// rule at the resolution the lane diff needs.
graph_revspec: Option<String>,
/// A graph fetch is running; suppresses duplicate spawns when a burst of
/// StatusAndChanges responses lands. Cleared when the reply drains.
graph_fetch_inflight: bool,
/// A refresh was requested while a fetch was in flight (Make Root, a
/// newer HEAD): re-fire once the stale reply drains instead of dropping
/// the request (see [`Self::refresh_commit_graph`]).
graph_refetch_queued: bool,
pub run_debug: RunDebugPanel,
/// The Testing side panel: the suite tree with live pass/fail status.
pub testing: crate::widgets::testing::TestingPanel,
/// Background `cargo test` worker feeding the Testing panel.
test_worker: crate::testing::worker::TestWorker,
/// The Extensions side panel: bundled + installed extensions with toggles.
pub extensions: crate::widgets::extensions::ExtensionsPanel,
/// Extension ids VS Code reported installed, from the last
/// "Extensions: Compare with VS Code" (#352). Empty until the user asks,
/// since listing them spawns `code`. Workspace recommendations are read
/// from `.vscode/extensions.json` on every refresh instead.
pub vscode_listed: Vec<String>,
/// The Explorer's OPEN EDITORS section: the open editor tabs, projected
/// from the active `editor` group each frame. See [`OpenEditorsPanel`].
pub open_editors: OpenEditorsPanel,
/// The Explorer's OUTLINE section, stacked below the file tree: the active
/// editor's `documentSymbol` tree. See [`OutlinePanel`].
pub outline: OutlinePanel,
/// The Explorer's TIMELINE section: the active file's git history, fetched
/// off-thread via [`crate::git::file_history`]. See [`TimelinePanel`].
pub timeline: TimelinePanel,
/// The Explorer's DEPENDENCIES section: the workspace's packages, resolved
/// off-thread per detected ecosystem. See [`DependenciesPanel`].
pub dependencies: DependenciesPanel,
/// Package ecosystems detected at the workspace root (by manifest file),
/// recomputed on every re-root. Empty means no recognised manifest, which
/// hides the DEPENDENCIES section entirely and drops it from the ⋯ menu —
/// the rule every reference editor follows. Drives the section's header
/// label too. Cached so the cheap detection never runs on the render path.
dep_ecosystems: Vec<Ecosystem>,
/// Which Explorer sub-views are shown, toggled from the ⋯ menu. Persisted.
pub explorer_views: ExplorerViewVisibility,
/// Every file of the layered-settings chain (#251), for hot-reload
/// matching on save; rebuilt by `remerge_settings`.
settings_chain: Vec<PathBuf>,
/// Which layer set each top-level settings key, for the hub's
/// provenance suffix ("· workspace").
settings_provenance: std::collections::BTreeMap<String, crate::config_layers::LayerKind>,
/// Extension ids the user has disabled in the Extensions panel. Loaded once
/// from prefs at startup and persisted on every toggle, mirroring how
/// `explorer_views` is held in memory rather than re-read each access. The
/// gates for the bundled features (PDF/CSV/Vim/LSPs) consult this set.
disabled_extensions: std::collections::BTreeSet<String>,
/// User key bindings from `~/.config/croft/keybindings.json`, consulted
/// ahead of the built-in chords so a rebind wins over the default.
keymap: crate::keymap::Keymap,
/// Live macro recording (#255), `None` when not recording. Carries the
/// vim register it will be stored under, or `None` for the palette
/// recorder, whose macro is the unnamed "last recording".
macro_recording: Option<crate::macros::Recording>,
/// The most recent finished recording: what "Replay Last" and vim's `@@`
/// run, and what a `q` with no register stores into.
macro_last: Option<crate::macros::Macro>,
/// Named registers (`qa` … `q`), loaded from macros.json at startup.
macro_registers: std::collections::HashMap<String, crate::macros::Macro>,
/// True while a replay is feeding keys back through `handle_key`, so a
/// replayed key is never recorded and a macro cannot invoke itself.
macro_replaying: bool,
/// The store path, held so tests can point saves at a tempdir.
macros_path: std::path::PathBuf,
/// The click a user mouse binding is running for (#259), set only for
/// the duration of that dispatch. Position-carrying commands read it;
/// `None` everywhere else, so a keyboard invocation of the same command
/// can never act on a stale click.
last_mouse_pos: Option<(u16, u16)>,
/// User snippets from `~/.config/croft/snippets.json`. Typing a snippet's
/// prefix and pressing Tab expands it with tab-stop navigation.
snippets: crate::snippets::SnippetSet,
/// VS Code `editor.formatOnSave`: when true, `Cmd+S` first asks the language
/// server to format the buffer, then writes once the reply lands. Loaded
/// from prefs at startup, toggled from the palette / `Cmd+K F`.
format_on_save: bool,
/// VS Code `terminal.integrated.copyOnSelection`: a finished terminal
/// mouse selection lands on the clipboard without an explicit Cmd+C.
/// Loaded from prefs at startup, toggled in the Settings hub.
copy_on_select: bool,
/// Tailspin highlighting in rendered log views (#466): the inverse of
/// the `disable_log_highlight` preference. Pushed into `log_view`'s
/// default for views opened later and into every open view on toggle.
log_highlight: bool,
/// Built-in secret redaction rules are in the trigger set (#360).
/// Settings "Terminal: Redact Secrets"; stored inverted in config.json
/// as `disable_secret_redaction` so the default is on.
secret_redaction: bool,
/// "Terminal: Reveal Redacted Secrets": masks paint as their real text
/// until this instant, then mask again on the next frame.
redaction_reveal_until: Option<std::time::Instant>,
/// VS Code's `files.autoSave: afterDelay`: dirty buffers write
/// themselves to disk once the delay elapses after the last edit.
auto_save: bool,
/// VS Code's `files.autoSave: onFocusChange`: a dirty buffer writes
/// itself the moment it loses focus. Independent of `auto_save`.
pub auto_save_on_focus_change: bool,
/// The focus signature (pane, group, active path) seen by the last
/// auto-save tick. A change means something lost focus, which is the
/// only trigger `onFocusChange` fires on. `None` until the first tick
/// so opening croft never writes anything on its own.
last_focus_signature: Option<(usize, usize, Option<PathBuf>)>,
/// Latch set while a save is waiting on a format reply. `drain_lsp_format`
/// consumes it to write the (now formatted) buffer to disk.
save_after_format: Option<PathBuf>,
/// Background `git log` results for the TIMELINE, keyed by the file they
/// describe so a stale reply for a since-closed file is ignored on drain.
timeline_rx: std::sync::mpsc::Receiver<(PathBuf, Vec<crate::git::FileHistoryEntry>)>,
timeline_tx: std::sync::mpsc::Sender<(PathBuf, Vec<crate::git::FileHistoryEntry>)>,
/// The file the TIMELINE has been fetched (or is being fetched) for, so the
/// fetch fires exactly once per active-file change.
timeline_fetched: Option<PathBuf>,
/// Off-thread per-line git blame for the active editor (GitLens-style
/// inline annotation). Fetched once per (file, HEAD) like the gutter.
blame_rx: std::sync::mpsc::Receiver<(PathBuf, Vec<crate::git::BlameLine>)>,
blame_tx: std::sync::mpsc::Sender<(PathBuf, Vec<crate::git::BlameLine>)>,
/// The file blame has been fetched (or is in flight) for; reset to `None`
/// on HEAD move so the annotation refreshes after a commit / checkout.
blame_fetched: Option<PathBuf>,
/// User pref: show the current-line inline blame annotation (default on).
inline_blame_enabled: bool,
/// The provenance lens (#349): who typed each line, in the gutter and
/// the blame annotation. Session-only for now; the persisted half of
/// #349 (the map beside local history) is a later slice. Pushed onto
/// every editor in every group by `sync_focus_flags`, since the gutter
/// bar paints in every pane, not only the focused one.
provenance_overlay: bool,
/// Indentation guides (#129), VS Code `editor.guides.indentation`: on by
/// default, pushed to every editor by the per-frame focus sync.
indent_guides_enabled: bool,
/// Bracket-pair colorization (#131): on by default, pushed to every
/// editor by the per-frame focus sync like the indent guides.
bracket_colors_enabled: bool,
/// Whitespace rendering mode (#133), frame-synced to every editor;
/// "selection" by default, the palette command cycles it.
whitespace_mode: crate::widgets::editor::WhitespaceMode,
/// Default ignore-whitespace mode applied to newly opened diffs (#258).
diff_ws_default: crate::widgets::diff::DiffWhitespace,
/// Debugger inline values (#135): on by default; rebuilt on every
/// `InspectionUpdated`, cleared wherever the stop arrow clears.
inline_values_enabled: bool,
/// Auto-closing pairs (#121), persisted; synced onto the active editor
/// beside the blame flag.
auto_close_pairs: bool,
/// LSP inlay hints (inline type / parameter annotations), on by default
/// like VS Code's `editor.inlayHints.enabled`; toggled from the palette
/// and persisted as `disable_inlay_hints` in config.json.
inlay_hints_enabled: bool,
/// Local-history root (`~/.config/croft/history`), cached so tests can
/// redirect snapshots to a tempdir.
history_root: PathBuf,
/// The snapshot currently shown in a local-history diff, `(live file,
/// snapshot millis, snapshot contents)`, so "Local History: Restore
/// Snapshot" can write it back and carry its seats (#349). Cleared when a
/// non-snapshot diff opens.
history_restore: Option<(PathBuf, u64, Vec<u8>)>,
/// Completed off-thread history recordings, drained to refresh the
/// TIMELINE once the snapshot actually exists on disk.
history_done_rx: std::sync::mpsc::Receiver<PathBuf>,
history_done_tx: std::sync::mpsc::Sender<PathBuf>,
/// The whole-project check's result: where it ran, and what the process
/// did (#256). The `io::Result` carries a spawn failure separately from
/// a run that produced output, because those need different messages.
#[allow(clippy::type_complexity)]
project_check_rx: std::sync::mpsc::Receiver<(PathBuf, std::io::Result<std::process::Output>)>,
#[allow(clippy::type_complexity)]
project_check_tx: std::sync::mpsc::Sender<(PathBuf, std::io::Result<std::process::Output>)>,
/// Whether a sweep is in flight, so a second invocation says so rather
/// than stacking compilers.
project_check_running: bool,
/// How many rows the last sweep produced (#256), counted before its
/// items join a store shared with every other producer.
project_check_rows: usize,
/// Whether the sweep may run unasked (#256): `auto`, `on` or `off`.
/// Read at startup; an unrecognised value behaves as `auto`.
problems_project_scope: String,
/// Signals that this workspace is too large for `auto` to run the sweep
/// unasked (#256). Sent from the sweep's worker, since deciding it is a
/// whole-workspace walk.
project_hint_rx: std::sync::mpsc::Receiver<()>,
project_hint_tx: std::sync::mpsc::Sender<()>,
/// One hint per session, not per run: repeating it every sweep would
/// train the user to ignore the status line.
project_check_hinted: bool,
/// Replies from the background test-source locator (the workspace grep is
/// too slow for the render thread): the root the search ran under, the
/// test name, and the hit. A reply from before a re-root is dropped.
#[allow(clippy::type_complexity)]
test_jump_rx: std::sync::mpsc::Receiver<(PathBuf, String, Option<(PathBuf, u32)>)>,
#[allow(clippy::type_complexity)]
test_jump_tx: std::sync::mpsc::Sender<(PathBuf, String, Option<(PathBuf, u32)>)>,
/// Background per-ecosystem dependency-resolution result for DEPENDENCIES.
deps_rx: std::sync::mpsc::Receiver<Vec<Dependency>>,
deps_tx: std::sync::mpsc::Sender<Vec<Dependency>>,
/// The workspace root DEPENDENCIES was detected/fetched for, so detection
/// and the fetch fire once per root (re-fired by Make Root / re-root).
deps_fetched: Option<PathBuf>,
/// Push-to-talk voice input (Termux OSK mic). The worker streams its
/// transcript over this channel; `voice_handle` lets the mic release kill
/// the in-flight recognizer.
voice_rx: std::sync::mpsc::Receiver<crate::voice::VoiceMsg>,
voice_tx: std::sync::mpsc::Sender<crate::voice::VoiceMsg>,
voice_handle: Option<crate::voice::VoiceHandle>,
/// Set when a mic tap cancels a live session, so the resulting empty result
/// is reported as "canceled" rather than "no speech detected".
voice_canceling: bool,
pub editor: EditorTabs,
/// The editor group layout tree. `editor` (above) is ALWAYS the active
/// (focused) group, hoisted out of the tree's single active leaf, so the
/// 430-odd `self.editor` call sites keep operating on whichever group has
/// focus. The tree holds every OTHER group plus the spatial split
/// structure; a single unsplit leaf is the just-launched state. Splitting,
/// moving focus, and collapsing all go through [`editor_layout`].
pub editor_layout: editor_layout::EditorLayout,
/// One-shot latch armed when a save is refused because the file changed
/// on disk. The next `save()` overwrites anyway, giving the user a
/// "press Cmd+S again to overwrite" escape hatch without a modal.
force_save_armed: bool,
pub terminals: Vec<PtyTerminal>,
pub active_terminal: usize,
perf: PerfHud,
/// The workspace's root-folder set (#143). One entry today; the
/// multi-root slices grow it. Read the primary via `workspace_root()`.
roots: crate::workspace::WorkspaceRoots,
sidebar_view: SidebarView,
sidebar_areas: SidebarAreas,
/// Active IDE color theme. Drives every explicit-background surface
/// (baked icon PNGs, editor image/sheet/diff canvases, the `SetColors`
/// session fill); `Color::Reset` surfaces follow the session bg for free.
/// Toggled from the activity-bar gear menu; persisted via `crate::prefs`.
theme: crate::theme::Theme,
focus: Pane,
show_tree: bool,
show_terminal: bool,
/// `Ctrl+Shift+J` maximizes the terminal pane: the editor / welcome
/// collapses to zero height and the terminal fills the entire right
/// column next to the Explorer. Pressing the chord again, or hiding
/// the terminal entirely with `Ctrl+J`, clears the flag.
terminal_maximized: bool,
/// Layout (Customize Layout popup): whether the left activity bar is
/// shown. Persisted via `crate::prefs`.
activity_bar_visible: bool,
/// Layout: whether the bottom status bar is shown. Persisted.
status_bar_visible: bool,
/// Layout: which edge the primary side bar (+ activity bar) docks to.
/// Persisted.
side_bar_position: SideBarPosition,
/// Layout: whether the secondary side bar (the active file's Outline) is
/// shown, on the edge opposite the primary side bar (⌥⌘B). Persisted.
secondary_side_bar_visible: bool,
/// Layout: horizontal span/alignment of the bottom panel. Persisted.
panel_alignment: PanelAlignment,
/// Layout: where the quick input (command palette / Go to File) anchors.
/// Persisted.
quick_input_position: QuickInputPosition,
/// Layout: Zen Mode hides the activity bar, both side bars, the panel,
/// and the status bar; toggling off restores `pre_zen`.
zen_mode: bool,
/// Auto-hide the sidebar when focus moves to the editor or a terminal
/// (#260, `sidebar_auto_hide`). Off by default. The sidebar comes back
/// on any deliberate sidebar action — Cmd+B, an activity-bar icon, or a
/// sidebar-targeting command like reveal-in-explorer.
sidebar_auto_hide: bool,
/// Set while a focus move is happening for a reason other than the user
/// asking for it (async results, launch, sidebar-internal activation).
sidebar_auto_hide_suspended: bool,
/// One-shot exemption: the next auto-hide collapse is skipped and the
/// flag consumed. Cmd+B reveals the sidebar WITHOUT moving focus, so a
/// sticky flag would stay set (focus never lands on the tree to clear
/// it) and silently disable auto-hide for the rest of the session.
/// Consuming it on the next attempt keeps the reveal usable while
/// guaranteeing the feature re-arms itself.
sidebar_pinned_open: bool,
/// Grace delay between focus leaving the sidebar and auto-hide collapsing
/// it (#302), so a click passing through the panel does not take it away
/// under the pointer.
sidebar_dwell: SidebarDwell,
/// Pre-Zen visibility snapshot; `None` whenever not in Zen Mode.
pre_zen: Option<PreZenLayout>,
/// Hit-test rects for the top-right layout-control icons.
layout_icon_areas: LayoutIconAreas,
status: String,
/// Orange status-bar badge shown for the whole session when this is a
/// remote (SSH) croft not running under dtach, so it can't survive a
/// transport drop. Set once at startup; rendered separately from `status`
/// so transient messages never clobber it. `None` otherwise.
persistence_warning: Option<&'static str>,
quit: bool,
drop_to_local: bool,
is_remote: bool,
context_menu: Option<ContextMenu>,
prompt: Option<Prompt>,
fs_watch: FsWatch,
/// One extra watcher per SECONDARY workspace root (#147), sharing the
/// primary's watch-cap budget. The primary `fs_watch` also owns the
/// adaptive poll (its dir-mtime snapshot walks the whole tree, all
/// roots included) and the open-file stats; extras are event-only.
fs_watch_extra: Vec<FsWatch>,
/// One git worker per SECONDARY workspace root (#149), keyed by the
/// root path. `git` stays the primary's worker. Each discovers its
/// own repo toplevel; replies are root-scoped by construction.
git_extra: Vec<(PathBuf, GitWorker)>,
/// The workspace root whose repository the Source Control panel and
/// the status line follow: the root owning the focused editor's
/// file, falling back to the primary. Recomputed each drain tick; a
/// change re-seeds the panel from that worker and re-requests its
/// change list.
active_scm_root: PathBuf,
/// A repositories-overview click pins the panel to that folder's repo
/// (#161); the pin clears when the FOCUS-derived folder changes, so
/// the panel resumes following the file the user works in.
scm_pin: Option<PathBuf>,
/// The last focus-derived folder, for detecting the change that
/// releases `scm_pin`.
scm_follow_root: PathBuf,
/// The workspace root the Testing panel and worker are bound to —
/// follows the focused file's folder like the SCM surfaces (#151).
active_test_root: PathBuf,
/// Folder set from an explicitly opened `.code-workspace` (#163):
/// consumed by `change_workspace_root` INSTEAD of the automatic
/// per-primary restore, so the file defines the arrangement exactly.
pending_workspace_folders: Option<Vec<PathBuf>>,
/// Per-workspace-root last-seen HEAD oid, for gutter-baseline and
/// commit-graph invalidation per repository (#149).
git_head_oids: std::collections::BTreeMap<PathBuf, Option<String>>,
git: GitWorker,
cursor_blink: CursorBlink,
editor_click: ClickTracker,
tree_click: ClickTracker,
terminal_click: ClickTracker,
/// Modified clicks, so `ctrl+double_click` and friends can be recognised
/// without arming the unmodified trackers above (see the type's docs).
/// One tracker, not one per region: it is only ever read by the binding
/// dispatch, and a double needs both clicks at the same cell, so two
/// regions cannot be confused for one another.
modified_click: ModifiedClickTracker,
/// Double-click tracking for PORTS rows: a second click on the same row
/// opens that port, the same as pressing Enter on it.
ports_click: ClickTracker,
/// Active edge auto-scroll while drag-selecting in the terminal: set
/// when the drag pointer is pinned past the top/bottom edge, serviced
/// each main-loop tick to keep growing the selection through
/// scrollback. `None` whenever the pointer is inside the pane or the
/// button is released.
terminal_select_autoscroll: Option<TerminalSelectAutoScroll>,
/// Pane whose scrollbar is currently being dragged with the left mouse button.
scrollbar_drag: Option<Pane>,
/// True while the editor's horizontal scrollbar thumb is being dragged.
/// Only the editor has a horizontal bar, so a bool suffices.
editor_hscrollbar_drag: bool,
/// A left-drag is moving the OUTLINE panel's scrollbar thumb. The outline
/// is not a focusable `Pane`, so it gets its own drag latch rather than
/// riding `scrollbar_drag`.
outline_scrollbar_drag: bool,
/// Scrollbar-thumb drag latches for the other stacked Explorer sub-views,
/// matching `outline_scrollbar_drag` (none is a focusable `Pane`).
open_editors_scrollbar_drag: bool,
timeline_scrollbar_drag: bool,
deps_scrollbar_drag: bool,
testing_scrollbar_drag: bool,
graph_scrollbar_drag: bool,
welcome: WelcomeState,
/// One-shot background refresh of the remote extension index. Polled in the
/// main loop; rebuilds the Extensions panel once if the verified cache
/// changed. `None` once consumed (or on a disarmed build, immediately).
ext_index_refresh: Option<std::sync::mpsc::Receiver<bool>>,
/// True when the in-flight refresh was triggered by the user (the ⟳ button),
/// so its completion reports a status line; the silent startup refresh
/// doesn't, to avoid clobbering more useful startup messages.
ext_index_manual_refresh: bool,
/// Channel to the background search worker. Each keystroke or toggle
/// flip pushes a `(query, opts)` request here; the worker debounces
/// and runs `search_workspace` off the UI thread.
search_query_tx: std::sync::mpsc::Sender<crate::widgets::search::SearchRequest>,
/// Results coming back from the search worker: `(query, hits)`. The
/// query is echoed so we can drop stale results when the user has
/// typed past the query that produced them.
search_results_rx: std::sync::mpsc::Receiver<crate::widgets::search::SearchEvent>,
/// Pixel size of one terminal cell, captured in `init_graphics`.
/// Required to bake OSC-1337 images at exact viewport pixel size so
/// iTerm draws them with no stretching or letterboxing.
cell_pixel: Option<(u32, u32)>,
/// Last wheel step applied to a PDF preview (when, in which direction,
/// and on which document), so a momentum flick's same-direction burst
/// coalesces instead of queueing one blocking rasteriser run per event.
/// Keyed by document: switching to another PDF starts fresh - a reader's
/// first gesture there is not a repeat.
last_pdf_wheel: Option<(std::time::Instant, i32, Option<PathBuf>)>,
/// One-shot consent to overwrite FORMULA cells on the next xlsx
/// save (#178/#194): armed by the save that held them back, distinct
/// from `force_save_armed` (the disk-conflict consent).
formula_overwrite_armed: bool,
/// Pre-encoded inline-image for the source-control change-count badge (an
/// accent pill + count, VS Code's `activityBarBadge`), emitted at z=1 over
/// the SCM activity icon's bottom-right. `None` when there are no changes,
/// not in a repo, or image rendering is off (the glyph path draws a text
/// badge instead). Rebuilt by `refresh_scm_change_badge` when the change
/// set, theme, or cell size shifts.
scm_change_badge: Option<String>,
/// Change count the cached `scm_change_badge` was built for; drives the
/// dirty check and the badge's on-screen cell width.
scm_change_badge_count: usize,
/// Pre-encoded inline-image for the Explorer change badge: the count of
/// open editors with unsaved edits (VS Code's Explorer activity badge),
/// emitted at z=1 over the Explorer icon's bottom-right. `None` when nothing
/// is unsaved or image rendering is off. Mirrors the SCM badge plumbing;
/// rebuilt by `refresh_explorer_unsaved_badge`.
explorer_unsaved_badge: Option<String>,
/// Unsaved-file count the cached `explorer_unsaved_badge` was built for.
explorer_unsaved_count: usize,
/// Pre-encoded inline-image for the Remote icon's forwarded-ports badge
/// (VS Code's Ports view count), emitted at z=1 over the Remote icon. `None`
/// when no port is forwarded or image rendering is off. Same plumbing as the
/// other count badges; rebuilt by `refresh_remote_ports_badge`.
remote_ports_badge: Option<String>,
/// Forwarded-port count the cached `remote_ports_badge` was built for.
remote_ports_count: usize,
/// Pre-encoded inline-image for the Testing icon's failing-test count badge
/// (red pill, VS Code's Testing badge), emitted at z=1 over the beaker icon.
/// `None` when nothing is failing or image rendering is off. Same plumbing as
/// the other count badges; rebuilt by `refresh_testing_badge`.
testing_badge: Option<String>,
/// Failing-test count the cached `testing_badge` was built for.
testing_badge_count: usize,
/// Problem count the cached `overlays.problems_badge` circle was built for;
/// gates the per-frame rebuild in `refresh_problems_badge`.
problems_badge_count: usize,
/// Anchor cell (top-left) where the PROBLEMS-tab circle badge should be
/// emitted this frame, recorded by `paint_panel_tabs` in images mode. `None`
/// when the panel strip isn't drawn or the count is zero; the post-frame
/// `flush_problems_badge_overlay` clears the image when it's `None`.
problems_badge_cell: Option<(u16, u16)>,
/// Which inline-image protocol the host terminal speaks, resolved once at
/// startup (env-fixed). Drives the [`crate::iterm2_inline::build_inline_image`]
/// dispatch (iTerm2 OSC-1337 vs Kitty graphics) and the Kitty-only
/// delete-all eviction on the clear chain.
inline_protocol: crate::iterm2_inline::InlineImageProtocol,
/// Set once by the runtime DA1 probe (`run`) when the host terminal lacks an
/// env-advertised protocol (iTerm2/Kitty) but answers DA1 with sixel
/// support. `init_graphics` promotes `inline_protocol` to `Sixel` when this
/// is true, and preserves it across the theme-switch re-detect that would
/// otherwise reset to `None` (sixel has no env signal to re-derive from).
sixel_supported: bool,
/// One-shot: a WINCH arrived, so the next frame must wipe and repaint every
/// cell on EVERY protocol. A dtach reattach fires WINCH (`-r winch`) against
/// a blank physical screen while ratatui's buffer still says everything is
/// painted, so the diff alone emits nothing; the Kitty path skips the
/// image-eviction wipe (the typing-blink fix), so resize owns its own.
resize_repaint_needed: bool,
/// VS Code-style editor minimap (rasterized document preview in a right/left
/// strip). On by default; toggled and re-sided from the strip's right-click
/// menu.
minimap_visible: bool,
minimap_side: MinimapSide,
/// Cached whole-file raster; recomposited (not rebaked) on scroll.
minimap_base: Option<MinimapBase>,
/// Hit-test rect of the on-screen minimap image (text-aligned rows), for
/// click-to-scroll and the right-click menu. Empty when the minimap is off.
minimap_img_rect: Rect,
/// Pixel height the lines are mapped into within the image (top-aligned;
/// `<=` the image's pixel height for short files). Click mapping divides by
/// this, not the full strip height, so clicks land on the right line.
minimap_content_h: u32,
/// A left-drag is panning the view via the minimap strip.
minimap_drag: bool,
/// Clipboard read entrypoint. Production uses the host clipboard; tests
/// can swap in a deterministic reader for Cmd+V routing assertions.
clipboard_reader: fn() -> Option<String>,
/// Whether this croft is a relay session: a `croft remote` child whose
/// LOCAL launcher runs the drop pump, so the clipboard the user pastes
/// from lives on the other machine (#538).
///
/// Resolved ONCE here rather than read per copy. `CROFT_RELAY_KEY` is
/// process-global, and `deliver_copied_text` asks this question on every
/// copy: a relay test that sets the variable would otherwise reroute the
/// copy of every test running beside it, which is exactly what it did
/// (three suites broke). Inert under `cfg(test)` for the same reason the
/// collab channel's read is — a test opts in by setting the field — so no
/// test can be steered by another's environment.
is_relay_session: bool,
remote_launch: Option<RemoteLaunch>,
pending_remote_launch_host: Option<String>,
pending_remote_launch_path: Option<String>,
/// The ssh-pane offer currently shown in the status bar (#364), if any.
/// Accepted with Cmd+K G, dismissed with Esc, dropped when the pane's
/// ssh ends or after `SSH_OFFER_TTL`.
ssh_offer: Option<SshOffer>,
/// What each pane (by uid) was last seen connected to, so an ssh session
/// is offered once when it starts rather than on every sample.
ssh_offer_seen: std::collections::BTreeMap<u64, Option<String>>,
/// The label thread's ssh samples (#364): `(shell pid, resolved host)`
/// per pane it looked at, shipped beside the names it already resolves
/// so the argv read and the `~/.ssh/config` parse stay off the loop.
ssh_rx: std::sync::mpsc::Receiver<Vec<(i32, Option<String>)>>,
ssh_tx: std::sync::mpsc::Sender<Vec<(i32, Option<String>)>>,
/// `disable_remote_offer` from prefs (#364).
remote_offer_disabled: bool,
/// `remote_offer_excluded_hosts` from prefs (#364).
remote_offer_excluded: Vec<String>,
/// `fleet_groups` from prefs (#363): named host sets a fleet run can
/// expand, so a fleet is named once rather than retyped per run.
fleet_groups: std::collections::BTreeMap<String, Vec<String>>,
/// Hosts whose provisioning failed recently (#364), loaded from the
/// cache file at startup and extended when an install fails.
remote_offer_refused: crate::remote::RefusedHosts,
/// The `agents.json` row a new worktree lane starts in its pane (#348);
/// `None` opens a plain shell. From `lane_agent` in settings.json.
lane_agent: Option<String>,
/// Which panes are worktree lanes' (#348), by pane uid: saved with the
/// terminal session so a relaunch seats the agent again, and consulted
/// when a lane closes so its pane goes with it.
lane_panes: std::collections::BTreeMap<u64, crate::terminal_session::LaneRecord>,
/// Explorer-scoped Cut/Copy buffer. Independent from the OS clipboard
/// (which carries text), this stores filesystem paths and the intent
/// (move vs. copy) until the next Paste consumes it.
tree_clipboard: Option<ExplorerClipboard>,
/// Explorer type-to-jump buffer. Each printable keystroke within
/// `TREE_TYPEAHEAD_WINDOW` of the previous one accumulates; a
/// keystroke after the gap resets the buffer and cycles past the
/// current selection. Matches VS Code's tree typeahead.
tree_typeahead: Option<TreeTypeahead>,
/// File the user picked via the explorer's "Select for Compare" menu
/// action. None until they pick one; cleared once they invoke
/// "Compare with Selected" against another file.
compare_anchor: Option<PathBuf>,
/// Whole-screen rect captured at the start of every `render`. The
/// context-menu hit-test reads this to clamp the menu's bounds the
/// same way the renderer does, so a menu that gets shifted up to fit
/// on screen still maps clicks to the right item.
last_frame_area: Rect,
/// The Explorer/sidebar column rect from the last render (`None` when
/// the sidebar is collapsed). The zoxide jump popup anchors over this
/// so it drops from the Explorer rather than centering on the frame.
last_sidebar_area: Option<Rect>,
/// Active explorer drag-and-drop, if any.
tree_drag: Option<ExplorerDrag>,
/// Pending SCP uploads queued by a Finder drag-drop onto the Remote
/// Explorer. These are intentionally NOT run inline — the main loop
/// drains the queue after suspending the alt-screen so scp can use
/// the host shell for password / FIDO / known_hosts prompts and the
/// user actually sees what's happening.
pending_scp_uploads: Vec<ScpUpload>,
/// Drops awaiting reverse-pull from the user's local Mac via the
/// drop-relay launched by the local croft parent. Polled each frame.
pending_remote_pulls: Vec<PendingRemotePull>,
/// This croft's `croft view` listener (#362).
///
/// `None` when the bind failed: a croft that cannot offer `croft view`
/// must still start, so the failure costs the feature and nothing else.
/// Panes then see no `CROFT_VIEW_SOCK` and the client says so plainly,
/// which is the same message a pane outside croft gets.
///
/// No path is kept alongside it. The doc used to promise "the socket path
/// to unlink when it goes away" and nothing unlinked it: there is no
/// `Drop for App`, both readers discarded the second element, and the
/// launch-time sweep is what actually reclaims a dead croft's socket -
/// deliberately, since an unclean exit leaves no `Drop` to run either.
/// A field carrying a promise the code does not keep is worse than no
/// field.
view_listener: Option<std::os::unix::net::UnixListener>,
/// URL awaiting the user's local-browser confirmation (remote-
/// launched croft only). When `Some`, a modal asks Y/A/N and all
/// other keys are swallowed.
pending_local_open: Option<String>,
/// Source Control entry awaiting Y/N confirmation for destructive
/// `Discard Changes`. Holds the relative path and whether it was an
/// Untracked entry (Untracked discard deletes the file from disk;
/// tracked discard runs `git checkout HEAD -- <path>`). Both paths
/// destroy uncommitted work, so the modal must always run first.
pending_discard: Option<PendingDiscard>,
/// Armed by R in a Source-Control diff; reverting a hunk destroys
/// uncommitted work, so the confirm modal always runs first.
pending_revert_hunk: Option<PendingRevertHunk>,
/// The tasks backing the open Run Task picker; the picker row `id`
/// indexes into this list.
run_tasks: Vec<crate::tasks::Task>,
/// The most recently run task, for "Tasks: Rerun Last Task".
last_task: Option<crate::tasks::Task>,
/// Set on startup (after `init_graphics` resolves the inline-image
/// protocol) when the host terminal can't render croft's icons/images
/// and the user hasn't silenced the nudge. Drawn as a dismissible modal
/// recommending iTerm2 (macOS) / Ghostty (macOS/Linux).
pending_terminal_warning: bool,
/// True while the Source Control commit dropdown (▾ caret) is open.
/// The caret button toggles this; clicking a menu row, the commit
/// button, or anywhere outside the menu closes it.
commit_menu_open: bool,
/// Cached default-branch name (e.g. "main" / "master"), refreshed
/// when the workspace root changes. Surfaced in the commit dropdown's
/// "View Changes vs <name>" label so users know which branch the
/// diff compares against. `None` until the resolver succeeds.
default_branch_label: Option<String>,
/// Last HEAD oid the git-gutter baselines were synced against. When the
/// git worker reports a different oid (commit, checkout, pull), the cached
/// per-tab HEAD snapshots are invalidated so the gutter refetches.
/// True after the user has chosen "Always for this session" on the
/// local-browser confirmation. Subsequent link clicks dispatch to
/// the relay silently.
trust_local_browser: bool,
/// Width in cells of the sidebar (Explorer / Search / Remote pane).
/// Defaults to 32 cells; user can drag the splitter between sidebar
/// and editor to widen or narrow.
sidebar_width: u16,
/// Height in cells of the bottom terminal pane. `None` = use the
/// default 35% split; Some = a user-specified pinned height. Stored
/// in cells (not percent) so it doesn't drift on window resize.
terminal_height: Option<u16>,
/// Active splitter drag, if any. Cleared on mouse-up.
splitter_drag: Option<SplitterDrag>,
/// Last-rendered geometry of the vertical splitter column (between
/// sidebar and editor) and the horizontal splitter row (between
/// editor and terminal). Used by the mouse handler to hit-test cleanly
/// without recomputing layout outside of `render`.
sidebar_splitter_x: Option<u16>,
terminal_splitter_y: Option<u16>,
/// Every draggable seam between editor groups, as laid out by the most
/// recent render. Empty when unsplit. Drives both the focus-on-click guard
/// (a press on a seam must not steal focus) and the seam-drag hit-test, for
/// a grid of any depth.
editor_seams: Vec<editor_layout::Seam>,
/// Hit-test rectangles of the "[+]" buttons - one per terminal pane,
/// indexed in lock-step with `terminals`. Empty when the pane is hidden
/// or every pane is too narrow for the label.
terminal_add_buttons: Vec<Rect>,
/// Hit-test rectangles of the profile-caret (`⌄`) buttons - one per pane,
/// in lock-step with `terminals`. Clicking one opens the profile picker.
terminal_profile_buttons: Vec<Rect>,
/// Hit-test rectangles of the "[-]" buttons - one per terminal pane,
/// indexed in lock-step with `terminals`. Empty when only one terminal
/// is open (closing the last one would leave the pane empty, which we
/// explicitly forbid) or the pane is hidden.
terminal_close_buttons: Vec<Rect>,
/// Hit-test rectangles of the maximize / restore (`⛶`) buttons - one per
/// pane, in lock-step with `terminals`. Hidden panes hold an empty rect
/// so a button's position still names its terminal index.
terminal_max_buttons: Vec<Rect>,
/// Hit-test rectangles of the maximize-mode rail rows down the panel's
/// right edge, in lock-step with `terminals`. Clicking one hands that
/// terminal the maximized pane. Empty outside maximize mode.
terminal_rail_rects: Vec<Rect>,
/// The maximize rail's own column, so the wheel can scroll it. Empty
/// whenever the rail is not on screen.
terminal_rail_area: Rect,
/// First terminal shown in the rail when there are more terminals than
/// rows. Clamped during paint, so nothing else has to keep it honest.
terminal_rail_scroll: usize,
/// Which terminal the rail last scrolled into view, so the reveal fires
/// when the active pane changes and never fights a deliberate wheel.
terminal_rail_revealed: Option<usize>,
/// Hit-test rectangles of the pane name pills at each pane's top-left, in
/// lock-step with `terminals`. A press on one starts a drag-reorder;
/// hidden or unlabeled panes hold an empty rect. Empty with one terminal.
terminal_label_rects: Vec<Rect>,
/// Hit-test rectangles of the collapse (`‹`) buttons, in lock-step with
/// `terminals` (#313). A pane that is hidden, already collapsed, too
/// narrow for the glyph, or maximized holds an empty rect.
terminal_collapse_buttons: Vec<Rect>,
/// Extensions whose programs the user has allowed to run (the MCP
/// consent set, loaded once from prefs and kept current when a consent
/// is granted here), so a viewer's gate is a set lookup rather than a
/// prefs read per click, and a test can seed it without a prefs file.
consented_extensions: std::collections::BTreeSet<String>,
/// The config dir this app reads extensions and consent from. Carried
/// rather than re-derived so a test can point one app at a scratch dir
/// instead of mutating the process-wide environment, which this repo
/// has twice seen take an unrelated test down.
config_dir: PathBuf,
/// Where "open scrollback in an editor tab" writes the pane's coloured
/// scrollback so the rendered log view can index it from disk (#257).
/// `~/.cache/croft/scrollback` normally; a test points it at a temp dir.
scrollback_dir: PathBuf,
/// Hit-test rectangles of the one-column strips collapsed panes leave
/// behind, in lock-step with `terminals` (#313). Clicking anywhere down a
/// strip gives that pane its width back; expanded panes hold an empty
/// rect. The WHOLE strip is the target, not just the chevron: one column
/// is already a small thing to hit without also demanding the right row.
terminal_strip_rects: Vec<Rect>,
/// Index of the terminal being drag-reordered (grabbed by its pane label
/// or its maximize-rail row). The reorder is live: crossing another pane
/// or rail row moves the terminal there immediately, and this follows it.
terminal_drag_from: Option<usize>,
/// A left press that was FORWARDED to a pane because its child tracks
/// the mouse (#474), live until the release. The release goes to the
/// same pane, clamped to its grid if the pointer left it. What the drag
/// in between does depends on what the child asked for: motion reports
/// under 1002/1003, croft's own text selection anchored at the press
/// cell under click-only 1000 (Claude Code's mode), since a child that
/// never asked for motion cannot use the drag and the user still needs
/// to copy text out of it. The pane is named by `uid`, so a pane closed
/// or reordered mid-press is found again (or found gone) rather than
/// confused with whichever pane now holds its old index. Every later
/// event of the gesture -- motion, selection extension, release,
/// copy-on-select -- is aimed at THAT pane, never at the active one:
/// the keyboard can move the active pane while the button is held.
///
/// Same hole as `terminal_drag_from`: a modal that takes the screen
/// while the button is held swallows the mouse-up in `handle_mouse`'s
/// overlay gates, so the latch stays set until the next release. Two
/// consequences the older latch never had: the child keeps a button it
/// believes is down until its next click, and the auto-scroll tick keeps
/// standing down for a pane that is not active. Reaching it needs a
/// keystroke with the button held.
terminal_pointer_forwarded: Option<ForwardedPointer>,
/// True while one terminal pane fills the panel's width and the others
/// are listed in the right-side rail (the per-pane `⛶` button / Cmd+K M).
/// Distinct from `terminal_maximized`, which grows the panel vertically
/// over the editor. Only meaningful with 2+ terminals; closing down to
/// one resets it.
terminal_pane_maximized: bool,
/// Which tab the bottom panel group is showing (TERMINAL or PROBLEMS).
bottom_panel_tab: BottomPanelTab,
/// The PROBLEMS view: aggregated workspace diagnostics, projected from
/// `lsp_diagnostics`. Rendered into the panel content when its tab is active.
problems: crate::widgets::problems::ProblemsPanel,
/// The OUTPUT view: a read-only per-channel log viewer over the in-process
/// `crate::output` bus. Rendered into the panel content when its tab active.
output: crate::widgets::output::OutputPanel,
/// The PORTS view: the registry of detected loopback ports, fed by the
/// terminal output scrape and the periodic socket poll. Rendered into the
/// panel content when its tab is active.
ports: crate::widgets::ports::PortsPanel,
/// The CAPTURES view: output lines collected by `capture` triggers
/// (iTerm2's Capture Output); Enter / click jumps back to the line.
pub captures: crate::widgets::captures::CapturesPanel,
/// Transient click-only notification for a freshly detected browsable port,
/// offering forward / open. `None` when nothing is pending.
port_toast: Option<PortToast>,
/// Last time the socket poll was kicked off, so it fires on a low cadence
/// rather than every tick.
last_port_poll: std::time::Instant,
/// Socket-poll snapshots arrive here from a one-shot background thread (one
/// complete listener set per cycle), so the blocking `lsof`/`ps` never runs
/// on the event loop (keeps input at 0ms). A full set, not individual hits,
/// so the app can reconcile ports that stopped listening.
port_poll_rx: std::sync::mpsc::Receiver<PortPoll>,
/// Results of a running fleet command (#363), delivered off the event
/// loop. A fleet run waits on the network for up to `FLEET_TIMEOUT`, and
/// blocking the loop for that would freeze the editor — the user could
/// not scroll, type, or cancel while their fleet answered.
fleet_rx: std::sync::mpsc::Receiver<Vec<crate::fleet::HostResult>>,
fleet_tx: std::sync::mpsc::Sender<Vec<crate::fleet::HostResult>>,
/// True while a run is in flight, so a second invocation says so rather
/// than starting a competing fleet against the same hosts.
fleet_running: bool,
port_poll_tx: std::sync::mpsc::Sender<PortPoll>,
/// True while a poll thread is in flight, so cadence ticks don't pile up
/// overlapping `lsof` invocations.
port_poll_inflight: std::sync::Arc<std::sync::atomic::AtomicBool>,
/// Auto-label refresh for terminal panes: `(shell_pid, process_name)` pairs
/// resolved off the event loop, applied to the pane with that shell pid.
last_label_refresh: std::time::Instant,
label_rx: std::sync::mpsc::Receiver<Vec<(i32, String)>>,
label_tx: std::sync::mpsc::Sender<Vec<(i32, String)>>,
label_inflight: std::sync::Arc<std::sync::atomic::AtomicBool>,
/// Hit-test rect of the "PROBLEMS" tab in the panel tab strip. Empty when
/// the panel is hidden.
problems_tab_rect: Rect,
/// Hit-test rect of the "OUTPUT" tab in the panel tab strip. Empty when the
/// panel is hidden.
output_tab_rect: Rect,
/// Hit-test rect of the "PORTS" tab in the panel tab strip. Empty when the
/// panel is hidden.
ports_tab_rect: Rect,
/// Hit-test rect of the "CAPTURES" tab in the panel tab strip.
captures_tab_rect: Rect,
/// Hit-test rect of the "TERMINAL" tab in the panel tab strip. Empty when
/// the panel is hidden.
terminal_tab_rect: Rect,
/// Last pointer cell reported by a `Moved` event. Render-time hover
/// hit-testing (the Black theme's teal pill behind the terminal `-`/`+`
/// buttons) reads this instead of tracking enter/leave transitions.
pointer_cell: Option<(u16, u16)>,
/// Which activity-bar icon the pointer is currently over, if any. Drives
/// the hover variant of the icon (brightened glyph, no selection pill).
/// Changing it arms `overlays.activity.mark_dirty()` so the swapped
/// pre-baked image is re-emitted; it never triggers a re-bake.
hovered_activity_icon: Option<ActivityIcon>,
/// Which layout toolbar icon the pointer is over (0 = side bar, 1 = panel,
/// 2 = customize), so a hover change can re-emit the brighter image variant
/// like [`Self::hovered_activity_icon`] does for the activity bar.
hovered_layout_icon: Option<usize>,
/// On-screen keyboard for touch-only environments (Termux). `Some`
/// while the bottom keyboard band is visible; taps on its keys
/// synthesize `KeyEvent`s through `handle_key`, so they reach the
/// editor, terminal PTY, and modals exactly like hardware keystrokes.
osk: Option<crate::widgets::osk::Osk>,
/// True when taps in editable areas (editor text, terminal panes, the
/// Search input) auto-raise the on-screen keyboard. Armed on Termux,
/// where active mouse tracking permanently suppresses the native soft
/// keyboard; `CROFT_FORCE_OSK=1` arms it elsewhere for testing.
osk_auto: bool,
/// Total width / height of the right-hand content area, captured on
/// every render so a splitter drag can clamp to the live viewport.
last_content_width: u16,
last_content_height: u16,
/// Optional LSP orchestrator. None when LspManager::new failed at
/// startup (e.g. the background tokio runtime couldn't spawn); the
/// rest of the editor stays fully functional without it.
pub lsp: Option<crate::lsp::LspManager>,
/// Per-path snapshot of the last edit_seq we forwarded to the LSP
/// manager. sync_lsp diffs every tick against the current tabs to
/// emit did_open / did_change / did_close.
lsp_last_seen: std::collections::HashMap<PathBuf, u64>,
/// Newest semantic-token request generation already applied per path.
/// `seq` alone is not enough: two full requests can be in flight at the
/// same seq (`sync_lsp` plus a server-driven refresh), and the request
/// retry loop emits an EMPTY batch once its backoff is exhausted, so a
/// late empty loser would otherwise blank a good overlay and be written
/// to the content-keyed disk cache.
semantic_generation_seen: std::collections::HashMap<PathBuf, u64>,
/// Diagnostics store: per file, the latest set from each server. Servers
/// push complete sets via `textDocument/publishDiagnostics`, so the inner
/// map is keyed by server name (ty + ruff can both publish for one file)
/// and a server's entry is replaced wholesale on each batch (an empty
/// batch removes it). The merged value for the visible file is handed to
/// the editor; the store outlives tab switches so re-focusing a file shows
/// its squiggles again without waiting for the next server push.
/// Open-buffer paths as of the last PROBLEMS rebuild. Open Files scope
/// filters on this set, so the panel must refresh when the set changes —
/// not only when diagnostics do, or opening a file with stored
/// diagnostics would show nothing until unrelated churn happened by.
problems_open_set: std::collections::BTreeSet<PathBuf>,
lsp_diagnostics: std::collections::HashMap<
PathBuf,
std::collections::HashMap<String, Vec<crate::lsp::manager::Diagnostic>>,
>,
/// Live LSP work-done progress, keyed by server name (e.g. "rust-analyzer"
/// -> "Indexing 112/340 33%"). An entry exists only while that server has
/// an active task; the status bar surfaces it so a busy-priming server is
/// never mistaken for a dead one. Cleared on the server's `End`.
lsp_progress: std::collections::HashMap<String, String>,
/// Active completion popup, when a completion request has been issued
/// and the user hasn't dismissed the result. Populated by drain_lsp_completion
/// once the worker sends a CompletionResult back.
pub completion_popup: Option<crate::widgets::completion_popup::CompletionPopup>,
/// Most recent completion request id; later responses with a stale
/// id are dropped so a slow earlier response cannot clobber a fresh
/// one (e.g. user already moved past the original trigger).
completion_request_id: Option<u64>,
/// Signature Help (parameter hints) popup, anchored to the caret while the
/// user is inside a call. Populated by `drain_lsp_signature_help`.
pub signature_help_popup: Option<crate::widgets::signature_help_popup::SignatureHelpPopup>,
signature_help_request_id: Option<u64>,
/// (cursor_row, cursor_col, edit_seq) at the last signatureHelp request, so
/// the tick can re-query when the caret moves or the buffer changes while
/// the popup is open and close it once the caret leaves the call.
signature_help_anchor: Option<(usize, usize, u64)>,
hover: HoverDwell,
hover_popup: Option<crate::widgets::hover_popup::HoverPopup>,
hover_request_id: Option<u64>,
hover_anchor: Option<(u16, u16)>,
hover_word: Option<(usize, usize, usize)>,
/// Diagnostic block for the point a hover is anchored to, captured
/// synchronously when the dwell fires (server diagnostics already live in
/// the editor). Stacked above the async LSP hover reply by `compose_hover`
/// so a squiggle's message shows even when the server returns no type info.
hover_diagnostic: Option<String>,
/// Separate dwell timer for the editor tab strip. Hovering a tab for
/// `HOVER_DELAY` surfaces `tab_tooltip` with the tab's full path so
/// same-named files can be told apart. Kept distinct from `hover`
/// (which drives LSP word hover in the editor body) so the two never
/// fight over the same timer.
tab_hover: HoverDwell,
tab_tooltip: Option<crate::widgets::hover_popup::HoverPopup>,
tab_hover_idx: Option<usize>,
/// Shared dwell + popup for chrome button hints (search-panel actions and
/// toggles, activity-bar icons, …). One timer for all chrome controls,
/// keyed on the label so the dwell only restarts when the pointer crosses
/// to a different control; extending coverage to a new surface is one arm
/// in `ui_tooltip_at`.
ui_hover: HoverDwell,
ui_tooltip: Option<crate::widgets::hover_popup::HoverPopup>,
ui_tooltip_label: Option<&'static str>,
/// The chrome tooltip's final on-screen rect from the most recent render
/// (after the activity-bar shift / viewport clamp), or `None` when no
/// tooltip is showing. Read by the post-draw flush so the box can be
/// re-painted on top of any sidebar illustration it overlaps, since
/// OSC-1337 images composite above ratatui's text layer.
ui_tooltip_area: Option<Rect>,
definition_request_id: Option<u64>,
/// In-flight Peek Definition request (#115): same LSP request as the
/// jump, different consumer — the response opens the peek popup at the
/// caret instead of moving it.
peek_definition_request_id: Option<u64>,
/// The open peek popup, rendered beside `hover_popup` against the whole
/// frame; `peek_target` is where Enter jumps.
peek_popup: Option<crate::widgets::hover_popup::HoverPopup>,
peek_target: Option<(PathBuf, u32, u32)>,
declaration_request_id: Option<u64>,
type_definition_request_id: Option<u64>,
/// The `(active file, last-seen LSP edit seq)` the OUTLINE was last synced
/// to, so `sync_outline` re-requests symbols exactly once per tab switch or
/// edit batch. `None` seq means the file has no language server.
outline_synced: Option<(PathBuf, Option<u64>)>,
implementation_request_id: Option<u64>,
references_request_id: Option<u64>,
call_hierarchy_request_id: Option<u64>,
/// In-flight documentHighlight request, with the (path, row, col,
/// edit_seq) it was fired for so a reply for a caret or buffer state the
/// editor has since left is dropped.
occurrences_request: Option<(u64, PathBuf, usize, usize, u64)>,
/// In-flight linkedEditingRange request (#254): (id, path, edit_seq).
linked_request: Option<(u64, PathBuf, u64)>,
/// Last observed `(path, row, col, seq)` for the linked-editing
/// debounce, and when it settled — occurrences' idle pattern.
linked_observed: Option<(PathBuf, usize, usize, u64)>,
linked_observed_at: std::time::Instant,
/// In-flight Expand Selection request (#254). Extra Shift+Alt+Right
/// presses while the chains are in flight stack up and apply
/// together on drain; an `unsupported` verdict resolves them via
/// tree-sitter instead. The reply is gated on id + path + edit_seq
/// AND the exact cursor positions the request was fired for — a
/// caret move without an edit leaves `edit_seq` unchanged, and a
/// chain computed for the old caret must not apply at the new one.
selection_range_request: Option<PendingSelectionRanges>,
/// The caret state `tick_occurrences` last observed, and when it changed.
/// A caret resting on one spot for `OCCURRENCES_IDLE` fires one request.
occ_observed: Option<(PathBuf, usize, usize, u64)>,
occ_observed_at: std::time::Instant,
rename_request_id: Option<u64>,
/// In-flight prepareRename (#254): (id, path, row, col, edit_seq) —
/// the deferred rename prompt's context.
prepare_rename_request: Option<(u64, PathBuf, usize, usize, u64)>,
format_request_id: Option<u64>,
/// True when the in-flight format request is Format Selection (#254)
/// — the drain words its statuses accordingly.
format_request_selection: bool,
/// VS Code's `editor.formatOnType` (#254): typing a server trigger
/// character runs onTypeFormatting at the spot. Off by default.
format_on_type: bool,
/// In-flight on-type request: (id, the edit_seq it was computed
/// against, the tab's path). The reply applies only while that same
/// tab is active and its buffer has not moved since — `edit_seq` is
/// per-tab, so the seq alone cannot tell tabs apart.
on_type_request: Option<(u64, u64, PathBuf)>,
code_action_request_id: Option<u64>,
/// True when the in-flight code-action request is a `codeAction/resolve`
/// (the reply is one resolved action to apply directly) rather than the
/// initial `textDocument/codeAction` (whose reply opens the picker).
code_action_pending_resolve: bool,
/// The actions from the in-flight `textDocument/codeAction` reply, indexed
/// by the row `id` the Quick Fix [`ListPicker`] presents.
pending_code_actions: Vec<crate::lsp::manager::CodeActionItem>,
/// Review threads loaded onto a file, as `(the file, its threads)` (#366).
///
/// A SEPARATE field from `editor.comment_boxes`, which the render loop
/// rebuilds from `navigator_notes` on every frame — assigning review
/// threads there directly meant they were wiped before the user saw
/// one, while the status line still reported having loaded them.
///
/// Keyed by PATH because the merge runs on every frame: keyed only by
/// "whatever was loaded last", one file's objections would hang off the
/// next file's line numbers, against unrelated code. That is the harm
/// `threads_are_filtered_to_the_file_being_viewed` prevents on the
/// filter axis, and it re-enters through the lifetime axis if the boxes
/// outlive the buffer they describe.
///
/// Holds `Thread`s rather than finished `CommentBox`es so the geometry
/// is derived against the LIVE buffer each frame. `box_line` clamps a
/// box past the end back into view; computed once at load, that clamp
/// goes stale the moment the user edits, and the box it was protecting
/// becomes invisible again.
review_boxes: Option<(PathBuf, Vec<crate::review_threads::Thread>)>,
/// An open asciicast recording (#356): the writer, the file it appends
/// to, and when it started. `None` when nothing is being recorded.
recording: Option<(
crate::asciicast::Recorder,
std::fs::File,
std::time::Instant,
)>,
/// The terminal size the open recording last wrote (#356). A resize is
/// an `r` event, and a player that never receives one keeps rendering
/// the header's size — so a session resized mid-recording plays back
/// with every later frame wrapped at the wrong width.
recorded_size: (u16, u16),
/// The symbol a symbol tab is showing (#369): its name and the byte
/// range it spans, which follows edits through
/// `SymbolRange::after_edit`. `None` when no symbol tab is open.
symbol_tab: Option<(String, PathBuf, crate::symbol_range::SymbolRange)>,
/// The open history scrubber (#371), or `None` when the editor is
/// showing the live buffer. `Some` at `Position::Working` is a real
/// state: the scrubber is open and parked at the user's own edits.
scrubber: Option<crate::scrubber::Scrubber>,
/// A breakpoint croft set itself at the assertion the last run failed
/// on (#373), as `(file, 1-based line)`. It is NOT one of the user's
/// breakpoints: it is added to the launch set, rendered hollow-red like
/// any unverified one, and removed when the session ends — a debugger
/// that silently left breakpoints behind would be worse than one that
/// set none.
debug_temp_breakpoint: Option<(PathBuf, usize)>,
/// Human-readable note about that breakpoint, folded into whichever
/// launch message the user actually ends up seeing.
debug_temp_note: Option<String>,
/// Per-agent ledger of files changed while an agent was working (#345),
/// and the review baselines that decide which of them still need a
/// look.
pub agent_ledger: crate::agent_lane::AgentLedger,
/// When the running Fix with Navigator turn started (#374): the clock
/// its PROBLEMS-row spinner runs on, and the flag that keeps the main
/// loop repainting while it runs. `None` when no fix is streaming.
problems_fix_started: Option<std::time::Instant>,
/// The in-flight `.http` request's channel (#370). One at a time: the
/// worker owns the socket, the drain owns the tab, and a second send
/// while one runs is refused rather than queued.
http_run: Option<std::sync::mpsc::Receiver<HttpRunOutcome>>,
/// The presentation edits behind the open Change Color Presentation
/// picker (#254), indexed by row id; cleared after a pick.
pending_color_presentations: Vec<(String, Vec<crate::widgets::editor::TextSpanEdit>)>,
/// The (path, edit_seq) the pending presentations were computed
/// against; a pick is refused when either moved while the picker was
/// open (an FS-sync reload bumps the seq without user edits).
pending_color_context: Option<(PathBuf, u64)>,
/// In-flight colorPresentation request: (id, path, edit_seq).
color_presentations_request: Option<(u64, PathBuf, u64)>,
nav: NavHistory,
editor_vim_chord: EditorVimChord,
/// `Cmd+K` leader: armed when the user presses the prefix, holding the
/// instant it started so the next key within `CMD_K_LEADER_TIMEOUT`
/// completes a `Cmd+K`-prefixed chord (VS Code's two-key model). `None`
/// when no chord is in flight.
cmd_k_leader: Option<std::time::Instant>,
/// Native modal (vim-style) editing for the editor pane. When enabled it
/// supersedes the always-on `editor_vim_chord` convenience layer.
vim: crate::vim::VimState,
/// Last `f`/`t`/`F`/`T` target, replayed by `;` and `,`.
vim_last_find: Option<(crate::vim::FindKind, char)>,
/// Whether the active visual selection is linewise (`V`), so the pending
/// visual operator deletes/yanks whole lines.
vim_visual_line: bool,
shortcuts_modal: Option<crate::widgets::shortcuts::ShortcutsModal>,
shortcuts_hit_rect: Option<Rect>,
/// Status-bar clickable-segment hit rects, recorded each render. Empty when
/// the bar is hidden or the segment doesn't fit. Diagnostics → PROBLEMS;
/// encoding / EOL / language → their respective "change" pickers.
status_diag_rect: Rect,
status_indent_rect: Rect,
status_encoding_rect: Rect,
status_eol_rect: Rect,
status_language_rect: Rect,
connect_dialog: Option<crate::widgets::connect_dialog::ConnectDialog>,
connect_auth: Option<crate::remote_connect::SshAuth>,
install_session: Option<crate::install_session::InstallSession>,
/// Background self-update watcher, present only on a remote-launched
/// croft (gated by `CROFT_REMOTE_AUTOUPDATE`). Polls the install-stamp
/// the local cross-build writes when it finishes shipping a newer
/// binary, so the running croft can re-exec into it in place.
update_watch: Option<crate::update_watch::UpdateWatch>,
/// One-shot startup probe (#242): does the repo this binary was built
/// from now sit at a different commit/dirty state than the binary has
/// baked in? Local-only — a remote-launched croft is re-stamped by its
/// launcher instead. Dropped once its verdict is drained.
drift_probe: Option<crate::update_watch::DriftProbe>,
/// The repo's current hash label when the probe found drift ("def456",
/// "def456-dirty"). Arms the "F9 to rebuild" status-bar hint. Kept
/// through a running rebuild — the Idle guards hide the hint while it
/// runs, and a failure then re-arms F9 for a retry instead of
/// silently reverting the key to its breakpoint meaning.
local_drift: Option<String>,
/// Background `cargo install --path <repo>` reinstalling the local
/// croft after the user pressed F9 on a drift hint. Reported through
/// the same UpdateEvent lifecycle as the remote watcher.
self_install: Option<crate::update_watch::SelfInstall>,
/// One-shot startup check (#333): is a newer release published than
/// the version this binary carries? Local-only, throttled to a daily
/// network request by its cache file. Dropped once its verdict lands.
update_check: Option<crate::update_check::UpdateCheck>,
/// The "vX available" popup, present from the offer landing until the
/// user picks Update, Later, or (once staged) Relaunch.
update_toast: Option<UpdateToast>,
/// A background `cargo install --root <cache>/staged` of the offered
/// release. Reported through the same UpdateEvent lifecycle as the
/// remote watcher; the binary on PATH is untouched until Relaunch.
staged_install: Option<crate::update_check::StagedInstall>,
/// The staged release build's own lifecycle (#333). `update_status`
/// belongs to the remote watcher and the drift rebuild; the two cells
/// are never written by the other's producer, so a rebuild starting or
/// failing after the release landed cannot disarm Relaunch, and the
/// reverse. Readers that mean "any update" consult both.
staged_status: UpdateStatus,
update_status: UpdateStatus,
/// When a background self-update is in progress, the instant it started.
/// Drives the spinning update glyph in the status bar (and the redraw
/// cadence that animates it). `None` whenever no update is running.
update_spinner_start: Option<std::time::Instant>,
/// Set when an update landed and croft should re-exec after the main
/// loop unwinds and the alt-screen is surrendered. Read by `run`.
pending_reexec: bool,
overlays: OverlayManager,
/// VS Code-style Cmd+F in-editor find overlay. None when closed.
pub editor_find: Option<crate::widgets::editor_find::EditorFind>,
/// Cmd+F find-in-terminal overlay: searches the active pane's grid +
/// scrollback (like iTerm2 / Ghostty scrollback search). Reuses the
/// editor find widget; the replace row is never shown. None when closed.
pub terminal_find: Option<crate::widgets::editor_find::EditorFind>,
/// The pane index `terminal_find` opened on. Find is bound to that pane
/// like quick-select and copy mode: a gesture that activates a sibling
/// closes it (per-frame invariant in `sync_focus_flags`), so its
/// highlight and jump anchor never stray onto another pane's grid.
terminal_find_pane: usize,
/// The active terminal-find match as `(clock, abs_grid_line, col, len)`,
/// the anchor next/prev navigation walks from — the line is stamped with
/// the scroll-clock reading of the snapshot it was found in, and every
/// use re-bases it first, so output streaming under an open find bar
/// cannot leave navigation walking from a phantom row. None until the
/// first match.
terminal_find_match: Option<(i64, i32, usize, usize)>,
/// Ctrl+Shift+Space quick-select hint mode on the active terminal pane
/// (WezTerm's quick-select): every labelled match on the viewport plus
/// the label prefix typed so far. None when the mode is off.
pub terminal_quick_select: Option<QuickSelectState>,
/// Durable cross-session command history (atuin's model): every
/// finished command from a shell-integrated pane, with cwd / exit /
/// duration / timestamp, persisted as JSONL under the config dir.
pub command_history: crate::command_history::CommandHistory,
/// Ctrl+Shift+H search popup over [`Self::command_history`]. None when
/// closed.
pub command_history_popup: Option<crate::widgets::history_popup::HistoryPopup>,
/// Where the terminal-session snapshot lives
/// (`terminal_sessions.json`); a field so tests point it at a tempdir.
pub terminal_session_path: PathBuf,
/// The most recent terminal-session persistence failure, latched by
/// `save_terminal_session` and cleared by a later success; composed
/// into structural-change statuses by `terminal_status` so a corrupt
/// store is never silently ignored (#157/#158).
terminal_store_error: Option<String>,
/// The persisted folder-set store (#153); a field so tests redirect it.
pub workspace_folders_path: PathBuf,
/// A pane reorder is pending a session write. `move_terminal` runs once
/// per motion report during a drag, and the write is a full
/// read-modify-write of the session file plus a cwd syscall per pane, so
/// it is marked here and flushed once per tick instead of inline.
pub terminal_session_dirty: bool,
/// Ctrl+Shift+Y copy mode on the active terminal pane (WezTerm / tmux):
/// vi keys walk a cursor through the scrollback, v / V / Ctrl+V select,
/// y copies. None when the mode is off.
pub terminal_copy_mode: Option<CopyModeState>,
/// The user's terminal trigger set (`triggers.json`), pushed into every
/// pane on the drain tick and swapped wholesale on config reload.
pub triggers: std::sync::Arc<crate::triggers::TriggerSet>,
/// The agents croft recognises in a pane's foreground (#344): built in
/// plus `agents.json`, reloaded on save.
agents: crate::agents::AgentTable,
/// Agent transitions from the last sample, drained on the tick.
agent_events: std::collections::VecDeque<crate::agents::AgentEvent>,
/// Hit rect of the status bar's agents chip; empty when no agent is seated.
status_agents_rect: Rect,
/// User-defined problem matchers (#252): `matchers.json` (user config
/// dir + workspace `.croft/`), batch-scanned at the FinishedCommand
/// boundary alongside the built-in table. Swapped wholesale on reload.
pub matchers: std::sync::Arc<crate::problem_matchers::MatcherSet>,
/// The background-capable subset of `matchers`, pushed into every pane
/// on the drain tick exactly like the trigger set.
pub watch_set: std::sync::Arc<crate::problem_matchers::WatchSet>,
/// tasks.json `problemMatcher` assignments: pane uid → the matcher the
/// task running there declared. Exclusive for that pane's batch scans
/// (VS Code's model: an explicit matcher replaces the defaults).
task_matcher_by_pane:
std::collections::HashMap<u64, std::sync::Arc<crate::problem_matchers::CompiledMatcher>>,
/// Panes whose PROBLEMS batch a watch matcher currently owns. The
/// watcher eventually exiting fires a FinishedCommand whose whole-
/// history rescan would resurrect every error of every past cycle, so
/// that one scan is skipped (the flag clears with it — the pane's next
/// ordinary command scans normally).
watch_published_panes: std::collections::HashSet<u64>,
/// Broadcast input (Cmd+K I, iTerm2's Cmd+Opt+I): while on, shell-bound
/// keystrokes and pastes in the terminal go to every pane instead of
/// just the focused one. Session-scoped; never persisted.
pub broadcast_input: bool,
/// True while the "enable broadcast?" confirm popup is up (enabling is
/// gated: the classic footgun is typing into panes you forgot were
/// listening).
pub pending_broadcast_enable: bool,
/// A runnable fence waiting on the confirm popup (#353): destructive-
/// looking blocks and `{confirm}` fences ask before they type.
pending_run_block: Option<PendingRunBlock>,
/// Blocks whose output croft is still waiting for (#354).
pending_captures: Vec<PendingCapture>,
/// Captured output per fence, keyed by the pane name (which already
/// encodes the document's path under the workspace) and the fence
/// opener's source line. In memory for the session unless the fence
/// said `{persist}`.
block_outputs: std::collections::HashMap<(String, usize), crate::markdown::BlockOutput>,
/// Paint the terminal panes' right-edge arrival-time gutter ("Terminal:
/// Toggle Timestamps"). Session-scoped, off by default.
pub show_terminal_timestamps: bool,
/// Notification sinks from config.json `notifications` (#358).
notifier: crate::notifications::Notifier,
/// Compiled per-host pane accent rules from config.json `host_accents`.
/// First match wins.
host_accents: Vec<HostAccent>,
/// Recently closed terminal panes parked for the undo-close grace window
/// (Ghostty's undo, iTerm2's Undo Close Session): the PTY and child stay
/// alive but hidden until Cmd+K ⇧T restores the newest or the tick reaps
/// entries older than [`UNDO_CLOSE_GRACE`]. Newest last.
pub closed_terminals: Vec<ClosedTerminal>,
/// Recently closed editor tabs (VS Code "Reopen Closed Editor"): the
/// path plus enough view state (pin, cursor, scroll) to restore the tab
/// as it was. Newest last; Cmd+K ⇧W pops. Bounded at
/// [`CLOSED_TAB_STACK_CAP`]; entries whose file has since vanished are
/// skipped at reopen time.
pub closed_tabs: Vec<ClosedTab>,
/// VS Code-style Cmd+P / Ctrl+P quick-open file finder. None when
/// the modal is closed.
pub file_finder: Option<crate::widgets::file_finder::FileFinder>,
/// The range the last hinted quick-open pick installed, and the file it
/// was installed in: the next pick clears it if it is still the
/// selection there, and nothing else, so a selection the user made by
/// hand (or extended from it) survives a re-pick of the same file.
quick_open_range: Option<(PathBuf, crate::widgets::editor::EditorSelection)>,
/// VS Code-style Cmd+Shift+P / Ctrl+Shift+P command palette. None when
/// the modal is closed.
pub command_palette: Option<crate::widgets::command_palette::CommandPalette>,
/// VS Code-style Cmd+Shift+O / Ctrl+Shift+O "Go to Symbol in Editor"
/// picker (also Go to Line via a `:` prefix). None when the modal is closed.
pub go_to_symbol: Option<crate::widgets::symbol_picker::SymbolPicker>,
/// "Go to Symbol in Workspace" (`#` in Quick Open): query + merged
/// `workspace/symbol` results across every running language server.
pub workspace_symbols: Option<crate::widgets::workspace_symbols::WorkspaceSymbolPicker>,
/// The newest `workspace/symbol` request id; stale replies are dropped.
ws_symbols_request_id: Option<u64>,
/// Armed by a picker keystroke; `workspace_symbols_dispatch_due` fires
/// the request once the query has been still for the debounce window.
ws_symbols_pending: Option<std::time::Instant>,
/// Receiver for an in-flight MCP sidecar command's result (the off-thread
/// worker delivers one [`crate::mcp::McpOutcome`] then disconnects). `None`
/// when no extension command is running; polled each frame by `poll_mcp`.
mcp_rx: Option<std::sync::mpsc::Receiver<crate::mcp::McpOutcome>>,
/// While an extension command runs: when it started (drives the status-bar
/// spinner frame) and its human label (the animated badge text). Both `None`
/// when idle; set in `spawn_mcp_command`, cleared in `poll_mcp`.
mcp_started: Option<std::time::Instant>,
mcp_busy_label: Option<String>,
/// "Debug: Attach to Python Process" picker (PEP 768). None when closed.
/// Lists running CPython 3.14+ processes; selecting one spawns
/// `pdb -p <pid>` in a PTY.
pub process_picker: Option<crate::widgets::process_picker::ProcessPicker>,
/// Active debug session: a debugpy DAP launch. None when not debugging.
/// Polled each frame by [`App::poll_dap`], which mirrors the paused location
/// into `editor.stop_line`.
pub dap_session: Option<crate::dap::session::DapSession>,
/// launch.json configurations discovered for the picker (#250); refreshed
/// on every picker open so edits are picked up without a restart.
debug_configs: Vec<crate::dap::configs::DebugConfig>,
/// Compounds declared beside those configurations. Listed in the picker so
/// a workspace's compounds are visible; launching one needs the
/// multi-session model tracked in #310.
debug_compounds: Vec<crate::dap::configs::Compound>,
/// Name of the launch.json configuration F5 starts. `None` = the
/// zero-config "Debug active file" behavior.
selected_debug_config: Option<String>,
/// A config launch parked behind its `preLaunchTask`: the task runs in
/// its pane, and the FinishedCommand sweep launches (exit 0) or aborts
/// (non-zero) when the matching command completes. Replaced by a newer
/// F5, so only one launch can be pending.
pending_debug_launch: Option<PendingDebugLaunch>,
/// In-flight background `cargo test --no-run` for debug-a-test: the
/// receiver yields the picked binary (or the build error) and the test
/// name rides along for the launch. Drained per tick; a second request
/// while one is pending is refused with a status line.
pending_test_debug: Option<PendingTestDebug>,
/// Variable `variablesReference`s the user has expanded in the Variables
/// panel. Persisted across polls so re-fetched variables stay open.
pub debug_expanded: std::collections::HashSet<i64>,
/// Debugger watch expressions (#112), in display order. Session-scoped.
pub watch_exprs: Vec<String>,
/// Latest evaluate result per expression: `(value, success)`.
pub watch_vals: std::collections::HashMap<String, (String, bool)>,
/// The previous stop's values, for the changed-value highlight.
watch_prev: std::collections::HashMap<String, String>,
/// Armed by every `Stopped` event, consumed by the first
/// `InspectionUpdated` that follows: the baseline rotates exactly once
/// per stop. `InspectionUpdated` also fires for frame switches and
/// variable expansions within the same stop, and rotating on those
/// clobbered the baseline with the stop's own values — the changed
/// highlight never fired (#112).
watch_baseline_pending: bool,
/// Debug console log: program stdout/stderr (DAP output events) plus REPL
/// echoes and results. Capped; the tail is shown in the Run & Debug panel.
pub debug_console: Vec<String>,
/// True once the current/just-ended debug session stopped at least once
/// (breakpoint / step / exception). Drives the "exited without hitting a
/// breakpoint" end message. Reset when a new session starts.
debug_ever_stopped: bool,
/// zoxide-backed Explorer jump popup (Cmd+Z). None when closed. Opens
/// only from the Explorer pane, so it never collides with the editor's
/// Cmd+Z undo.
pub zoxide_jump: Option<crate::widgets::zoxide_jump::ZoxideJump>,
/// True while the zoxide popup is picking a folder to ADD to the
/// workspace (#147) rather than re-rooting; reset on close.
pub zoxide_add_folder: bool,
pub branch_picker: Option<crate::widgets::branch_picker::BranchPicker>,
/// Why the branch picker is open, so its Enter dispatches the right
/// verb (checkout vs merge vs rebase vs delete vs create-from base).
pub branch_purpose: BranchPurpose,
/// The Source Control "⋯" title menu (open/expanded state + hit rects).
pub scm_menu: crate::widgets::scm_menu::ScmMenuState,
/// Single-line input modal for SCM ops that need a typed value
/// (clone URL, branch rename, remote name/URL, tag name).
pub input_prompt: Option<crate::widgets::input_prompt::InputPrompt>,
/// Single-choice picker for SCM ops that act on one of a git-owned list
/// (apply/pop/drop a stash, delete a tag, remove/push-to a remote).
pub list_picker: Option<crate::widgets::list_picker::ListPicker>,
/// Privileged control channel to this session's host when running under
/// a persistent multiplayer session (docs/MULTIPLAYER.md); drives the
/// participants picker's grant/revoke/disconnect actions. None outside
/// a session host.
pub session_channel: Option<crate::session_host::InnerChannel>,
/// Roster last read from the session host's presence sidecar.
pub session_participants: Vec<crate::session_host::Participant>,
/// Whether the host's stale-image marker (#238) has already been
/// announced, so the status hint fires once per session, not per poll.
session_host_stale_seen: bool,
/// Multiplayer: the participant whose keystrokes are currently flowing
/// into this croft (from the host's typing attribution frames).
session_typist: Option<u64>,
/// Multiplayer: every participant's last-known caret, stashed when the
/// typist changes and restored when they type again, so interleaved
/// input drives per-participant carets in the shared buffer.
session_carets: std::collections::HashMap<u64, SessionCaret>,
/// Sidecar mtime at the last roster read, so the poll is a cheap stat.
session_presence_mtime: Option<std::time::SystemTime>,
/// Cadence gate for the presence poll (stat every 500ms, not every tick).
last_session_presence_poll: std::time::Instant,
/// Phase D independent-viewport collab session (docs/MULTIPLAYER.md):
/// per-file replicated documents over the workspace's collab relay.
/// None until the lazy connect in `poll_collab` succeeds.
collab: Option<crate::collab::CollabSession>,
/// The collab socket and role the launch tail exported, read once at
/// startup. None when this croft is not a collab participant.
collab_config: Option<(PathBuf, crate::collab::CollabRole)>,
/// Throttle for the lazy relay connect (the owner starts before any
/// guest has spawned the relay, so the first attempts fail by design).
last_collab_connect: Option<std::time::Instant>,
/// Per-file merge base harvested when the relay link died: the last
/// replicated text every participant agreed on. A reconnect bootstrap
/// replays only this side's offline delta against it (three-way with the
/// owner's snapshot), so owner edits made during the outage survive.
collab_offline_base: std::collections::HashMap<String, String>,
/// Peers' last-known carets by site id. Painted as ghost carets in the
/// peer's color when their file is active, with a name tag while the
/// caret is inside its fade window.
collab_carets: std::collections::HashMap<u64, CollabCaret>,
/// The last caret this croft broadcast, so an unmoved cursor sends
/// nothing on the tick.
collab_caret_sent: Option<(String, usize, usize)>,
/// Whether any caret name tag was inside its fade window last tick;
/// flipping to false is the one redraw an expiring tag needs.
collab_labels_visible: bool,
/// Some while an AI pilot (`croft pair`) streams an edit into a shared
/// file: drives the status badge and the gutter stop button; cleared by
/// the pilot's StreamState(inactive) broadcast.
collab_stream: Option<CollabStreamInfo>,
/// The resident navigator (docs/MULTIPLAYER.md): the in-process pilot
/// host, seated while the workspace's pair record is enabled. Dropping
/// it tears the seat down (revert, hang up, grace-kill).
pair_host: Option<crate::pair_host::PairHost>,
/// Where the workspace's pair activation record lives. A field so tests
/// point it at a tempdir instead of the real sessions dir.
pair_record_path: PathBuf,
/// The collab socket the navigator (and a self-appointed owner seat)
/// uses. A field for the same test reason.
pair_socket: PathBuf,
/// Path of the single-host lock (see [`pair_host_lock`]). A field for the
/// same test reason.
pair_host_lock_path: PathBuf,
/// Cadence gate for the pair-record stat (1s, not every tick).
last_pair_check: Option<std::time::Instant>,
/// Per-file (0-based row, body) snapshots of the navigator's anchored
/// notes, refreshed each tick from the host; drives the gutter ◆ marks
/// and the note popup.
navigator_notes: std::collections::HashMap<String, Vec<(u64, usize, String)>>,
/// The navigator's prose accumulated over the streaming turn; lands as
/// one comment box at the turn's origin when the turn ends (boxes are
/// the navigator's single voice — there is no OUTPUT channel for it).
pair_commentary_buf: String,
/// Where the current turn was invoked: (collab file key, 0-based row).
/// Anchors the turn's commentary box.
pair_turn_origin: Option<(String, usize)>,
/// Notes the navigator left since its turn started, so the TurnDone
/// status can surface them instead of overwriting the NoteAdded status.
pair_notes_this_turn: usize,
/// The file the turn's notes LAST landed in (anchors the turn's prose
/// when the invocation origin is unknown).
pair_last_noted_file: Option<String>,
/// Every file the turn's notes landed in: the TurnDone hint names the
/// file only when there is exactly one ("3 comments in b.rs" was a lie
/// when two of them sat in a.rs).
pair_noted_files: std::collections::BTreeSet<String>,
/// Held while this croft is the self-appointed navigator owner: exactly
/// one plain croft per workspace may host the pilot (and claim collab
/// owner site 1). Released by the OS on exit, so a crashed host hands off.
pair_host_lock: Option<crate::session::PairHostLock>,
/// Set when the pilot died or failed to seat: suppresses the 1s re-seat
/// so a broken claude (unauthenticated, missing, crashing) is not
/// respawned forever. Cleared when the record is deactivated OR
/// rewritten (any `croft pair` run re-arms seating, as the CLI
/// promises), so an explicit off/on (or toggle) re-activates. Matches
/// the LSP precedent: no auto-respawn within a session; a fresh croft
/// retries.
navigator_down: bool,
/// The pair record's raw bytes at the last 1s check: changed bytes mean
/// someone ran `croft pair` (even enabled→enabled — every write stamps
/// the record, so no rewrite is byte-identical) and clear
/// [`navigator_down`]. Content, not mtime: a same-grain rewrite on a
/// coarse-timestamp filesystem keeps its mtime.
last_pair_record_raw: Option<Vec<u8>>,
/// Which host-lock refusal has already been announced: the losing
/// window keeps polling for takeover every second, and re-announcing
/// each poll clobbered its status line forever (and forced a 1 Hz
/// repaint). The KIND is latched, not just the fact, so a refusal that
/// changes reason (an fd limit clears and another window now holds the
/// lock, or the reverse) is announced again rather than leaving a
/// message that is no longer true (#337). Per kind, not per message: an
/// open failure whose errno changes keeps the first announcement.
pair_lock_denied: Option<PairLockDenial>,
/// Proactive navigator looks (docs/MULTIPLAYER.md): a completed new
/// construct plus a typing pause hands the seated navigator a
/// comment-only turn on its own. Opt-out via
/// `Prefs::disable_proactive_navigator` / the palette toggle.
proactive_navigator_enabled: bool,
/// Per file, the edit_seq the proactive trigger last scanned: one
/// buffer state is parsed at most once, however long the pause lasts
/// and however often the driver switches tabs across visited files.
proactive_scanned: std::collections::HashMap<PathBuf, u64>,
/// Test seam: builds the PairHost from the config (the real path spawns
/// the claude CLI, which a test must never do).
#[cfg(test)]
#[allow(clippy::type_complexity)]
pair_spawn_override:
Option<Box<dyn Fn(&crate::pair::PairConfig) -> anyhow::Result<crate::pair_host::PairHost>>>,
/// Rolling log of git commands croft has run and their summaries, shown
/// read-only by the "Show Git Output" action (VS Code's Git channel).
pub git_output_log: Vec<String>,
/// Build diagnostics from the problem matchers (#119): finished-command
/// output scanned into PROBLEMS entries, keyed by resolved file path.
/// Paired with the producer that installed it (the pane uid, or
/// `PROJECT_CHECK_ID` for the whole-project sweep). Without the pairing
/// a re-run removed the whole entry and took the OTHER producer's rows
/// with it, and the second producer to reach a file could not clear its
/// own rows at all (#532).
build_diagnostics:
std::collections::HashMap<PathBuf, Vec<(u64, crate::widgets::problems::ProblemItem)>>,
/// Which files each terminal pane contributed, keyed by the pane's
/// STABLE uid (Vec positions shift on close/insert/reorder), so a
/// pane's next scanned command replaces its previous run's diagnostics
/// (VS Code clears a task's problems when the task re-runs).
build_diag_files_by_pane: std::collections::HashMap<u64, Vec<PathBuf>>,
/// True while the "Discard All Changes" confirmation modal is up.
pub pending_discard_all: bool,
/// The Replace All confirmation (#123): `(occurrences, files, dirty
/// files to be skipped)` counted without writing; the modal shows them,
/// Enter/Y commits, Esc cancels.
pending_replace_all: Option<(usize, usize, usize)>,
/// Cached workspace file index. Built lazily on first Cmd+P and
/// shared across reopens so repeated invocations are instant.
file_finder_index: Option<std::sync::Arc<Vec<crate::widgets::file_finder::FileEntry>>>,
/// Background-build receiver: App::new spawns a thread that walks
/// the workspace and sends the index here; Cmd+P opens against the
/// hot index instead of walking on the UI thread. None once the
/// index has been received (or if a build was never kicked off).
file_finder_index_rx:
Option<std::sync::mpsc::Receiver<Vec<crate::widgets::file_finder::FileEntry>>>,
/// Set when a rebuild was requested while one was already in flight.
/// poll_file_finder_index drains it on completion and re-kicks the
/// background walker so a long-running rebuild (multi-GB monorepo)
/// can never miss a later FS event that landed mid-walk.
file_finder_index_dirty: bool,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
enum VimOp {
#[default]
None,
G,
Y,
}
#[derive(Clone, Copy, Debug, Default)]
struct EditorVimChord {
op: VimOp,
count: usize,
}
impl EditorVimChord {
fn reset(&mut self) {
self.op = VimOp::None;
self.count = 0;
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct EditorImageLayout {
pub cell_x: u16,
pub cell_y: u16,
pub cell_w: u16,
pub cell_h: u16,
pub path: PathBuf,
/// Which page of a PDF is baked into this overlay (1 for anything else).
/// Part of the re-emit key so paging re-bakes on its own: without it the
/// path and rect are unchanged on a page turn and the stale picture stays
/// on screen unless every call site remembers to invalidate the layout.
pub page: u32,
/// Content stamp of the baked bytes ([`crate::widgets::editor::ImageView::generation`]).
/// Part of the re-emit key so a file rebuilt on disk re-bakes even when
/// the path, rect and page are all unchanged (a pdflatex rebuild lands
/// on the same page the reader was on).
pub generation: u64,
}
/// Re-emit key for the terminal pane's inline-image overlay: the cell rect
/// the picture occupies plus which image (per-pane `seq`) and pane it is.
/// Scrolling moves the anchor row, changing `cell_y` — a layout mismatch —
/// so the overlay clears and re-emits at the new position.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TerminalImageLayout {
pub cell_x: u16,
pub cell_y: u16,
pub cell_w: u16,
pub cell_h: u16,
pub seq: u64,
pub pane: usize,
}
/// Markdown-preview inline image placement (#176): geometry plus the
/// bake identity (path + mtime), so an externally rewritten picture
/// re-bakes and a pure scroll reuses the payload.
#[derive(Clone, Debug, PartialEq)]
pub struct MarkdownImageLayout {
pub cell_x: u16,
pub cell_y: u16,
pub cell_w: u16,
pub cell_h: u16,
pub path: PathBuf,
pub mtime_ms: u128,
}
/// Which edge of the editor pane the minimap strip sits on.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MinimapSide {
Left,
Right,
}
/// Width of the minimap strip in cells (the user picked the ~6-cell option).
const MINIMAP_WIDTH_CELLS: u16 = 6;
/// Minimum editor-text width that must remain after carving the strip; below
/// this the minimap is suppressed so the code never gets squeezed to nothing.
const MINIMAP_MIN_EDITOR_WIDTH: u16 = 44;
/// Maximum pixel height per source line in the minimap. Only kicks in for very
/// short files: it caps a six-line file to a compact sliver instead of
/// stretching those lines down the whole strip. Any file long enough that its
/// natural fit is already <= this (roughly > a screenful) fills the strip
/// exactly as a plain whole-file fit would, so normal files are unaffected.
const MINIMAP_MAX_LINE_PX: u32 = 6;
/// Cached full-document raster for the minimap. The expensive part (walking
/// every line's syntax spans) runs only when `sig` changes; scrolling reuses
/// `rgba` and just re-composites the viewport box on top.
struct MinimapBase {
rgba: Vec<u8>,
w: u32,
h: u32,
/// (path, edit_seq, canvas_w_px, canvas_h_px, bg) — a change rebakes.
sig: (Option<PathBuf>, u64, u32, u32, (u8, u8, u8)),
}
/// Re-emit key for the minimap overlay. Differs from the base sig: the
/// viewport fields move on scroll (recomposite, no rebake), the cell fields
/// move on resize/layout.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MinimapLayout {
cell_x: u16,
cell_y: u16,
cell_w: u16,
cell_h: u16,
top: usize,
rows: usize,
total: usize,
edit_seq: u64,
side: MinimapSide,
/// Theme editor bg; a change here (theme switch) forces a rebake.
bg: (u8, u8, u8),
/// Active selection `(start_row, end_row)`; a change recomposites the band.
selection: Option<(usize, usize)>,
}
/// One socket-poll result. `hits` is the pane-subtree scan that decides what to
/// surface; `listening` is every loopback port on the box, the only set that can
/// say a port has stopped. `None` when neither probe ran.
struct PortPoll {
hits: Vec<crate::port_detect::PortHit>,
listening: Option<std::collections::HashSet<u16>>,
}
/// The per-frame minimap overlays (everything not baked into the raster).
struct MinimapOverlay {
/// First visible line, and number of visible lines (the viewport box).
top: usize,
rows: usize,
total: usize,
light: bool,
/// Active selection `(start_row, end_row)`, marked by a thin left accent.
selection: Option<(usize, usize)>,
sel_rgb: (u8, u8, u8),
/// Pixel height the lines are mapped into (top-aligned); `<= h` for short
/// files so the viewport box and selection accent track the raster.
content_h: u32,
}
/// Composite the per-frame overlays onto the cached raster: the translucent
/// viewport box (style A) blending the visible-line rows toward white (dark
/// theme) or black (light), plus a thin left-edge accent in the selection color
/// marking the selected rows. The accent is deliberately tiny so the minimap's
/// look and feel is unchanged. Returns a fresh buffer.
fn composite_minimap_viewport(base: &[u8], w: u32, h: u32, ov: MinimapOverlay) -> Vec<u8> {
let MinimapOverlay {
top,
rows,
total,
light,
selection,
sel_rgb,
content_h,
} = ov;
let mut buf = base.to_vec();
if total == 0 || w == 0 || h == 0 {
return buf;
}
// Map a 0-based line index to a pixel row, matching `minimap_rgba`'s
// top-aligned `content_h` scale.
let row_y = |line: usize| (line as u64 * content_h as u64 / total as u64) as u32;
// Blend cols `x0..x1` of rows `r0..r1` toward `tint` by alpha `a` (0..=255).
let band = |buf: &mut [u8], r0: u32, r1: u32, x0: u32, x1: u32, tint: [u16; 3], a: u16| {
for y in r0..r1.min(h) {
for x in x0..x1.min(w) {
let idx = ((y * w + x) * 4) as usize;
for k in 0..3 {
let c = buf[idx + k] as u16;
buf[idx + k] = ((c * (255 - a) + tint[k] * a) / 255) as u8;
}
}
}
};
// Viewport box: a translucent fill plus a crisp bright border so "where am
// I" is unmistakable. Clamp the visible range to the line count so an
// all-visible short file's box covers only its content, not the empty
// strip below it.
let y0 = row_y(top);
let y1 = row_y((top + rows).min(total)).clamp(y0 + 1, h);
// Fill (toward white on dark, black on light), then the four edges at a
// much higher alpha so the rectangle outline reads against both the dark
// strip and the colored code.
let fill: [u16; 3] = if light { [0, 0, 0] } else { [255, 255, 255] };
let edge: [u16; 3] = if light { [20, 20, 20] } else { [235, 240, 250] };
band(&mut buf, y0, y1, 0, w, fill, 46);
band(&mut buf, y0, y0 + 1, 0, w, edge, 200); // top
band(&mut buf, y1.saturating_sub(1), y1, 0, w, edge, 200); // bottom
band(&mut buf, y0, y1, 0, 1, edge, 200); // left
band(&mut buf, y0, y1, w.saturating_sub(1), w, edge, 200); // right
// Selection: a thin (~2-3px) accent stripe down the left edge of the
// selected rows, in the selection color. Tiny on purpose.
if let Some((s, e)) = selection {
let r0 = row_y(s);
let r1 = row_y(e + 1).clamp(r0 + 1, h);
let aw = (w / 12).clamp(1, 3);
band(
&mut buf,
r0,
r1,
0,
aw,
[sel_rgb.0 as u16, sel_rgb.1 as u16, sel_rgb.2 as u16],
210,
);
}
buf
}
/// Encode an RGBA pixel buffer to PNG (the format `build_inline_image` wants).
fn rgba_to_png(rgba: Vec<u8>, w: u32, h: u32) -> Option<Vec<u8>> {
let img: image::RgbaImage = image::ImageBuffer::from_raw(w, h, rgba)?;
let mut out = Vec::new();
image::DynamicImage::ImageRgba8(img)
.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png)
.ok()?;
Some(out)
}
#[derive(Clone, Debug, PartialEq, Eq)]
enum SplitterDrag {
Sidebar,
Terminal,
/// Dragging a seam between two editor groups in the grid. Carries the seam
/// snapshot taken at mouse-down (stable for the drag's duration), so the
/// drag adjusts exactly that boundary in a grid of any depth.
EditorSeam(editor_layout::Seam),
}
/// Minimum width in cells of either editor column while split, so a drag
/// can't collapse a pane to nothing.
const EDITOR_SPLIT_MIN: u16 = 10;
/// Maximum pinned sticky-scroll header rows (VS Code's default is 5).
const STICKY_SCROLL_MAX: usize = 5;
const SIDEBAR_WIDTH_DEFAULT: u16 = 32;
const SIDEBAR_WIDTH_MIN: u16 = 12;
const TERMINAL_HEIGHT_MIN: u16 = 3;
const EDITOR_HEIGHT_MIN: u16 = 3;
/// Shortest frame that still shows the on-screen keyboard band; below this
/// the workspace would be unusably squeezed, so the band collapses instead.
const OSK_MIN_FRAME_HEIGHT: u16 = 16;
const RIGHT_PANE_MIN: u16 = 20;
/// Minimum width of the zoxide jump popup. The Explorer column it anchors
/// over is typically ~32 cells, too narrow to read frecency paths like
/// `~/Documents/platform/app/...`, so the box widens rightward to at least
/// this many cells (capped to the frame) while staying left-anchored on
/// the Explorer.
const ZOXIDE_JUMP_MIN_WIDTH: u16 = 56;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct WelcomeLayout {
cell_x: u16,
cell_y: u16,
cell_w: u16,
cell_h: u16,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ScpUpload {
pub alias: String,
pub src: PathBuf,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PendingRemotePull {
pub request_id: String,
pub src_display: String,
pub basename: String,
pub dest_dir: PathBuf,
pub started_at: std::time::Instant,
pub kind: RemotePullKind,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RemotePullKind {
/// File or directory copied from the user's local Mac into the
/// inbox; on completion the relay file is moved into `dest_dir`.
File,
/// Local-Mac clipboard contents staged at `<inbox>/<id>/clipboard.txt`;
/// on completion the bytes are pasted into the focused terminal.
Clipboard,
/// URL handed to the user's local Mac `open(1)`; on completion croft
/// just surfaces a status confirmation. No payload is shipped back.
Open,
/// Remote loopback port forwarded home over the SSH master; the `.ok`
/// payload carries the chosen local port, which croft records so the PORTS
/// panel can label and open it. `remote_port` is the port being forwarded.
Forward { remote_port: u16 },
}
const REMOTE_PULL_TIMEOUT: Duration = Duration::from_secs(120);
/// How long the port-detection toast lingers before auto-dismissing.
const PORT_TOAST_TTL: Duration = Duration::from_secs(12);
/// How often the socket-table poll runs (the output scrape is continuous;
/// this is the backstop for servers that announce nothing).
const PORT_POLL_INTERVAL: Duration = Duration::from_secs(3);
/// How often terminal pane labels are refreshed from their foreground process.
const TERMINAL_LABEL_INTERVAL: Duration = Duration::from_millis(1500);
struct RemoteLaunch {
host: String,
path: Option<String>,
adopted: Option<crate::remote::AdoptedMaster>,
}
fn split_at_char_count(s: &str, count: usize) -> (String, String) {
let left: String = s.chars().take(count).collect();
let right: String = s.chars().skip(count).collect();
(left, right)
}
fn wrap_cells_variable_width(text: &str, first_width: u16, rest_width: u16) -> Vec<String> {
let first_width = first_width.max(1) as usize;
let rest_width = rest_width.max(1) as usize;
let trimmed = text.trim();
if trimmed.is_empty() {
return vec![String::new()];
}
let mut lines = Vec::new();
let mut current = String::new();
for word in trimmed.split_whitespace() {
let mut remaining = word.to_string();
while !remaining.is_empty() {
let width = if lines.is_empty() {
first_width
} else {
rest_width
};
let sep = usize::from(!current.is_empty());
let remaining_len = remaining.chars().count();
let current_len = current.chars().count();
if current_len + sep + remaining_len <= width {
if sep == 1 {
current.push(' ');
}
current.push_str(&remaining);
break;
}
if !current.is_empty() {
lines.push(std::mem::take(&mut current));
continue;
}
let (head, tail) = split_at_char_count(&remaining, width);
lines.push(head);
remaining = tail;
}
}
if !current.is_empty() {
lines.push(current);
}
if lines.is_empty() {
vec![String::new()]
} else {
lines
}
}
/// Cells reserved at the left of each highlight row for the kind glyph plus
/// a one-cell gap before the summary text.
const WELCOME_NOTE_GUTTER: u16 = 2;
fn welcome_note_summary_width(block_w: u16) -> u16 {
block_w.saturating_sub(WELCOME_NOTE_GUTTER).max(1)
}
fn wrapped_welcome_note_summary(
note: &crate::release_notes::ReleaseNote,
block_w: u16,
) -> Vec<String> {
let w = welcome_note_summary_width(block_w);
wrap_cells_variable_width(note.summary, w, w)
}
fn welcome_note_row_height(note: &crate::release_notes::ReleaseNote, block_w: u16) -> u16 {
wrapped_welcome_note_summary(note, block_w).len().max(1) as u16
}
/// Width of the release-note card's content area for a card spanning
/// `block_w` cells: one border cell plus a one-cell inset on each side.
/// The height measure and the paint pass MUST both wrap through this —
/// measuring 2 cells wider than the paint made the paint produce more
/// wrapped lines than the card reserved rows for, and the overflow rows
/// were silently dropped, ending the note mid-sentence (#99).
fn welcome_card_inner_width(block_w: u16) -> u16 {
block_w.saturating_sub(4)
}
fn welcome_recents_height(notes: &[crate::release_notes::ReleaseNote], block_w: u16) -> u16 {
if notes.is_empty() {
return 0;
}
// Header row + one blank row + each highlight (which may wrap).
let notes_h: u16 = notes
.iter()
.map(|n| welcome_note_row_height(n, block_w))
.sum();
1 + 1 + notes_h
}
const WELCOME_TAGLINE: &str = "LIGHTWEIGHT. BLAZINGLY FAST. BUILT FOR DEVELOPERS.";
use crate::gradient::{GRAD_TL, GRAD_TR, POPUP_SEL_BG, paint_gradient_box, rgb_color};
fn open_url(url: &str) -> Result<()> {
#[cfg(target_os = "macos")]
let mut cmd = {
let mut c = std::process::Command::new("open");
c.arg(url);
c
};
#[cfg(target_os = "linux")]
let mut cmd = {
let mut c = std::process::Command::new("xdg-open");
c.arg(url);
c
};
#[cfg(target_os = "windows")]
let mut cmd = {
let mut c = std::process::Command::new("cmd");
c.args(["/C", "start", "", url]);
c
};
#[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
let mut cmd = {
let mut c = std::process::Command::new("open");
c.arg(url);
c
};
// Detach the opener's stdio: croft is on the alternate screen in raw
// mode, and `open`/`xdg-open` chatter ("No application knows how to
// open URL ...") would land straight on the grid.
cmd.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null());
cmd.spawn().with_context(|| format!("opening {url}"))?;
Ok(())
}
/// Short label for this machine, shown as the origin of a remote port in the
/// PORTS panel (`⇄ build-box`). Resolved once via `hostname`, falling back to a
/// generic word so the column is never blank.
fn remote_host_label() -> String {
static HOST: std::sync::OnceLock<String> = std::sync::OnceLock::new();
HOST.get_or_init(|| {
std::process::Command::new("hostname")
.output()
.ok()
.and_then(|o| String::from_utf8(o.stdout).ok())
.map(|s| s.trim().split('.').next().unwrap_or("remote").to_string())
.filter(|s| !s.is_empty())
.unwrap_or_else(|| String::from("remote"))
})
.clone()
}
/// What activating a PORTS row (Enter / double-click) should do, computed from
/// the entry and whether this is a remote (relay-active) session. Pure so it's
/// testable without spawning a browser or standing up a relay.
#[derive(Debug, Clone, PartialEq, Eq)]
enum PortOpenAction {
/// Remote port not yet forwarded: forward it home, then open.
Forward(u16),
/// A locally reachable address to open in the user's browser via the relay
/// — a remote session, so the opener must run on the local Mac, not the
/// headless remote.
OpenViaRelay(String),
/// A locally reachable address to open directly (local session).
OpenDirect(String),
/// Nothing actionable.
Nothing,
}
fn plan_port_open(entry: &crate::widgets::ports::PortEntry, relay_active: bool) -> PortOpenAction {
use crate::widgets::ports::PortOrigin;
if matches!(entry.origin, PortOrigin::Remote(_)) && !entry.forwarded {
return PortOpenAction::Forward(entry.port);
}
match entry.open_url() {
Some(url) if relay_active => PortOpenAction::OpenViaRelay(url),
Some(url) => PortOpenAction::OpenDirect(url),
None => PortOpenAction::Nothing,
}
}
impl App {
pub fn new(root: PathBuf) -> Result<Self> {
// Reap any js-debug adapter tree a previous croft left orphaned (a
// crash or force-quit skips `DapTransport`'s `Drop`, so the server +
// its detached watchdog get reparented to init and linger). Runs on a
// detached thread to stay off the time-to-first-frame critical path,
// and is safe even while another croft session is live: only processes
// reparented to init are touched. See `crate::dap::reaper`.
crate::dap::reaper::reap_orphaned_js_debug_async(std::time::Duration::ZERO);
let tree = FileTree::new(root.clone());
let search = SearchPanel::new(root.clone());
let remote = RemotePanel::new();
let source_control = SourceControlPanel::new();
let run_debug = RunDebugPanel::new();
let extensions = crate::widgets::extensions::ExtensionsPanel::new();
let outline = OutlinePanel::new();
let open_editors = OpenEditorsPanel::new();
let timeline = TimelinePanel::new();
let mut dependencies = DependenciesPanel::new();
// Detect the workspace's package ecosystems up front so the DEPENDENCIES
// section's visibility, ⋯-menu entry, and header are correct before the
// first sync tick. Re-detected on every re-root (see sync_explorer_panels).
let dep_ecosystems = crate::widgets::dependencies::detect_ecosystems(&root);
dependencies.set_header(crate::widgets::dependencies::header_label(&dep_ecosystems));
// Layered settings (#251): defaults ← user ← user-local ← workspace
// layers of the primary root, one merged view. Warnings (refused
// workspace keys, parse errors) land in the Settings OUTPUT channel.
let merged_settings = crate::config_layers::load_merged(Some(&root));
for w in &merged_settings.warnings {
crate::output::push("Settings", crate::output::OutputLevel::Warn, w);
}
let loaded_prefs = merged_settings.prefs.clone();
// Seed the log view's opening default from the saved preference
// BEFORE any log can be opened (#466): the toggle keeps the two in
// step afterwards, but a startup that set only `App::log_highlight`
// opened the first log highlighted despite a saved opt-out. Test-
// inert like the keymap and matcher loads below: the suite builds
// hundreds of apps on parallel threads, and an unguarded write to
// the process-wide default from each would race the tests that
// read it; those call `seed_log_highlight_default` explicitly.
seed_log_highlight_default_at_startup(!loaded_prefs.disable_log_highlight);
// Same treatment for keybindings: a row croft refused (an unknown
// command id, a gesture that can never fire, a reserved bare click)
// used to vanish silently, which reads as croft being broken rather
// than the binding being wrong (#259).
// Under test an empty keymap, exactly like the matcher set below: the
// developer's real keybindings.json must never steer app tests. That
// mattered less when a user keymap only rebound key chords, which no
// test dispatches; a mouse row now gates an early return at the top
// of `handle_mouse` that every mouse test flows through, so one line
// in a file the suite does not control could redirect thousands of
// tests. Tests that want a keymap assign `app.keymap` themselves.
let loaded_keymap = if cfg!(test) {
crate::keymap::Keymap::default()
} else {
crate::keymap::Keymap::load(&crate::keymap::keybindings_path())
};
// `Keymap::load` already reports its own warnings to OUTPUT ·
// Keybindings, so nothing to do here.
// Problem matchers (#252). Under test an empty set: the developer's
// real matchers.json must never steer app tests; tests inject their
// own. Compile warnings surface once, in OUTPUT · Matchers.
let matchers = std::sync::Arc::new(if cfg!(test) {
crate::problem_matchers::MatcherSet::default()
} else {
crate::problem_matchers::MatcherSet::load(
&crate::problem_matchers::matchers_path(),
Some(&crate::problem_matchers::workspace_matchers_path(&root)),
)
});
for w in &matchers.warnings {
crate::output::push("Matchers", crate::output::OutputLevel::Warn, w);
}
let watch_set = std::sync::Arc::new(matchers.watch_set());
let explorer_views = ExplorerViewVisibility::from_prefs(loaded_prefs.explorer_views);
let disabled_extensions = loaded_prefs.disabled_extensions.clone();
let (timeline_tx, timeline_rx) = std::sync::mpsc::channel();
let (history_done_tx, history_done_rx) = std::sync::mpsc::channel();
let (project_check_tx, project_check_rx) = std::sync::mpsc::channel();
let (project_hint_tx, project_hint_rx) = std::sync::mpsc::channel();
let (test_jump_tx, test_jump_rx) = std::sync::mpsc::channel();
let (graph_tx, graph_rx) = std::sync::mpsc::channel();
let (blame_tx, blame_rx) = std::sync::mpsc::channel();
let (deps_tx, deps_rx) = std::sync::mpsc::channel();
let (voice_tx, voice_rx) = std::sync::mpsc::channel();
let editor = EditorTabs::new();
// Bound before the first pane, so that pane's shell carries the
// socket like every later one. `spawn_with_preamble` reads
// `view_ipc::SOCK_PATH` at spawn time, so this ordering is what
// decides whether the startup pane can use `croft view` at all (#362).
let view_listener = Self::bind_view_socket();
let view_bind_error = VIEW_BIND_ERROR.lock().unwrap().take();
let term = PtyTerminal::new(&root).context("spawning terminal")?;
// Background git worker: every `git status` / `git status
// --porcelain` shell-out goes through this channel instead of
// running on the UI thread. The very first request seeds the
// status-bar badge; subsequent ones come from the FS watcher
// and from sidebar-icon clicks (see `refresh_source_control`,
// `refresh_git_status_debounced`). Removes the 15-50 ms
// input-to-paint stall that used to fire on every Source
// Control click.
let git = GitWorker::spawn(root.clone());
let welcome = WelcomeState::new();
let ext_index_refresh = Some(crate::mcp::registry_index::spawn_refresh());
let (search_query_tx, search_query_rx) = std::sync::mpsc::channel();
let (search_results_tx, search_results_rx) = std::sync::mpsc::channel();
let (port_poll_tx, port_poll_rx) = std::sync::mpsc::channel();
let (fleet_tx, fleet_rx) = std::sync::mpsc::channel();
let (label_tx, label_rx) = std::sync::mpsc::channel();
let (ssh_tx, ssh_rx) = std::sync::mpsc::channel();
let search_root = root.clone();
std::thread::spawn(move || {
crate::widgets::search::search_worker_loop(
search_root,
search_query_rx,
search_results_tx,
);
});
// Pre-build the Cmd+P file index on a background thread so the
// first Cmd+P keystroke does not stall the UI for the length
// of a workspace walk. The result is delivered via channel;
// open_file_finder calls poll_file_finder_index to consume it.
let (file_finder_index_tx, file_finder_index_rx) =
std::sync::mpsc::channel::<Vec<crate::widgets::file_finder::FileEntry>>();
let index_root = root.clone();
std::thread::spawn(move || {
let entries = crate::widgets::file_finder::build_file_index(&index_root);
let _ = file_finder_index_tx.send(entries);
});
let fs_watch = FsWatch::spawn(&root, &tree);
// Persisted layout preferences (Customize Layout popup). Skipped under
// test so the suite never reads/writes the developer's ~/.config,
// mirroring the theme load above.
let layout_prefs = if cfg!(test) {
crate::prefs::LayoutPrefs::default()
} else {
loaded_prefs.layout
};
let mut app = Self {
tree,
search,
remote,
source_control,
commit_graph: crate::widgets::commit_graph::CommitGraphPanel::new(),
graph_rx,
graph_revspec: None,
graph_tx,
graph_fetch_inflight: false,
graph_refetch_queued: false,
run_debug,
testing: crate::widgets::testing::TestingPanel::new(),
test_worker: crate::testing::worker::TestWorker::spawn(root.clone()),
extensions,
vscode_listed: Vec::new(),
disabled_extensions,
// Built from `loaded_keymap` above, which applies the same
// cfg!(test) guard main landed here independently: the
// developer's real keybindings.json must never steer app tests.
// Hoisted rather than inlined so the parse warnings can be
// reported once, in OUTPUT · Keybindings.
keymap: loaded_keymap,
last_mouse_pos: None,
macro_recording: None,
macro_last: None,
macro_registers: crate::macros::load(&crate::macros::macros_path()),
macro_replaying: false,
macros_path: crate::macros::macros_path(),
snippets: crate::snippets::SnippetSet::load(&crate::snippets::snippets_path()),
format_on_save: loaded_prefs.format_on_save,
copy_on_select: loaded_prefs.copy_on_select,
log_highlight: !loaded_prefs.disable_log_highlight,
secret_redaction: !loaded_prefs.disable_secret_redaction,
redaction_reveal_until: None,
auto_save: loaded_prefs.auto_save,
auto_save_on_focus_change: loaded_prefs.auto_save_on_focus_change,
last_focus_signature: None,
save_after_format: None,
outline,
open_editors,
timeline,
dependencies,
dep_ecosystems,
explorer_views,
settings_chain: merged_settings.chain,
settings_provenance: merged_settings.provenance,
timeline_rx,
timeline_tx,
history_done_rx,
history_done_tx,
project_check_rx,
project_check_tx,
project_check_running: false,
project_check_rows: 0,
project_hint_rx,
project_hint_tx,
project_check_hinted: false,
problems_project_scope: if loaded_prefs.problems_project_scope.is_empty() {
String::from("auto")
} else {
loaded_prefs.problems_project_scope.clone()
},
test_jump_rx,
test_jump_tx,
timeline_fetched: None,
blame_rx,
blame_tx,
blame_fetched: None,
inline_blame_enabled: !loaded_prefs.disable_inline_blame,
provenance_overlay: false,
indent_guides_enabled: !loaded_prefs.disable_indent_guides,
bracket_colors_enabled: !loaded_prefs.disable_bracket_colors,
whitespace_mode: crate::widgets::editor::WhitespaceMode::from_pref(
&loaded_prefs.render_whitespace,
),
diff_ws_default: crate::widgets::diff::DiffWhitespace::from_config(
&loaded_prefs.diff_ignore_whitespace,
),
inline_values_enabled: !loaded_prefs.disable_inline_values,
auto_close_pairs: !loaded_prefs.disable_auto_close_pairs,
inlay_hints_enabled: !loaded_prefs.disable_inlay_hints,
// Keep the suite off the user's real ~/.config/croft/history: a
// per-process temp root in test builds, the real dir otherwise.
history_root: if cfg!(test) {
std::env::temp_dir().join(format!("croft-test-history-{}", std::process::id()))
} else {
crate::history::history_dir()
},
history_restore: None,
deps_rx,
deps_tx,
deps_fetched: None,
voice_rx,
voice_tx,
voice_handle: None,
voice_canceling: false,
editor,
editor_layout: editor_layout::EditorLayout::single(),
force_save_armed: false,
terminals: vec![term],
active_terminal: 0,
perf: PerfHud::default(),
roots: crate::workspace::WorkspaceRoots::single(root.clone()),
sidebar_view: SidebarView::Explorer,
sidebar_areas: SidebarAreas::default(),
// Read the persisted theme from the real config only outside tests;
// under test fall back to the default so the suite stays hermetic
// and never depends on (nor mutates) the developer's ~/.config. This
// mirrors the cfg!(test) write-skip in `apply_theme`.
theme: if cfg!(test) {
crate::theme::Theme::default()
} else {
loaded_prefs.theme()
},
focus: Pane::Tree,
show_tree: true,
show_terminal: true,
terminal_maximized: false,
activity_bar_visible: layout_prefs.activity_bar,
status_bar_visible: layout_prefs.status_bar,
side_bar_position: layout_prefs.side_bar_position,
secondary_side_bar_visible: layout_prefs.secondary_side_bar,
panel_alignment: layout_prefs.panel_alignment,
quick_input_position: layout_prefs.quick_input_position,
zen_mode: false,
sidebar_auto_hide: loaded_prefs.sidebar_auto_hide,
sidebar_auto_hide_suspended: false,
sidebar_pinned_open: false,
sidebar_dwell: SidebarDwell::default(),
pre_zen: None,
layout_icon_areas: LayoutIconAreas::default(),
status: view_status(view_bind_error.as_deref()),
persistence_warning: remote_persistence_status(
is_remote_session(),
std::env::var_os("CROFT_SESSION_PERSISTENT").is_some(),
),
quit: false,
drop_to_local: false,
is_remote: is_remote_session(),
context_menu: None,
prompt: None,
fs_watch,
fs_watch_extra: Vec::new(),
git_extra: Vec::new(),
active_scm_root: root.clone(),
scm_pin: None,
scm_follow_root: root.clone(),
active_test_root: root.clone(),
pending_workspace_folders: None,
git_head_oids: std::collections::BTreeMap::new(),
git,
cursor_blink: CursorBlink::new(),
editor_click: ClickTracker::default(),
tree_click: ClickTracker::default(),
terminal_click: ClickTracker::default(),
modified_click: ModifiedClickTracker::default(),
ports_click: ClickTracker::default(),
terminal_select_autoscroll: None,
scrollbar_drag: None,
editor_hscrollbar_drag: false,
outline_scrollbar_drag: false,
open_editors_scrollbar_drag: false,
timeline_scrollbar_drag: false,
deps_scrollbar_drag: false,
testing_scrollbar_drag: false,
graph_scrollbar_drag: false,
welcome,
ext_index_refresh,
ext_index_manual_refresh: false,
search_query_tx,
search_results_rx,
cell_pixel: None,
last_pdf_wheel: None,
formula_overwrite_armed: false,
scm_change_badge: None,
scm_change_badge_count: 0,
explorer_unsaved_badge: None,
explorer_unsaved_count: 0,
remote_ports_badge: None,
remote_ports_count: 0,
testing_badge: None,
testing_badge_count: 0,
problems_badge_count: 0,
problems_badge_cell: None,
inline_protocol: crate::iterm2_inline::detect_inline_image_protocol(),
sixel_supported: false,
resize_repaint_needed: false,
minimap_visible: true,
minimap_side: MinimapSide::Right,
minimap_base: None,
minimap_img_rect: Rect::default(),
minimap_content_h: 0,
minimap_drag: false,
clipboard_reader: read_system_clipboard,
is_relay_session: !cfg!(test) && std::env::var_os("CROFT_RELAY_KEY").is_some(),
remote_launch: None,
pending_remote_launch_host: None,
pending_remote_launch_path: None,
ssh_offer: None,
ssh_offer_seen: std::collections::BTreeMap::new(),
ssh_rx,
ssh_tx,
remote_offer_disabled: loaded_prefs.disable_remote_offer,
remote_offer_excluded: loaded_prefs.remote_offer_excluded_hosts.clone(),
fleet_groups: loaded_prefs.fleet_groups.clone(),
remote_offer_refused: crate::remote::load_refused_hosts(
&crate::remote::refused_hosts_path(&croft_cache_dir()),
std::time::SystemTime::now(),
),
lane_agent: loaded_prefs.lane_agent.clone(),
lane_panes: std::collections::BTreeMap::new(),
tree_clipboard: None,
tree_typeahead: None,
compare_anchor: None,
last_frame_area: Rect::default(),
last_sidebar_area: None,
tree_drag: None,
pending_scp_uploads: Vec::new(),
pending_remote_pulls: Vec::new(),
view_listener,
pending_local_open: None,
pending_discard: None,
pending_revert_hunk: None,
run_tasks: Vec::new(),
last_task: None,
pending_terminal_warning: false,
commit_menu_open: false,
default_branch_label: None,
trust_local_browser: false,
sidebar_width: SIDEBAR_WIDTH_DEFAULT,
terminal_height: None,
splitter_drag: None,
editor_seams: Vec::new(),
sidebar_splitter_x: None,
terminal_splitter_y: None,
terminal_add_buttons: Vec::new(),
terminal_profile_buttons: Vec::new(),
terminal_close_buttons: Vec::new(),
terminal_collapse_buttons: Vec::new(),
consented_extensions: crate::prefs::Prefs::load_or_default().mcp_consented,
config_dir: crate::prefs::config_dir(),
scrollback_dir: crate::session_state::dirs_cache_croft().join("scrollback"),
terminal_strip_rects: Vec::new(),
terminal_max_buttons: Vec::new(),
terminal_rail_rects: Vec::new(),
terminal_rail_area: Rect::default(),
terminal_rail_scroll: 0,
terminal_rail_revealed: None,
terminal_label_rects: Vec::new(),
terminal_drag_from: None,
terminal_pointer_forwarded: None,
terminal_pane_maximized: false,
bottom_panel_tab: BottomPanelTab::Terminal,
problems: crate::widgets::problems::ProblemsPanel::new(),
output: crate::widgets::output::OutputPanel::new(),
ports: crate::widgets::ports::PortsPanel::new(),
captures: crate::widgets::captures::CapturesPanel::new(),
port_toast: None,
last_port_poll: std::time::Instant::now(),
port_poll_rx,
fleet_rx,
fleet_tx,
fleet_running: false,
port_poll_tx,
port_poll_inflight: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
last_label_refresh: std::time::Instant::now(),
label_rx,
label_tx,
label_inflight: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
problems_tab_rect: Rect::default(),
output_tab_rect: Rect::default(),
ports_tab_rect: Rect::default(),
captures_tab_rect: Rect::default(),
terminal_tab_rect: Rect::default(),
pointer_cell: None,
hovered_activity_icon: None,
hovered_layout_icon: None,
osk: None,
osk_auto: crate::iterm2_inline::detect_osk_auto(),
last_content_width: 0,
last_content_height: 0,
lsp: match crate::lsp::LspManager::new(root.clone()) {
Ok(m) => Some(m),
Err(e) => {
eprintln!("lsp manager init failed: {e}");
None
}
},
lsp_last_seen: std::collections::HashMap::new(),
semantic_generation_seen: std::collections::HashMap::new(),
problems_open_set: std::collections::BTreeSet::new(),
lsp_diagnostics: std::collections::HashMap::new(),
lsp_progress: std::collections::HashMap::new(),
completion_popup: None,
editor_vim_chord: EditorVimChord::default(),
cmd_k_leader: None,
vim: crate::vim::VimState::new(),
vim_last_find: None,
vim_visual_line: false,
shortcuts_modal: None,
shortcuts_hit_rect: None,
status_diag_rect: Rect::default(),
status_indent_rect: Rect::default(),
status_encoding_rect: Rect::default(),
status_eol_rect: Rect::default(),
status_language_rect: Rect::default(),
connect_dialog: None,
connect_auth: None,
install_session: None,
update_watch: None,
drift_probe: None,
local_drift: None,
self_install: None,
update_check: None,
update_toast: None,
staged_install: None,
staged_status: UpdateStatus::Idle,
update_status: UpdateStatus::Idle,
update_spinner_start: None,
pending_reexec: false,
overlays: {
let mut overlays = OverlayManager::default();
overlays.welcome.mark_dirty();
overlays.hero.mark_dirty();
overlays.activity.mark_dirty();
overlays
},
editor_find: None,
terminal_find: None,
terminal_find_pane: 0,
terminal_find_match: None,
terminal_quick_select: None,
// Under test, both durable stores point at per-process scratch
// files so app tests that run commands or split panes can never
// touch (or race on) the user's real history / session files;
// tests that exercise the stores inject their own paths.
command_history: crate::command_history::CommandHistory::load(&if cfg!(test) {
std::env::temp_dir().join(format!(
"croft-test-command-history-{}.jsonl",
std::process::id()
))
} else {
crate::command_history::history_path()
}),
command_history_popup: None,
terminal_session_dirty: false,
terminal_store_error: None,
terminal_session_path: if cfg!(test) {
std::env::temp_dir().join(format!(
"croft-test-terminal-sessions-{}.json",
std::process::id()
))
} else {
crate::terminal_session::path()
},
workspace_folders_path: if cfg!(test) {
std::env::temp_dir().join(format!(
"croft-test-workspace-folders-{}.json",
std::process::id()
))
} else {
crate::workspace::folders_store_path()
},
terminal_copy_mode: None,
triggers: load_trigger_set(!loaded_prefs.disable_secret_redaction),
agents: crate::agents::AgentTable::load(&crate::agents::agents_path()),
agent_events: std::collections::VecDeque::new(),
status_agents_rect: Rect::default(),
matchers,
watch_set,
task_matcher_by_pane: std::collections::HashMap::new(),
watch_published_panes: std::collections::HashSet::new(),
broadcast_input: false,
pending_broadcast_enable: false,
pending_run_block: None,
pending_captures: Vec::new(),
block_outputs: std::collections::HashMap::new(),
show_terminal_timestamps: false,
notifier: crate::notifications::Notifier::new(&loaded_prefs.notifications),
host_accents: compile_host_accents(&loaded_prefs.host_accents),
closed_terminals: Vec::new(),
closed_tabs: Vec::new(),
file_finder: None,
quick_open_range: None,
command_palette: None,
go_to_symbol: None,
workspace_symbols: None,
ws_symbols_request_id: None,
ws_symbols_pending: None,
mcp_rx: None,
mcp_started: None,
mcp_busy_label: None,
process_picker: None,
dap_session: None,
debug_configs: Vec::new(),
debug_compounds: Vec::new(),
selected_debug_config: None,
pending_debug_launch: None,
pending_test_debug: None,
debug_expanded: std::collections::HashSet::new(),
watch_exprs: Vec::new(),
watch_vals: std::collections::HashMap::new(),
watch_prev: std::collections::HashMap::new(),
watch_baseline_pending: false,
debug_console: Vec::new(),
debug_ever_stopped: false,
zoxide_jump: None,
zoxide_add_folder: false,
branch_picker: None,
branch_purpose: BranchPurpose::Checkout,
scm_menu: crate::widgets::scm_menu::ScmMenuState::default(),
input_prompt: None,
list_picker: None,
session_channel: crate::session_host::InnerChannel::from_env(),
session_participants: Vec::new(),
session_host_stale_seen: false,
session_typist: None,
session_carets: std::collections::HashMap::new(),
session_presence_mtime: None,
last_session_presence_poll: std::time::Instant::now(),
collab: None,
collab_config: crate::collab::CollabChannel::env_config(),
last_collab_connect: None,
collab_offline_base: std::collections::HashMap::new(),
collab_carets: std::collections::HashMap::new(),
collab_caret_sent: None,
collab_stream: None,
pair_host: None,
pair_record_path: crate::session::pair_record_path(&root),
pair_socket: crate::session::collab_socket_path(&root),
pair_host_lock_path: crate::session::pair_host_lock_path(&root),
last_pair_check: None,
navigator_notes: std::collections::HashMap::new(),
pair_commentary_buf: String::new(),
pair_turn_origin: None,
pair_notes_this_turn: 0,
pair_last_noted_file: None,
pair_host_lock: None,
navigator_down: false,
last_pair_record_raw: None,
pair_lock_denied: None,
pair_noted_files: std::collections::BTreeSet::new(),
proactive_navigator_enabled: !loaded_prefs.disable_proactive_navigator,
proactive_scanned: std::collections::HashMap::new(),
#[cfg(test)]
pair_spawn_override: None,
collab_labels_visible: false,
git_output_log: Vec::new(),
build_diagnostics: std::collections::HashMap::new(),
build_diag_files_by_pane: std::collections::HashMap::new(),
pending_discard_all: false,
pending_replace_all: None,
file_finder_index: None,
file_finder_index_rx: Some(file_finder_index_rx),
file_finder_index_dirty: false,
completion_request_id: None,
signature_help_popup: None,
signature_help_request_id: None,
signature_help_anchor: None,
rename_request_id: None,
prepare_rename_request: None,
format_request_id: None,
format_request_selection: false,
format_on_type: loaded_prefs.format_on_type,
on_type_request: None,
code_action_request_id: None,
code_action_pending_resolve: false,
pending_code_actions: Vec::new(),
review_boxes: None,
recording: None,
recorded_size: (0, 0),
symbol_tab: None,
scrubber: None,
debug_temp_breakpoint: None,
debug_temp_note: None,
agent_ledger: crate::agent_lane::AgentLedger::new(),
problems_fix_started: None,
http_run: None,
pending_color_presentations: Vec::new(),
pending_color_context: None,
color_presentations_request: None,
hover: HoverDwell::default(),
hover_popup: None,
hover_request_id: None,
hover_anchor: None,
hover_word: None,
hover_diagnostic: None,
tab_hover: HoverDwell::default(),
tab_tooltip: None,
tab_hover_idx: None,
ui_hover: HoverDwell::default(),
ui_tooltip: None,
ui_tooltip_label: None,
ui_tooltip_area: None,
definition_request_id: None,
peek_definition_request_id: None,
peek_popup: None,
peek_target: None,
outline_synced: None,
declaration_request_id: None,
type_definition_request_id: None,
implementation_request_id: None,
references_request_id: None,
call_hierarchy_request_id: None,
occurrences_request: None,
linked_request: None,
linked_observed: None,
linked_observed_at: std::time::Instant::now(),
selection_range_request: None,
occ_observed: None,
occ_observed_at: std::time::Instant::now(),
nav: NavHistory::default(),
};
// Initialise the per-pane focus/gradient flags to match the starting
// pane (Tree) and persisted theme. Without this, the explorer boots
// focused-but-not-gradient: the Black-theme gradient border only
// arms on the first focus change because nothing ran the sync at
// construction time.
// #256: the PROBLEMS scope comes from prefs; set it after
// construction so the panel keeps one plain `new()`.
app.problems.scope =
crate::widgets::problems::ProblemScope::from_config(&loaded_prefs.problems_scope);
app.sync_focus_flags();
// Seed the highlighter with the persisted theme's code palette so a
// file opened before the first theme switch already highlights in the
// active theme's colors (not the Base16 default).
crate::highlight::set_syntax_palette(app.theme.syntax());
// Pre-warm the workspace's evident language servers (Cargo.toml →
// rust-analyzer, and so on), VS Code's `workspaceContains`
// activation: the cold indexing overlaps with the user browsing
// the tree instead of starting only at the first file open (#27).
// The send is one channel post; the spawns run on the LSP worker.
if let Some(lsp) = app.lsp.as_ref() {
lsp.prewarm_workspace();
}
Ok(app)
}
/// Detect inline-image support via env vars only — no stdin queries, no
/// raw-mode contention. Queries the terminal cell pixel size via
/// crossterm's `window_size` (TIOCGWINSZ ioctl, no stdin involvement).
/// SSH PTYs often report only rows/columns and leave pixel dimensions
/// as zero, so fall back to a sane 10×20 cell estimate; OSC-1337 still
/// scales the image to the requested cell rectangle.
/// The active theme's background as a fully-opaque image pixel. Used to
/// fill the OSC-1337 icon/hero canvases so the baked PNGs sit on the same
/// color as the surrounding (session-bg) panes, with no visible seam.
fn theme_bg_pixel(&self) -> image::Rgba<u8> {
let (r, g, b) = self.theme.editor_bg_rgb();
image::Rgba([r, g, b, 0xff])
}
/// True when the host terminal can render inline images via either
/// protocol. Gates the bake/emit path; the iTerm2-only `SetColors` /
/// `Color::Reset` tricks stay behind `detect_iterm2_inline_support`.
fn inline_images_enabled(&self) -> bool {
self.inline_protocol != crate::iterm2_inline::InlineImageProtocol::None
}
/// Whether evicting stale inline images requires wiping the whole screen.
/// iTerm2 OSC-1337 and sixel graphics live in the normal cell buffer, so
/// only a `\x1b[2J` removes their cached cells. Kitty graphics live on
/// their own layer and are deleted by [`Self::evict_inline_images_on_clear`]
/// without touching a single text cell - wiping the screen there blanks
/// the whole app for an SSH round trip on every latch (the "croft blinks
/// while I type" bug), so the Kitty path must never `terminal.clear()`.
pub fn image_eviction_needs_screen_wipe(&self) -> bool {
self.inline_protocol != crate::iterm2_inline::InlineImageProtocol::Kitty
}
/// Kitty graphics live on a layer that survives the `\x1b[2J` the main
/// loop fires to evict iTerm2's image cells, so on the Kitty path that
/// same clear frame must also delete every placement; the visible
/// overlays re-emit themselves on the following post-draw flush. No-op on
/// the iTerm2 path, where the clear already evicted the cached cells.
pub fn evict_inline_images_on_clear(&self) {
use std::io::Write;
if self.inline_protocol == crate::iterm2_inline::InlineImageProtocol::Kitty {
let mut out = stdout();
let _ = out.write_all(crate::iterm2_inline::delete_all_kitty_images().as_bytes());
let _ = out.flush();
}
}
/// One-shot consumer for [`Self::resize_repaint_needed`]: the main loop
/// answers `true` with an unconditional `terminal.clear()` on every
/// protocol, Kitty included. Resize is not image eviction: the wipe here
/// restores text a WINCH (window resize or dtach reattach) invalidated,
/// and it never fires while the user merely types.
pub fn consume_resize_repaint(&mut self) -> bool {
std::mem::take(&mut self.resize_repaint_needed)
}
pub fn init_graphics(&mut self) {
// Env-advertised protocols (iTerm2/Kitty) win; otherwise fall back to a
// sixel host detected earlier by the DA1 probe. Re-derived here so the
// theme-switch re-bake keeps the right protocol, and `sixel_supported`
// carries the probe result across the env re-detect (sixel has none).
self.inline_protocol = match crate::iterm2_inline::detect_inline_image_protocol() {
crate::iterm2_inline::InlineImageProtocol::None if self.sixel_supported => {
crate::iterm2_inline::InlineImageProtocol::Sixel
}
other => other,
};
if !self.inline_images_enabled() {
return;
}
let Ok(ws) = crossterm::terminal::window_size() else {
return;
};
if ws.columns == 0 || ws.rows == 0 {
return;
}
let (cell_w, cell_h) = if ws.width > 0 && ws.height > 0 {
(
(ws.width / ws.columns).max(1) as u32,
(ws.height / ws.rows).max(1) as u32,
)
} else {
FALLBACK_CELL_PIXEL
};
self.cell_pixel = Some((cell_w, cell_h));
// OSC-1337 hero will own the no-repo illustration cells; the
// widget skips its ASCII fallback so resize doesn't flash old
// text through the image.
self.source_control.inline_hero_image_active = true;
let canvas_w = cell_w * ACTIVITY_BAR_WIDTH as u32;
let canvas_h = cell_h * ACTIVITY_ICON_HEIGHT as u32;
let is_tmux = crate::iterm2_inline::detect_tmux();
let w_cells = ACTIVITY_BAR_WIDTH;
let h_cells = ACTIVITY_ICON_HEIGHT;
let icon_bg = self.theme_bg_pixel();
// The bar background above is the theme's; so is the ink painted on
// it. A baked icon can't route its colors through `Theme::ui` the way
// a styled cell does, so the palette is resolved once here and rides
// into every compose call (issue #225).
let icon_ink = crate::iterm2_inline::IconInk::new(
self.theme.activity_icon_inactive_rgb(),
self.theme.activity_icon_active_rgb(),
self.theme.activity_icon_pill_rgb(),
);
let protocol = self.inline_protocol;
// The activity-bar icons are codicon SVGs, rasterised at the exact icon
// pixel size (no multi-MB raster decode, crisp at any cell size). `id`
// is the icon's stable per-slot Kitty image/placement id (shared by its
// active and inactive variants so swapping one for the other replaces
// the placement in place); ignored on the iTerm2 path.
let encode = |src_svg: &[u8],
state: crate::iterm2_inline::IconState,
off_y_bias: i64,
id: u32|
-> Option<String> {
let baked = crate::iterm2_inline::compose_icon_svg(
src_svg, canvas_w, canvas_h, state, icon_ink, icon_bg, off_y_bias,
)?;
// preserveAspectRatio=0: stretch to exactly fill 4×2 cells.
// Since the canvas was composed at exactly that pixel size,
// there's no actual scaling and the codicon's square area
// remains a true square on screen.
let raw = crate::iterm2_inline::build_inline_image(
protocol, &baked, w_cells, h_cells, false, id,
)?;
Some(crate::iterm2_inline::maybe_tmux_wrap(
protocol, is_tmux, raw,
))
};
// View icons render dead-centered in their cell block; the gear gets a
// downward bias so it bottom-aligns within its (bottom-inset) block,
// shaving the canvas's bottom padding off the gap above the status bar.
// The value need only exceed the no-clip ceiling; `compose_icon_svg`
// clamps it, so this stays correct at any cell size.
let gear_off_y_bias = canvas_h as i64;
use crate::iterm2_inline as ki;
// Bake all three states per icon up front (selected / hovered / resting)
// so the render path only ever swaps which pre-encoded sequence it emits
// — a hover never triggers a re-bake, just a different cached string.
let bake = |src: &[u8], off_y_bias: i64, id: u32| -> Option<(String, String, String)> {
Some((
encode(src, ki::IconState::Active, off_y_bias, id)?,
encode(src, ki::IconState::Inactive, off_y_bias, id)?,
encode(src, ki::IconState::Hovered, off_y_bias, id)?,
))
};
// Customize Layout toolbar icons: baked OPAQUE on the editor bg at the
// 4×2-cell box so they paint IN FRONT of the container's top line
// (the line sits behind the icon's solid background). `Inactive` is the
// muted resting grey; `Hovered` is the bright variant emitted while the
// pointer rests on the icon. The side-bar / panel ids swap their on/off
// image in place.
let layout_canvas_w = cell_w * LAYOUT_ICON_CELLS_W as u32;
let layout_canvas_h = cell_h * LAYOUT_ICON_CELLS_H as u32;
let bake_layout = |src_svg: &[u8], state: ki::IconState, id: u32| -> Option<String> {
let baked = crate::iterm2_inline::compose_icon_svg(
src_svg,
layout_canvas_w,
layout_canvas_h,
state,
icon_ink,
icon_bg,
0,
)?;
let raw = crate::iterm2_inline::build_inline_image(
protocol,
&baked,
LAYOUT_ICON_CELLS_W,
LAYOUT_ICON_CELLS_H,
false,
id,
)?;
Some(crate::iterm2_inline::maybe_tmux_wrap(
protocol, is_tmux, raw,
))
};
let bake_layout_pair = |src: &[u8], id: u32| -> Option<(String, String)> {
Some((
bake_layout(src, ki::IconState::Inactive, id)?,
bake_layout(src, ki::IconState::Hovered, id)?,
))
};
let layout_imgs = (|| {
let (so, soh) =
bake_layout_pair(ki::LAYOUT_SIDEBAR_ON_SRC_SVG, ki::KITTY_ID_LAYOUT_SIDEBAR)?;
let (sf, sfh) =
bake_layout_pair(ki::LAYOUT_SIDEBAR_OFF_SRC_SVG, ki::KITTY_ID_LAYOUT_SIDEBAR)?;
let (po, poh) =
bake_layout_pair(ki::LAYOUT_PANEL_ON_SRC_SVG, ki::KITTY_ID_LAYOUT_PANEL)?;
let (pf, pfh) =
bake_layout_pair(ki::LAYOUT_PANEL_OFF_SRC_SVG, ki::KITTY_ID_LAYOUT_PANEL)?;
let (cu, cuh) =
bake_layout_pair(ki::LAYOUT_CUSTOMIZE_SRC_SVG, ki::KITTY_ID_LAYOUT_CUSTOMIZE)?;
Some((so, soh, sf, sfh, po, poh, pf, pfh, cu, cuh))
})();
if let (
Some((ea, ei, eh)),
Some((sa, si, sh)),
Some((sca, sci, sch)),
Some((ra, ri, rh)),
Some((rda, rdi, rdh)),
Some((exta, exti, exth)),
Some((tsta, tsti, tsth)),
Some((gea, gei, geh)),
Some((lso, lsoh, lsf, lsfh, lpo, lpoh, lpf, lpfh, lcu, lcuh)),
) = (
bake(ki::EXPLORER_SRC_SVG, 0, ki::KITTY_ID_EXPLORER),
bake(ki::SEARCH_SRC_SVG, 0, ki::KITTY_ID_SEARCH),
bake(ki::SOURCE_CONTROL_SRC_SVG, 0, ki::KITTY_ID_SOURCE_CONTROL),
bake(ki::REMOTE_SRC_SVG, 0, ki::KITTY_ID_REMOTE),
bake(ki::RUN_DEBUG_SRC_SVG, 0, ki::KITTY_ID_RUN_DEBUG_BAR),
bake(ki::EXTENSIONS_SRC_SVG, 0, ki::KITTY_ID_EXTENSIONS),
bake(ki::TESTING_SRC_SVG, 0, ki::KITTY_ID_TESTING),
bake(
ki::SETTINGS_GEAR_SRC_SVG,
gear_off_y_bias,
ki::KITTY_ID_SETTINGS,
),
layout_imgs,
) {
self.overlays.activity.set_images(ActivityBarImages {
explorer_active: ea,
explorer_inactive: ei,
explorer_hovered: eh,
search_active: sa,
search_inactive: si,
search_hovered: sh,
source_control_active: sca,
source_control_inactive: sci,
source_control_hovered: sch,
remote_active: ra,
remote_inactive: ri,
remote_hovered: rh,
run_debug_active: rda,
run_debug_inactive: rdi,
run_debug_hovered: rdh,
extensions_active: exta,
extensions_inactive: exti,
extensions_hovered: exth,
testing_active: tsta,
testing_inactive: tsti,
testing_hovered: tsth,
settings_active: gea,
settings_inactive: gei,
settings_hovered: geh,
layout_sidebar_on: lso,
layout_sidebar_on_hover: lsoh,
layout_sidebar_off: lsf,
layout_sidebar_off_hover: lsfh,
layout_panel_on: lpo,
layout_panel_on_hover: lpoh,
layout_panel_off: lpf,
layout_panel_off_hover: lpfh,
layout_customize: lcu,
layout_customize_hover: lcuh,
});
}
// The activity-bar count badges ride the same overlay machinery; rebuild
// them against the freshly-baked icons / new background or cell size. The
// Explorer badge's per-frame refresh is count-gated, so force a rebuild
// here by invalidating its cached count first.
self.refresh_scm_change_badge();
self.explorer_unsaved_count = usize::MAX;
self.refresh_explorer_unsaved_badge();
self.remote_ports_count = usize::MAX;
self.refresh_remote_ports_badge();
self.testing_badge_count = usize::MAX;
self.refresh_testing_badge();
self.problems_badge_count = usize::MAX;
self.refresh_problems_badge();
// Run-and-Debug headline icon: the same debug-alt PNG used in the
// activity bar, fitted to the panel's icon block (RUN_DEBUG_ICON_CELLS_W
// cells wide × RUN_DEBUG_ICON_CELLS_H cells tall) and tinted at icon-
// inactive grey so it reads as the same monochrome family as the rest
// of the activity-bar icons. Encoded once at init; emitted post-frame
// by `flush_run_debug_icon_overlay` while the panel is visible.
let rd_icon_w_cells = crate::widgets::run_debug::RUN_DEBUG_ICON_CELLS_W as u32;
let rd_icon_h_cells = crate::widgets::run_debug::RUN_DEBUG_ICON_CELLS_H as u32;
let rd_icon_w_px = cell_w * rd_icon_w_cells;
let rd_icon_h_px = cell_h * rd_icon_h_cells;
if let Ok(baked) = crate::iterm2_inline::compose_icon(
crate::iterm2_inline::RUN_DEBUG_SRC_PNG,
rd_icon_w_px,
rd_icon_h_px,
false,
icon_ink,
icon_bg,
0,
) && let Some(raw) = crate::iterm2_inline::build_inline_image(
protocol,
&baked,
crate::widgets::run_debug::RUN_DEBUG_ICON_CELLS_W,
crate::widgets::run_debug::RUN_DEBUG_ICON_CELLS_H,
false,
crate::iterm2_inline::KITTY_ID_RUN_DEBUG_PANEL,
) {
self.overlays
.run_debug
.set_image(crate::iterm2_inline::maybe_tmux_wrap(
protocol, is_tmux, raw,
));
}
// SSH empty-state illustration baked to a fixed cell box (18 × 8
// cells). Letterboxed onto the card's dark bg so iTerm2 has no
// transparent edge to ghost the underlying buffer. Emitted post-
// draw by `flush_ssh_empty_state_overlay` while the SSH section
// shows no hosts.
let ssh_cells_w: u16 = crate::widgets::remote::SSH_EMPTY_STATE_CELLS_W;
let ssh_cells_h: u16 = crate::widgets::remote::SSH_EMPTY_STATE_CELLS_H;
let ssh_w_px = cell_w * ssh_cells_w as u32;
let ssh_h_px = cell_h * ssh_cells_h as u32;
// Transparent letterbox so the host terminal's session bg shows
// through the empty padding around the illustration. Any opaque
// fill here would render as a visible darker rectangle behind the
// PNG, which is exactly what the user told us to remove.
let card_bg = ::image::Rgba([0x00, 0x00, 0x00, 0x00]);
if let Ok(baked) = crate::iterm2_inline::fit_image_auto(
crate::iterm2_inline::SSH_EMPTY_STATE_PNG,
ssh_w_px,
ssh_h_px,
card_bg,
) && let Some(raw) = crate::iterm2_inline::build_inline_image_z(
protocol,
&baked,
ssh_cells_w,
ssh_cells_h,
false,
crate::iterm2_inline::KITTY_ID_SSH,
crate::iterm2_inline::KITTY_Z_BELOW_TEXT_AND_BG,
) {
self.overlays
.ssh
.set_image(crate::iterm2_inline::maybe_tmux_wrap(
protocol, is_tmux, raw,
));
}
}
/// Emit the OSC-1337 image carrying the run-debug headline icon at the
/// cell the panel reserved on its most recent render. No-op when the
/// panel isn't the active sidebar view, when the icon hasn't been
/// baked (non-iTerm2 host), or when the panel didn't reserve a cell
/// (too short to fit the icon). Critically, the panel-hidden case
/// does NOT stamp blanks or any other "wipe" payload here: doing so
/// after `terminal.clear()` + redraw stomps freshly-painted text in
/// the next sidebar (this was the bug in the prior space-stamp wipe
/// attempt). Eviction of iTerm2's cached image cells is handled
/// exclusively by the `consume_run_debug_image_clear` →
/// `terminal.clear()` gate in the main loop, the same pipeline the
/// welcome wordmark and editor preview image use.
/// Stop showing the Run/Debug empty-state icon: if an OSC-1337 image was
/// emitted, arm the one-shot `terminal.clear()` latch so the cached image
/// cells are evicted (text painted over an inline image does not remove
/// it), then reset the emitted-position tracking so the clear fires exactly
/// once rather than every frame.
fn clear_run_debug_icon_if_emitted(&mut self) {
if self.overlays.run_debug.was_emitted() {
self.overlays.run_debug.request_clear();
}
self.overlays.run_debug.clear_emitted();
}
pub fn flush_run_debug_icon_overlay(&mut self) {
use std::io::Write;
if self.modal_overlay_open() {
return;
}
let panel_visible = self.show_tree
&& self.sidebar_view == SidebarView::RunDebug
&& self.overlays.run_debug.has_image();
if !panel_visible {
self.clear_run_debug_icon_if_emitted();
return;
}
// No icon cell this frame means the panel is showing the paused
// call-stack tree (debug_active) or is too short for the icon. The
// empty-state icon is an OSC-1337 image; drawing the tree over it does
// NOT evict it, so an emitted icon must be cleared with the one-shot
// `\x1b[2J` latch or it ghosts on top of the call stack.
let Some((cx, cy)) = self.run_debug.last_icon_cell else {
self.clear_run_debug_icon_if_emitted();
return;
};
// The icon moved since the last emit (terminal resize OR an internal
// pane-drag, which never fires Event::Resize and so escapes
// `on_resize`). A plain re-emit at the new cell stacks a fresh
// OSC-1337 image on top of the one iTerm2 still caches at the old
// cell — the doubled/garbled headline-icon ghost. Plain SGR
// overwrites don't evict those cells, so reuse the proven
// `terminal.clear()` latch: arm one clear, drop the stale emit
// position, and skip painting this frame. Next frame the main loop's
// OR chain fires `\x1b[2J`, full-redraws, and this flush re-emits a
// single clean icon at the new cell.
if let Some(prev) = self.overlays.run_debug.last_emitted()
&& prev != (cx, cy)
{
self.overlays.run_debug.request_clear();
self.overlays.run_debug.clear_emitted();
return;
}
let Some(osc) = self.overlays.run_debug.image() else {
return;
};
let mut out = stdout();
let cursor_on = self.cursor_should_be_visible();
let _ = write!(out, "\x1b[?25l\x1b[s");
let _ = write!(out, "\x1b[{};{}H", cy + 1, cx + 1);
let _ = out.write_all(osc.as_bytes());
let _ = write!(out, "\x1b[u");
if cursor_on {
let _ = write!(out, "\x1b[?25h");
}
let _ = out.flush();
self.overlays.run_debug.mark_emitted_at((cx, cy));
}
/// Arm the one-shot `terminal.clear()` latch if the PROBLEMS circle was
/// emitted, so its cached image cells are evicted when the badge goes away
/// (text painted over an inline image does not remove it), then reset the
/// emit position so the clear fires exactly once.
fn clear_problems_badge_if_emitted(&mut self) {
if self.overlays.problems_badge.was_emitted() {
self.overlays.problems_badge.request_clear();
}
self.overlays.problems_badge.clear_emitted();
}
/// Emit the PROBLEMS-tab orange circle as an OSC-1337/Kitty inline image at
/// the cell `paint_panel_tabs` recorded this frame, re-emitted every frame
/// (like the activity-bar badges) so heavy SGR traffic can't evict it.
/// Clears when the panel strip is hidden, the count is zero, or a modal owns
/// the screen; arms a one-shot clear when the anchor moves so no ghost stacks.
pub fn flush_problems_badge_overlay(&mut self) {
use std::io::Write;
if self.modal_overlay_open() {
return;
}
let Some((cx, cy)) = self.problems_badge_cell.filter(|_| self.show_terminal) else {
self.clear_problems_badge_if_emitted();
return;
};
if !self.overlays.problems_badge.has_image() {
self.clear_problems_badge_if_emitted();
return;
}
if let Some(prev) = self.overlays.problems_badge.last_emitted()
&& prev != (cx, cy)
{
self.overlays.problems_badge.request_clear();
self.overlays.problems_badge.clear_emitted();
return;
}
let Some(osc) = self.overlays.problems_badge.image() else {
return;
};
let mut out = stdout();
let cursor_on = self.cursor_should_be_visible();
let _ = write!(out, "\x1b[?25l\x1b[s");
let _ = write!(out, "\x1b[{};{}H", cy + 1, cx + 1);
let _ = out.write_all(osc.as_bytes());
let _ = write!(out, "\x1b[u");
if cursor_on {
let _ = write!(out, "\x1b[?25h");
}
let _ = out.flush();
self.overlays.problems_badge.mark_emitted_at((cx, cy));
}
/// Re-bake (when needed) and re-emit the OSC-1337 inline image for
/// the no-repo source-control hero. Pure no-op when the sidebar isn't
/// on Source Control, the workspace IS a git repo, or the host
/// terminal can't render inline images. Called from the post-draw
/// flush each frame so iTerm2 keeps the image painted even after
/// surrounding cells redraw.
pub fn flush_no_repo_hero_overlay(&mut self) {
use std::io::Write;
if self.modal_overlay_open() {
return;
}
let panel_visible = self.show_tree
&& self.sidebar_view == SidebarView::SourceControl
&& !self.source_control.status.in_repo;
if !panel_visible {
self.overlays.hero.mark_hidden();
return;
}
let hero = self.source_control.last_hero_area;
if hero.width == 0 || hero.height == 0 {
return;
}
// The hero asset carries its own opaque dark backdrop; on a light
// theme it would sit as a dark slab on the white panel, so the
// panel keeps its text-only empty state instead.
if self.theme.is_light() {
self.overlays.hero.mark_hidden();
return;
}
let Some((cw, ch)) = self.cell_pixel else {
return;
};
let desired = WelcomeLayout {
cell_x: hero.x,
cell_y: hero.y,
cell_w: hero.width,
cell_h: hero.height,
};
if !self.overlays.hero.layout_matches(&desired) || !self.overlays.hero.has_image() {
let canvas_w = (hero.width as u32) * cw;
let canvas_h = (hero.height as u32) * ch;
let bg = self.theme_bg_pixel();
let protocol = self.inline_protocol;
if let Ok(baked) = crate::iterm2_inline::fit_image(
crate::iterm2_inline::NO_REPO_HERO_PNG,
canvas_w,
canvas_h,
bg,
) && let Some(raw) = crate::iterm2_inline::build_inline_image_z(
protocol,
&baked,
hero.width,
hero.height,
false,
crate::iterm2_inline::KITTY_ID_HERO,
crate::iterm2_inline::KITTY_Z_BELOW_TEXT_AND_BG,
) {
let osc = crate::iterm2_inline::maybe_tmux_wrap(
protocol,
crate::iterm2_inline::detect_tmux(),
raw,
);
self.overlays.hero.set(osc, desired);
}
}
let Some(osc) = self.overlays.hero.image() else {
return;
};
let mut out = stdout();
let cursor_on = self.cursor_should_be_visible();
let _ = write!(out, "\x1b[?25l\x1b[s");
let _ = write!(out, "\x1b[{};{}H", hero.y + 1, hero.x + 1);
let _ = out.write_all(osc.as_bytes());
let _ = write!(out, "\x1b[u");
if cursor_on {
let _ = write!(out, "\x1b[?25h");
}
let _ = out.flush();
self.overlays.hero.mark_emitted();
}
/// Emit the OSC-1337 SSH-empty-state illustration at the cell the
/// remote panel reserved on its most recent render. When the panel
/// is no longer the active view (or has hosts, or the shortcuts
/// modal is open), this arms a one-shot terminal.clear() via
/// `consume_ssh_empty_state_image_clear()` so iTerm2 evicts the
/// cached image cells — otherwise the illustration ghosts onto
/// whatever view (Explorer / Search / …) replaces it.
pub fn flush_ssh_empty_state_overlay(&mut self) {
use std::io::Write;
let should_show = self.shortcuts_modal.is_none()
&& self.file_finder.is_none()
&& self.zoxide_jump.is_none()
&& self.command_history_popup.is_none()
&& self.branch_picker.is_none()
&& self.input_prompt.is_none()
&& self.list_picker.is_none()
&& self.show_tree
&& self.sidebar_view == SidebarView::Remote
&& self.remote.targets.is_empty();
if !should_show {
self.overlays.ssh.hide_and_request_clear();
return;
}
let Some((cx, cy)) = self.remote.last_image_cell else {
return;
};
let Some(osc) = self.overlays.ssh.image() else {
return;
};
let mut out = stdout();
let cursor_on = self.cursor_should_be_visible();
let _ = write!(out, "\x1b[?25l\x1b[s");
let _ = write!(out, "\x1b[{};{}H", cy + 1, cx + 1);
let _ = out.write_all(osc.as_bytes());
let _ = write!(out, "\x1b[u");
if cursor_on {
let _ = write!(out, "\x1b[?25h");
}
let _ = out.flush();
self.overlays.ssh.mark_displayed();
}
/// One-shot consumer paired with `flush_ssh_empty_state_overlay`. The
/// main loop ORs the result into its `terminal.clear()` chain so
/// iTerm2's cached image cells are evicted on view change.
pub fn consume_ssh_empty_state_image_clear(&mut self) -> bool {
self.overlays.ssh.consume_clear_latch()
}
/// One-shot consumer for the "leaving Run-Debug after the icon was
/// emitted" flag. The main loop folds the result into the same OR
/// chain that fires `terminal.clear()` for the welcome wordmark and
/// editor preview image.
pub fn consume_run_debug_image_clear(&mut self) -> bool {
self.overlays.run_debug.consume_clear()
}
/// One-shot consumer for the "the PROBLEMS circle went away / moved after it
/// was emitted" flag. Folded into the main loop's `terminal.clear()` OR chain
/// so iTerm2 evicts the cached badge bitmap.
pub fn consume_problems_badge_image_clear(&mut self) -> bool {
self.overlays.problems_badge.consume_clear()
}
/// One-shot consumer for the "a resize may have left stale activity-bar
/// icon bitmaps in iTerm2's image layer" flag, armed by `on_resize`. The
/// main loop folds the result into the same OR chain that fires
/// `terminal.clear()` for the welcome wordmark and editor preview image,
/// evicting the ghost before the icons re-emit on the next draw.
pub fn consume_activity_image_clear(&mut self) -> bool {
self.overlays.activity.consume_clear()
}
/// Handle a terminal/pane resize. The alt-screen reflow blanks the SGR
/// cells but iTerm2's OSC-1337 image layer survives, so a plain re-emit
/// would stack a fresh icon on top of the stale one (the doubled-icon
/// ghost). Re-mark the icons dirty so they re-emit, and — in images mode,
/// the only state the stale layer can exist in — arm a one-shot
/// `terminal.clear()` so iTerm2 drops the cached bitmaps first.
pub fn on_resize(&mut self) {
self.overlays.activity.mark_dirty();
if self.overlays.activity.has_images() {
self.overlays.activity.request_clear();
}
// A WINCH invalidates the physical screen (window resize reflow, or a
// dtach reattach against a blank terminal) while ratatui's back buffer
// still claims every cell is painted; force the next frame to wipe and
// re-emit everything on every protocol.
self.resize_repaint_needed = true;
}
/// One-shot consumer for the "leaving Source Control after the no-repo
/// hero PNG was emitted" flag. Same shape as
/// `consume_run_debug_image_clear` - the main loop folds the result
/// into its `terminal.clear()` chain so iTerm2's cached image cells
/// are evicted on view change.
pub fn consume_no_repo_hero_image_clear(&mut self) -> bool {
self.overlays.hero.consume_clear_latch()
}
/// The rect of the sidebar OSC-1337 illustration currently on screen (the
/// Source Control no-repo hero or the Remote SSH empty-state), or `None`
/// when neither is showing. Those images composite above ratatui's text
/// layer, so a tooltip overlapping one must be re-painted last.
fn active_sidebar_image_rect(&self) -> Option<Rect> {
if !self.show_tree {
return None;
}
let rect = match self.sidebar_view {
SidebarView::SourceControl if !self.source_control.status.in_repo => {
self.source_control.last_hero_area
}
SidebarView::Remote if self.remote.targets.is_empty() => self.remote.last_image_area,
_ => return None,
};
(rect.width > 0 && rect.height > 0).then_some(rect)
}
/// Re-paint the chrome tooltip directly to the terminal AFTER the inline
/// images have been flushed, so its box sits in the foreground over any
/// sidebar illustration it overlaps. The hero / SSH image is emitted
/// post-draw and would otherwise composite over the tooltip's text; since
/// the last writer wins each cell, re-emitting the box here puts it on top
/// while the illustration itself stays fully painted everywhere else.
/// No-op unless a tooltip is showing and actually lands on an illustration.
pub fn flush_tooltip_over_image(&mut self) {
use std::io::Write;
// Only the cell-buffer protocols (iTerm2 OSC-1337, Sixel) need this: a
// later text write wins those cells. The Kitty path instead places the
// illustration at a deep-negative z so text already draws on top, and
// re-blitting would be wasted stdout traffic.
match self.inline_protocol {
crate::iterm2_inline::InlineImageProtocol::ITerm2
| crate::iterm2_inline::InlineImageProtocol::Sixel => {}
_ => return,
}
let Some(area) = self.ui_tooltip_area else {
return;
};
let Some(img) = self.active_sidebar_image_rect() else {
return;
};
if !rects_intersect(area, img) {
return;
}
let Some(popup) = self.ui_tooltip.as_ref() else {
return;
};
// Render the popup into a standalone buffer at its on-screen rect, then
// blit each cell as an absolutely-positioned SGR write. The box is fully
// opaque (its block fills the bg), so it cleanly occludes the slice of
// the illustration it covers, exactly like a floating tooltip.
let mut buf = ratatui::buffer::Buffer::empty(area);
ratatui::widgets::Widget::render(popup, area, &mut buf);
let mut out = stdout();
let cursor_on = self.cursor_should_be_visible();
let _ = write!(out, "\x1b[?25l\x1b[s");
for y in area.top()..area.bottom() {
let _ = write!(out, "\x1b[{};{}H", y + 1, area.left() + 1);
for x in area.left()..area.right() {
let cell = &buf[(x, y)];
let _ = out.write_all(sgr_for_cell(cell).as_bytes());
let _ = out.write_all(cell.symbol().as_bytes());
}
let _ = write!(out, "\x1b[0m");
}
let _ = write!(out, "\x1b[u");
if cursor_on {
let _ = write!(out, "\x1b[?25h");
}
let _ = out.flush();
}
/// Returns the post-frame OSC-1337 escapes to write under the activity
/// bar, paired with the absolute terminal cell where each one starts
/// (just past the active-pill column). Empty when image rendering is
/// disabled or the activity bar hasn't been laid out yet.
pub fn pending_activity_image_overlays(&self) -> Vec<((u16, u16), &str)> {
let Some(images) = self.overlays.activity.images() else {
return Vec::new();
};
let exp_block = self.sidebar_areas.explorer_icon;
let sea_block = self.sidebar_areas.search_icon;
let scm_block = self.sidebar_areas.source_control_icon;
let rem_block = self.sidebar_areas.remote_icon;
let rdb_block = self.sidebar_areas.run_debug_icon;
let ext_block = self.sidebar_areas.extensions_icon;
let tst_block = self.sidebar_areas.testing_icon;
// The activity bar is all-or-nothing: emit its icons only when every
// block is laid out (a partial bar would look broken). When it's hidden
// (Customize Layout / Zen) the blocks are zero-width and skipped, but
// the layout toolbar icons below still emit independently.
let activity_ready = exp_block.width > 0
&& sea_block.width > 0
&& scm_block.width > 0
&& rem_block.width > 0
&& rdb_block.width > 0
&& ext_block.width > 0
&& tst_block.width > 0;
// Three-way per icon: the selected view shows the active (pilled)
// variant; otherwise the pointer-hovered icon brightens (no pill); the
// rest stay muted. Selected always wins over hovered.
let hov = self.hovered_activity_icon;
let exp_state = if self.sidebar_view == SidebarView::Explorer {
&images.explorer_active
} else if hov == Some(ActivityIcon::Explorer) {
&images.explorer_hovered
} else {
&images.explorer_inactive
};
let sea_state = if self.sidebar_view == SidebarView::Search {
&images.search_active
} else if hov == Some(ActivityIcon::Search) {
&images.search_hovered
} else {
&images.search_inactive
};
let scm_state = if self.sidebar_view == SidebarView::SourceControl {
&images.source_control_active
} else if hov == Some(ActivityIcon::SourceControl) {
&images.source_control_hovered
} else {
&images.source_control_inactive
};
let rem_state = if self.sidebar_view == SidebarView::Remote {
&images.remote_active
} else if hov == Some(ActivityIcon::Remote) {
&images.remote_hovered
} else {
&images.remote_inactive
};
let rdb_state = if self.sidebar_view == SidebarView::RunDebug {
&images.run_debug_active
} else if hov == Some(ActivityIcon::RunDebug) {
&images.run_debug_hovered
} else {
&images.run_debug_inactive
};
let ext_state = if self.sidebar_view == SidebarView::Extensions {
&images.extensions_active
} else if hov == Some(ActivityIcon::Extensions) {
&images.extensions_hovered
} else {
&images.extensions_inactive
};
let tst_state = if self.sidebar_view == SidebarView::Testing {
&images.testing_active
} else if hov == Some(ActivityIcon::Testing) {
&images.testing_hovered
} else {
&images.testing_inactive
};
// The gear is bottom-anchored and may be absent on a short bar
// (empty block). It reads "active" while its menu/picker is open.
let set_block = self.sidebar_areas.settings_icon;
let set_state = if self.settings_menu_active() {
&images.settings_active
} else if hov == Some(ActivityIcon::Settings) {
&images.settings_hovered
} else {
&images.settings_inactive
};
// The shortcuts modal and file finder are centered over the editor
// column, not the far-left activity bar, so the icons stay visible
// beside them. Suppress an icon only when its block actually
// intersects an open panel (possible only when the terminal is
// narrow enough that the centered panel reaches column 0); otherwise
// a terminal.clear() armed by the modal wipes iTerm2's cached image
// cells and they never repaint while the panel is up.
let occluders = [
self.shortcuts_modal.as_ref().map(|m| m.last_rect),
self.file_finder.as_ref().map(|f| f.last_rect),
self.command_palette.as_ref().map(|p| p.last_rect),
self.go_to_symbol.as_ref().map(|p| p.last_rect),
self.workspace_symbols.as_ref().map(|p| p.last_rect),
self.process_picker.as_ref().map(|p| p.last_rect),
];
let visible = |block: Rect| {
occluders
.iter()
.flatten()
.all(|panel| !block.intersects(*panel))
};
let mut blocks: Vec<(Rect, &str)> = Vec::new();
if activity_ready {
blocks.extend_from_slice(&[
(exp_block, exp_state.as_str()),
(sea_block, sea_state.as_str()),
(scm_block, scm_state.as_str()),
(rem_block, rem_state.as_str()),
(rdb_block, rdb_state.as_str()),
(ext_block, ext_state.as_str()),
(tst_block, tst_state.as_str()),
]);
if set_block.width > 0 {
blocks.push((set_block, set_state.as_str()));
}
// Change-count badge over the SCM icon's bottom-right corner. Pushed
// after the SCM icon so the iTerm2 path (last writer wins each cell)
// paints it on top; the Kitty path baked it at z=1 for the same
// effect. Dropping it from the list when the count hits zero shifts
// the emit positions, which arms the overlay's move-detection clear.
if let Some(badge) = self.scm_change_badge.as_deref() {
let bw = crate::iterm2_inline::count_badge_cells_w(self.scm_change_badge_count);
let bx = scm_block.x + scm_block.width.saturating_sub(bw);
let by = scm_block.y + scm_block.height.saturating_sub(1);
blocks.push((
Rect {
x: bx,
y: by,
width: bw,
height: 1,
},
badge,
));
}
// Same badge over the Explorer icon for the unsaved-file count.
if let Some(badge) = self.explorer_unsaved_badge.as_deref() {
let bw = crate::iterm2_inline::count_badge_cells_w(self.explorer_unsaved_count);
let bx = exp_block.x + exp_block.width.saturating_sub(bw);
let by = exp_block.y + exp_block.height.saturating_sub(1);
blocks.push((
Rect {
x: bx,
y: by,
width: bw,
height: 1,
},
badge,
));
}
// And over the Remote icon for the forwarded-ports count.
if let Some(badge) = self.remote_ports_badge.as_deref() {
let bw = crate::iterm2_inline::count_badge_cells_w(self.remote_ports_count);
let bx = rem_block.x + rem_block.width.saturating_sub(bw);
let by = rem_block.y + rem_block.height.saturating_sub(1);
blocks.push((
Rect {
x: bx,
y: by,
width: bw,
height: 1,
},
badge,
));
}
// And the failing-test count over the Testing (beaker) icon.
if let Some(badge) = self.testing_badge.as_deref() {
let bw = crate::iterm2_inline::count_badge_cells_w(self.testing_badge_count);
let bx = tst_block.x + tst_block.width.saturating_sub(bw);
let by = tst_block.y + tst_block.height.saturating_sub(1);
blocks.push((
Rect {
x: bx,
y: by,
width: bw,
height: 1,
},
badge,
));
}
}
// Customize Layout toolbar icons (top-right of the editor / welcome).
// Their image swaps with the side-bar / panel visibility, exactly like
// an activity icon swaps active/inactive. Independent of the activity
// bar, so they still emit when it's hidden.
let li = self.layout_icon_areas;
let hovered = |r: Rect| {
self.pointer_cell
.is_some_and(|(px, py)| rect_contains(r, px, py))
};
let side_img = match (self.show_tree, hovered(li.toggle_side_bar)) {
(true, false) => &images.layout_sidebar_on,
(true, true) => &images.layout_sidebar_on_hover,
(false, false) => &images.layout_sidebar_off,
(false, true) => &images.layout_sidebar_off_hover,
};
let panel_img = match (self.show_terminal, hovered(li.toggle_panel)) {
(true, false) => &images.layout_panel_on,
(true, true) => &images.layout_panel_on_hover,
(false, false) => &images.layout_panel_off,
(false, true) => &images.layout_panel_off_hover,
};
let cust_img = if hovered(li.customize) {
&images.layout_customize_hover
} else {
&images.layout_customize
};
blocks.push((li.toggle_side_bar, side_img.as_str()));
blocks.push((li.toggle_panel, panel_img.as_str()));
blocks.push((li.customize, cust_img.as_str()));
blocks
.into_iter()
// A zero-width block means the icon is hidden (the activity bar is
// off in Customize Layout / Zen, or the toolbar isn't laid out):
// emit nothing so the image can't ghost.
.filter(|(block, _)| block.width > 0 && visible(*block))
.map(|(block, state)| ((block.x, block.y), state))
.collect()
}
/// True while the activity-bar gear's menu or theme picker is open, so the
/// gear renders in its pressed/active state. Derived from the live context
/// menu's actions rather than a separate flag that could drift out of sync
/// with the many places the menu is dismissed.
fn settings_menu_active(&self) -> bool {
self.context_menu.as_ref().is_some_and(|menu| {
menu.items.iter().any(|entry| {
matches!(
entry.action(),
Some(MenuAction::OpenThemePicker | MenuAction::SetTheme(_))
)
})
})
}
/// Post-draw flush of the activity-bar icons. Re-emits the pre-encoded
/// OSC-1337 image bytes each frame (ratatui doesn't track image cells, so
/// neighbouring SGR traffic can evict them from iTerm2's cache) — but
/// first applies the same emit-time move-detection as the run-debug
/// headline icon: if the icon cells shifted since the last emit (a
/// terminal resize, or any future layout change that recenters the bar),
/// a plain re-emit stacks a fresh image on top of the one iTerm2 still
/// caches at the old cell, the doubled-icon ghost. On a move it arms one
/// `terminal.clear()` (the proven `\x1b[2J` eviction the main loop folds
/// into its OR chain), forgets the emit positions, and skips painting
/// this frame; the next frame clears, full-redraws, and re-emits a single
/// clean set at the new cells.
pub fn flush_activity_image_overlays(&mut self) {
use std::io::Write;
// The keepalive re-emit fights iTerm2's image-cache eviction; the sixel
// cell buffer doesn't evict, so its icons re-emit only when dirty.
let allow_keepalive =
self.inline_protocol != crate::iterm2_inline::InlineImageProtocol::Sixel;
if !self.overlays.activity.should_refresh(allow_keepalive) {
return;
}
let overlays = self.pending_activity_image_overlays();
if overlays.is_empty() {
return;
}
let positions: Vec<(u16, u16)> = overlays.iter().map(|(cell, _)| *cell).collect();
if self.overlays.activity.positions_moved(&positions) {
self.overlays.activity.request_clear();
self.overlays.activity.forget_positions();
return;
}
let mut out = stdout();
let cursor_on = self.cursor_should_be_visible();
let _ = write!(out, "\x1b[?25l\x1b[s");
for ((x, y), seq) in &overlays {
// Same screen bound as the image writers (#513): a raw
// absolute-CUP write that ratatui cannot repair, so the origin
// is checked before it is used.
//
// 1x1 is NARROWER than some payloads here, and knowingly so.
// `pending_activity_image_overlays` discards each block's
// `Rect` and returns only its origin, and a count badge is 2-3
// cells wide (`count_badge_cells_w`), so a badge whose left
// edge is on screen and right edge is not would pass this.
// Not reachable today -- the badges anchor to the left-hand
// activity bar -- and making it exact means returning the
// `Rect` from that function, which is a wider change than this
// guard. Recorded rather than left to be rediscovered.
if !self.overlay_fits_on_screen(*x, *y, 1, 1) {
continue;
}
let _ = write!(out, "\x1b[{};{}H", y + 1, x + 1); // 1-based
let _ = out.write_all(seq.as_bytes());
}
let _ = write!(out, "\x1b[u");
if cursor_on {
let _ = write!(out, "\x1b[?25h");
}
let _ = out.flush();
self.overlays.activity.mark_emitted();
self.overlays.activity.store_positions(positions);
}
/// Whether a post-draw overlay at this cell rect may be emitted (#513).
///
/// The flush block below writes with absolute CUP straight to stdout,
/// after ratatui's diff. Two properties make a wrong origin dangerous
/// rather than merely wrong: it is a raw write, not a buffer index, so
/// an out-of-range origin cannot panic the way `Buffer` would; and
/// ratatui has no record of the cells it touched, so nothing repairs
/// them on the next frame. The corruption persists instead of clearing
/// on repaint, which is what #510 looked like from the outside.
///
/// So the payload is checked against the screen at EMIT time rather
/// than trusting whichever cached rect produced the layout. Every
/// writer in the block goes through it, which is the part #512's shape
/// could not give: that fixed the terminal carrier by clearing its
/// stored rect, but each other writer keeps its own rect with its own
/// lifecycle, so every future site a frame can decline to paint is one
/// more place to remember the clear.
///
/// What this does NOT do, stated plainly because the bound is easy to
/// oversell: it removes OFF-SCREEN writes only. It is a screen bound,
/// not the owning widget's rect, so an overlay anchored on a stale rect
/// that still lands somewhere on screen passes it untouched -- and that
/// is the case #510 actually exhibited, a terminal image painted over a
/// sibling pane, the sidebar and the status bar, all of them mid-screen
/// (#512 records the landing sites). So this does not subsume #512 and
/// does not close #513's class; it removes the unbounded half, where a
/// wild origin can write anywhere in the terminal.
///
/// The bound is the screen because the emitter does not know which
/// widget a payload belongs to. Making it exact needs each payload to
/// carry its owning rect, which is the wider change #513 describes.
fn overlay_fits_on_screen(&self, cell_x: u16, cell_y: u16, cell_w: u16, cell_h: u16) -> bool {
let area = self.last_frame_area;
if area.width == 0 || area.height == 0 {
// No frame has been drawn yet, so there is no screen to land on.
return false;
}
// A zero-sized payload has nothing to place; treat it as unemittable
// rather than trivially in-bounds, so a cleared rect cannot slip a
// bare cursor park through.
if cell_w == 0 || cell_h == 0 {
return false;
}
cell_x.saturating_add(cell_w) <= area.width && cell_y.saturating_add(cell_h) <= area.height
}
/// Reset the blink phase so the caret is solidly visible for the next
/// 530ms. Call after any edit, cursor movement, or focus change so the
/// user always sees where the cursor just landed before it starts to
/// blink off.
fn poke_cursor(&mut self) {
self.cursor_blink.poke();
}
/// Mirrors the predicate used in `App::render` to decide whether to call
/// `frame.set_cursor_position`. Used by the post-draw overlay writer so
/// it can re-Show the caret after the OSC-1337 image emit only when the
/// editor would have shown it this frame.
fn cursor_should_be_visible(&self) -> bool {
if self.context_menu.is_some() || self.prompt.is_some() || !self.cursor_visible_phase() {
return false;
}
let editor_caret = if self.editor.diff.is_some() {
self.editor.diff_caret_screen_pos()
} else {
self.editor.cursor_screen_pos()
};
if self.focus == Pane::Editor && editor_caret.is_some() {
return true;
}
if self.focus == Pane::Tree
&& self.sidebar_view == SidebarView::SourceControl
&& self.source_control.cursor_screen_pos().is_some()
{
return true;
}
if self.focus == Pane::Tree
&& self.sidebar_view == SidebarView::Search
&& self.search.cursor_screen_pos().is_some()
{
return true;
}
if self.focus == Pane::Tree
&& self.sidebar_view == SidebarView::Extensions
&& self.extensions.cursor_screen_pos().is_some()
{
return true;
}
false
}
/// True iff the caret is currently in its visible half of the blink
/// cycle. VS Code uses a 530ms half-period; we match. We blink in
/// software (by toggling whether `frame.set_cursor_position` is called
/// each frame) instead of relying on the host terminal's own blink
/// support, which iTerm2 / Terminal.app may have disabled in user
/// preferences.
fn cursor_visible_phase(&self) -> bool {
self.cursor_blink.visible_phase()
}
/// Re-query git status, but no more than once every ~400ms to avoid
/// spawning a `git` process on every keystroke. Called after the file
/// watcher reports any changes.
fn refresh_git_status_debounced(&mut self) {
let want_changes = self.sidebar_view == SidebarView::SourceControl;
self.git.request_status_debounced(want_changes);
for (_, w) in &mut self.git_extra {
w.request_status_debounced(want_changes);
}
}
fn sync_open_file_poll_mtime(&mut self) {
let paths = self.open_tab_paths();
self.fs_watch.sync_open_file_mtime(&paths);
self.drop_symbol_tab_if_file_changed();
}
/// Close a symbol tab once the editor is showing a different file (#369).
///
/// The range is BYTE offsets into ONE buffer, so it cannot survive the
/// move: `follow_symbol_tab_edit` would apply the new file's edits
/// against the old file's offsets and walk the range somewhere
/// meaningless rather than reporting `Gone`.
///
/// Keyed on the ACTIVE path after the change, not on a path passed in.
/// `open_at` looked like the chokepoint and is not - search hits, a
/// quick-open pick with no line hint, file-tree clicks, reopen-closed-tab
/// and plain `editor.select` all reach another file without it, and
/// `select` carries no path a guard could inspect. Every one of those
/// paths does reach `sync_open_file_poll_mtime`.
///
/// A plain comparison is enough, and a canonicalising fallback was tried
/// and removed. `go_to_definition` does arrive with the server's
/// realpath-resolved URI while the tab stored whatever the user opened -
/// but `open_preview` resolves through `find_tab_matching`, which
/// canonicalises, so it selects the ALREADY-OPEN tab and `editor.path`
/// keeps its original spelling. The two sides therefore cannot diverge
/// FOR THE SAME FILE - they diverge freely when the file really changes,
/// which is the point - because the tab's path is a copy of
/// `editor.path` and `find_tab_matching` canonicalises before selecting.
/// The field itself is not canonical. A canonicalising branch was
/// therefore unreachable: three attempts to
/// write a test that entered it all failed, and a mutation deleting it
/// survived, which is what proved it dead rather than merely untested.
fn drop_symbol_tab_if_file_changed(&mut self) {
let Some((_, tab_path, _)) = self.symbol_tab.as_ref() else {
return;
};
let Some(active) = self.editor.path.as_deref() else {
// No file open at all: nothing for the range to describe.
self.symbol_tab = None;
return;
};
if tab_path.as_path() != active {
self.symbol_tab = None;
}
}
/// Every file backing an open tab, across all editor groups. The poll
/// stats these, so a background tab in a dir that carries no watch still
/// sees an external write.
fn open_tab_paths(&self) -> Vec<PathBuf> {
std::iter::once(&self.editor)
.chain(self.editor_layout.inactive_groups())
.flat_map(|g| g.editors.iter())
.filter_map(|e| e.path.clone())
.collect()
}
/// Sweep EVERY open tab for external on-disk changes, not just the
/// focused one — in every editor GROUP, not just the focused one either.
/// The poll stats each open path once and re-baselines its stamp, so a
/// change reported to a sweep that could not reach the tab is burned: no
/// later tick reports it again and that pane keeps stale text forever.
/// Clean tabs reload silently; dirty tabs are flagged as conflicts (the
/// buffer and the disk are both preserved); tabs whose reload FAILED
/// keep their last good view and say so in the status line (#37).
/// Returns true if any tab reloaded, failed, or entered conflict, so
/// the caller redraws.
fn reload_open_file_after_external_change(&mut self) -> bool {
let guest = self.is_collab_guest();
let root = self.tree.root.clone();
let skip = |p: &Path| guest && collab_file_key(&root, p).is_some();
let mut report = self.editor.reload_externally_changed_tabs(&skip);
for group in self.editor_layout.inactive_groups_mut() {
let extra = group.reload_externally_changed_tabs(&skip);
report.reloaded.extend(extra.reloaded);
report.conflicts.extend(extra.conflicts);
report.failed.extend(extra.failed);
}
if report.is_empty() {
return false;
}
self.refresh_git_status_debounced();
match (
report.reloaded.len(),
report.conflicts.len(),
report.failed.len(),
) {
// A dirty-buffer collision outranks everything: it needs a
// decision, so it gets the modal.
(_, c, _) if c > 0 => {
self.prompt_disk_conflict(report.conflicts.clone());
}
// A failed reload used to be silently discarded (#37): the tab
// keeps its last good view, and the status must say so instead
// of letting the user read stale content as current.
(0, 0, 1) => {
let p = report.failed[0].display();
self.status = format!("Reload failed for {p}; keeping the last good view");
}
(r, 0, f) if f > 0 => {
self.status = if r == 0 {
format!("Reload failed for {f} files changed on disk")
} else {
format!("Reloaded {r} files, reload failed for {f} (kept their last good view)")
};
}
(1, 0, 0) => {
let p = report.reloaded[0].display();
self.status = format!("Reloaded {p} (external change)");
}
(n, ..) => {
self.status = format!("Reloaded {n} files changed on disk");
}
}
// Keep the watcher's active-file baseline aligned with the reload so
// a just-applied change doesn't re-trigger on the next poll.
self.sync_open_file_poll_mtime();
true
}
/// A dirty buffer collided with an external write. Surface it unmissably
/// via the confirm popup (Enter reloads and discards local edits, Esc
/// keeps them). Falls back to the status line only when another prompt
/// already owns the modal slot, so we never stomp an in-progress input.
fn prompt_disk_conflict(&mut self, paths: Vec<PathBuf>) {
use crate::widgets::input_prompt::{InputPrompt, InputPurpose};
let (title, placeholder) = match paths.as_slice() {
[one] => (
format!(
"{} changed on disk and you have unsaved edits.",
one.display()
),
"Enter to reload (discard your edits) · Esc to keep editing",
),
many => (
format!(
"{} open files changed on disk with unsaved edits.",
many.len()
),
"Enter to reload all (discard your edits) · Esc to keep editing",
),
};
if self.input_prompt.is_some() {
self.status = title;
return;
}
self.open_input_prompt(
InputPrompt::new(InputPurpose::ReloadConflict { paths }, title, placeholder)
.with_value("reload"),
);
}
fn poll_filesystem_changes(&mut self) -> bool {
// Runs every frame; the poll itself fires at most every 50ms and backs
// off from there, so don't build the path list until it would be used.
if !self.fs_watch.poll_due() {
return false;
}
let open_paths = self.open_tab_paths();
let poll = self.fs_watch.poll(&mut self.tree, &open_paths);
// Any directory change can also be a write to a file open in some
// tab (background or active), so sweep all tabs whenever the poll
// saw activity, not only when the active file's own stat moved.
if poll.open_file_changed || poll.dirs_changed {
self.reload_open_file_after_external_change();
}
if poll.dirs_changed {
self.refresh_git_status_debounced();
if poll.finder_relevant {
self.kick_file_finder_index_rebuild();
}
}
// Stamp-gated, so an idle poll costs a stat per open diff view; on
// hosts without a native watcher this is how a diff follows the
// file (#471).
let diffs_changed =
self.refresh_open_diff_views(false, &[], &std::collections::BTreeSet::new());
poll.open_file_changed || poll.dirs_changed || diffs_changed
}
/// Drain any pending filesystem events from the watcher and refresh the
/// tree directories whose contents may have changed. Also reloads the
/// editor's open file when an external write (vim, git pull, etc.)
/// changes it on disk.
/// Drain pending filesystem events. Returns `true` iff anything was
/// processed (so the main loop knows it owes a redraw).
/// Install background-initialised resources (fs watcher, git status) if
/// their threads have finished. Returns true if any were installed this
/// tick (so the caller redraws). Cheap no-op once both are installed.
pub fn try_install_pending_init(&mut self) -> bool {
let mut changed = self.fs_watch.try_install_watcher();
for w in &mut self.fs_watch_extra {
if w.try_install_watcher() {
changed = true;
}
}
if self.drain_git_responses() {
changed = true;
}
// Land the background-built Cmd+P file index the moment the
// walker thread finishes, so the very next Cmd+P opens
// against a hot index instead of triggering the synchronous
// fallback walk.
self.poll_file_finder_index();
changed
}
/// Drain everything the git worker has shipped back since the last
/// tick and apply each response to the matching cache (`git_status`
/// for the status-bar badge, `source_control.entries` for the SC
/// panel rows). Returns true iff anything was applied so the main
/// loop knows to redraw. Cheap when the rx is empty: a single
/// non-blocking try_recv. Called from `try_install_pending_init`,
/// which already runs every tick.
pub fn drain_git_responses(&mut self) -> bool {
// The SCM surfaces follow the repository of the root owning the
// focused file (#149): on a switch, seed the panel from that
// worker's cached status and re-request its change list — the
// non-active workers' lists are discarded at their drains below.
let follow = self.active_workspace_root();
if follow != self.scm_follow_root {
// The user moved focus across folders: the panel resumes
// following, releasing any overview pin (#161).
self.scm_follow_root = follow.clone();
self.scm_pin = None;
}
// A pin naming a folder that has since left the workspace would
// re-seed a dead root forever (#162 review): drop it here so the
// guard holds whichever path removed the folder.
if self
.scm_pin
.as_ref()
.is_some_and(|p| !self.roots.iter().any(|r| r == p))
{
self.scm_pin = None;
}
let active = self.scm_pin.clone().unwrap_or_else(|| follow.clone());
if active != self.active_scm_root {
self.seed_active_scm(active);
}
if follow != self.active_test_root {
self.rebind_test_root(follow);
}
// Ship any refresh the debounce window coalesced once the gap clears,
// so the trailing edge of an edit burst lands without another FS event.
let mut changed = false;
// Roots whose HEAD oid moved in this drain: the open Source Control
// diffs for THESE re-read their HEAD blob (#471); the rest are
// stamp-gated like any filesystem tick.
let mut heads_moved: Vec<PathBuf> = Vec::new();
let mut status_arrived = false;
let primary_root = self.roots.primary().to_path_buf();
let mut worker_roots: Vec<PathBuf> = vec![primary_root];
worker_roots.extend(self.git_extra.iter().map(|(r, _)| r.clone()));
for ws_root in worker_roots {
let is_active = ws_root == self.active_scm_root;
// Split the borrows: the panel is only handed to the active
// repo's worker.
let panel = &mut self.source_control;
let w = match self.git_extra.iter_mut().find(|(r, _)| *r == ws_root) {
Some((_, w)) => w,
None => &mut self.git,
};
w.flush_pending();
let this_changed = w.drain_into(is_active.then_some(panel));
// A completed refresh whose status came back identical is still
// news to an open staged / branch / previous-commit diff (#471):
// those read the index or a ref, which porcelain status does
// not fully describe.
if w.take_status_arrival() {
status_arrived = true;
}
if !this_changed {
continue;
}
changed = true;
let status = w.status().clone();
if is_active && status.in_repo && self.default_branch_label.is_none() {
self.default_branch_label = crate::git::default_branch(&self.active_scm_root).ok();
}
// HEAD moved in THIS repo (commit, checkout, pull): the cached
// gutter baselines for ITS files are stale, as is blame; the
// COMMITS graph refetches only for the active repo.
let oid = status.head_oid.clone();
if self.git_head_oids.get(&ws_root) != Some(&oid) {
self.git_head_oids.insert(ws_root.clone(), oid);
// The diff tag stores `scm_root()`, the git TOPLEVEL, which
// is not the workspace root for a subdirectory workspace or
// for a root reached through a symlink (git canonicalises
// `--show-toplevel`). Record what the tag will compare with.
heads_moved.push(status.repo_root.clone().unwrap_or_else(|| ws_root.clone()));
if is_active {
self.refresh_commit_graph();
}
for group in std::iter::once(&mut self.editor)
.chain(self.editor_layout.inactive_groups_mut())
{
for ed in &mut group.editors {
let owned = ed
.path
.as_deref()
.and_then(|p| self.roots.owning_root(p))
.is_some_and(|r| r == ws_root);
if owned {
ed.git_baseline_for = None;
}
}
}
self.blame_fetched = None;
}
}
if changed {
self.refresh_scm_change_badge();
// The overview rows track the same drains that feed the badge
// (#162 review: sync_focus_flags runs on focus TRANSITIONS,
// not per tick, so background-repo updates lagged).
self.refresh_scm_repositories();
// The Explorer dims git-ignored rows across EVERY root: each
// worker's set is cwd-scoped to its root already, so the union
// is exact. Single-root keeps the Arc clone (no set copy).
if self.git_extra.is_empty() {
self.tree.ignored = self.git.status().ignored.clone();
} else {
let mut union: std::collections::HashSet<PathBuf> =
self.git.status().ignored.as_ref().clone();
for (_, w) in &self.git_extra {
union.extend(w.status().ignored.iter().cloned());
}
self.tree.ignored = std::sync::Arc::new(union);
}
}
// A completed status refresh means HEAD or the index may have moved:
// a Source Control diff re-reads its HEAD blob when its root's HEAD
// oid changed, a staged / branch / previous-commit view re-runs its
// `git diff` on every arrival (#471). This is the debounced cadence,
// so a burst of writes costs one re-run, and a rebuilt view owes a
// redraw even when the status itself was unchanged.
let diffs_refreshed = (changed || status_arrived)
&& self.refresh_open_diff_views(true, &heads_moved, &std::collections::BTreeSet::new());
changed || diffs_refreshed
}
/// Point the SCM surfaces at `active`'s repository: seed the panel
/// from its worker's cached status, drop the outgoing repo's change
/// list (rendering another repository's entries under this branch
/// header would be wrong; the fresh list lands one worker roundtrip
/// later), re-request it past the debounce, and refetch the COMMITS
/// graph. Shared by the focus-follow switch and the remove-folder
/// fallback (#150 review: assigning the field directly left the
/// removed repo's panel on screen, since the switch-detect saw no
/// difference).
fn seed_active_scm(&mut self, active: PathBuf) {
self.active_scm_root = active.clone();
self.default_branch_label = None;
// A lane diff belongs to the root it was asked for. Carried into
// another repo the range names a branch that does not exist there,
// and `branch_history_range` answers an unresolvable range with an
// EMPTY vec rather than an error - so the panel would show a repo
// with commits as having none, with nothing on screen saying why.
self.graph_revspec = None;
let w = self.git_worker_for_root_mut(&active);
w.bypass_debounce();
w.request_status_and_changes();
let status = self.git_worker_for_root(&active).status().clone();
self.source_control.set_status(status, Vec::new());
self.refresh_scm_repositories();
self.refresh_commit_graph();
}
/// Rebuild the cached source-control change-count badge after the change
/// set, theme, or cell size shifts, and mark the activity overlay dirty so
/// the next post-draw flush re-emits. On the glyph-fallback path (no inline
/// images) it only tracks the count for the dirty check; that path draws a
/// text badge directly in `render_activity_bar`.
fn refresh_scm_change_badge(&mut self) {
// Across EVERY folder's repository (#161): work pending in a
// background folder must never be invisible. Single-folder, the
// sum is exactly the active repo's porcelain count.
let count: usize = std::iter::once(&self.git)
.chain(self.git_extra.iter().map(|(_, w)| w))
.map(|w| w.status().changed_count)
.sum();
if !self.overlays.activity.has_images() {
self.scm_change_badge = None;
if count != self.scm_change_badge_count {
self.scm_change_badge_count = count;
self.overlays.activity.mark_dirty();
}
return;
}
if count == 0 {
if self.scm_change_badge.is_some() {
self.scm_change_badge = None;
self.overlays.activity.mark_dirty();
}
self.scm_change_badge_count = 0;
return;
}
self.scm_change_badge = self.build_count_badge_image(
count,
crate::iterm2_inline::KITTY_ID_SCM_BADGE,
self.theme.accent_rgb(),
);
self.scm_change_badge_count = count;
self.overlays.activity.mark_dirty();
}
/// Build the inline-image for an activity-bar count badge (accent pill +
/// count) at the given Kitty image id. `None` when image rendering is off or
/// the cell size isn't known yet. Shared by the SCM, Explorer, and Remote
/// badges so the compose/encode/tmux-wrap chain lives in one place.
fn build_count_badge_image(
&self,
count: usize,
kitty_id: u32,
color: (u8, u8, u8),
) -> Option<String> {
let (cw, ch) = self.cell_pixel?;
let png =
crate::iterm2_inline::compose_count_badge(count, cw, ch, color, self.theme_bg_pixel())?;
let raw = crate::iterm2_inline::build_inline_image_z(
self.inline_protocol,
&png,
crate::iterm2_inline::count_badge_cells_w(count),
1,
false,
kitty_id,
1,
)?;
Some(crate::iterm2_inline::maybe_tmux_wrap(
self.inline_protocol,
crate::iterm2_inline::detect_tmux(),
raw,
))
}
/// Count of open editors with unsaved edits, across the active group and any
/// split groups, deduped by path (a file open in two splits is one unsaved
/// file; each dirty path-less buffer counts once). Drives the Explorer
/// activity badge, mirroring VS Code.
fn unsaved_count(&self) -> usize {
let mut paths: std::collections::HashSet<&std::path::Path> =
std::collections::HashSet::new();
let mut pathless = 0usize;
let groups = std::iter::once(&self.editor).chain(self.editor_layout.inactive_groups());
for ed in groups.flat_map(|g| g.editors.iter()).filter(|e| e.dirty) {
match ed.path.as_deref() {
Some(p) => {
paths.insert(p);
}
None => pathless += 1,
}
}
paths.len() + pathless
}
/// Rebuild the cached Explorer unsaved-file badge when the count, theme, or
/// cell size shifts, and mark the activity overlay dirty so the next flush
/// re-emits. Cheap to call every frame: it recomputes the count and bails
/// unless it changed. The glyph-fallback path draws a text badge in
/// `render_activity_bar` instead.
pub fn refresh_explorer_unsaved_badge(&mut self) {
let count = self.unsaved_count();
if !self.overlays.activity.has_images() {
self.explorer_unsaved_badge = None;
if count != self.explorer_unsaved_count {
self.explorer_unsaved_count = count;
self.overlays.activity.mark_dirty();
}
return;
}
if count == self.explorer_unsaved_count {
return;
}
if count == 0 {
self.explorer_unsaved_badge = None;
self.explorer_unsaved_count = 0;
self.overlays.activity.mark_dirty();
return;
}
self.explorer_unsaved_badge = self.build_count_badge_image(
count,
crate::iterm2_inline::KITTY_ID_EXPLORER_BADGE,
self.theme.accent_rgb(),
);
self.explorer_unsaved_count = count;
self.overlays.activity.mark_dirty();
}
/// Rebuild the cached Remote forwarded-ports badge when the count, theme, or
/// cell size shifts. Count-gated like the Explorer badge so it's a cheap
/// per-frame no-op; the glyph-fallback path draws a text badge instead.
pub fn refresh_remote_ports_badge(&mut self) {
let count = self.ports.forwarded_count();
if !self.overlays.activity.has_images() {
self.remote_ports_badge = None;
if count != self.remote_ports_count {
self.remote_ports_count = count;
self.overlays.activity.mark_dirty();
}
return;
}
if count == self.remote_ports_count {
return;
}
if count == 0 {
self.remote_ports_badge = None;
self.remote_ports_count = 0;
self.overlays.activity.mark_dirty();
return;
}
self.remote_ports_badge = self.build_count_badge_image(
count,
crate::iterm2_inline::KITTY_ID_REMOTE_BADGE,
self.theme.accent_rgb(),
);
self.remote_ports_count = count;
self.overlays.activity.mark_dirty();
}
/// Rebuild the cached Testing failing-count badge (red pill) when the count,
/// theme, or cell size shifts. Count-gated per-frame no-op; the glyph path
/// draws a text badge instead.
pub fn refresh_testing_badge(&mut self) {
let count = self.testing.failed_count();
if !self.overlays.activity.has_images() {
self.testing_badge = None;
if count != self.testing_badge_count {
self.testing_badge_count = count;
self.overlays.activity.mark_dirty();
}
return;
}
if count == self.testing_badge_count {
return;
}
if count == 0 {
self.testing_badge = None;
self.testing_badge_count = 0;
self.overlays.activity.mark_dirty();
return;
}
self.testing_badge = self.build_count_badge_image(
count,
crate::iterm2_inline::KITTY_ID_TESTING_BADGE,
self.theme.git_deleted_rgb(),
);
self.testing_badge_count = count;
self.overlays.activity.mark_dirty();
}
/// Rebuild the cached PROBLEMS-tab circle badge (orange, like the activity
/// bar badges) when the count, theme, or cell size shifts. The badge is an
/// inline-image circle emitted post-frame by `flush_problems_badge_overlay`;
/// glyph-fallback terminals keep the powerline-cap pill in `paint_panel_tabs`.
/// Count-gated, so a frame with no churn is a cheap no-op.
pub fn refresh_problems_badge(&mut self) {
let count = self.problems.total_count();
if !self.overlays.activity.has_images() {
self.problems_badge_count = count;
return;
}
if count == self.problems_badge_count {
return;
}
self.problems_badge_count = count;
if count == 0 {
self.overlays.problems_badge.clear_image();
self.overlays.problems_badge.request_clear();
return;
}
if let Some(img) = self.build_count_badge_image(
count,
crate::iterm2_inline::KITTY_ID_PROBLEMS_BADGE,
crate::gradient::GRAD_TR,
) {
self.overlays.problems_badge.set_image(img);
}
}
/// Push the current search query string and toggle state onto the
/// worker channel and keep the editor's match highlight synced to the
/// same term so the active file lights up matches as the user types.
/// Called whenever the search input or one of the toggles changes.
/// Clears the live result list so streamed `Hits` events accumulate
/// from zero rather than appending to leftover hits from the prior query.
fn submit_search_query(&mut self) {
self.search.complete = false;
self.search.hits.clear();
self.search.selected = 0;
self.search.scroll = 0;
// Snapshot unsaved editor buffers so the worker searches their live
// content (and skips the stale disk copy). This is what makes an
// unsaved edit — e.g. a Rename Symbol — findable before save, matching
// VS Code / Zed. Sent before the query so the next scan sees it.
let dirty: Vec<(PathBuf, String)> = self
.editor
.iter_tabs()
.filter(|t| t.dirty)
.filter_map(|t| t.path.clone().map(|p| (p, t.lines.join("\n"))))
.collect();
let _ = self
.search_query_tx
.send(SearchRequest::SetDirtyBuffers(dirty));
// Push the current files-to-include / files-to-exclude globs so the
// next scan honours them (VS Code's Search filter inputs).
let _ = self.search_query_tx.send(SearchRequest::SetFilter(
self.search.include.clone(),
self.search.exclude.clone(),
));
let _ = self.search_query_tx.send(SearchRequest::Query(
self.search.query.clone(),
self.search.opts,
));
let term = if self.search.query.trim().is_empty() {
None
} else {
Some(self.search.query.clone())
};
self.editor.set_search_highlight(term, self.search.opts);
}
/// Apply any pending search events from the background worker. Drops
/// stale events whose query no longer matches the input field (the
/// user has typed past it). `Hits` events append to the live result
/// list as files yield matches; `Done` is informational. Returns true
/// iff hits were updated, so the main loop knows to redraw.
pub fn drain_search_results(&mut self) -> bool {
use crate::widgets::search::SearchEvent;
let mut applied = false;
while let Ok(event) = self.search_results_rx.try_recv() {
match event {
SearchEvent::Hits(q, opts, batch) => {
if q == self.search.query && opts == self.search.opts {
self.search.hits.extend(batch);
applied = true;
}
}
SearchEvent::Done(q, opts) => {
if q == self.search.query && opts == self.search.opts {
self.search.complete = true;
applied = true;
}
}
}
}
applied
}
/// Pull the one-shot remote-extension-index refresh if it has finished.
/// Rebuilds the Extensions panel exactly once, when the verified cache
/// actually changed, then drops the receiver so later calls are no-ops.
pub fn drain_ext_index_refresh(&mut self) -> bool {
let Some(rx) = self.ext_index_refresh.as_ref() else {
return false;
};
match rx.try_recv() {
Ok(updated) => {
self.ext_index_refresh = None;
if updated {
self.refresh_extensions();
}
// A user-triggered refresh reports its outcome; the silent
// startup refresh does not (it must not clobber other status).
if std::mem::take(&mut self.ext_index_manual_refresh) {
self.status = String::from(if updated {
"Extensions index refreshed"
} else {
"Extensions index already up to date"
});
}
updated
}
Err(std::sync::mpsc::TryRecvError::Empty) => false,
Err(std::sync::mpsc::TryRecvError::Disconnected) => {
self.ext_index_refresh = None;
false
}
}
}
/// Manually re-pull the signed remote extension index (the panel's ⟳
/// button). Re-arms the background refresh; the cached entries keep showing
/// meanwhile, and [`Self::drain_ext_index_refresh`] rebuilds the panel and
/// reports the outcome when it lands.
fn refresh_extension_index(&mut self) {
self.ext_index_manual_refresh = true;
self.ext_index_refresh = Some(crate::mcp::registry_index::spawn_refresh());
self.status = String::from("Refreshing extensions index\u{2026}");
}
/// Per-tick LSP doc sync. Diffs every text-buffer tab's edit_seq
/// against `lsp_last_seen` and forwards did_open / did_change /
/// did_close to the LspManager. Building `lines.join("\n")` only
/// happens when a tab's edit_seq has actually moved, so the cost
/// scales with edits, not with frames.
pub fn sync_lsp(&mut self) {
if self.lsp.is_none() {
return;
}
let mut current: std::collections::HashSet<PathBuf> = std::collections::HashSet::new();
// `(is_open, path, text, seq, viewport)`. The viewport `(start, end)`
// lines are captured only for opens, so the first paint can fire a fast
// `semanticTokens/range` over what is on screen ahead of the
// whole-document request.
type DocSync = (bool, PathBuf, String, u64, Option<(u32, u32)>);
let mut to_send: Vec<DocSync> = Vec::new();
// Semantic-token batches recovered from the on-disk cache for files
// being opened this tick. Applied after the tab loop (which borrows the
// editor immutably) so the correct colours paint on the first frame,
// before the server finishes its ~1.8s cold analysis. See
// `crate::lsp::semantic_cache`.
let mut cache_hits: Vec<(PathBuf, std::sync::Arc<Vec<String>>, Vec<u32>)> = Vec::new();
for tab in self.editor.iter_tabs() {
if tab.has_non_text_view() {
continue;
}
let Some(path) = tab.path.as_ref() else {
continue;
};
let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
if crate::lsp::Language::from_extension(ext).is_none() {
continue;
}
current.insert(path.clone());
let seq = tab.edit_seq;
let prev = self.lsp_last_seen.get(path).copied();
match prev {
None => {
// A small look-ahead past the visible rows keeps colour
// stable through the first nudge of the scroll wheel
// before the full-document reply lands.
let start = tab.scroll as u32;
let end = (tab.scroll + tab.page_size() + 16).min(tab.lines.len()) as u32;
let text = tab.lines.join("\n");
// Paint the last-known semantic colours instantly from the
// disk cache, so an import-heavy file does not flash grey
// then snap to the server's class/namespace colours seconds
// later. A hit is identical to what the server will send, so
// the live reply is a no-op repaint.
if let Some((legend, data)) = crate::lsp::semantic_cache::load(path, &text) {
cache_hits.push((path.clone(), legend, data));
}
to_send.push((true, path.clone(), text, seq, Some((start, end))));
}
Some(p) if p != seq => {
to_send.push((false, path.clone(), tab.lines.join("\n"), seq, None))
}
_ => {}
}
}
let lsp = match self.lsp.as_ref() {
Some(l) => l,
None => return,
};
for (is_open, path, text, seq, viewport) in to_send {
let line_count = text.lines().count() as u32 + 1;
if is_open {
lsp.open_doc(path.clone(), text);
// Paint the visible lines first: ty answers a viewport range
// query in tens of ms even on a cold workspace, so on-screen
// code colours immediately while the full request fills in the
// rest. The editor refuses to let this range batch overwrite
// the full one when it arrives.
if let Some((start, end)) = viewport {
lsp.request_semantic_tokens_range(path.clone(), start, end, seq);
}
} else {
lsp.change_doc(path.clone(), text);
}
// Refresh the whole document's semantic tokens whenever it is
// opened or changed. Gated by the same `seq` diff as did_change
// above, so this fires once per edit-batch, not per keystroke.
lsp.request_semantic_tokens(path.clone(), seq);
// Same cadence for inlay hints; the reply carries `seq` so a
// stale batch (computed against older text) is dropped on drain.
if self.inlay_hints_enabled {
lsp.request_inlay_hints(path.clone(), line_count, seq);
}
// Document links ride the same cadence (#254); silent when no
// server advertises a documentLinkProvider, so Ctrl+click
// keeps meaning Go to Definition there.
lsp.request_document_links(path.clone(), seq);
// Fold spans ride the same cadence (#254); the worker drops
// the request silently when no server advertises the
// provider, which is what leaves the editor's indentation /
// region fallback in charge.
lsp.request_folding_ranges(path.clone(), seq);
// Document colors ride the same cadence (#254); the worker is
// silent when no server advertises a colorProvider, which is
// what keeps the swatches from ever appearing unadvertised.
lsp.request_document_colors(path.clone(), seq);
self.lsp_last_seen.insert(path, seq);
}
let closed: Vec<PathBuf> = self
.lsp_last_seen
.keys()
.filter(|p| !current.contains(*p))
.cloned()
.collect();
let mut dropped_any = false;
for p in closed {
lsp.close_doc(p.clone());
self.lsp_last_seen.remove(&p);
// Drop the closed file's diagnostics so the store doesn't grow
// unbounded across a long session of opening and closing files.
dropped_any |= self.lsp_diagnostics.remove(&p).is_some();
}
// A closed file's problems must leave the PROBLEMS panel too.
// Under Open Files scope the panel also depends on WHICH buffers are
// open, so a tab opening or closing changes the answer even when no
// diagnostic moved — rebuild when that set shifts (#256).
let open_now: std::collections::BTreeSet<PathBuf> = self.open_buffer_paths();
let open_changed = open_now != self.problems_open_set;
if open_changed {
self.problems_open_set = open_now;
}
let scope_depends_on_open_set =
self.problems.scope == crate::widgets::problems::ProblemScope::OpenFiles;
if dropped_any || (open_changed && scope_depends_on_open_set) {
self.rebuild_problems();
self.refresh_problems_badge();
}
// Paint cached semantic colours onto the visible editor(s) now that the
// immutable tab borrow above has ended. `is_full = true` so a later
// server `range` reply can't blank the off-screen colours, and the
// identical `full` reply repaints to the same pixels (no snap).
for (path, legend, data) in cache_hits {
if self.editor.path.as_deref() == Some(path.as_path()) {
self.editor
.apply_semantic_tokens(path.clone(), data.clone(), legend.clone(), true);
}
for group in self.editor_layout.inactive_groups_mut() {
if group.path.as_deref() == Some(path.as_path()) {
group.apply_semantic_tokens(path.clone(), data.clone(), legend.clone(), true);
}
}
}
}
/// The repository toplevel owning the workspace, from the git worker's
/// last status reply — the only correct base for porcelain-derived
/// paths and `HEAD:<rel>` pathspecs, which git resolves against the
/// toplevel however `-C` is set (#139). Identical to the workspace
/// root whenever that root IS the toplevel; falls back to it outside
/// a repo (where the ops fail with their own message) and before the
/// first status reply lands.
/// The primary workspace root — what `workspace_root` the field meant
/// before the set model (#143). Single-root semantics throughout.
pub fn workspace_root(&self) -> &Path {
self.roots.primary()
}
fn scm_root(&self) -> PathBuf {
let ws = self.active_scm_root.clone();
self.git_worker_for_root(&ws)
.status()
.repo_root
.clone()
.unwrap_or(ws)
}
/// The workspace root the focus-following surfaces resolve against:
/// the root owning the focused editor's file, else the primary
/// (#149 git, #151 testing/tasks/run).
fn active_workspace_root(&self) -> PathBuf {
self.editor
.path
.as_deref()
.and_then(|p| self.roots.owning_root(p))
.unwrap_or_else(|| self.roots.primary())
.to_path_buf()
}
/// The git worker for a workspace root: the primary's, or the
/// matching secondary's (#149).
fn git_worker_for_root(&self, ws_root: &Path) -> &GitWorker {
self.git_extra
.iter()
.find(|(r, _)| r == ws_root)
.map(|(_, w)| w)
.unwrap_or(&self.git)
}
fn git_worker_for_root_mut(&mut self, ws_root: &Path) -> &mut GitWorker {
match self.git_extra.iter().position(|(r, _)| r == ws_root) {
Some(i) => &mut self.git_extra[i].1,
None => &mut self.git,
}
}
/// The active repository's worker — what `self.git` meant while
/// there was one root (#149).
fn scm_worker(&self) -> &GitWorker {
self.git_worker_for_root(&self.active_scm_root)
}
/// Rebuild the multi-root repositories overview rows (#161) from the
/// per-folder workers: called from the git drain (fresh statuses),
/// the focus sync, and the seed (active-highlight moves with a row
/// click). Empty — section hidden — with one folder.
fn refresh_scm_repositories(&mut self) {
self.source_control.repositories = if self.roots.is_multi() {
let roots: Vec<PathBuf> = self.roots.iter().map(Path::to_path_buf).collect();
let labels = crate::workspace::root_display_labels(&roots);
roots
.iter()
.zip(labels)
.filter_map(|(ws, label)| {
let status = self.git_worker_for_root(ws).status();
if !status.in_repo {
return None;
}
Some(crate::widgets::source_control::RepoRow {
label,
branch: status.branch.clone(),
changes: status.changed_count,
active: *ws == self.active_scm_root,
workspace_root: ws.clone(),
})
})
.collect()
} else {
Vec::new()
};
}
/// Let the ACTIVE repo's next debounced refresh through immediately —
/// every Source Control mutation runs against the active repo (#149).
fn active_git_bypass_debounce(&mut self) {
let ws = self.active_scm_root.clone();
self.git_worker_for_root_mut(&ws).bypass_debounce();
}
/// Keep each text tab's git-gutter baseline current. The first time a tab
/// is seen (or after it switches files, or after HEAD moves), shell out
/// once for the committed version of the file and hand it to the editor;
/// the per-line diff is then recomputed in-buffer on every edit with no
/// further subprocess. Cheap no-op once every open tab has a baseline:
/// just a path compare per tab.
///
/// `read_file_at_head` is a `git show` (~tens of ms) but runs at most once
/// per (file, HEAD) pair, never on the keystroke path. Baselines are shared
/// across groups within a sweep: a split usually holds the SAME file in two
/// panes, and a HEAD move invalidates every tab in every group at once, so
/// without the cache one tick would shell out once per tab per group.
/// ponytail: synchronous fetch on the tick. Move to the git worker thread
/// if opening a file in a huge repo ever visibly hitches.
fn sync_git_gutters(&mut self) {
// `HEAD:<rel>` pathspecs resolve against the toplevel (#139), and
// each file resolves against the repo of ITS owning workspace
// root (#149). Precompute (workspace root → repo toplevel) so the
// editor loop below borrows nothing else off self.
let repo_bases: Vec<(PathBuf, PathBuf)> = self
.roots
.iter()
.map(Path::to_path_buf)
.collect::<Vec<_>>()
.into_iter()
.map(|ws| {
let repo = self
.git_worker_for_root(&ws)
.status()
.repo_root
.clone()
.unwrap_or_else(|| ws.clone());
(ws, repo)
})
.collect();
let repo_for = |path: &Path| -> Option<PathBuf> {
repo_bases
.iter()
.filter(|(ws, _)| path.starts_with(ws))
.max_by_key(|(ws, _)| ws.components().count())
.map(|(_, repo)| repo.clone())
};
let mut fetched: std::collections::HashMap<PathBuf, Option<Vec<String>>> =
std::collections::HashMap::new();
let groups =
std::iter::once(&mut self.editor).chain(self.editor_layout.inactive_groups_mut());
for ed in groups.flat_map(|g| g.editors.iter_mut()) {
let Some(path) = ed.path.clone() else {
continue;
};
if ed.git_baseline_for.as_deref() == Some(path.as_path()) {
continue;
}
// Untracked files / non-repo dirs yield Err here, so the gutter
// simply shows nothing; the baseline-for marker still updates so we
// don't re-shell every tick.
let head = fetched
.entry(path.clone())
.or_insert_with(|| {
let root = repo_for(&path)?;
path.strip_prefix(&root)
.ok()
.and_then(|rel| rel.to_str())
.and_then(|rel| crate::git::read_file_at_head(&root, rel).ok())
.map(|text| text.lines().map(str::to_string).collect())
})
.clone();
ed.set_git_head_lines(path, head);
}
}
/// Fetch per-line git blame for the active editor off-thread, once per
/// (file, HEAD). Mirrors the TIMELINE fetch: a marker gates the spawn so
/// it fires exactly once per active-file change, and a HEAD move resets
/// the marker (see the git-drain path) so blame refreshes after a commit.
/// Gated on the pref so a subprocess never runs when blame is off.
fn sync_blame(&mut self) {
self.editor.blame_enabled = self.inline_blame_enabled;
self.editor.provenance_overlay = self.provenance_overlay;
self.editor.auto_close_pairs = self.auto_close_pairs;
if !self.inline_blame_enabled {
return;
}
let Some(path) = self.editor.path.clone() else {
self.blame_fetched = None;
return;
};
if self.blame_fetched.as_deref() == Some(path.as_path()) {
return;
}
self.blame_fetched = Some(path.clone());
// Pair `-C` and the pathspec with the OWNING workspace root
// (#149): a secondary root's file blames within its own repo;
// the cwd-relative pathspec stays consistent by construction.
let root = self
.roots
.owning_root(&path)
.unwrap_or_else(|| self.roots.primary())
.to_path_buf();
let Some(rel) = path
.strip_prefix(&root)
.ok()
.and_then(|r| r.to_str())
.map(String::from)
else {
// Outside the repo: no blame, but the marker is set so we don't
// respawn every tick.
self.editor.set_blame(path, None);
return;
};
let tx = self.blame_tx.clone();
std::thread::spawn(move || {
let blame = crate::git::blame(&root, &rel);
let _ = tx.send((path, blame));
});
}
/// Install any blame reply whose file is still the active editor. An
/// empty result (untracked file, git unavailable) clears the annotation.
/// Returns true when a reply landed so the frame redraws with it.
fn drain_blame(&mut self) -> bool {
let mut changed = false;
while let Ok((path, blame)) = self.blame_rx.try_recv() {
if self.editor.path.as_deref() == Some(path.as_path()) {
let data = if blame.is_empty() { None } else { Some(blame) };
self.editor.set_blame(path, data);
changed = true;
}
}
changed
}
/// Drain LSP completion responses. Drops responses with stale request
/// ids so a slow earlier reply cannot clobber a fresher popup. Returns
/// true when the popup state changed and the next frame should redraw.
pub fn drain_lsp_completion(&mut self) -> bool {
let Some(lsp) = self.lsp.as_ref() else {
return false;
};
let mut changed = false;
while let Some(result) = lsp.drain_completion() {
if Some(result.request_id) != self.completion_request_id {
continue;
}
let Some((cx, cy)) = self.editor.cursor_screen_pos() else {
continue;
};
let prefix = self.editor.word_before_cursor();
let server_count = result.items.len();
// Merge user snippets whose prefix matches the typed word into the
// suggestion list (VS Code shows snippets in the suggest widget);
// the popup's own prefix filter narrows them further.
let mut items = result.items;
let lang = self.editor.scope_id();
for snip in self.snippets.matching(&prefix, lang) {
items.push(snippet_completion_item(snip));
}
if items.is_empty() {
if self.completion_popup.is_some() {
self.completion_popup = None;
changed = true;
}
continue;
}
let popup = crate::widgets::completion_popup::CompletionPopup::new(
items,
prefix.clone(),
(cx, cy),
result.path,
result.request_id,
);
let filtered = popup.visible_indices().len();
crate::lsp::log_file::log(&format!(
"popup filter: prefix={prefix:?} server={server_count} visible={filtered}"
));
if popup.visible_is_empty() {
self.completion_popup = None;
self.status =
format!("No completions match '{prefix}' ({server_count} from server)");
} else {
self.completion_popup = Some(popup);
}
changed = true;
}
changed
}
/// Tab in the editor: advance a live snippet, else expand a user snippet
/// whose prefix sits before the caret, else fall back to indentation.
fn handle_editor_tab(&mut self) {
if self.editor.snippet_active() {
self.editor.snippet_next();
return;
}
if self.try_expand_snippet() {
return;
}
if self.editor.selection_is_multiline() {
self.editor.indent_lines();
} else {
self.editor.indent_at_cursor();
}
}
/// Expand the user snippet whose prefix exactly matches the word before the
/// caret (in the buffer's language). Returns false when nothing matches, so
/// Tab can fall through to indenting.
fn try_expand_snippet(&mut self) -> bool {
if self.snippets.is_empty() || self.editor.selection.is_some() {
return false;
}
let word = self.editor.word_before_cursor();
if word.is_empty() {
return false;
}
let lang = self.editor.scope_id();
let Some(body) = self.snippets.exact(&word, lang).map(|s| s.body.clone()) else {
return false;
};
self.completion_popup = None;
self.completion_request_id = None;
self.editor.expand_snippet(&body, word.chars().count());
true
}
pub fn trigger_completion(&mut self) {
if self.editor.has_non_text_view() {
return;
}
let Some(path) = self.editor.path.clone() else {
return;
};
let (line, character) = self
.editor
.pos_to_utf16(self.editor.cursor_row, self.editor.cursor_col);
let Some(lsp) = self.lsp.as_mut() else {
return;
};
let id = lsp.request_completion(path, line, character);
self.completion_request_id = Some(id);
}
/// Ask the server for parameter hints at the caret (typing `(` or `,`).
pub fn trigger_signature_help(&mut self) {
if self.editor.has_non_text_view() {
return;
}
let Some(path) = self.editor.path.clone() else {
return;
};
let (line, character) = self
.editor
.pos_to_utf16(self.editor.cursor_row, self.editor.cursor_col);
let Some(lsp) = self.lsp.as_mut() else {
return;
};
let id = lsp.request_signature_help(path, line, character);
self.signature_help_request_id = Some(id);
self.signature_help_anchor = Some((
self.editor.cursor_row,
self.editor.cursor_col,
self.editor.edit_seq,
));
}
/// Dismiss the parameter-hints popup (typing `)`, Esc, or moving away).
fn dismiss_signature_help(&mut self) {
self.signature_help_popup = None;
self.signature_help_request_id = None;
self.signature_help_anchor = None;
}
/// While the parameter-hints popup is open, re-query when the caret moves
/// or the buffer changes (typing an argument, backspacing, arrowing, a
/// click). The empty-response path closes the popup once the caret is no
/// longer inside a call; a non-empty reply keeps it open with the active
/// parameter following the caret. Cheap: only runs while a popup is up.
fn refresh_signature_help_if_moved(&mut self) {
if self.signature_help_popup.is_none() {
return;
}
let now = (
self.editor.cursor_row,
self.editor.cursor_col,
self.editor.edit_seq,
);
if self.signature_help_anchor == Some(now) {
return;
}
// The caret left the editor entirely (focus moved to tree/terminal):
// drop the hint rather than re-query against a stale position.
if self.focus != Pane::Editor {
self.dismiss_signature_help();
return;
}
self.trigger_signature_help();
}
/// Drain LSP signatureHelp responses, dropping stale ids. An empty reply
/// closes any open popup; otherwise the popup is re-anchored to the caret.
pub fn drain_lsp_signature_help(&mut self) -> bool {
let Some(lsp) = self.lsp.as_ref() else {
return false;
};
let mut changed = false;
while let Some(result) = lsp.drain_signature_help() {
if Some(result.request_id) != self.signature_help_request_id {
continue;
}
if result.signatures.is_empty() {
if self.signature_help_popup.is_some() {
self.signature_help_popup = None;
changed = true;
}
continue;
}
let Some((cx, cy)) = self.editor.cursor_screen_pos() else {
continue;
};
self.signature_help_popup = Some(
crate::widgets::signature_help_popup::SignatureHelpPopup::new(
result.signatures,
result.active_signature,
(cx, cy),
result.path,
result.request_id,
),
);
changed = true;
}
changed
}
/// Map a pointer cell to the activity-bar icon under it, if any. Uses the
/// same per-icon rectangles the click handler hit-tests, so hover and
/// click target exactly the same cells.
fn activity_icon_at(&self, col: u16, row: u16) -> Option<ActivityIcon> {
let a = &self.sidebar_areas;
if rect_contains(a.explorer_icon, col, row) {
Some(ActivityIcon::Explorer)
} else if rect_contains(a.search_icon, col, row) {
Some(ActivityIcon::Search)
} else if rect_contains(a.source_control_icon, col, row) {
Some(ActivityIcon::SourceControl)
} else if rect_contains(a.remote_icon, col, row) {
Some(ActivityIcon::Remote)
} else if rect_contains(a.run_debug_icon, col, row) {
Some(ActivityIcon::RunDebug)
} else if rect_contains(a.extensions_icon, col, row) {
Some(ActivityIcon::Extensions)
} else if rect_contains(a.testing_icon, col, row) {
Some(ActivityIcon::Testing)
} else if rect_contains(a.settings_icon, col, row) {
Some(ActivityIcon::Settings)
} else {
None
}
}
/// The hover-tooltip label for whatever chrome control sits under the
/// pointer, or `None` over inert space. The single dispatch point for
/// button hints: each surface contributes one branch that reuses that
/// surface's own hit-test, so adding a new tooltipped control is a
/// one-line change here plus a label in the widget.
fn ui_tooltip_at(&self, col: u16, row: u16) -> Option<&'static str> {
// Layout-control icons at the top-right of the editor strip / welcome.
let icons = self.layout_icon_areas;
if rect_contains(icons.toggle_side_bar, col, row) {
return Some("Toggle Primary Side Bar");
}
if rect_contains(icons.toggle_panel, col, row) {
return Some("Toggle Panel");
}
if rect_contains(icons.customize, col, row) {
return Some("Customize Layout");
}
// Activity bar: always visible, so it is checked regardless of which
// sidebar view is open.
if let Some(icon) = self.activity_icon_at(col, row) {
return Some(match icon {
ActivityIcon::Explorer => "Explorer",
ActivityIcon::Search => "Search",
ActivityIcon::SourceControl => "Source Control",
ActivityIcon::Remote => "Remote",
ActivityIcon::RunDebug => "Run and Debug",
ActivityIcon::Extensions => "Extensions",
ActivityIcon::Testing => "Testing",
ActivityIcon::Settings => "Manage",
});
}
// Sidebar header actions, dispatched by the view that owns them so a
// panel's stored geometry is never consulted once another view has
// replaced it on screen.
match self.sidebar_view {
SidebarView::Search => {
if let Some(label) = self.search.tooltip_at(col, row) {
return Some(label);
}
}
SidebarView::Explorer => {
let t = &self.tree;
if rect_contains(t.header_new_file_btn, col, row) {
return Some("New File");
}
if rect_contains(t.header_new_folder_btn, col, row) {
return Some("New Folder");
}
if rect_contains(t.header_refresh_btn, col, row) {
return Some("Refresh Explorer");
}
if rect_contains(t.header_collapse_btn, col, row) {
return Some("Collapse Folders in Explorer");
}
if rect_contains(t.header_views_btn, col, row) {
return Some("Views and More Actions");
}
}
SidebarView::Remote => {
let r = &self.remote;
if rect_contains(r.header_add_btn, col, row) {
return Some("Open SSH Configuration File");
}
if rect_contains(r.header_refresh_btn, col, row) {
return Some("Refresh");
}
}
SidebarView::SourceControl => {
if rect_contains(self.source_control.header_refresh_btn, col, row) {
return Some("Refresh");
}
}
SidebarView::RunDebug => {}
SidebarView::Extensions => {
if let Some(label) = self.extensions_tooltip_at(col, row) {
return Some(label);
}
}
SidebarView::Testing => {}
}
None
}
/// Resolve the hover tooltip for whatever the pointer is over in the
/// Extensions panel: the toggle switch (state-aware enable/disable), the
/// `+Add` affordance on AVAILABLE rows, or a row body (which conveys the
/// extension's class and how to remove it). Catalog-aware so an installed
/// catalog entry advertises Delete-to-uninstall while a hand-dropped user
/// manifest is correctly described as disable-only.
fn extensions_tooltip_at(&self, col: u16, row: u16) -> Option<&'static str> {
// A tooltip fires ONLY over an actual control, never over the row's
// name/blurb — so hovering the body shows nothing, and each control
// describes just itself. The trash button takes precedence over the
// switch since it sits left of it (and is checked first regardless).
if self.extensions.click_refresh(col, row) {
return Some("Refresh the extension index");
}
if self.extensions.click_clear(col, row) {
return Some("Clear the filter");
}
if self.extensions.click_uninstall(col, row) {
return Some("Uninstall this extension (returns to Available)");
}
if !self.extensions.click_action(col, row) {
return None;
}
let idx = self.extensions.row_at(row)?;
let item = self.extensions.item_at(idx)?;
Some(if item.available {
"Add to your installed extensions"
} else if item.enabled {
"Enabled \u{2014} click to disable"
} else {
"Disabled \u{2014} click to enable"
})
}
/// Fire the chrome button-hint tooltip once its dwell crosses
/// `HOVER_DELAY`. Returns `true` when a tooltip was created so the frame
/// loop redraws. Suppressed while a context menu is open so the two never
/// overlap.
fn poll_ui_tooltip(&mut self) -> bool {
if !self.ui_hover.due(std::time::Instant::now(), HOVER_DELAY) {
return false;
}
self.ui_hover.mark_fired();
if self.context_menu.is_some() {
return false;
}
let Some(label) = self.ui_tooltip_label else {
return false;
};
let Some((col, row)) = self.ui_hover.cell() else {
return false;
};
self.ui_tooltip = Some(crate::widgets::hover_popup::HoverPopup::new_compact(
label.to_string(),
(col, row),
));
true
}
fn on_mouse_moved(&mut self, col: u16, row: u16, in_editor: bool) {
// Activity-bar hover: brighten the icon under the pointer. Re-emit the
// swapped pre-baked image only when the hovered icon actually changes,
// so a pointer drifting within one icon (or anywhere else) costs
// nothing. Computed before the tab/editor early-returns below so the
// hover clears the moment the pointer leaves the bar.
let new_hover = self.activity_icon_at(col, row);
if self.hovered_activity_icon != new_hover {
self.hovered_activity_icon = new_hover;
self.overlays.activity.mark_dirty();
}
// Layout toolbar hover: same affordance, re-emit the brighter image
// variant only when the hovered icon changes.
let li = self.layout_icon_areas;
let new_layout_hover = if rect_contains(li.toggle_side_bar, col, row) {
Some(0)
} else if rect_contains(li.toggle_panel, col, row) {
Some(1)
} else if rect_contains(li.customize, col, row) {
Some(2)
} else {
None
};
if self.hovered_layout_icon != new_layout_hover {
self.hovered_layout_icon = new_layout_hover;
self.overlays.activity.mark_dirty();
}
// Chrome button hints: dwell over a labelled control (activity-bar
// icons, search-panel actions/toggles) to surface its name. Keyed on
// the label so the dwell only restarts when the pointer crosses to a
// different control, and is left running while it drifts within one.
// Computed before the tab/editor early-returns so it tracks the
// pointer everywhere, including over the sidebar.
match self.ui_tooltip_at(col, row) {
// Same label AND still on the same row: keep the dwell running so the
// tooltip persists while the pointer drifts within one control. The
// row check matters because adjacent controls can share a label (e.g.
// every enabled extension toggle reads "Enabled — click to disable");
// without it the anchor would freeze on the first such control and
// the box would appear detached from the one actually under the
// pointer.
Some(label)
if self.ui_tooltip_label == Some(label)
&& self.ui_hover.cell().map(|(_, r)| r) == Some(row) => {}
Some(label) => {
self.ui_hover.on_move(std::time::Instant::now(), col, row);
self.ui_tooltip_label = Some(label);
self.ui_tooltip = None;
}
None => {
self.ui_hover.clear();
self.ui_tooltip = None;
self.ui_tooltip_label = None;
}
}
// Editor tab strip: dwell over a tab to surface its full path. The
// dwell only restarts when the pointer crosses into a *different*
// tab, so the tooltip keeps showing while the pointer drifts a few
// cells within the same tab (matches the LSP "same word" rule).
if let Some(idx) = self.editor.tab_at(col, row) {
self.hover.clear();
self.hover_popup = None;
self.hover_word = None;
self.hover_diagnostic = None;
self.hover_request_id = None;
if self.tab_hover_idx != Some(idx) {
self.tab_hover.on_move(std::time::Instant::now(), col, row);
self.tab_hover_idx = Some(idx);
self.tab_tooltip = None;
}
return;
}
self.tab_hover.clear();
self.tab_tooltip = None;
self.tab_hover_idx = None;
if !in_editor {
self.hover.clear();
// A terminal-annotation note survives pointer drift while the
// pointer stays on its own span (the editor's same-region rule);
// leaving the span dismisses it. Matching the popup's text to
// the span's note keeps a stale editor hover from hiding here.
let over_own_note = self
.hover_popup
.as_ref()
.zip(self.terminal().annotation_at(col, row))
.is_some_and(|(popup, (_, note))| popup.lines.join("\n") == note);
if !over_own_note {
self.hover_popup = None;
}
self.hover_word = None;
self.hover_diagnostic = None;
self.hover_request_id = None;
return;
}
self.hover.on_move(std::time::Instant::now(), col, row);
if self.hover_popup.is_some() {
let current = self
.editor
.buffer_pos_at(col, row)
.and_then(|(line, c)| self.editor.hover_region_at(line, c));
if current != self.hover_word {
self.hover_popup = None;
self.hover_word = None;
self.hover_diagnostic = None;
self.hover_request_id = None;
}
}
}
fn poll_hover(&mut self) {
if !self.hover.due(std::time::Instant::now(), HOVER_DELAY) {
return;
}
self.hover.mark_fired();
if self.completion_popup.is_some() {
return;
}
if self.editor.has_non_text_view() {
return;
}
let Some((col, row)) = self.hover.cell() else {
return;
};
self.hover_at_cell(col, row);
}
/// Resolve a hover at screen cell `(col, row)`: capture any diagnostic
/// under the point synchronously and, for a real identifier, fire the
/// async `textDocument/hover`. Split out of `poll_hover` so the dwell
/// timer doesn't have to be driven to test the resolution logic.
fn hover_at_cell(&mut self, col: u16, row: u16) {
let Some((line, c)) = self.editor.buffer_pos_at(col, row) else {
return;
};
// The region (word, or else a diagnostic span over punctuation) the
// popup belongs to. Nothing of interest under the point → no hover.
let Some(region) = self.editor.hover_region_at(line, c) else {
return;
};
self.hover_anchor = Some((col, row));
self.hover_word = Some(region);
// Debug hover-to-evaluate: while paused, hovering a variable shows its
// current value (from the loaded locals/globals) instead of the LSP
// type hover. Takes priority because the live value is what the user
// wants mid-debug.
if let Some(text) = self.debug_hover_value(line, c) {
self.hover_request_id = None;
self.hover_diagnostic = None;
self.hover_popup = Some(crate::widgets::hover_popup::HoverPopup::new(
text,
(col, row),
));
return;
}
// Server diagnostics are already in the editor, so capture the
// message synchronously; the squiggle's message must show even if the
// server has no type info (or no LSP is attached at all).
self.hover_diagnostic = format_diagnostics(&self.editor.diagnostics_at(line, c));
// Only a real word is worth a `textDocument/hover` round-trip; over
// punctuation there is no symbol to describe, so show the diagnostic
// alone right away.
let word = self.editor.word_at(line, c).is_some();
// Converted before the match: `self.lsp.as_mut()` borrows self for the
// whole scrutinee, so the editor is unreachable inside the arm.
let (uline, uchar) = self.editor.pos_to_utf16(line, c);
match (word, self.editor.path.clone(), self.lsp.as_mut()) {
(true, Some(path), Some(lsp)) => {
let id = lsp.request_hover(path, uline, uchar);
self.hover_request_id = Some(id);
}
_ => {
self.hover_request_id = None;
self.hover_popup = compose_hover(self.hover_diagnostic.as_deref(), None)
.map(|text| crate::widgets::hover_popup::HoverPopup::new(text, (col, row)));
}
}
}
/// Fire the tab-strip tooltip once its dwell crosses `HOVER_DELAY`.
/// Returns `true` when a tooltip was created so the frame loop knows
/// to redraw. Suppressed while a tab context menu is open so the
/// right-click menu never collides with the tooltip.
fn poll_tab_hover(&mut self) -> bool {
if !self.tab_hover.due(std::time::Instant::now(), HOVER_DELAY) {
return false;
}
self.tab_hover.mark_fired();
if self.context_menu.is_some() {
return false;
}
let Some(idx) = self.tab_hover_idx else {
return false;
};
let Some((col, row)) = self.tab_hover.cell() else {
return false;
};
let Some(path) = self.editor.tab_full_path(idx) else {
return false;
};
self.tab_tooltip = Some(crate::widgets::hover_popup::HoverPopup::new(
path,
(col, row),
));
true
}
pub fn drain_lsp_hover(&mut self) -> bool {
let Some(lsp) = self.lsp.as_ref() else {
return false;
};
let mut changed = false;
while let Some(result) = lsp.drain_hover() {
if Some(result.request_id) != self.hover_request_id {
continue;
}
let current = self
.hover
.cell()
.and_then(|(c, r)| self.editor.buffer_pos_at(c, r))
.and_then(|(line, ch)| self.editor.hover_region_at(line, ch));
if current != self.hover_word {
continue;
}
// Diagnostic on top, type info below (VS Code PR #166560). Either
// side may be empty; an all-empty compose hides the popup.
let anchor = self.hover_anchor.unwrap_or((0, 0));
self.hover_popup =
compose_hover(self.hover_diagnostic.as_deref(), result.text.as_deref())
.map(|text| crate::widgets::hover_popup::HoverPopup::new(text, anchor));
changed = true;
}
changed
}
/// Drain semantic-token batches and hand each to whichever editor group
/// currently shows that file. Returns true when an overlay changed and
/// the next frame should redraw.
pub fn drain_lsp_semantic_tokens(&mut self) -> bool {
let Some(lsp) = self.lsp.as_ref() else {
return false;
};
// Collect first so the immutable borrow of `lsp` ends before the
// editors are mutated below.
let mut updates = Vec::new();
while let Some(u) = lsp.drain_semantic_tokens() {
updates.push(u);
}
let mut changed = false;
for u in updates {
// Drop a batch measured against text the buffer has moved past —
// an external reload swaps the whole document while a request is
// still in its retry backoff. Decoding it over the new lines
// paints the old file's colours at the wrong offsets, and the
// `is_full` cache store below would persist that under the NEW
// content's key, replaying it on every future open.
if !semantic_reply_is_current(
self.semantic_generation_seen.get(&u.path).copied(),
u.generation,
) {
continue;
}
let mut applied_anywhere = false;
if self.editor.path.as_deref() == Some(u.path.as_path())
&& self.editor.edit_seq == u.seq
{
self.editor.apply_semantic_tokens(
u.path.clone(),
u.data.clone(),
u.legend.clone(),
u.is_full,
);
changed = true;
applied_anywhere = true;
}
for group in self.editor_layout.inactive_groups_mut() {
if group.path.as_deref() == Some(u.path.as_path()) && group.edit_seq == u.seq {
group.apply_semantic_tokens(
u.path.clone(),
u.data.clone(),
u.legend.clone(),
u.is_full,
);
changed = true;
applied_anywhere = true;
}
}
// Persist whole-document batches so the next open of this exact
// content paints these colours instantly instead of waiting out the
// server's cold analysis. Only when a visible editor holds the file
// unchanged, so the cache key matches the bytes the next open reads.
if applied_anywhere {
self.semantic_generation_seen
.insert(u.path.clone(), u.generation);
}
if u.is_full && applied_anywhere {
let mut clean_text = (self.editor.path.as_deref() == Some(u.path.as_path()))
.then(|| self.editor.clean_cache_text())
.flatten();
if clean_text.is_none() {
clean_text = self
.editor_layout
.inactive_groups_mut()
.into_iter()
.find(|g| g.path.as_deref() == Some(u.path.as_path()))
.and_then(|g| g.clean_cache_text());
}
if let Some(text) = clean_text {
crate::lsp::semantic_cache::store(&u.path, &text, &u.legend, &u.data);
}
}
}
changed
}
/// Route drained inlay-hint batches to whichever visible editor holds the
/// file. A reply whose `seq` no longer matches the buffer's last-synced
/// edit seq is dropped: its anchors were computed against older text, and
/// the request fired for the current seq is still in flight.
pub fn drain_lsp_inlay_hints(&mut self) -> bool {
let Some(lsp) = self.lsp.as_ref() else {
return false;
};
let mut updates = Vec::new();
while let Some(u) = lsp.drain_inlay_hints() {
updates.push(u);
}
let mut changed = false;
for u in updates {
if self.lsp_last_seen.get(&u.path) != Some(&u.seq) {
continue;
}
if self.editor.path.as_deref() == Some(u.path.as_path()) {
self.editor
.apply_inlay_hints(u.path.clone(), u.hints.clone());
changed = true;
}
for group in self.editor_layout.inactive_groups_mut() {
if group.path.as_deref() == Some(u.path.as_path()) {
group.apply_inlay_hints(u.path.clone(), u.hints.clone());
changed = true;
}
}
}
changed
}
/// Drain document-link batches (#254) into every editor showing the
/// file — the inlay fan-out, seq gate included. Links change no
/// pixels, so this never asks for a redraw.
pub fn drain_lsp_document_links(&mut self) {
let Some(lsp) = self.lsp.as_ref() else {
return;
};
let mut updates = Vec::new();
while let Some(u) = lsp.drain_document_links() {
updates.push(u);
}
for u in updates {
if self.lsp_last_seen.get(&u.path) != Some(&u.seq) {
continue;
}
if self.editor.path.as_deref() == Some(u.path.as_path()) {
self.editor
.apply_document_links(u.path.clone(), u.links.clone());
}
for group in self.editor_layout.inactive_groups_mut() {
if group.path.as_deref() == Some(u.path.as_path()) {
group.apply_document_links(u.path.clone(), u.links.clone());
}
}
}
}
/// Follow a server-resolved document link (#254): `file://` targets
/// open in the editor, web links go to the system opener — or, on a
/// relay-capable session, to the user's own browser through the relay.
///
/// Web links only past the `file://` branch, matching
/// `open_detected_url`: the target comes from a language server and the
/// text it decorates says nothing about where it points, so a
/// custom-scheme URI would hand `open`/`xdg-open` an arbitrary target
/// (app launch, protocol handler) off one disguised Ctrl+click. The
/// refusal surfaces the real destination in the status line.
fn open_document_link(&mut self, target: &str) {
// One normalisation for every branch below, so the string that is
// checked is the string that is forwarded: surrounding whitespace is
// dropped, a control character (which the relay's own validator
// rejects, and which has no business in a URI) refuses outright, and
// the scheme match is case-insensitive like `file_ref`'s.
let target = target.trim();
if target.chars().any(char::is_control) {
self.status = format!("Refused to open malformed link: {target:?}");
return;
}
let lower = target.to_ascii_lowercase();
if lower.starts_with("file://") {
if let Ok(url) = lsp_types::Url::parse(target)
&& let Ok(p) = url.to_file_path()
{
// Record where the user was so Back returns to it, exactly
// like go-to-definition and terminal file links.
let from = self.editor.path.clone().map(|path| NavLoc {
path,
row: self.editor.cursor_row,
col: self.editor.cursor_col,
});
match self.editor.open_pinned(&p) {
Ok(()) => {
if let Some(loc) = from {
self.nav.record(loc);
}
self.focus_pane(Pane::Editor);
self.status = format!("Opened {}", self.status_path(&p));
}
Err(e) => self.status = format!("Open failed: {e}"),
}
return;
}
self.status = String::from("Malformed file link");
return;
}
// Deliberately NOT delegated to `open_detected_url`, despite the
// duplicated guard below: that path first probes `diff://` and
// `editor_file_uri`, which resolves `vscode://file/<path>` (and the
// Cursor/Windsurf/Zed schemes) into a file open. A terminal link is
// text the user's own program printed; a document link's target is
// chosen by the language server, so letting it name an editor URI
// would hand a server the ability to open arbitrary paths from a
// click on unrelated-looking text.
let scheme_ok = lower.starts_with("http://") || lower.starts_with("https://");
if !scheme_ok {
self.status = format!("Refused to open non-web link: {target}");
return;
}
// Web link on a remote session: the relay can put it in front of the
// user's own browser, exactly like a terminal link.
if self.drop_relay_active() || is_remote_session() {
self.open_detected_url(target);
return;
}
self.status = match open_url(target) {
Ok(()) => format!("Opened {target}"),
Err(e) => format!("Open link failed: {e}"),
};
}
/// Drain the LSP fold-span replies (#254) into every editor showing
/// the file. Seq-gated like inlay hints; an EMPTY reply is dropped so
/// a server that answers before indexing (or lacks real spans) never
/// erases the indentation/region fallback — the outline's guard.
pub fn drain_lsp_folding_ranges(&mut self) -> bool {
let Some(lsp) = self.lsp.as_ref() else {
return false;
};
let mut updates = Vec::new();
while let Some(u) = lsp.drain_folding_ranges() {
updates.push(u);
}
let mut changed = false;
for u in updates {
if self.lsp_last_seen.get(&u.path) != Some(&u.seq) {
continue;
}
if u.ranges.is_empty() {
continue;
}
if self.editor.path.as_deref() == Some(u.path.as_path()) {
self.editor.set_lsp_folds(u.ranges.clone());
changed = true;
}
for group in self.editor_layout.inactive_groups_mut() {
if group.path.as_deref() == Some(u.path.as_path()) {
group.set_lsp_folds(u.ranges.clone());
changed = true;
}
}
}
changed
}
/// Drain document-color batches (#254) into every editor showing the
/// file — the inlay-hints fan-out, seq gate included. An empty batch
/// clears the swatches (a stylesheet that lost its last color).
pub fn drain_lsp_document_colors(&mut self) -> bool {
let Some(lsp) = self.lsp.as_ref() else {
return false;
};
let mut updates = Vec::new();
while let Some(u) = lsp.drain_document_colors() {
updates.push(u);
}
let mut changed = false;
for u in updates {
if self.lsp_last_seen.get(&u.path) != Some(&u.seq) {
continue;
}
if self.editor.path.as_deref() == Some(u.path.as_path()) {
self.editor
.apply_document_colors(u.path.clone(), u.colors.clone());
changed = true;
}
for group in self.editor_layout.inactive_groups_mut() {
if group.path.as_deref() == Some(u.path.as_path()) {
group.apply_document_colors(u.path.clone(), u.colors.clone());
changed = true;
}
}
}
changed
}
/// "Change Color Presentation" (#254): ask for the alternative
/// spellings of the color value at the cursor and defer the picker on
/// the reply.
fn change_color_presentation(&mut self) {
if !self.editor_is_text() {
return;
}
let (row, col) = (self.editor.cursor_row, self.editor.cursor_col);
let Some(item) = self.editor.color_at(row, col).cloned() else {
self.status = String::from("No color value at the cursor");
return;
};
let Some(path) = self.editor.path.clone() else {
return;
};
let seq = self.editor.edit_seq;
let Some(lsp) = self.lsp.as_mut() else {
self.status = String::from("No language server for this file");
return;
};
let id = lsp.request_color_presentations(
path.clone(),
item.raw,
(item.line, item.character),
(item.end_line, item.end_character),
);
self.color_presentations_request = Some((id, path, seq));
self.status = String::from("Fetching color presentations…");
}
/// Open the presentation picker when the reply lands (#254); gated on
/// id + path + edit_seq like every deferred caret request.
pub fn drain_lsp_color_presentations(&mut self) -> bool {
let mut results = Vec::new();
{
let Some(lsp) = self.lsp.as_ref() else {
return false;
};
while let Some(r) = lsp.drain_color_presentations() {
results.push(r);
}
}
let mut changed = false;
for result in results {
let Some((id, path, seq)) = self.color_presentations_request.clone() else {
continue;
};
if result.request_id != id {
continue;
}
self.color_presentations_request = None;
if self.editor.path.as_deref() != Some(path.as_path()) || self.editor.edit_seq != seq {
continue;
}
changed = true;
if result.presentations.is_empty() {
self.status = String::from("No color presentations offered here");
continue;
}
let rows: Vec<crate::widgets::list_picker::ListRow> = result
.presentations
.iter()
.enumerate()
.map(|(i, (label, _))| crate::widgets::list_picker::ListRow {
id: i.to_string(),
label: label.clone(),
})
.collect();
self.pending_color_presentations = result.presentations;
self.pending_color_context = Some((path.clone(), seq));
self.open_list_picker(
crate::widgets::list_picker::ListPicker::new(
crate::widgets::list_picker::ListPurpose::ColorPresentation,
"Change Color Presentation",
rows,
),
"No color presentations offered here",
);
}
changed
}
/// Flatten the per-server diagnostics stored for `path` into one list for
/// the editor. Servers are layered, not merged across (each owns its own
/// findings), so this is a simple concatenation of every server's set.
fn merged_diagnostics(&self, path: &Path) -> Vec<crate::lsp::manager::Diagnostic> {
self.lsp_diagnostics
.get(path)
.map(|by_server| by_server.values().flatten().cloned().collect())
.unwrap_or_default()
}
/// The producer id for the whole-project check (#256).
///
/// `build_diag_files_by_pane` keys a producer's contribution so its next
/// run replaces its previous one. Pane uids are allocated from 1 upward
/// by an `AtomicU64`, so `u64::MAX` cannot collide with a real pane. The
/// sweep needs its OWN id rather than borrowing one: sharing would make a
/// pane's next command wipe the sweep's rows, and the sweep wipe the
/// pane's.
const PROJECT_CHECK_ID: u64 = u64::MAX;
/// The first line with something to say, escapes stripped (#256).
///
/// A checker's failure output is not a tidy single line: npx opens with
/// a blank line and an ANSI-coloured banner, so both a leading-blank
/// skip and the stripping are needed for the message to carry a reason
/// rather than an escape sequence.
fn first_meaningful_line(text: &str) -> Option<String> {
text.lines()
.map(|l| crate::remote_connect::strip_ansi(l.as_bytes()))
.map(|l| l.trim().to_string())
.find(|l| !l.is_empty())
}
/// Take a finished project check off the channel and report it (#256).
///
/// Three outcomes, deliberately distinguished. A spawn failure names the
/// error. A run that produced no rows AND exited non-zero is an
/// INVOCATION failure, not a clean project: `tsc` prints global errors
/// like `error TS5023: Unknown compiler option` with no `file(line,col)`
/// prefix, so no matcher claims them and the row count is zero - exactly
/// what a clean project looks like. Reporting "no problems" there tells
/// the user their code is fine when the checker never checked it.
/// Otherwise the count is this producer's own, not the panel's.
fn drain_project_check(&mut self) -> bool {
let Ok((cwd, done)) = self.project_check_rx.try_recv() else {
return false;
};
self.project_check_running = false;
match done {
Err(e) => {
// true, not false: the status changed, so the frame must be
// redrawn or the message waits for an unrelated repaint.
self.status = format!("Could not run the project checker: {e}");
true
}
Ok(out) => {
let text = String::from_utf8_lossy(&out.stdout).into_owned();
self.ingest_project_check(Some(&cwd), &text);
self.rebuild_problems();
let n = self.project_check_count();
if n == 0 && !out.status.success() {
// The first NON-BLANK line, from either stream. Which
// stream carries the reason is not predictable: npx
// reports a missing compiler on STDOUT (with an empty
// stderr and a leading blank line), while tsc's own
// global errors also go to stdout and a missing binary
// goes to stderr. Taking `.next()` showed the blank line
// and reported a failure with no reason at all.
let stderr = String::from_utf8_lossy(&out.stderr).into_owned();
let why = Self::first_meaningful_line(&stderr)
.or_else(|| Self::first_meaningful_line(&text))
.unwrap_or_else(|| String::from("no output"));
self.status = format!("The project checker failed: {why}");
} else {
self.status = match n {
0 => String::from("Whole-project check: no problems"),
1 => String::from("Whole-project check: 1 problem"),
n => format!("Whole-project check: {n} problems"),
};
}
true
}
}
}
/// Queue a finished check on the REAL channel WITHOUT draining (#256).
///
/// Test-only. The sibling helper drains immediately, which is right for
/// testing the reporting logic but wrong for the same-tick race: the
/// hint is applied by `sync_explorer_panels`, so the test must let that
/// function do the draining.
#[cfg(all(test, unix))]
pub(crate) fn queue_project_check_result_for_test(
&mut self,
cwd: &Path,
stdout: &str,
stderr: &str,
success: bool,
) {
use std::os::unix::process::ExitStatusExt;
let out = std::process::Output {
status: std::process::ExitStatus::from_raw(if success { 0 } else { 256 }),
stdout: stdout.as_bytes().to_vec(),
stderr: stderr.as_bytes().to_vec(),
};
self.project_check_running = true;
let _ = self.project_check_tx.send((cwd.to_path_buf(), Ok(out)));
}
/// Whether the session's one-shot size hint has been spent (#256).
/// Test-only reader; the field is private.
#[cfg(all(test, unix))]
pub(crate) fn project_check_hinted_for_test(&self) -> bool {
self.project_check_hinted
}
/// Queue a size hint on the REAL channel (#256). Test-only.
///
/// Does not drain: the point is to have it in flight when the result
/// arrives, which is the race that erased it.
#[cfg(all(test, unix))]
pub(crate) fn send_project_hint_for_test(&mut self) {
let _ = self.project_hint_tx.send(());
}
/// Push a finished check through the REAL channel and drain it (#256).
///
/// Test-only, and deliberately not a shortcut: it sends down
/// `project_check_tx` and calls `drain_project_check`, so the reporting
/// logic under test is the shipped one. A helper that set the status
/// itself would pass while the drain was broken.
/// Unix-only: `ExitStatusExt::from_raw` has a different meaning on
/// Windows, and an ungated spawning helper breaks that target's test
/// build without failing anything here or in CI.
#[cfg(all(test, unix))]
pub(crate) fn finish_project_check_for_test(
&mut self,
cwd: &Path,
stdout: &str,
stderr: &str,
success: bool,
) {
use std::os::unix::process::ExitStatusExt;
let out = std::process::Output {
status: std::process::ExitStatus::from_raw(if success { 0 } else { 256 }),
stdout: stdout.as_bytes().to_vec(),
stderr: stderr.as_bytes().to_vec(),
};
self.project_check_running = true;
let _ = self.project_check_tx.send((cwd.to_path_buf(), Ok(out)));
self.drain_project_check();
}
/// Scan a whole-project checker's output into PROBLEMS (#256).
///
/// Routed through `apply_build_scan` rather than a parallel path, so the
/// sweep inherits the matcher table (tsc's two output shapes are already
/// handled), the relative-path resolution, and the replace-wholesale
/// semantics a re-run needs. `cwd` is where the checker ran, which is
/// what its relative paths are against; `None` means the workspace root.
pub(crate) fn ingest_project_check(&mut self, cwd: Option<&Path>, output: &str) -> bool {
let root = self.workspace_root().to_path_buf();
let cwd = cwd.unwrap_or(&root).to_path_buf();
// Count what THIS scan produced, before it is merged into a store
// shared with every other producer.
self.project_check_rows = self.matchers.scan_batch(output, "tsc").len();
self.apply_build_scan(Self::PROJECT_CHECK_ID, Some(&cwd), "tsc", output)
}
/// How many files put a root out of the sweep's automatic reach (#256).
///
/// VS Code's own workspace-diagnostics guidance draws the line around
/// the size where a project-wide compile stops being a background cost
/// and starts being the foreground one. The exact number matters less
/// than having one: the setting overrides it either way.
const PROJECT_CHECK_AUTO_MAX_FILES: usize = 100_000;
/// Whether `root` holds more than `limit` files worth counting (#256).
///
/// Stops at `limit + 1` rather than completing the walk. Counting a
/// giant tree to decide not to walk a giant tree would cost exactly what
/// the cap exists to avoid, and the question is a threshold one - the
/// total is never used.
///
/// Ignored and vendored directories do not count: `node_modules` alone
/// puts most JS projects over any sensible cap, and disabling the sweep
/// for JS projects would disable it for the projects it is FOR.
pub(crate) fn workspace_exceeds(root: &Path, limit: usize) -> bool {
let mut seen = 0usize;
for entry in ignore::WalkBuilder::new(root)
.git_ignore(true)
.require_git(false)
.hidden(false)
.filter_entry(|e| {
e.depth() == 0
|| !e.file_type().is_some_and(|t| t.is_dir())
|| !crate::widgets::file_finder::is_noise_dir(e.file_name())
})
.build()
{
let Ok(entry) = entry else { continue };
if entry.file_type().is_some_and(|t| t.is_file()) {
seen += 1;
if seen > limit {
return true;
}
}
}
false
}
/// Whether the sweep may run WITHOUT the user asking, for `mode` (#256).
///
/// `on` and `off` are answers, not hints: a cap that only ever declined
/// would make `on` useless on the monorepos that most want it, and a cap
/// that could not be turned off would surprise someone who knows their
/// tree. `auto` asks the size question. Anything else reads as `auto`
/// rather than as `on`, so a typo cannot start a compile on a 100k-file
/// root - the failure the cap exists to prevent.
pub(crate) fn project_check_auto_enabled(root: &Path, mode: &str, limit: usize) -> bool {
match Self::project_scope_mode(mode) {
"on" => true,
"off" => false,
_ => !Self::workspace_exceeds(root, limit),
}
}
/// Normalise a `problems_project_scope` value (#256).
///
/// Mirrors `ProblemScope::from_config`: a hand-edited config saying
/// `"Off"` or `" off "` means off, and reading it as `auto` would give
/// the user a size-dependent maybe when they asked for never. Anything
/// unrecognised still becomes `auto`, so a typo cannot turn the sweep
/// ON. Returns a `&'static str` so the cycle and the predicate agree by
/// construction rather than by both remembering to normalise.
pub(crate) fn project_scope_mode(raw: &str) -> &'static str {
match raw.trim().to_ascii_lowercase().as_str() {
"on" | "always" => "on",
"off" | "never" => "off",
_ => "auto",
}
}
/// The whole-project check command for this workspace (#256).
///
/// `tsc --noEmit` when a `tsconfig.json` sits at the root, which is the
/// path VS Code users already take: vtsls exposes project-wide checking
/// poorly over LSP, so the pragmatic route is the compiler itself. `None`
/// when nothing is recognised - the command then says so rather than
/// running a guess.
///
/// The PROJECT's compiler first, `npx --no-install` second. Bare `npx
/// tsc` on a project without TypeScript installed does not fail: it
/// fetches `tsc` from the registry, which is an unrelated Unix
/// terminal-control tool, and runs THAT against the user's source. The
/// `--no-install` flag turns a missing compiler into an error, which is
/// the honest outcome.
fn project_check_command(root: &Path) -> Option<(std::ffi::OsString, Vec<&'static str>)> {
if !root.join("tsconfig.json").is_file() {
return None;
}
let local = root.join("node_modules").join(".bin").join("tsc");
if local.is_file() {
return Some((local.into_os_string(), vec!["--noEmit"]));
}
Some((
std::ffi::OsString::from("npx"),
vec!["--no-install", "tsc", "--noEmit"],
))
}
/// How many rows the last project check contributed (#256).
///
/// NOT `problems.total_count()`: that is the panel's projection, which
/// mixes in every language server's diagnostics and every pane's build
/// output, and which the Open Files scope filters down - so under that
/// scope a sweep whose findings are all in unopened files would report
/// "no problems", defeating the feature. Count this producer's own
/// contribution instead.
///
/// Recorded at install time rather than summed from the store: a file's
/// entry in `build_diagnostics` holds EVERY producer's items for that
/// file, so summing it double-counts a file the sweep and a pane both
/// report. Filtering on the item's `source` would not help either: a
/// pane running tsc produces the same source string as this sweep.
/// (The rows do carry an owner since #532, so an owner-filtered count
/// would work - but this field is already exact and cheaper.)
fn project_check_count(&self) -> usize {
self.project_check_rows
}
/// Scan one finished command's output through the build matchers and
/// install the results (#119). The pane's PREVIOUS contribution is
/// replaced wholesale — a rebuild that fixed everything clears its old
/// entries because the fresh scan is empty. Relative tool paths resolve
/// against the command's cwd (falling back to the workspace root);
/// resolution is lexical, no filesystem probe, so a path the tool
/// printed oddly still gets a row even if navigation later misses.
pub(crate) fn apply_build_scan(
&mut self,
pane: u64,
cwd: Option<&Path>,
cmd: &str,
output: &str,
) -> bool {
// A watch matcher already published this pane's batch mid-run: the
// watcher's exit must not overwrite the last cycle with a rescan of
// its whole history. One skip only — the pane's next command scans.
if self.watch_published_panes.remove(&pane) {
return false;
}
// A task-declared problemMatcher is exclusive for its pane
// (VS Code's model); otherwise user matchers claiming the command
// run alongside the built-in table.
let diags = match self.task_matcher_by_pane.get(&pane) {
Some(m) => m.scan_batch(output),
None => self.matchers.scan_batch(output, cmd),
};
self.install_build_diags(pane, cwd, diags)
}
/// Install `diags` as pane `pane`'s PROBLEMS contribution (#119/#252).
fn install_build_diags(
&mut self,
pane: u64,
cwd: Option<&Path>,
diags: Vec<crate::build_matchers::BuildDiag>,
) -> bool {
let had_old = self
.build_diag_files_by_pane
.get(&pane)
.is_some_and(|v| !v.is_empty());
if diags.is_empty() && !had_old {
return false;
}
if let Some(files) = self.build_diag_files_by_pane.remove(&pane) {
for f in files {
// Filter, never remove: another producer may hold rows on
// this same file, and dropping the entry took them too
// (#532). The entry goes only once nothing is left in it.
if let Some(rows) = self.build_diagnostics.get_mut(&f) {
rows.retain(|(owner, _)| *owner != pane);
if rows.is_empty() {
self.build_diagnostics.remove(&f);
}
}
}
}
let base = cwd.unwrap_or(self.workspace_root()).to_path_buf();
let mut touched = Vec::new();
for d in diags {
let path = {
let p = Path::new(&d.file);
if p.is_absolute() {
p.to_path_buf()
} else {
base.join(p)
}
};
let entry = self.build_diagnostics.entry(path.clone()).or_default();
// Unconditionally: recording only when the entry was empty meant
// the SECOND producer to reach a file never listed it, so its
// next run had nothing to clear (#532). `touched` is this
// producer's own file list, not a set of first-touchers.
if !touched.contains(&path) {
touched.push(path);
}
entry.push((
pane,
crate::widgets::problems::ProblemItem {
line: d.line,
col: d.col,
// Build tools report characters (rustc counts code
// points), not the UTF-16 units an LSP position carries.
col_utf16: false,
severity: d.severity,
message: d.message,
source: d.source.to_string(),
},
));
}
self.build_diag_files_by_pane.insert(pane, touched);
self.rebuild_problems();
true
}
/// Re-read matchers.json (user + workspace) after a save, surfacing
/// compile warnings once in OUTPUT · Matchers (#252).
fn reload_matchers(&mut self) {
// Same isolation guard as App::new: the developer's real
// matchers.json must never steer app tests — a test that saves a
// path equal to the real matchers_path() would otherwise reload
// the runner's actual config here.
let set = if cfg!(test) {
crate::problem_matchers::MatcherSet::default()
} else {
crate::problem_matchers::MatcherSet::load(
&crate::problem_matchers::matchers_path(),
Some(&crate::problem_matchers::workspace_matchers_path(
self.workspace_root(),
)),
)
};
for w in &set.warnings {
crate::output::push("Matchers", crate::output::OutputLevel::Warn, w);
}
let warned = set.warnings.len();
self.watch_set = std::sync::Arc::new(set.watch_set());
self.matchers = std::sync::Arc::new(set);
self.status = if warned == 0 {
format!(
"Problem matchers reloaded ({} active)",
self.matchers.matchers.len()
)
} else {
format!(
"Problem matchers reloaded ({} active, {warned} warning{} — see OUTPUT · Matchers)",
self.matchers.matchers.len(),
if warned == 1 { "" } else { "s" }
)
};
}
fn clear_build_diagnostics(&mut self) {
let n: usize = self.build_diagnostics.values().map(Vec::len).sum();
self.build_diagnostics.clear();
self.build_diag_files_by_pane.clear();
self.rebuild_problems();
self.status = format!(
"Cleared {n} build diagnostic{}",
if n == 1 { "" } else { "s" }
);
}
/// Every open buffer's path, across the active leaf and every inactive
/// one. `App::editor` is the hoisted active leaf and `inactive_leaf_tabs`
/// walks the rest, so together they cover each leaf exactly once.
fn open_buffer_paths(&self) -> std::collections::BTreeSet<PathBuf> {
self.editor
.editors
.iter()
.chain(
self.editor_layout
.inactive_leaf_tabs()
.into_iter()
.flat_map(|g| g.editors.iter()),
)
.filter_map(|e| e.path.clone())
.collect()
}
/// Rebuild the PROBLEMS panel's grouped projection from the per-file
/// diagnostics store. Returns whether the projection changed (so the caller
/// can fold it into its redraw decision). Files are grouped, ordered by
/// path; each group's diagnostics are ordered by position.
fn rebuild_problems(&mut self) -> bool {
use crate::widgets::problems::{ProblemGroup, ProblemItem};
let mut paths: Vec<&PathBuf> = self
.lsp_diagnostics
.keys()
.chain(self.build_diagnostics.keys())
.collect();
paths.sort();
paths.dedup();
// Scope (#256): Open Files keeps only paths with a live buffer, so the
// panel and the status-bar badge (which counts the same list) agree.
let scoped = self.problems.scope == crate::widgets::problems::ProblemScope::OpenFiles;
let open = if scoped {
self.open_buffer_paths()
} else {
std::collections::BTreeSet::new()
};
let scoped_out = |p: &PathBuf| scoped && !open.contains(p);
let mut groups = Vec::new();
for path in paths {
if scoped_out(path) {
continue;
}
let mut items: Vec<ProblemItem> = Vec::new();
if let Some(by_server) = self.lsp_diagnostics.get(path) {
for (server, diags) in by_server {
for d in diags {
items.push(ProblemItem {
line: d.start_line,
col: d.start_char,
col_utf16: true,
severity: d.severity,
message: d.message.clone(),
source: server.clone(),
});
}
}
}
if let Some(build) = self.build_diagnostics.get(path) {
items.extend(build.iter().map(|(_, item)| item.clone()));
}
if items.is_empty() {
continue;
}
items.sort_by_key(|i| (i.line, i.col));
let name = path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
let rel_dir = path
.strip_prefix(self.workspace_root())
.unwrap_or(path)
.parent()
.map(|p| p.to_string_lossy().into_owned())
.unwrap_or_default();
groups.push(ProblemGroup {
path: path.clone(),
name,
rel_dir,
items,
});
}
self.problems.set_groups(groups)
}
/// Drain server-pushed diagnostics into the per-file store, then refresh
/// the underline overlay on whichever editor group shows an affected (or
/// just-switched-to) file. Returns true when an overlay changed and the
/// next frame should redraw.
pub fn drain_lsp_diagnostics(&mut self) -> bool {
// Collect first so the immutable borrow of `lsp` ends before the store
// and the editors are mutated below.
let mut updates = Vec::new();
if let Some(lsp) = self.lsp.as_ref() {
while let Some(u) = lsp.drain_diagnostics() {
updates.push(u);
}
}
let mut touched: std::collections::HashSet<PathBuf> = std::collections::HashSet::new();
for u in updates {
touched.insert(u.path.clone());
let by_server = self.lsp_diagnostics.entry(u.path).or_default();
// An empty batch is the server saying "all clear" for its findings.
if u.diagnostics.is_empty() {
by_server.remove(&u.server);
} else {
by_server.insert(u.server, u.diagnostics);
}
}
let mut changed = false;
// The active editor re-decodes when its file was touched this tick OR
// when it now shows a file whose stored diagnostics it hasn't applied
// yet (a tab switch: diagnostics are pushed, never re-requested).
if let Some(path) = self.editor.path.clone() {
let stale = self.editor.diagnostics_path() != Some(path.as_path());
if stale || touched.contains(&path) {
let merged = self.merged_diagnostics(&path);
self.editor.apply_diagnostics(path, merged);
changed = true;
}
}
// Same for every inactive group, computed without overlapping borrows.
let mut split_targets: Vec<PathBuf> = self
.editor_layout
.inactive_groups_mut()
.into_iter()
.filter_map(|s| {
let p = s.path.clone()?;
let stale = s.diagnostics_path() != Some(p.as_path());
(stale || touched.contains(&p)).then_some(p)
})
.collect();
split_targets.dedup();
for path in split_targets {
let merged = self.merged_diagnostics(&path);
for group in self.editor_layout.inactive_groups_mut() {
if group.path.as_deref() == Some(path.as_path()) {
group.apply_diagnostics(path.clone(), merged.clone());
changed = true;
}
}
}
// The PROBLEMS panel aggregates every file's diagnostics, including
// files no editor group has open, so rebuild it whenever any server
// republished this tick (not only when an editor overlay changed).
if !touched.is_empty() {
changed |= self.rebuild_problems();
}
changed
}
/// Drain server work-done progress updates into the per-server map the
/// status bar reads. Returns true when anything changed so the main loop
/// repaints the bar. A `Some(message)` upserts the server's status; a
/// `None` (the server's `End`) clears it.
pub fn drain_lsp_progress(&mut self) -> bool {
let mut updates = Vec::new();
if let Some(lsp) = self.lsp.as_ref() {
while let Some(u) = lsp.drain_progress() {
updates.push(u);
}
}
let mut changed = false;
for u in updates {
match u.message {
Some(message) => {
self.lsp_progress.insert(u.server, message);
changed = true;
}
None => {
if self.lsp_progress.remove(&u.server).is_some() {
changed = true;
}
}
}
}
changed
}
/// The active LSP progress line for the status bar, if any server is busy
/// (e.g. `rust-analyzer: Indexing 112/340 33%`). Joins multiple busy
/// servers with ` · ` so a Rust + Python workspace shows both.
fn lsp_progress_status(&self) -> Option<String> {
if self.lsp_progress.is_empty() {
return None;
}
let mut entries: Vec<String> = self
.lsp_progress
.iter()
.map(|(server, msg)| format!("{server}: {msg}"))
.collect();
entries.sort();
Some(entries.join(" · "))
}
/// Re-pull semantic tokens when a server asked us to via
/// `workspace/semanticTokens/refresh`. rust-analyzer answers the first
/// request from partial syntax analysis, then sends refresh once its
/// cargo/crate-graph analysis resolves the richer type-aware tokens; this
/// is how that upgraded set reaches the editor without an edit. Only the
/// visible editor(s) are re-requested (matching VS Code), and only for
/// files the manager has open. The fresh full batch replaces the partial
/// one via the editor's `is_full` guard.
pub fn refresh_semantic_tokens_if_requested(&self) {
let Some(lsp) = self.lsp.as_ref() else {
return;
};
if !lsp.take_semantic_refresh() {
return;
}
let mut paths: Vec<PathBuf> = Vec::new();
if let Some(p) = self.editor.path.clone() {
paths.push(p);
}
for group in self.editor_layout.inactive_groups() {
if let Some(p) = group.path.clone() {
paths.push(p);
}
}
for p in paths {
// Re-request at the seq the doc was last synced at, so a reply
// arriving after an external reload is recognised as stale.
if let Some(&seq) = self.lsp_last_seen.get(&p) {
lsp.request_semantic_tokens(p, seq);
}
}
}
/// Re-request inlay hints when a server asked us to via
/// `workspace/inlayHint/refresh` (rust-analyzer sends it after a config
/// reload or when cross-file analysis changes the hints without an edit).
/// Mirrors [`refresh_semantic_tokens_if_requested`].
pub fn refresh_inlay_hints_if_requested(&mut self) {
let Some(lsp) = self.lsp.as_ref() else {
return;
};
if !lsp.take_inlay_refresh() {
return;
}
if self.inlay_hints_enabled {
self.request_inlay_hints_for_open_editors();
}
}
/// Re-pull whole-project diagnostics when a server asked us to via
/// `workspace/diagnostic/refresh` (#533).
///
/// Mirrors [`refresh_semantic_tokens_if_requested`], with one difference:
/// there is nothing to aim it at. A pull covers the whole workspace, not
/// the visible editors, which is the point - it is what puts problems from
/// files no editor has open into PROBLEMS. The manager filters to the
/// servers advertising `workspaceDiagnostics`, so a workspace whose
/// servers all PUSH never sends a request.
pub fn refresh_workspace_diagnostics_if_requested(&self) {
let Some(lsp) = self.lsp.as_ref() else {
return;
};
if !lsp.take_diagnostic_refresh() {
return;
}
lsp.request_workspace_diagnostics();
}
/// Fire an inlay-hint request for every visible editor's file at its
/// current edit seq. Shared by the server-driven refresh and the palette
/// toggle's re-enable path.
fn request_inlay_hints_for_open_editors(&mut self) {
let Some(lsp) = self.lsp.as_ref() else {
return;
};
let mut targets: Vec<(PathBuf, u32)> = Vec::new();
if let Some(p) = self.editor.path.clone() {
targets.push((p, self.editor.line_count() as u32 + 1));
}
for group in self.editor_layout.inactive_groups() {
if let Some(p) = group.path.clone() {
targets.push((p, group.line_count() as u32 + 1));
}
}
for (p, line_count) in targets {
if let Some(&seq) = self.lsp_last_seen.get(&p) {
lsp.request_inlay_hints(p, line_count, seq);
}
}
}
/// Editor: Toggle Inlay Hints — flips the hint display live and persists
/// the choice. Off clears every editor's hints; on re-requests them for
/// the visible files.
fn toggle_inlay_hints(&mut self) {
self.inlay_hints_enabled = !self.inlay_hints_enabled;
if self.inlay_hints_enabled {
self.request_inlay_hints_for_open_editors();
self.status = String::from("Inlay Hints: on");
} else {
self.editor.clear_inlay_hints();
for group in self.editor_layout.inactive_groups_mut() {
group.clear_inlay_hints();
}
self.status = String::from("Inlay Hints: off");
}
if !cfg!(test) {
let _ = crate::prefs::save_inlay_hints(self.inlay_hints_enabled);
}
}
fn go_to_definition(&mut self, path: PathBuf, line: u32, col: u32) {
if let Some(from) = self.editor.path.clone() {
self.nav.record(NavLoc {
path: from,
row: self.editor.cursor_row,
col: self.editor.cursor_col,
});
}
// `col` is the server's UTF-16 column, not a character column.
match self.open_at_utf16(&path, line, col) {
Ok(()) => {
self.status = format!("Jumped to {} line {}", self.status_path(&path), line + 1)
}
Err(e) => self.status = format!("Go to definition failed: {e}"),
}
}
/// The breadcrumb segments for the active editor: the workspace-relative
/// path folders and file name, then the enclosing symbol chain at the
/// caret. Empty for the welcome screen, preview tabs, and buffers with no
/// path (so the bar hides). Symbol crumbs carry a jump target; path crumbs
/// are informational.
fn build_breadcrumbs(&self) -> Vec<crate::widgets::editor::Crumb> {
use crate::widgets::editor::Crumb;
let Some(path) = self.editor.path.as_deref() else {
return Vec::new();
};
if self.editor.has_non_text_view() {
return Vec::new();
}
let mut crumbs = Vec::new();
// Strip against the OWNING root (#147): a secondary-root file
// crumbs from its own root (folder-relative, like status_path),
// never the primary — which yielded the full absolute chain.
let rel = self
.roots
.owning_root(path)
.and_then(|r| path.strip_prefix(r).ok())
.unwrap_or(path);
for comp in rel.components() {
if let std::path::Component::Normal(os) = comp {
crumbs.push(Crumb {
label: os.to_string_lossy().into_owned(),
target: None,
});
}
}
// Symbol scope chain, only when the outline belongs to this file so a
// stale outline from the previous tab never leaks into the bar.
if self.outline.path() == Some(path) {
let line = self.editor.cursor_row as u32;
let symbols = self.outline.symbols();
for i in breadcrumb_symbol_chain(symbols, line) {
let s = &symbols[i];
crumbs.push(Crumb {
label: s.name.clone(),
target: Some((s.line, s.character)),
});
}
}
crumbs
}
/// The scope-header lines to pin as sticky scroll: the enclosing symbols of
/// the top visible line whose header has scrolled above the viewport,
/// outermost first, capped. Empty when the feature does not apply (welcome
/// screen, preview tab, no outline, or nothing scrolled off).
fn build_sticky_lines(&self) -> Vec<u32> {
let Some(path) = self.editor.path.as_deref() else {
return Vec::new();
};
if self.editor.has_non_text_view() {
return Vec::new();
}
if self.outline.path() != Some(path) {
return Vec::new();
}
let top = self.editor.scroll as u32;
let symbols = self.outline.symbols();
breadcrumb_symbol_chain(symbols, top)
.into_iter()
.map(|i| symbols[i].range_start_line)
.filter(|&l| l < top)
.take(STICKY_SCROLL_MAX)
.collect()
}
/// Keep the OUTLINE in sync with the active editor: request fresh symbols
/// when the file or its edit-seq changed (once per change), settle a
/// loaded-empty outline for files no language server tracks, and advance
/// follow-cursor. Returns whether the highlight moved (for redraw).
pub fn sync_outline(&mut self) -> bool {
let Some(path) = self.editor.path.clone() else {
// Back on the welcome screen: drop any stale outline.
if self.outline.path.is_some() {
self.outline.clear();
}
self.outline_synced = None;
return false;
};
// `lsp_last_seen` carries the edit seq the manager last saw for an open
// doc; absent means no language server tracks this file.
let seq = self.lsp_last_seen.get(&path).copied();
let key = (path.clone(), seq);
if self.outline_synced.as_ref() != Some(&key) {
self.outline_synced = Some(key);
// Tree-sitter paints the outline instantly from the buffer's own
// syntax tree, before any language server replies. The LSP request
// below refines it with richer kinds/detail when (and if) it lands.
let syntax = self.compute_syntax_outline(&path);
let lsp_pending = seq.is_some();
self.outline
.set_syntax_symbols(path.clone(), syntax, lsp_pending);
if lsp_pending && let (Some(lsp), Some(seq)) = (self.lsp.as_ref(), seq) {
lsp.request_document_symbols(path, seq);
}
}
// Follow-cursor every tick; cheap (O(symbols)) and only repaints when
// the enclosing symbol actually changes.
self.outline.follow_caret(self.editor.cursor_row as u32)
}
/// Keep the Explorer's non-OUTLINE stacked sub-views current: re-project the
/// OPEN EDITORS list from the tabs, kick off the TIMELINE / DEPENDENCIES
/// background fetches when their input (active file / workspace root) changed,
/// and drain any worker replies. Returns whether anything changed, so the
/// main loop only repaints when it must. All the heavy work (`git log`,
/// `cargo metadata`) runs on spawned threads — never on this tick.
fn sync_explorer_panels(&mut self) -> bool {
let mut changed = false;
// --- OPEN EDITORS: a pure projection of the focused group's tabs. ---
let active = self.editor.active_index();
// Same disambiguated titles as the tab strip (#167), so the two
// views never name one file two ways.
let labels = self.editor.tab_display_labels();
let items: Vec<OpenEditorItem> = self
.editor
.iter_tabs()
.enumerate()
.filter_map(|(i, ed)| {
ed.path.as_ref().map(|p| OpenEditorItem {
path: p.clone(),
name: labels
.get(i)
.cloned()
.unwrap_or_else(|| p.display().to_string()),
dirty: ed.dirty,
active: i == active,
})
})
.collect();
changed |= self.open_editors.set_items(items);
// --- TIMELINE: git history of the active file, fetched off-thread. ---
if self.explorer_views.is_visible(ExplorerView::Timeline) {
match self.editor.path.clone() {
Some(path) => {
if self.timeline_fetched.as_ref() != Some(&path) {
self.timeline_fetched = Some(path.clone());
self.timeline.begin_loading(path.clone());
changed = true;
let timeline_root = self
.roots
.owning_root(&path)
.unwrap_or_else(|| self.roots.primary())
.to_path_buf();
let rel = path
.strip_prefix(&timeline_root)
.ok()
.map(|r| r.to_string_lossy().into_owned());
let root = timeline_root;
let tx = self.timeline_tx.clone();
let history_root = self.history_root.clone();
let abs = path.clone();
let now = now_millis();
std::thread::spawn(move || {
// Merge git commits with local snapshots so the
// TIMELINE shows both sources, like VS Code. Git
// history only exists inside the workspace, but
// snapshots are path-keyed and repo-free, so a
// file outside the root still lists its versions.
let commits = rel
.map(|rel| crate::git::file_history(&root, &rel, 50))
.unwrap_or_default();
let snaps = crate::history::entries_in(&history_root, &abs);
let entries = crate::history::merged_timeline(commits, &snaps, now);
let _ = tx.send((path, entries));
});
}
}
None => {
if self.timeline_fetched.is_some() {
self.timeline_fetched = None;
self.timeline.clear();
changed = true;
}
}
}
}
// A background test-source lookup landed: jump or say it missed. A
// reply from before an Explorer re-root names the old root; drop it.
while let Ok((root, name, hit)) = self.test_jump_rx.try_recv() {
if root != self.workspace_root() {
continue;
}
match hit {
Some((path, line)) => self.go_to_definition(path, line, 0),
None => self.status = format!("No source found for test {name}"),
}
changed = true;
}
// A history snapshot finished writing: refetch the TIMELINE so the
// new version shows (resetting the marker before the write landed
// would list the store without it).
while let Ok(path) = self.history_done_rx.try_recv() {
if self.editor.path.as_deref() == Some(path.as_path()) {
self.timeline_fetched = None;
changed = true;
}
}
// The workspace is too large for the sweep to start on its own.
// Held rather than written: the result below sets `status`
// unconditionally and nothing paints between the two, so writing it
// here DESTROYED the hint whenever the checker finished inside one
// tick - and it is a one-shot, so it never came back. The
// fast-failure path (over-cap root, no compiler installed) is
// exactly where that happened.
let hinted_now = self.project_hint_rx.try_recv().is_ok();
if hinted_now {
// Here, not at the spawn: only a hint that was actually WARRANTED
// spends the one-shot.
self.project_check_hinted = true;
}
// A whole-project check finished: its rows and its verdict land
// together, so the status cannot describe a different run's result.
if self.drain_project_check() {
changed = true;
}
if hinted_now {
// Appended, so the outcome the user asked for still leads.
self.status.push_str(
" - too large for the whole-project check to run on its own; \
set it to always in Problems: Whole-Project Check Auto-Run",
);
changed = true;
}
// Drain any TIMELINE replies; ignore one for a since-closed file.
while let Ok((path, entries)) = self.timeline_rx.try_recv() {
if self.editor.path.as_deref() == Some(path.as_path()) {
self.timeline.set_history(path, entries);
changed = true;
}
}
// Drain any COMMITS graph replies; ignore one for a since-left root.
while let Ok((root, revspec, rows)) = self.graph_rx.try_recv() {
self.graph_fetch_inflight = false;
if root == self.active_scm_root && revspec == self.graph_revspec {
self.commit_graph.set_rows(rows);
changed = true;
}
// A trigger arrived while this reply was in flight: what it
// asked for (new root, newer HEAD) is not what just landed.
if self.graph_refetch_queued {
self.graph_refetch_queued = false;
self.refresh_commit_graph();
}
}
// --- DEPENDENCIES: detect the workspace's package ecosystems from its
// manifest files (cheap, once per root), set the language-aware header,
// then resolve the packages off-thread. The section is gated on
// detection: a root with no recognised manifest detects nothing, so it
// is hidden and dropped from the ⋯ menu (the rule every reference editor
// follows). The fetch only fires when the section is actually shown. ---
let root = self.tree.root.clone();
if self.deps_fetched.as_ref() != Some(&root) {
self.deps_fetched = Some(root.clone());
self.dep_ecosystems = crate::widgets::dependencies::detect_ecosystems(&root);
self.dependencies
.set_header(crate::widgets::dependencies::header_label(
&self.dep_ecosystems,
));
changed = true;
if !self.dep_ecosystems.is_empty()
&& self.explorer_views.is_visible(ExplorerView::Dependencies)
{
let tx = self.deps_tx.clone();
std::thread::spawn(move || {
let deps = crate::widgets::dependencies::fetch_dependencies(&root);
let _ = tx.send(deps);
});
}
}
while let Ok(deps) = self.deps_rx.try_recv() {
self.dependencies.set_deps(deps);
changed = true;
}
changed
}
/// Activate the editor tab for `path` (clicked in OPEN EDITORS). The path is
/// already open by definition, so this selects its tab; should it have been
/// closed between the projection and the click, it re-opens it.
fn activate_open_editor(&mut self, path: PathBuf) {
if let Some(idx) = self.editor.find_tab_with_path(&path) {
self.editor.select(idx);
} else if self.editor.open(&path).is_err() {
self.status = format!("Could not open {}", path.display());
return;
}
self.focus_pane(Pane::Editor);
self.sync_open_file_poll_mtime();
}
/// Open the diff a TIMELINE commit introduced for `path` (`git show <hash>
/// -- <path>`) in a read-only side-by-side editor tab.
fn open_timeline_diff(&mut self, path: PathBuf, hash: String) {
// Disarm first: every early exit below must leave "Restore Snapshot"
// pointing at nothing, never at whatever snapshot was viewed before.
self.history_restore = None;
let rel = match path.strip_prefix(&self.tree.root) {
Ok(r) => r.to_string_lossy().into_owned(),
Err(_) => path.display().to_string(),
};
// A local-history row: diff the snapshot against the working file and
// remember it so "Restore Snapshot" can write it back.
if let Some(millis) = crate::history::snapshot_millis(&hash) {
let Some(snap_file) =
crate::history::snapshot_file_in(&self.history_root, &path, millis)
else {
self.status = String::from("Snapshot no longer available");
return;
};
let Ok(content) = std::fs::read(&snap_file) else {
self.status = String::from("Could not read snapshot");
return;
};
// Snapshots hold the file's raw bytes; decode like `Editor::open`
// so a UTF-16 file's history diffs as text, not mojibake.
let enc = encoding_rs::Encoding::for_bom(&content)
.map(|(e, _)| e)
.unwrap_or(encoding_rs::UTF_8);
let text = enc.decode(&content).0.into_owned();
let label = std::path::PathBuf::from(format!("{rel} (local snapshot)"));
if let Err(e) = self
.editor
.open_head_diff_with_text(label, &text, &path, false)
{
self.status = format!("Could not open snapshot diff: {e}");
return;
}
self.tag_open_diff(crate::widgets::diff::DiffSource::FixedLeft { left_text: text });
self.history_restore = Some((path, millis, content));
self.focus_pane(Pane::Editor);
self.status = format!("Showing {rel} at a local snapshot");
return;
}
// A git commit row: no snapshot to restore.
let timeline_root = self
.editor
.path
.as_deref()
.and_then(|p| self.roots.owning_root(p))
.unwrap_or_else(|| self.roots.primary())
.to_path_buf();
match crate::git::show_commit_file_diff(&timeline_root, &hash, &rel) {
Ok(raw) => {
let label = std::path::PathBuf::from(format!("{rel} @ {hash}"));
if let Err(e) = self.editor.open_git_diff_side_by_side(&label, &raw) {
self.status = format!("Could not open diff: {e}");
return;
}
self.focus_pane(Pane::Editor);
self.status = format!("Showing {rel} at {hash}");
}
Err(e) => {
self.status = format!("git show failed: {e}");
}
}
}
/// Restore the local snapshot currently shown in a TIMELINE diff: write its
/// contents back to the file and reload the buffer. Reachable from the
/// Command Palette once a snapshot diff is open (which records the target).
fn restore_history_snapshot(&mut self) {
let Some((file, millis, content)) = self.history_restore.clone() else {
self.status = String::from("Open a local snapshot from the TIMELINE first");
return;
};
if let Err(e) = std::fs::write(&file, &content) {
self.status = format!("Restore failed: {e}");
return;
}
// The snapshot's seats describe exactly the bytes just written (#349),
// so they come along: onto the buffer, and onto the snapshot this
// restore records below. No open tab's map can serve instead: a
// reverted tab has just had its map cleared, and an unreverted one
// still describes the text the restore replaced. A snapshot with no
// sidecar restores every line unknown, which is what it knows.
let seats =
crate::history::seats_for(&self.history_root, &file, millis).unwrap_or_default();
// If that file is the active tab (the snapshot diff opened it), reload
// so the editor shows the restored contents and the disk stamp resyncs.
// `holds_exactly` re-checks rather than assuming the reload landed the
// restored bytes: another process can rewrite the file between the
// write above and the read inside the revert.
if self.editor.path.as_deref() == Some(file.as_path())
&& self.editor.revert_to_disk().is_ok()
&& self.editor.holds_exactly(&content)
{
let mut onto_buffer = seats.clone();
onto_buffer.truncate(self.editor.lines.len());
self.editor.provenance = onto_buffer;
}
// The restore is itself a new version worth keeping.
self.record_history_snapshot(&file, seats);
self.status = format!("Restored {}", self.status_path(&file));
}
/// Apply a `documentSymbol` reply to the OUTLINE panel, but only when its
/// `path` is still the active editor file — a reply for a file the user
/// navigated away from is dropped. Refreshes follow-cursor on success.
/// Returns whether the outline changed (for redraw).
fn apply_outline_symbols(
&mut self,
path: std::path::PathBuf,
seq: u64,
symbols: Vec<crate::lsp::manager::OutlineSymbol>,
) -> bool {
if self.editor.path.as_ref() != Some(&path) {
return false;
}
// Drop a reply answering an older buffer than the newest request: its
// ranges are shifted by the edits made since, the caret falls outside
// them, and the breadcrumb's symbol crumb flickers off and on with
// every keystroke (visible against a slow remote rust-analyzer while
// tree-sitter and the late reply take turns owning the outline). Only
// enforced when a request seq is tracked for this file; an untracked
// file has no newer request to be stale against.
if let Some((p, Some(newest))) = self.outline_synced.as_ref()
&& *p == path
&& seq != *newest
{
return false;
}
// An empty reply (server lacks `documentSymbol`, or answered before it
// finished indexing) must not blank an outline tree-sitter already
// filled. Keep the syntactic symbols rather than flashing "No symbols".
if symbols.is_empty() && !self.outline.is_empty() {
return false;
}
self.outline.set_symbols(path, symbols);
self.outline.follow_caret(self.editor.cursor_row as u32);
true
}
/// Compute the active editor's outline directly from its syntax tree, so
/// the OUTLINE panel can paint before a (possibly cold) language server
/// answers `documentSymbol`. Empty for files whose language has no outline
/// query; those fall back to the LSP reply.
fn compute_syntax_outline(
&self,
path: &std::path::Path,
) -> Vec<crate::lsp::manager::OutlineSymbol> {
let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
let Some(kind) = crate::highlight::lang_for_extension(ext) else {
return Vec::new();
};
let text = self.editor.lines.join("\n");
crate::outline_syntax::symbols_for(kind, text.as_bytes())
}
/// Drain pending `documentSymbol` replies and offer every one to
/// `apply_outline_symbols`, which is the sole judge of what applies.
///
/// Deliberately no pre-selection. The drain used to collapse a tick's
/// replies to whichever ARRIVED last and discard the rest, which lost the
/// active file's reply whenever a slow one for the file just left landed
/// after it — the guard then rejected the survivor on path, and
/// `sync_outline` never re-requests because its `(path, seq)` key has not
/// changed. Picking the highest seq instead would be just as wrong: `seq`
/// is a per-`Editor` counter that RESTARTS at zero when a file lands in a
/// fresh editor group (a split, or close-and-reopen), so the outstanding
/// request can carry a lower number than a reply still in flight from the
/// old group. Offering all of them keeps the decision in the one place
/// that knows which request is outstanding.
pub fn drain_lsp_document_symbols(&mut self) -> bool {
let mut replies = Vec::new();
if let Some(lsp) = self.lsp.as_ref() {
while let Some(r) = lsp.drain_document_symbols() {
replies.push((r.path, r.seq, r.symbols));
}
}
let mut applied = false;
for (path, seq, symbols) in replies {
applied |= self.apply_outline_symbols(path, seq, symbols);
}
applied
}
pub fn drain_lsp_definition(&mut self) -> bool {
let mut target = None;
let mut peek = None;
{
let Some(lsp) = self.lsp.as_ref() else {
return false;
};
let mut peek_replied = false;
while let Some(result) = lsp.drain_definition() {
if Some(result.request_id) == self.peek_definition_request_id {
peek_replied = true;
peek = result.target;
continue;
}
if Some(result.request_id) != self.definition_request_id {
continue;
}
target = result.target;
}
if peek_replied && peek.is_none() {
// The reply arrived empty: without this the "Peeking
// definition" status hung forever with no popup.
self.peek_definition_request_id = None;
self.status = String::from("No definition found");
}
}
let mut changed = false;
if let Some((path, line, col)) = peek {
self.peek_definition_request_id = None;
self.open_peek_popup(path, line, col);
changed = true;
}
if let Some((path, line, col)) = target {
self.go_to_definition(path, line, col);
changed = true;
}
changed
}
/// Build and show the Peek Definition popup: a `path:line` header and a
/// numbered excerpt of the target region with the definition line marked.
/// The open buffer supplies the text when the target file is already open
/// (unsaved edits visible); disk otherwise.
fn open_peek_popup(&mut self, path: PathBuf, line: u32, col: u32) {
// Any open buffer wins over disk — the ACTIVE group's tabs plus
// every inactive split leaf's — so unsaved edits show wherever the
// target file happens to be open.
let open_buffer = self
.editor
.editors
.iter()
.chain(
self.editor_layout
.inactive_leaf_tabs()
.into_iter()
.flat_map(|tabs| tabs.editors.iter()),
)
.find(|e| e.path.as_deref() == Some(path.as_path()))
.map(|e| e.lines.clone());
let lines: Vec<String> = match open_buffer {
Some(lines) => lines,
None => match std::fs::read_to_string(&path) {
Ok(text) => text.lines().map(|s| s.to_string()).collect(),
Err(e) => {
self.status = format!("Peek failed: {e}");
return;
}
},
};
let target = line as usize;
let (start, excerpt) = peek_excerpt(&lines, target, 4, 12);
let mut body = vec![format!("{}:{}", self.status_path(&path), target + 1)];
let num_w = (start + excerpt.len()).to_string().len();
for (i, text) in excerpt.iter().enumerate() {
let n = start + i;
let marker = if n == target { '\u{25b6}' } else { ' ' };
body.push(format!("{marker}{:>num_w$} {text}", n + 1));
}
body.push(String::from("Enter jumps \u{00b7} Esc closes"));
let anchor = self.editor.cursor_screen_pos().unwrap_or((
self.editor.last_full_area.x + 1,
self.editor.last_full_area.y + 1,
));
self.peek_popup = Some(crate::widgets::hover_popup::HoverPopup::new(
body.join("\n"),
anchor,
));
self.peek_target = Some((path, line, col));
self.status = String::new();
}
fn close_peek_popup(&mut self) {
self.peek_popup = None;
self.peek_target = None;
}
pub fn drain_lsp_declaration(&mut self) -> bool {
let mut target = None;
let mut unsupported = false;
{
let Some(lsp) = self.lsp.as_ref() else {
return false;
};
while let Some(result) = lsp.drain_declaration() {
if Some(result.request_id) != self.declaration_request_id {
continue;
}
target = result.target;
unsupported = result.unsupported;
}
}
match target {
// The jump itself is identical to definition: open the target file,
// move the caret, record nav history.
Some((path, line, col)) => {
self.go_to_definition(path, line, col);
true
}
// Be explicit rather than silently no-op: say when the language
// server has no declaration provider (e.g. TypeScript's vtsls) and
// when it simply found nothing at this position.
None if unsupported => {
self.status =
String::from("Go to Declaration: not supported by this file's language server");
true
}
None => false,
}
}
pub fn drain_lsp_type_definition(&mut self) -> bool {
let mut target = None;
let mut unsupported = false;
{
let Some(lsp) = self.lsp.as_ref() else {
return false;
};
while let Some(result) = lsp.drain_type_definition() {
if Some(result.request_id) != self.type_definition_request_id {
continue;
}
target = result.target;
unsupported = result.unsupported;
}
}
match target {
// The jump itself is identical to definition: open the target file,
// move the caret, record nav history.
Some((path, line, col)) => {
self.go_to_definition(path, line, col);
true
}
None if unsupported => {
self.status = String::from(
"Go to Type Definition: not supported by this file's language server",
);
true
}
None => false,
}
}
pub fn drain_lsp_implementation(&mut self) -> bool {
let mut targets: Vec<(PathBuf, u32, u32)> = Vec::new();
let mut unsupported = false;
let mut responded = false;
{
let Some(lsp) = self.lsp.as_ref() else {
return false;
};
while let Some(result) = lsp.drain_implementation() {
if Some(result.request_id) != self.implementation_request_id {
continue;
}
targets = result.targets;
unsupported = result.unsupported;
responded = true;
}
}
if !responded {
return false;
}
if unsupported {
self.status =
String::from("Go to Implementations: not supported by this file's language server");
return true;
}
match targets.len() {
0 => self.status = String::from("No implementations found"),
// One implementor: behave exactly like Go to Definition.
1 => {
let (path, line, col) = targets.into_iter().next().expect("len == 1");
self.go_to_definition(path, line, col);
}
// Many implementors: offer a picker rather than silently choosing
// the first. This 1:many case is the whole point of the feature.
_ => self.open_location_picker(targets, "implementations"),
}
true
}
pub fn drain_lsp_references(&mut self) -> bool {
let mut targets: Vec<(PathBuf, u32, u32)> = Vec::new();
let mut unsupported = false;
let mut responded = false;
{
let Some(lsp) = self.lsp.as_ref() else {
return false;
};
while let Some(result) = lsp.drain_references() {
if Some(result.request_id) != self.references_request_id {
continue;
}
targets = result.targets;
unsupported = result.unsupported;
responded = true;
}
}
if !responded {
return false;
}
if unsupported {
self.status =
String::from("Go to References: not supported by this file's language server");
return true;
}
match targets.len() {
0 => self.status = String::from("No references found"),
// A symbol used exactly once: jump straight there like Go to
// Definition rather than pop a one-row picker.
1 => {
let (path, line, col) = targets.into_iter().next().expect("len == 1");
self.go_to_definition(path, line, col);
}
// The common case: a symbol used in many places. Offer every use as
// a picker, exactly like Go to Implementations.
_ => self.open_location_picker(targets, "references"),
}
true
}
/// Apply a call-hierarchy reply: a picker of callers/callees labelled
/// `name — path:line`, jumping on select. Invoking the command again at a
/// picked site walks the next level of the hierarchy.
pub fn drain_lsp_call_hierarchy(&mut self) -> bool {
let mut result = None;
{
let Some(lsp) = self.lsp.as_ref() else {
return false;
};
while let Some(r) = lsp.drain_call_hierarchy() {
if Some(r.request_id) == self.call_hierarchy_request_id {
result = Some(r);
}
}
}
let Some(result) = result else {
return false;
};
let noun = if result.incoming {
"incoming calls"
} else {
"outgoing calls"
};
if result.unsupported {
self.status =
String::from("Call hierarchy: not supported by this file's language server");
return true;
}
if result.sites.is_empty() {
self.status = format!("No {noun}");
return true;
}
let root = self.tree.root.clone();
let items: Vec<(String, MenuAction)> = result
.sites
.into_iter()
.map(|s| {
let label = format!(
"{} — {}:{}",
s.name,
s.path.strip_prefix(&root).unwrap_or(&s.path).display(),
s.line + 1
);
(
label,
MenuAction::GoToLocation {
path: s.path,
line: s.line,
col: s.character,
},
)
})
.collect();
self.present_call_hierarchy_menu(items, noun);
true
}
/// Show a call-hierarchy reply as a picker at the caret — unless another
/// menu is already open: rust-analyzer can answer seconds later, and a
/// late reply must not replace what the user is looking at (or yank
/// focus to the editor under them).
fn present_call_hierarchy_menu(&mut self, items: Vec<(String, MenuAction)>, noun: &str) {
if self.context_menu.is_some() {
self.status = String::from("Call hierarchy ready, but another menu is open");
return;
}
self.status = format!("{} {noun}", items.len());
let origin = self.editor.cursor_screen_pos().unwrap_or((
self.editor.last_full_area.x + 1,
self.editor.last_full_area.y + 1,
));
// A late server reply is not the user asking to leave the sidebar.
// The `context_menu` guard cannot cover this: it is set on the NEXT
// line, so auto-hide would already have fired.
self.without_auto_hide(|app| app.focus_pane(Pane::Editor));
let root = self.tree.root.clone();
self.context_menu = Some(ContextMenu::flat(origin, items, root));
}
/// Request the callers (`incoming`) or callees of the symbol at the
/// cursor. Cmd+K H / Cmd+K Shift+H and the right-click menu rows.
fn request_call_hierarchy_at_cursor(&mut self, incoming: bool) {
let (line, character) = self
.editor
.pos_to_utf16(self.editor.cursor_row, self.editor.cursor_col);
let Some(path) = self.editor.path.clone() else {
return;
};
let Some(lsp) = self.lsp.as_mut() else {
self.status = String::from("Call hierarchy: no language server for this file");
return;
};
let id = lsp.request_call_hierarchy(path, line, character, incoming);
self.call_hierarchy_request_id = Some(id);
}
/// Whether the current file's language server implements call hierarchy;
/// drives the right-click menu rows, like the other capability gates.
fn editor_language_supports_call_hierarchy(&self) -> bool {
let Some(lang) = self
.editor
.path
.as_deref()
.and_then(|p| p.extension())
.and_then(|e| e.to_str())
.and_then(crate::lsp::Language::from_extension)
else {
return false;
};
self.lsp
.as_ref()
.and_then(|lsp| lsp.language_supports_call_hierarchy(lang))
.unwrap_or(false)
}
/// On-type formatting (#254), run once per frame: when enabled and the
/// last edit was a keystroke in the server's advertised trigger set,
/// fire `textDocument/onTypeFormatting` at the caret. The typed record
/// is consumed here — examined exactly once, on the frame right after
/// the keystroke — so a later tab switch or settings toggle can never
/// replay a stale trigger. Never fires unadvertised: the trigger set
/// comes from the capability the server declared, and `None` (no server
/// probed, or no provider) means stay inert.
pub fn tick_on_type_formatting(&mut self) {
let taken = self.editor.last_typed.take();
// A keystroke and a tab switch can arrive in the same input burst,
// draining before this tick runs — the record is then armed on a tab
// that is no longer active, and nothing else ever clears it. Sweep
// every editor in every group (the active one is already drained by
// the `take` above) so a trigger can only ever fire from the tab
// that was active at its tick.
let groups =
std::iter::once(&mut self.editor).chain(self.editor_layout.inactive_groups_mut());
for ed in groups.flat_map(|g| g.editors.iter_mut()) {
ed.last_typed = None;
}
let Some((ch, seq)) = taken else {
return;
};
if !self.format_on_type || !self.editor_is_text() {
return;
}
if seq != self.editor.edit_seq {
return;
}
let Some(path) = self.editor.path.clone() else {
return;
};
let Some(lang) = path
.extension()
.and_then(|e| e.to_str())
.and_then(crate::lsp::Language::from_extension)
else {
return;
};
let triggers = self
.lsp
.as_ref()
.and_then(|lsp| lsp.language_on_type_triggers(lang));
if !triggers.is_some_and(|t| t.contains(ch)) {
return;
}
let (line, character) = self
.editor
.pos_to_utf16(self.editor.cursor_row, self.editor.cursor_col);
let (tab_size, insert_spaces) = self.editor.indent_preference();
let Some(lsp) = self.lsp.as_mut() else {
return;
};
let id = lsp.request_on_type_formatting(
path.clone(),
line,
character,
ch,
tab_size,
insert_spaces,
);
self.on_type_request = Some((id, seq, path));
}
/// What to do with one on-type formatting reply. Extracted from the
/// drain loop so the three-way decision is testable without a live
/// server: the channel's sender lives inside the LSP worker, so a test
/// cannot inject a `FormatResult` through it.
fn on_type_reply_disposition(&self, result: &crate::lsp::manager::FormatResult) -> OnTypeReply {
let Some((id, seq, ref requested)) = self.on_type_request else {
return OnTypeReply::NotOurs;
};
// A superseded reply must NOT clear the armed request: a newer one
// is in flight and its own reply still has to apply.
if result.request_id != id {
return OnTypeReply::NotOurs;
}
// `edit_seq` is per-tab, so the counter comparison only means
// "buffer unchanged" when the active tab is still the one the
// request was computed against — require the path to match too.
// Content-unchanged is also the whole test on purpose: caret-only
// motion (arrow keys, auto-pair type-over) leaves the counter
// alone, and that is correct — the server's edits are document
// edits computed against text that is still byte-identical, so
// they apply cleanly wherever the caret has wandered.
if self.editor.edit_seq != seq
|| requested != &result.path
|| self.editor.path.as_deref() != Some(result.path.as_path())
{
return OnTypeReply::Stale;
}
OnTypeReply::Apply
}
/// Apply an on-type formatting reply — quietly, and only while the
/// buffer has not moved since the request (the edits were computed
/// against exactly that text; continued typing makes them stale).
pub fn drain_lsp_on_type_format(&mut self) -> bool {
let mut results = Vec::new();
{
let Some(lsp) = self.lsp.as_ref() else {
return false;
};
while let Some(r) = lsp.drain_on_type_formatting() {
results.push(r);
}
}
let mut changed = false;
for result in results {
match self.on_type_reply_disposition(&result) {
OnTypeReply::NotOurs => continue,
OnTypeReply::Stale => {
self.on_type_request = None;
continue;
}
OnTypeReply::Apply => self.on_type_request = None,
}
if let Some(edits) = result.edits.filter(|e| !e.is_empty())
&& self
.editor
.apply_rename_to_open_tab(&result.path, &edits)
.is_some()
{
self.editor.clamp_cursor();
changed = true;
}
}
changed
}
/// Linked editing (#254): replay the last keystroke across the
/// sibling tag ranges, keep the set alive only while the caret
/// stays inside one, and (debounced on caret idle) ask the server
/// for the set at a new caret position. Never fires a request for a
/// language the LSP layer isn't tracking; a server without the
/// provider simply never answers, and the feature stays inert.
pub fn tick_linked_editing(&mut self) -> bool {
const LINKED_IDLE: std::time::Duration = std::time::Duration::from_millis(250);
let mirrored = self.editor.mirror_linked_edit();
let eligible = self.editor_is_text() && self.lsp.is_some();
let Some(path) = self.editor.path.clone().filter(|_| eligible) else {
self.linked_observed = None;
self.linked_request = None;
self.editor.clear_linked_ranges();
return mirrored;
};
let (row, col) = (self.editor.cursor_row, self.editor.cursor_col);
// While the caret stays inside the live set, keep it — the whole
// point is typing inside a range. (The mirror above re-synced
// positions for this frame's keystroke.)
if self.editor.has_linked_ranges() {
if self.editor.linked_ranges_contain(row, col) {
return mirrored;
}
self.editor.clear_linked_ranges();
}
let cur = (path, row, col, self.editor.edit_seq);
if self.linked_observed.as_ref() != Some(&cur) {
self.linked_observed = Some(cur);
self.linked_observed_at = std::time::Instant::now();
self.linked_request = None;
return mirrored;
}
let already = self
.linked_request
.as_ref()
.is_some_and(|(_, p, s)| (p, s) == (&cur.0, &cur.3));
if already || self.linked_observed_at.elapsed() < LINKED_IDLE {
return mirrored;
}
let (uline, uchar) = self.editor.cursor_position_utf16();
let Some(lsp) = self.lsp.as_mut() else {
return mirrored;
};
let id = lsp.request_linked_editing(cur.0.clone(), uline, uchar);
self.linked_request = Some((id, cur.0, cur.3));
mirrored
}
/// Install a linkedEditingRange reply, gated on the in-flight id,
/// the path, and the edit seq the spans were computed against.
pub fn drain_lsp_linked_editing(&mut self) -> bool {
let mut results = Vec::new();
{
let Some(lsp) = self.lsp.as_ref() else {
return false;
};
while let Some(r) = lsp.drain_linked_editing() {
results.push(r);
}
}
let mut changed = false;
for result in results {
let Some((id, path, seq)) = self.linked_request.as_ref() else {
continue;
};
if result.request_id != *id
|| self.editor.path.as_deref() != Some(path.as_path())
|| self.editor.edit_seq != *seq
{
continue;
}
self.linked_request = None;
self.editor.set_linked_ranges(&result.ranges);
changed = true;
}
changed
}
/// Expand Selection (#254): grow every cursor to the next
/// semantically meaningful range. Cached chain steps apply
/// instantly; otherwise the LSP `selectionRange` chains are fetched
/// (one request, all cursors), with tree-sitter node ancestry as the
/// serverless fallback — so the gesture works with no LSP at all.
fn expand_selection(&mut self) {
if !self.editor_is_text() {
return;
}
self.editor.validate_expand_stacks();
if self.editor.expand_selection_from_stack() {
return;
}
let lang_known = self
.editor
.path
.as_deref()
.and_then(|p| p.extension())
.and_then(|e| e.to_str())
.and_then(crate::lsp::Language::from_extension)
.is_some();
if lang_known
&& self.lsp.is_some()
&& let Some(path) = self.editor.path.clone()
{
let seq = self.editor.edit_seq;
let positions = self.editor.cursor_positions_utf16();
// Reuse the pending request only when it was fired for these
// exact cursors; a caret move re-fires for the new spot.
if let Some(pending) = self.selection_range_request.as_mut()
&& pending.path == path
&& pending.seq == seq
&& pending.positions == positions
{
pending.presses += 1;
return;
}
if let Some(lsp) = self.lsp.as_mut() {
let id = lsp.request_selection_ranges(path.clone(), positions.clone());
self.selection_range_request = Some(PendingSelectionRanges {
id,
path,
seq,
presses: 1,
positions,
});
}
return;
}
if !self.editor.expand_selection_syntax() {
self.status = String::from("No larger range to select");
}
}
/// Shrink Selection: retrace the expand stack one step. Purely
/// local — the stack already remembers the exact ranges.
fn shrink_selection(&mut self) {
if !self.editor_is_text() {
return;
}
self.editor.shrink_selection_step();
}
/// Drain `selectionRange` replies (#254): triple-gated like
/// occurrences (id + path + edit_seq), then either install the
/// server's chains or resolve the queued presses via tree-sitter
/// when the request came back unsupported/empty.
fn drain_lsp_selection_ranges(&mut self) -> bool {
let Some(lsp) = self.lsp.as_ref() else {
return false;
};
let mut results = Vec::new();
while let Some(r) = lsp.drain_selection_ranges() {
results.push(r);
}
let mut changed = false;
for r in results {
let Some(pending) = self.selection_range_request.as_ref() else {
continue;
};
// Gate on id + path + edit_seq AND the cursors the request
// was fired for: a click between request and reply leaves
// `edit_seq` unchanged, but the chains describe the OLD
// caret and must not apply at the new one.
if r.request_id != pending.id
|| self.editor.path.as_deref() != Some(pending.path.as_path())
|| self.editor.edit_seq != pending.seq
|| self.editor.cursor_positions_utf16() != pending.positions
{
if r.request_id == pending.id {
self.selection_range_request = None;
}
continue;
}
let presses = pending.presses;
self.selection_range_request = None;
if r.unsupported || r.chains.is_empty() {
for _ in 0..presses {
if !self.editor.expand_selection_syntax() {
break;
}
}
changed = true;
continue;
}
self.editor.install_selection_chains(r.chains);
for _ in 0..presses {
if !self.editor.expand_selection_from_stack() {
break;
}
}
changed = true;
}
changed
}
/// Idle-caret occurrences trigger, run once per frame: when the caret has
/// rested on one buffer position for `OCCURRENCES_IDLE`, fire ONE
/// `documentHighlight` request for it; the moment it moves (or the buffer
/// edits), drop the painted set. Mirrors VS Code's word highlight, which
/// follows the cursor with a small debounce rather than every keystroke.
pub fn tick_occurrences(&mut self) -> bool {
const OCCURRENCES_IDLE: std::time::Duration = std::time::Duration::from_millis(250);
let eligible = self.editor.diff.is_none()
&& self.editor.sheet.is_none()
&& self.editor.image.is_none()
&& self.lsp.is_some();
let Some(path) = self.editor.path.clone().filter(|_| eligible) else {
self.occ_observed = None;
self.occurrences_request = None;
return self.editor.clear_occurrences();
};
let cur = (
path,
self.editor.cursor_row,
self.editor.cursor_col,
self.editor.edit_seq,
);
if self.occ_observed.as_ref() != Some(&cur) {
self.occ_observed = Some(cur);
self.occ_observed_at = std::time::Instant::now();
// The old symbol's tints are stale the moment the caret leaves it
// (an edit already cleared them via mark_buffer_changed), and an
// in-flight reply for the old spot must never paint late.
self.occurrences_request = None;
return self.editor.clear_occurrences();
}
let already_requested = self
.occurrences_request
.as_ref()
.is_some_and(|(_, p, r, c, s)| (p, r, c, s) == (&cur.0, &cur.1, &cur.2, &cur.3));
if already_requested || self.occ_observed_at.elapsed() < OCCURRENCES_IDLE {
return false;
}
let (uline, uchar) = self.editor.pos_to_utf16(cur.1, cur.2);
let Some(lsp) = self.lsp.as_mut() else {
return false;
};
let id = lsp.request_document_highlights(cur.0.clone(), uline, uchar);
self.occurrences_request = Some((id, cur.0, cur.1, cur.2, cur.3));
false
}
/// Apply a documentHighlight reply to the editor, dropping it unless it
/// answers the in-flight request AND the editor still shows that file at
/// that edit seq (the columns were computed against that text).
pub fn drain_lsp_document_highlights(&mut self) -> bool {
let mut results = Vec::new();
{
let Some(lsp) = self.lsp.as_ref() else {
return false;
};
while let Some(r) = lsp.drain_document_highlights() {
results.push(r);
}
}
let mut changed = false;
for result in results {
let Some((id, path, _row, _col, seq)) = self.occurrences_request.as_ref() else {
continue;
};
if result.request_id != *id
|| self.editor.path.as_deref() != Some(path.as_path())
|| self.editor.edit_seq != *seq
{
continue;
}
self.editor.apply_occurrences(result.items);
changed = true;
}
changed
}
/// Build a multi-location picker as a `ContextMenu` anchored at the editor
/// cursor: one row per target, labelled `relative/path:line`, each carrying a
/// `GoToLocation` that jumps on select. Reuses the context menu's existing
/// keyboard (arrows + Enter) and mouse handling. Shared by Go to
/// Implementations and Go to References; `noun` is the status-line plural
/// ("implementations" / "references").
fn open_location_picker(&mut self, targets: Vec<(PathBuf, u32, u32)>, noun: &str) {
// Same guard as present_call_hierarchy_menu: the LSP can answer
// seconds later, and the reply must not replace a menu the user
// opened while waiting (or yank focus to the editor).
if self.context_menu.is_some() {
self.status = String::from("Locations ready, but another menu is open");
return;
}
let root = self.tree.root.clone();
let items: Vec<(String, MenuAction)> = targets
.into_iter()
.map(|(path, line, col)| {
let label = format!(
"{}:{}",
path.strip_prefix(&root).unwrap_or(&path).display(),
line + 1
);
(label, MenuAction::GoToLocation { path, line, col })
})
.collect();
self.status = format!("{} {noun}", items.len());
let origin = self.editor.cursor_screen_pos().unwrap_or((
self.editor.last_full_area.x + 1,
self.editor.last_full_area.y + 1,
));
// As in `present_call_hierarchy_menu`: the reply arrives whenever the
// server is ready, and the `context_menu` guard is armed a line too
// late to protect the sidebar from this focus move.
self.without_auto_hide(|app| app.focus_pane(Pane::Editor));
self.context_menu = Some(ContextMenu::flat(origin, items, root));
}
/// Anchor a `ContextMenu` at the activity-bar gear. `menu_rect` clamps it
/// onto the screen, so a bottom-anchored gear pops the menu upward — the
/// same direction VS Code's "Manage" menu opens.
fn settings_menu_origin(&self) -> (u16, u16) {
let gear = self.sidebar_areas.settings_icon;
(gear.x + gear.width, gear.y)
}
/// Open the activity-bar gear's settings menu (VS Code's "Manage" menu).
/// Currently one entry — Color Theme — which opens the theme picker; more
/// settings entries slot in here later.
fn open_settings_menu(&mut self) {
let origin = self.settings_menu_origin();
self.context_menu = Some(ContextMenu::flat(
origin,
vec![
(String::from("Color Theme"), MenuAction::OpenThemePicker),
(
String::from("Customize Layout"),
MenuAction::OpenCustomizeLayout,
),
],
self.workspace_root().to_path_buf(),
));
// The gear renders "active" while its menu is open; re-emit it so the
// pressed-state PNG replaces the idle one.
self.overlays.activity.mark_dirty();
}
/// Anchor for the Customize Layout popup: just under the Customize Layout
/// (⛶) title-bar icon when it has been laid out, else the activity-bar gear
/// (the gear-menu entry path).
fn customize_layout_origin(&self) -> (u16, u16) {
let icon = self.layout_icon_areas.customize;
if icon.width > 0 {
// Pull left so the wider popup doesn't spill off the right edge;
// `menu_rect` clamps anything that still would.
(icon.x.saturating_sub(18), icon.y + 1)
} else {
self.settings_menu_origin()
}
}
/// Build the Customize Layout popup rows (VS Code's title-bar layout
/// controls): visibility checkboxes, then radio groups for Side Bar
/// Position, Panel Alignment, and Quick Input Position, then Zen Mode.
/// A leading `✔` marks an enabled toggle / the active radio option.
fn customize_layout_items(&self) -> Vec<MenuEntry> {
let check = |on: bool| if on { "\u{2713} " } else { " " };
vec![
MenuEntry::item(
format!("{}Activity Bar", check(self.activity_bar_visible)),
MenuAction::ToggleActivityBar,
),
MenuEntry::item(
format!("{}Primary Side Bar", check(self.show_tree)),
MenuAction::ToggleSideBar,
),
MenuEntry::item(
format!(
"{}Secondary Side Bar",
check(self.secondary_side_bar_visible)
),
MenuAction::ToggleSecondarySideBar,
),
MenuEntry::item(
format!("{}Panel", check(self.show_terminal)),
MenuAction::TogglePanel,
),
MenuEntry::item(
format!("{}Status Bar", check(self.status_bar_visible)),
MenuAction::ToggleStatusBar,
),
MenuEntry::item(
format!("{}Minimap", check(self.minimap_visible)),
MenuAction::ToggleMinimap,
),
MenuEntry::item(
format!("{}Auto-Hide Side Bar", check(self.sidebar_auto_hide)),
MenuAction::ToggleAutoHideSideBar,
),
MenuEntry::Separator,
MenuEntry::header("Primary Side Bar Position"),
MenuEntry::item(
format!(
"{}Left",
check(self.side_bar_position == SideBarPosition::Left)
),
MenuAction::SetSideBarPosition(SideBarPosition::Left),
),
MenuEntry::item(
format!(
"{}Right",
check(self.side_bar_position == SideBarPosition::Right)
),
MenuAction::SetSideBarPosition(SideBarPosition::Right),
),
MenuEntry::Separator,
MenuEntry::header("Panel Alignment"),
MenuEntry::item(
format!(
"{}Left",
check(self.panel_alignment == PanelAlignment::Left)
),
MenuAction::SetPanelAlignment(PanelAlignment::Left),
),
MenuEntry::item(
format!(
"{}Center",
check(self.panel_alignment == PanelAlignment::Center)
),
MenuAction::SetPanelAlignment(PanelAlignment::Center),
),
MenuEntry::item(
format!(
"{}Right",
check(self.panel_alignment == PanelAlignment::Right)
),
MenuAction::SetPanelAlignment(PanelAlignment::Right),
),
MenuEntry::item(
format!(
"{}Justify",
check(self.panel_alignment == PanelAlignment::Justify)
),
MenuAction::SetPanelAlignment(PanelAlignment::Justify),
),
MenuEntry::Separator,
MenuEntry::header("Quick Input Position"),
MenuEntry::item(
format!(
"{}Top",
check(self.quick_input_position == QuickInputPosition::Top)
),
MenuAction::SetQuickInputPosition(QuickInputPosition::Top),
),
MenuEntry::item(
format!(
"{}Center",
check(self.quick_input_position == QuickInputPosition::Center)
),
MenuAction::SetQuickInputPosition(QuickInputPosition::Center),
),
MenuEntry::Separator,
MenuEntry::item(
format!("{}Zen Mode", check(self.zen_mode)),
MenuAction::ToggleZenMode,
),
]
}
/// Reopen the Customize Layout popup with the cursor on the row carrying
/// `action`. Looking the row up beats hardcoding an index: the indices
/// were already stale for every row below the first separator (a row
/// insert shifts them and nothing catches it), so this makes that whole
/// class of bug unrepresentable.
fn open_customize_layout_menu_on(&mut self, action: &MenuAction) {
let idx = self
.customize_layout_items()
.iter()
.position(|e| matches!(e, MenuEntry::Item { action: a, .. } if a == action))
.unwrap_or(0);
self.open_customize_layout_menu_at(idx);
}
/// Open (or re-open) the Customize Layout popup with the cursor on row
/// `selected`. Each toggle re-opens it so the popup stays put while the
/// user flips several controls, exactly like VS Code's dropdown.
fn open_customize_layout_menu_at(&mut self, selected: usize) {
let origin = self.customize_layout_origin();
self.context_menu = Some(ContextMenu {
origin,
items: self.customize_layout_items(),
selected,
open_submenu: None,
submenu_selected: 0,
target_dir: self.workspace_root().to_path_buf(),
});
self.overlays.activity.mark_dirty();
}
/// Open the Customize Layout popup fresh (cursor on the first row).
fn open_customize_layout_menu(&mut self) {
self.open_customize_layout_menu_at(0);
}
/// Persist the current Customize Layout chrome to `~/.config/croft`.
/// Best-effort and skipped under test (hermetic suite, like `apply_theme`).
fn persist_layout(&self) {
if cfg!(test) {
return;
}
let _ = crate::prefs::save_layout(crate::prefs::LayoutPrefs {
activity_bar: self.activity_bar_visible,
status_bar: self.status_bar_visible,
side_bar_position: self.side_bar_position,
secondary_side_bar: self.secondary_side_bar_visible,
panel_alignment: self.panel_alignment,
quick_input_position: self.quick_input_position,
});
}
/// Hide the activity bar's inline images when the bar is collapsed so the
/// OSC-1337 icons don't ghost over the editor; arm a re-emit when shown.
fn after_chrome_visibility_change(&mut self) {
self.overlays.activity.mark_dirty();
if self.overlays.activity.has_images() {
self.overlays.activity.request_clear();
}
// The welcome logo re-bakes against the new editor rect on next render.
self.overlays.welcome.mark_dirty();
}
/// Show or hide the primary side bar. Every route that flips it by hand —
/// the Cmd+B keybinding, the palette command, the Customize Layout row and
/// the layout-icon click — goes through here, because each one is a
/// deliberate sidebar action and so must take the auto-hide pin (#260).
/// Four hand-rolled copies is exactly how three of them ended up without
/// it: the pin lived only on the palette route, so the real Cmd+B revealed
/// the panel and the next click into the editor collapsed it again.
fn toggle_side_bar(&mut self) {
let was_visible = self.show_tree;
self.show_tree = !self.show_tree;
// A reveal the user asked for outlives the focus move that follows it.
// Taken only when auto-hide is live: a pin set while the feature is
// off would sit unconsumed and silently eat the first collapse after
// they turn it on.
// Structural suppression (Zen Mode, or a hidden activity bar) means no
// collapse can fire for as long as it lasts, so a pin taken now is the
// "sits unconsumed and silently eats a later collapse" case this line
// already guards against for `!sidebar_auto_hide` — same bug, same
// answer: refuse to bank it rather than hold it indefinitely.
self.sidebar_pinned_open =
self.show_tree && self.sidebar_auto_hide && self.activity_bar_visible && !self.zen_mode;
// A deliberate toggle supersedes any pending automatic collapse: the
// dwell was armed against a sidebar state the user has since changed by
// hand. Leaving it armed lets a later idle tick fire against the NEW
// state — spending the pin this reveal just banked on a collapse the
// user never saw, which is #294 reached by a different door.
self.sidebar_dwell.disarm();
// Hiding the sidebar while Run-Debug was on screen: arm the same
// OSC-1337 image-cell evict gate that fires on a sidebar-view change.
// Without this the bug+play icon ghosts on top of the editor /
// terminal that fills the space the panel just vacated.
if was_visible
&& !self.show_tree
&& self.sidebar_view == SidebarView::RunDebug
&& self.overlays.run_debug.was_emitted()
{
self.overlays.run_debug.request_clear();
}
}
/// Toggle the secondary side bar (the Outline of the active file), on the
/// edge opposite the primary side bar. Mirrors ⌥⌘B.
fn toggle_secondary_side_bar(&mut self) {
self.secondary_side_bar_visible = !self.secondary_side_bar_visible;
self.persist_layout();
self.after_chrome_visibility_change();
self.status = String::from(if self.secondary_side_bar_visible {
"Secondary side bar shown"
} else {
"Secondary side bar hidden"
});
}
/// Toggle Zen Mode: hide the activity bar, both side bars, the panel, and
/// the status bar; toggling off restores the pre-Zen snapshot. Mirrors VS
/// Code's ⌘K Z.
fn toggle_zen_mode(&mut self) {
if let Some(prev) = self.pre_zen.take() {
self.activity_bar_visible = prev.activity_bar;
self.status_bar_visible = prev.status_bar;
self.show_tree = prev.side_bar;
self.secondary_side_bar_visible = prev.secondary_side_bar;
self.show_terminal = prev.panel;
self.zen_mode = false;
self.status = String::from("Zen Mode off");
} else {
self.pre_zen = Some(PreZenLayout {
activity_bar: self.activity_bar_visible,
status_bar: self.status_bar_visible,
side_bar: self.show_tree,
secondary_side_bar: self.secondary_side_bar_visible,
panel: self.show_terminal,
});
self.activity_bar_visible = false;
self.status_bar_visible = false;
self.show_tree = false;
// Zen is structural, not a transient suppression: it can last the
// session, and a dwell left armed would fire on the frame Zen
// exits — a collapse the user long since stopped associating with
// the focus move that armed it.
//
// The pin goes too, for the reason `toggle_side_bar` refuses to
// bank one here: Zen sets both structural conditions, so no
// collapse can fire while it lasts and a pin held across it is
// unconsumable — it would silently eat the first real collapse
// after Zen exits. Main cleared this incidentally, by taking the
// pin on every focus move; consuming at fire time instead is
// correct but leaves this boundary to say so explicitly.
self.sidebar_dwell.disarm();
self.sidebar_pinned_open = false;
self.secondary_side_bar_visible = false;
self.show_terminal = false;
self.zen_mode = true;
self.status = String::from("Zen Mode on");
}
self.after_chrome_visibility_change();
}
/// Replace the gear menu with the Color Theme picker: one row per theme,
/// a check on the active one. Selecting a row switches + persists it.
fn open_theme_picker(&mut self) {
let origin = self.settings_menu_origin();
let active = self.theme;
let items: Vec<(String, MenuAction)> = crate::theme::Theme::all()
.iter()
.map(|&t| {
let mark = if t == active { "✔ " } else { " " };
(format!("{mark}{}", t.label()), MenuAction::SetTheme(t))
})
.collect();
let selected = crate::theme::Theme::all()
.iter()
.position(|&t| t == active)
.unwrap_or(0);
self.context_menu = Some(ContextMenu {
origin,
items: items.into_iter().map(MenuEntry::from).collect(),
selected,
open_submenu: None,
submenu_selected: 0,
target_dir: self.workspace_root().to_path_buf(),
});
self.overlays.activity.mark_dirty();
}
/// Open the Explorer's "Views and More Actions" (⋯) menu: one row per
/// stacked sub-view, each prefixed with a check when currently shown.
/// Selecting a row toggles that view (see [`Self::toggle_explorer_view`]).
/// The ⋯-menu / status label for a sub-view. DEPENDENCIES is language-aware
/// ("Rust Dependencies", "Python Dependencies", or plain "Dependencies" for
/// a polyglot root), computed from the detected ecosystems; every other view
/// uses its static name.
fn explorer_view_label(&self, view: ExplorerView) -> String {
match view {
ExplorerView::Dependencies => {
crate::widgets::dependencies::menu_label(&self.dep_ecosystems)
}
other => other.label().to_string(),
}
}
/// Whether a sub-view may appear in the ⋯ menu and stack in the panel.
/// DEPENDENCIES is additionally gated on a manifest being detected at the
/// root, so a plain folder shows no dependency view at all; every other view
/// is always available.
fn explorer_view_available(&self, view: ExplorerView) -> bool {
match view {
ExplorerView::Dependencies => !self.dep_ecosystems.is_empty(),
_ => true,
}
}
/// Anchored just below the ⋯ button on the EXPLORER title line; the
/// menu-rect clamp pulls it left so it never spills off the right edge.
fn open_explorer_views_menu(&mut self) {
let btn = self.tree.header_views_btn;
let origin = if btn.width > 0 {
(btn.x, btn.y + 1)
} else {
(self.tree.last_area.x + 1, self.tree.last_area.y + 1)
};
let items: Vec<(String, MenuAction)> = ExplorerView::ALL
.iter()
.filter(|&&view| self.explorer_view_available(view))
.map(|&view| {
let mark = if self.explorer_views.is_visible(view) {
"\u{2713} "
} else {
" "
};
(
format!("{mark}{}", self.explorer_view_label(view)),
MenuAction::ToggleExplorerView(view),
)
})
.collect();
self.context_menu = Some(ContextMenu::flat(
origin,
items,
self.workspace_root().to_path_buf(),
));
}
/// Flip one Explorer sub-view's visibility, persist the new set, and (for a
/// data-backed view turned on) clear its fetch latch so the next frame
/// re-populates it. The layout reads `explorer_views` directly, so no other
/// wiring is needed for the section to appear or vanish.
fn toggle_explorer_view(&mut self, view: ExplorerView) {
let now_visible = self.explorer_views.toggle(view);
let _ = crate::prefs::save_explorer_views(self.explorer_views.as_prefs());
if now_visible {
match view {
ExplorerView::Timeline => self.timeline_fetched = None,
ExplorerView::Dependencies => self.deps_fetched = None,
_ => {}
}
}
self.status = format!(
"{} {}",
if now_visible { "Showing" } else { "Hiding" },
self.explorer_view_label(view)
);
}
/// Lay out and paint the Explorer's visible stacked sub-views top-to-bottom
/// inside `area` (the region above the SYSTEM footer). Folders (the file
/// tree) is the flexible region that absorbs leftover rows; every other
/// visible section takes its own collapsible height, clipped so the tree
/// always keeps a few rows. Sections hidden via the ⋯ menu are skipped, and
/// their hit-test rects are zeroed so a stale click can't reach them.
fn render_explorer_sections(&mut self, frame: &mut ratatui::Frame, area: Rect) {
self.open_editors.last_area = Rect::default();
self.outline.last_area = Rect::default();
self.timeline.last_area = Rect::default();
self.dependencies.last_area = Rect::default();
let folders_visible = self.explorer_views.is_visible(ExplorerView::Folders);
if !folders_visible {
// The tree isn't painted, so zero its geometry too — otherwise a
// click on a since-hidden row would still resolve against it.
self.tree.last_inner = Rect::default();
self.tree.last_area = Rect::default();
}
if area.height == 0 || area.width == 0 {
if folders_visible {
frame.render_widget(&mut self.tree, area);
}
return;
}
// Requested rows per visible section, in stacking order. Folders is a
// placeholder (0) here; it claims the leftover after the others.
let mut heights: Vec<(ExplorerView, u16)> = Vec::new();
for &v in &ExplorerView::ALL {
if !self.explorer_views.is_visible(v) || !self.explorer_view_available(v) {
continue;
}
let h = match v {
ExplorerView::Folders => 0,
ExplorerView::OpenEditors => self.open_editors.desired_height(area.height),
ExplorerView::Outline => self.outline.desired_height(area.height),
ExplorerView::Timeline => self.timeline.desired_height(area.height),
ExplorerView::Dependencies => self.dependencies.desired_height(area.height),
};
heights.push((v, h));
}
if heights.is_empty() {
return;
}
// Reserve a floor for the tree, then hand the fixed (non-Folders)
// sections rows in order, clipping each to what's left.
let total = area.height;
let tree_floor = if folders_visible { 3u16.min(total) } else { 0 };
let mut budget = total.saturating_sub(tree_floor);
let mut fixed_sum = 0u16;
for (v, h) in heights.iter_mut() {
if *v == ExplorerView::Folders {
continue;
}
let assigned = (*h).min(budget);
*h = assigned;
budget -= assigned;
fixed_sum += assigned;
}
if folders_visible {
if let Some(slot) = heights
.iter_mut()
.find(|(v, _)| *v == ExplorerView::Folders)
{
slot.1 = total.saturating_sub(fixed_sum);
}
} else {
// No tree to absorb slack: grow the first section to fill the gap.
let used: u16 = heights.iter().map(|(_, h)| *h).sum();
if used < total
&& let Some(first) = heights.first_mut()
{
first.1 += total - used;
}
}
let mut y = area.y;
for (v, h) in heights {
if h == 0 {
continue;
}
let rect = Rect {
x: area.x,
y,
width: area.width,
height: h,
};
y = y.saturating_add(h);
match v {
ExplorerView::Folders => frame.render_widget(&mut self.tree, rect),
ExplorerView::OpenEditors => frame.render_widget(&mut self.open_editors, rect),
ExplorerView::Outline => frame.render_widget(&mut self.outline, rect),
ExplorerView::Timeline => frame.render_widget(&mut self.timeline, rect),
ExplorerView::Dependencies => frame.render_widget(&mut self.dependencies, rect),
}
}
}
/// Switch the IDE color theme: persist it, repaint the iTerm2 session
/// background (so every `Color::Reset` surface follows), re-bake the
/// OSC-1337 icon PNGs against the new background, and drop the lazily-baked
/// image overlays + arm a full clear so nothing ghosts the old background.
fn apply_theme(&mut self, theme: crate::theme::Theme) {
self.apply_theme_visuals(theme);
// Persistence is best-effort: a write failure never blocks the
// in-session switch, which has already taken effect above. Skipped
// under test so the suite never clobbers the developer's real config.
// The layered-settings reload path calls `apply_theme_visuals`
// directly instead — a workspace-set theme must not be written back
// into the user's own config.
if !cfg!(test) {
let _ = crate::prefs::save_theme(theme);
}
}
/// Everything [`Self::apply_theme`] does except persisting the choice.
fn apply_theme_visuals(&mut self, theme: crate::theme::Theme) {
self.theme = theme;
// Push the theme's code palette into the highlighter and re-highlight
// every open editor (across all split groups): cached spans carry baked
// colors, so the syntax colors only follow the theme once recomputed.
crate::highlight::set_syntax_palette(theme.syntax());
// Assign the theme before re-highlighting: the rebuilds below (the
// markdown preview in particular) read `ed.theme`, and the per-frame
// push in render would hand it over one frame too late.
for ed in &mut self.editor.editors {
ed.theme = theme;
ed.rehighlight_for_theme();
}
for group in self.editor_layout.inactive_groups_mut() {
for ed in &mut group.editors {
ed.theme = theme;
ed.rehighlight_for_theme();
}
}
// Refresh the per-pane gradient-border flag for the new theme so the
// focused box switches its highlight style on the very next frame.
self.sync_focus_flags();
if !cfg!(test) {
use std::io::Write;
let mut out = stdout();
// Portable dynamic colors first (all hosts), then the iTerm2
// sRGB override where supported.
let _ = out.write_all(host_colors_seq(theme).as_bytes());
if crate::iterm2_inline::detect_iterm2_inline_support() {
let _ = out.write_all(set_session_bg_srgb_seq(theme.editor_bg_rgb()).as_bytes());
}
let _ = out.flush();
}
// Re-bake the fixed icon/badge/run-debug PNGs against the new bg.
self.init_graphics();
// The welcome wordmark, no-repo hero, SSH empty state, and editor
// image previews are baked lazily and keyed on layout, not theme —
// drop them so the next render re-bakes them on the new background.
self.overlays.welcome.disable();
self.overlays.hero.disable();
self.overlays.ssh.disable();
self.overlays.editor[0].disable();
self.overlays.editor[1].disable();
// Evict the stale activity-icon image layer and force a full repaint
// (the clear latch the main loop folds into `terminal.clear()`), so
// every cell — SGR and image alike — repaints on the new background.
self.overlays.activity.mark_dirty();
self.overlays.activity.request_clear();
self.status = format!("Color Theme: {}", theme.label());
}
/// [`Self::open_at`] for a position that came FROM a language server, whose
/// column counts UTF-16 code units rather than characters. The file has to
/// be open before the conversion can happen — the mapping needs the target
/// line's text — so this opens at column 0 and then re-seats the caret.
///
/// Out-of-range answers are clamped rather than rejected, matching
/// `open_at`: a server that names a line past the end of a buffer we have
/// since edited should still land the user on the right file.
fn open_at_utf16(&mut self, path: &Path, line: u32, character: u32) -> Result<()> {
self.open_at(path, line as usize, 0)?;
let row = self.editor.cursor_row;
let col = self.editor.utf16_col_to_char_pub(row, character);
let max_col = self
.editor
.lines
.get(row)
.map(|l| l.chars().count())
.unwrap_or(0);
self.editor.cursor_col = col.min(max_col);
self.editor.ensure_cursor_col_visible();
Ok(())
}
fn open_at(&mut self, path: &Path, row: usize, col: usize) -> Result<()> {
self.hover_popup = None;
self.hover_diagnostic = None;
self.editor.open_preview(path)?;
self.sync_open_file_poll_mtime();
let row = row.min(self.editor.lines.len().saturating_sub(1));
let max_col = self
.editor
.lines
.get(row)
.map(|l| l.chars().count())
.unwrap_or(0);
self.editor.cursor_row = row;
self.editor.cursor_col = col.min(max_col);
let page = self.editor.page_size().max(1);
self.editor.scroll = row.saturating_sub(page / 2);
self.editor.scroll_col = 0;
self.editor.ensure_cursor_col_visible();
self.focus_pane(Pane::Editor);
self.poke_cursor();
Ok(())
}
/// The active editor's position as a NavLoc, for threading through
/// back/forward so the walk is reversible. None on file-less surfaces
/// (welcome screen, image tabs without a path).
fn current_nav_loc(&self) -> Option<NavLoc> {
let path = self.editor.path.clone()?;
Some(NavLoc {
path,
row: self.editor.cursor_row,
col: self.editor.cursor_col,
})
}
fn nav_back(&mut self) {
let current = self.current_nav_loc();
let Some(loc) = self.nav.back(current) else {
self.status = "No previous location".to_string();
return;
};
let line = loc.row;
match self.open_at(&loc.path, loc.row, loc.col) {
Ok(()) => {
self.status = format!("Back to {} line {}", self.status_path(&loc.path), line + 1)
}
Err(e) => self.status = format!("Go back failed: {e}"),
}
}
/// VS Code "Go Forward" (Ctrl+Shift+-): return along the trail Go Back
/// walked, restoring the position each back step left.
fn nav_forward(&mut self) {
let current = self.current_nav_loc();
let Some(loc) = self.nav.forward(current) else {
self.status = "No forward location".to_string();
return;
};
let line = loc.row;
match self.open_at(&loc.path, loc.row, loc.col) {
Ok(()) => {
self.status = format!(
"Forward to {} line {}",
self.status_path(&loc.path),
line + 1
)
}
Err(e) => self.status = format!("Go forward failed: {e}"),
}
}
/// VS Code "Go to Last Edit Location" (Cmd+K Cmd+Q): jump to the most
/// recent buffer edit across the open editors, threading the current
/// position onto the back stack so Ctrl+- returns. The location lives
/// on each editor (`last_edit_pos`), so an edit in a background split
/// counts too; a buffer closed since its edit takes its location with
/// it, like the rest of its view state.
fn goto_last_edit_location(&mut self) {
let mut best: Option<(std::time::Instant, NavLoc)> = None;
let groups = std::iter::once(&self.editor).chain(self.editor_layout.inactive_groups());
for group in groups {
for ed in &group.editors {
let (Some(at), Some((row, col)), Some(path)) =
(ed.last_edit_at, ed.last_edit_pos, ed.path.clone())
else {
continue;
};
if best.as_ref().is_none_or(|(b, _)| at > *b) {
best = Some((at, NavLoc { path, row, col }));
}
}
}
let Some((_, loc)) = best else {
self.status = String::from("No edits this session");
return;
};
if let Some(cur) = self.current_nav_loc() {
self.nav.record(cur);
}
let line = loc.row;
match self.open_at(&loc.path, loc.row, loc.col) {
Ok(()) => {
self.status = format!(
"Last edit: {} line {}",
self.status_path(&loc.path),
line + 1
)
}
Err(e) => self.status = format!("Go to last edit failed: {e}"),
}
}
fn trigger_definition_at(&mut self, col: u16, row: u16) {
if self.editor.has_non_text_view() {
return;
}
let Some((line, c)) = self.editor.buffer_pos_at(col, row) else {
return;
};
self.editor.cursor_row = line;
self.editor.cursor_col = c;
// A server-resolved document link outranks Go to Definition at
// this spot (#254): URLs in comments have no definition at all,
// and an import specifier's link and definition land in the same
// file anyway — VS Code follows the link too.
if let Some(target) = self.editor.document_link_at(line, c).map(str::to_string) {
self.open_document_link(&target);
return;
}
let Some(path) = self.editor.path.clone() else {
return;
};
let (uline, uchar) = self.editor.pos_to_utf16(line, c);
let Some(lsp) = self.lsp.as_mut() else {
return;
};
let id = lsp.request_definition(path, uline, uchar);
self.definition_request_id = Some(id);
}
/// Alt+F12 / palette "Peek Definition": the definition request whose
/// response opens an excerpt popup instead of jumping (#115).
fn peek_definition_at_cursor(&mut self) {
let (line, character) = self
.editor
.pos_to_utf16(self.editor.cursor_row, self.editor.cursor_col);
let Some(path) = self.editor.path.clone() else {
self.status = String::from("No file open");
return;
};
let Some(lsp) = self.lsp.as_mut() else {
self.status = String::from("No language server for this file");
return;
};
let id = lsp.request_definition(path, line, character);
self.peek_definition_request_id = Some(id);
self.status = String::from("Peeking definition");
}
/// Request the LSP definition of the symbol at the current cursor (buffer)
/// position. Used by the editor right-click "Go to Definition" item, where
/// the cursor has already been moved to the click point.
fn request_definition_at_cursor(&mut self) {
let (line, character) = self
.editor
.pos_to_utf16(self.editor.cursor_row, self.editor.cursor_col);
let Some(path) = self.editor.path.clone() else {
return;
};
let Some(lsp) = self.lsp.as_mut() else {
return;
};
let id = lsp.request_definition(path, line, character);
self.definition_request_id = Some(id);
}
/// Request the LSP declaration of the symbol at the current cursor (buffer)
/// position. Used by the editor right-click "Go to Declaration" item and the
/// `⇧F12` keybinding. Declaration and definition coincide for languages with
/// no separate declaration site (e.g. Python); they diverge for C/C++ (header
/// prototype) and TypeScript (`.d.ts`).
fn request_declaration_at_cursor(&mut self) {
let (line, character) = self
.editor
.pos_to_utf16(self.editor.cursor_row, self.editor.cursor_col);
let Some(path) = self.editor.path.clone() else {
return;
};
let Some(lsp) = self.lsp.as_mut() else {
return;
};
let id = lsp.request_declaration(path, line, character);
self.declaration_request_id = Some(id);
}
/// Request the LSP type definition of the symbol at the current cursor
/// (buffer) position. Used by the editor right-click "Go to Type Definition"
/// item and the `⌃F12` keybinding. Jumps to where the *type* of the
/// expression is defined, as opposed to the symbol itself (definition).
fn request_type_definition_at_cursor(&mut self) {
let (line, character) = self
.editor
.pos_to_utf16(self.editor.cursor_row, self.editor.cursor_col);
let Some(path) = self.editor.path.clone() else {
return;
};
let Some(lsp) = self.lsp.as_mut() else {
return;
};
let id = lsp.request_type_definition(path, line, character);
self.type_definition_request_id = Some(id);
}
/// Request the LSP implementations of the abstraction at the current cursor
/// (buffer) position. Used by the editor right-click "Go to Implementations"
/// item and the `⌘F12` keybinding. Meaningful on traits / interfaces /
/// abstract methods; the server may return many, and croft jumps to the first.
fn request_implementation_at_cursor(&mut self) {
let (line, character) = self
.editor
.pos_to_utf16(self.editor.cursor_row, self.editor.cursor_col);
let Some(path) = self.editor.path.clone() else {
return;
};
let Some(lsp) = self.lsp.as_mut() else {
return;
};
let id = lsp.request_implementation(path, line, character);
self.implementation_request_id = Some(id);
}
/// Request the LSP references of the symbol at the current cursor (buffer)
/// position. Used by the editor right-click "Go to References" item and the
/// `⇧F12` keybinding. The server almost always returns many uses, which
/// `drain_lsp_references` then offers as a picker.
fn request_references_at_cursor(&mut self) {
let (line, character) = self
.editor
.pos_to_utf16(self.editor.cursor_row, self.editor.cursor_col);
let Some(path) = self.editor.path.clone() else {
return;
};
let Some(lsp) = self.lsp.as_mut() else {
return;
};
let id = lsp.request_references(path, line, character);
self.references_request_id = Some(id);
}
/// Whether the current editor file's language server implements
/// `textDocument/declaration`. Drives whether the right-click menu shows the
/// "Go to Declaration" row. Unknown (server not yet spawned) or no server is
/// treated as unsupported, so the row only appears once support is confirmed.
fn editor_language_supports_declaration(&self) -> bool {
let Some(lang) = self
.editor
.path
.as_deref()
.and_then(|p| p.extension())
.and_then(|e| e.to_str())
.and_then(crate::lsp::Language::from_extension)
else {
return false;
};
self.lsp
.as_ref()
.and_then(|lsp| lsp.language_supports_declaration(lang))
.unwrap_or(false)
}
/// Whether the current editor file's language server implements
/// `textDocument/typeDefinition`. Drives whether the right-click menu shows
/// the "Go to Type Definition" row. Unknown (server not yet spawned) or no
/// server is treated as unsupported, so the row only appears once support is
/// confirmed.
fn editor_language_supports_type_definition(&self) -> bool {
let Some(lang) = self
.editor
.path
.as_deref()
.and_then(|p| p.extension())
.and_then(|e| e.to_str())
.and_then(crate::lsp::Language::from_extension)
else {
return false;
};
self.lsp
.as_ref()
.and_then(|lsp| lsp.language_supports_type_definition(lang))
.unwrap_or(false)
}
/// Whether the current editor file's language server implements
/// `textDocument/implementation`. Drives whether the right-click menu shows
/// the "Go to Implementations" row. Unknown (server not yet spawned) or no
/// server is treated as unsupported, so the row only appears once support is
/// confirmed.
fn editor_language_supports_implementation(&self) -> bool {
let Some(lang) = self
.editor
.path
.as_deref()
.and_then(|p| p.extension())
.and_then(|e| e.to_str())
.and_then(crate::lsp::Language::from_extension)
else {
return false;
};
self.lsp
.as_ref()
.and_then(|lsp| lsp.language_supports_implementation(lang))
.unwrap_or(false)
}
/// Whether the current editor file's language server implements
/// `textDocument/references`. Drives whether the right-click menu shows the
/// "Go to References" row. Unknown (server not yet spawned) or no server is
/// treated as unsupported, so the row only appears once support is confirmed.
fn editor_language_supports_references(&self) -> bool {
let Some(lang) = self
.editor
.path
.as_deref()
.and_then(|p| p.extension())
.and_then(|e| e.to_str())
.and_then(crate::lsp::Language::from_extension)
else {
return false;
};
self.lsp
.as_ref()
.and_then(|lsp| lsp.language_supports_references(lang))
.unwrap_or(false)
}
fn editor_language_supports_code_action(&self) -> bool {
let Some(lang) = self
.editor
.path
.as_deref()
.and_then(|p| p.extension())
.and_then(|e| e.to_str())
.and_then(crate::lsp::Language::from_extension)
else {
return false;
};
self.lsp
.as_ref()
.and_then(|lsp| lsp.language_supports_code_action(lang))
.unwrap_or(false)
}
/// VS Code "Change All Occurrences" (Cmd/Ctrl+F2): select every textual
/// match of the word under the cursor in the current file as multi-cursor
/// carets so the next keystrokes edit them all at once.
fn start_change_all_occurrences(&mut self) {
if self.editor.has_non_text_view() {
return;
}
let n = self.editor.select_all_occurrences_of_word_at_cursor();
if n == 0 {
self.status = String::from("No symbol under cursor");
} else {
self.status = format!("Selected {n} occurrences (type to replace, Esc to cancel)");
}
}
/// VS Code "Add Selection to Next Find Match" (`Cmd+D`): select the word
/// under the cursor, then grow the multi-cursor one occurrence per press.
fn start_select_next_occurrence(&mut self) {
if self.editor.has_non_text_view() {
return;
}
let n = self.editor.select_next_occurrence();
if n == 0 {
self.status = String::from("No symbol under cursor");
} else if n > 1 {
self.status = format!("Selected {n} occurrences (type to replace, Esc to cancel)");
}
}
/// VS Code "Delete Line" (`Cmd+Shift+K`): delete the cursor's line, or
/// every line a selection touches, yanking the removed text to the
/// clipboard. Replaces the old `Cmd+d d` convenience, whose leader now
/// belongs to Add Selection to Next Match.
fn delete_current_line(&mut self) {
if self.editor.has_non_text_view() {
return;
}
let yanked = self.editor.delete_caret_lines();
if !yanked.is_empty() {
copy_to_clipboard(&yanked);
}
let n = yanked.lines().count();
self.status = format!("Deleted {n} {}", if n == 1 { "line" } else { "lines" });
}
/// VS Code "Rename Symbol" (F2): prompt for a new name pre-filled with the
/// identifier under the cursor; committing fires an LSP `rename` request.
fn start_rename_symbol(&mut self) {
if self.editor.has_non_text_view() {
return;
}
let Some(path) = self.editor.path.clone() else {
self.status = String::from("No file open");
return;
};
if self.lsp.is_none() {
self.status = String::from("No language server for this file");
return;
}
// Prepare-rename first (#254): the server validates the position
// and hands back the exact range + placeholder, so the prompt
// pre-fills the real symbol and an invalid position fails fast
// with the server's own message. The worker always answers;
// an `unsupported` verdict falls back to the word-under-cursor
// prompt below (today's behavior, kept for servers without the
// capability).
let (row, col) = (self.editor.cursor_row, self.editor.cursor_col);
let (line, character) = self.editor.pos_to_utf16(row, col);
let Some(lsp) = self.lsp.as_mut() else {
return;
};
let id = lsp.request_prepare_rename(path.clone(), line, character);
// Overwriting also disarms any previous in-flight prepare: its caret
// is abandoned, and a late verdict for it must not reopen a prompt
// carrying the old (row, col) into the rename request.
self.prepare_rename_request = Some((id, path, row, col, self.editor.edit_seq));
self.status = String::from("Preparing rename…");
}
/// The pre-#254 rename prompt: pre-fill with the word under the
/// cursor. The fallback when no server advertises `prepareProvider`
/// (or it answers "default behavior").
fn open_rename_prompt_fallback(&mut self, path: PathBuf, row: usize, col: usize) {
let Some((start, end)) = self.editor.word_at(row, col) else {
self.status = String::from("No symbol under cursor");
return;
};
let word: String = self.editor.lines[row]
.chars()
.skip(start)
.take(end - start)
.collect();
self.prompt = Some(Prompt {
label: format!("Rename Symbol '{word}'"),
buffer: word,
kind: PromptKind::RenameSymbol { path, row, col },
target_dir: PathBuf::new(),
error: None,
});
}
/// Resolve a prepare-rename verdict (#254) into the prompt, an
/// error, or the fallback. Gated on id + path + edit_seq like every
/// deferred caret request.
pub fn drain_lsp_prepare_rename(&mut self) -> bool {
let mut results = Vec::new();
{
let Some(lsp) = self.lsp.as_ref() else {
return false;
};
while let Some(r) = lsp.drain_prepare_rename() {
results.push(r);
}
}
let mut changed = false;
for result in results {
changed |= self.apply_prepare_rename_verdict(result);
}
changed
}
/// Resolve one prepare-rename verdict into the prompt, a status, or the
/// word-under-cursor fallback. Split out of the drain loop so the four
/// verdict shapes are testable: the reply channel's sender lives inside
/// the LSP worker, so a test cannot inject a `PrepareRenameResult`
/// through it. Returns whether the screen needs a repaint.
fn apply_prepare_rename_verdict(
&mut self,
result: crate::lsp::manager::PrepareRenameResult,
) -> bool {
let Some((id, path, row, col, seq)) = self.prepare_rename_request.clone() else {
return false;
};
if result.request_id != id {
return false;
}
self.prepare_rename_request = None;
if self.editor.path.as_deref() != Some(path.as_path()) || self.editor.edit_seq != seq {
// The caret moved on (an edit, or a tab switch — which also
// bumps edit_seq). Say so: bailing silently would strand
// "Preparing rename…" on screen with no way to tell the
// rename died.
self.status = String::from("Rename cancelled");
return true;
}
if result.unsupported {
self.open_rename_prompt_fallback(path, row, col);
return true;
}
if let Some(msg) = result.error {
self.status = format!("Rename rejected: {msg}");
return true;
}
let Some(((sl, sc, el, ec), placeholder)) = result.target else {
self.status = String::from("Nothing renameable at the cursor");
return true;
};
// Placeholder wins; otherwise the validated range's text.
let word = placeholder.unwrap_or_else(|| {
let (sr, er) = (sl as usize, el as usize);
let scol = self.editor.utf16_col_to_char_pub(sr, sc);
let ecol = self.editor.utf16_col_to_char_pub(er, ec);
if sr == er {
self.editor
.lines
.get(sr)
.map(|l| {
l.chars()
.skip(scol)
.take(ecol.saturating_sub(scol))
.collect()
})
.unwrap_or_default()
} else {
String::new()
}
});
if word.is_empty() {
self.open_rename_prompt_fallback(path, row, col);
return true;
}
self.prompt = Some(Prompt {
label: format!("Rename Symbol '{word}'"),
buffer: word,
kind: PromptKind::RenameSymbol { path, row, col },
target_dir: PathBuf::new(),
error: None,
});
true
}
pub fn drain_lsp_rename(&mut self) -> bool {
let mut arrived = false;
let mut edits: Option<Vec<(PathBuf, Vec<crate::widgets::editor::TextSpanEdit>)>> = None;
{
let Some(lsp) = self.lsp.as_ref() else {
return false;
};
while let Some(result) = lsp.drain_rename() {
if Some(result.request_id) != self.rename_request_id {
continue;
}
arrived = true;
edits = result.edits;
}
}
if !arrived {
return false;
}
self.rename_request_id = None;
match edits {
Some(files) => match self.apply_rename_edits(&files) {
Ok((file_count, occ)) => {
self.status =
format!("Renamed {occ} occurrence(s) across {file_count} file(s)");
}
Err(e) => self.status = format!("Rename failed: {e}"),
},
None => self.status = String::from("Rename produced no changes"),
}
true
}
/// Apply an LSP rename `WorkspaceEdit` (already normalised to per-file
/// char-indexed spans). Open tabs are edited in-memory as one undo step
/// and left dirty; closed files are rewritten on disk (the fs watcher
/// refreshes the tree). Returns (files touched, occurrences replaced).
fn apply_rename_edits(
&mut self,
files: &[(PathBuf, Vec<crate::widgets::editor::TextSpanEdit>)],
) -> Result<(usize, usize)> {
let mut file_count = 0;
let mut occ_count = 0;
for (path, edits) in files {
if edits.is_empty() {
continue;
}
if let Some(n) = self.editor.apply_rename_to_open_tab(path, edits) {
occ_count += n;
} else if self.is_collab_guest() && collab_file_key(&self.tree.root, path).is_some() {
// Closed-file rename edits are raw disk writes; a collab
// guest never writes shared files (open tabs above are fine:
// those edits flow to the owner as ops).
continue;
} else {
let content = std::fs::read_to_string(path)?;
let mut lines: Vec<String> = content.split('\n').map(str::to_string).collect();
occ_count += crate::widgets::editor::apply_span_edits_to_lines(&mut lines, edits);
std::fs::write(path, lines.join("\n"))?;
}
file_count += 1;
}
Ok((file_count, occ_count))
}
/// VS Code "Format Document" (Cmd+Opt+Shift+F): ask the language server to
/// reformat the active buffer. No-op on read-only diff / sheet / image
/// tabs. The reply is applied in [`drain_lsp_format`].
fn start_format_document(&mut self) {
if self.editor.has_non_text_view() {
return;
}
let Some(path) = self.editor.path.clone() else {
self.status = String::from("No file open");
return;
};
let Some(lsp) = self.lsp.as_mut() else {
self.status = String::from("No language server for this file");
return;
};
// Mirror the editor's indentation preference; servers that carry their
// own config (rustfmt, ruff, prettier) ignore these but the fields are
// required by the LSP request.
let (tab_size, insert_spaces) = self.editor.indent_preference();
let id = lsp.request_formatting(path, tab_size, insert_spaces);
self.format_request_id = Some(id);
self.format_request_selection = false;
self.status = String::from("Formatting document");
}
/// "Format Selection" (#254): `textDocument/rangeFormatting` over the
/// primary selection, applied through the same reply path as
/// whole-document formatting.
fn format_selection(&mut self) {
if self.editor.has_non_text_view() {
return;
}
let Some(sel) = self.editor.selection.filter(|s| s.has_area()) else {
self.status = String::from("Select something to format");
return;
};
let Some(path) = self.editor.path.clone() else {
self.status = String::from("No file open");
return;
};
let ((sr, sc), (er, ec)) = sel.normalised();
let start = self.editor.pos_to_utf16(sr, sc);
let end = self.editor.pos_to_utf16(er, ec);
let (tab_size, insert_spaces) = self.editor.indent_preference();
let Some(lsp) = self.lsp.as_mut() else {
self.status = String::from("No language server for this file");
return;
};
let id = lsp.request_range_formatting(path, start, end, tab_size, insert_spaces);
self.format_request_id = Some(id);
self.format_request_selection = true;
self.status = String::from("Formatting selection");
}
pub fn drain_lsp_format(&mut self) -> bool {
let mut arrived = false;
let mut edits: Option<Vec<crate::widgets::editor::TextSpanEdit>> = None;
let mut unsupported = false;
let mut path: Option<PathBuf> = None;
{
let Some(lsp) = self.lsp.as_ref() else {
return false;
};
while let Some(result) = lsp.drain_formatting() {
if Some(result.request_id) != self.format_request_id {
continue;
}
arrived = true;
edits = result.edits;
unsupported = result.unsupported;
path = Some(result.path);
}
}
if !arrived {
return false;
}
self.format_request_id = None;
let selection = std::mem::take(&mut self.format_request_selection);
if unsupported {
self.status = if selection {
String::from("No range formatter available for this file")
} else {
String::from("No formatter available for this file")
};
self.complete_pending_save();
return true;
}
match (edits, path) {
(Some(edits), Some(path)) if !edits.is_empty() => {
match self.editor.apply_rename_to_open_tab(&path, &edits) {
Some(_) => {
self.editor.clamp_cursor();
self.status = if selection {
String::from("Formatted selection")
} else {
String::from("Formatted document")
};
}
None => self.status = String::from("Format failed: document not open"),
}
}
_ => {
self.status = if selection {
String::from("Selection already formatted")
} else {
String::from("Document already formatted")
}
}
}
// A format-on-save write is deferred until now so the disk file gets the
// formatted text in one go.
self.complete_pending_save();
true
}
/// VS Code "Quick Fix" (`Cmd+.`): ask the language server for the code
/// actions available at the cursor (with the diagnostics on that line as
/// context) and present them in a picker. No-op on read-only preview tabs.
/// The reply is handled in [`Self::drain_lsp_code_actions`].
/// The Quick Fix picker for a merge conflict at the cursor: VS Code's
/// three accept actions, applied locally with no LSP involvement.
/// F7 / Shift+F7: move the caret to the next / previous conflict header,
/// wrapping, and say which of how many the caret landed on.
fn jump_conflict(&mut self, backwards: bool) {
let blocks = self.editor.conflicts().to_vec();
let from = self.editor.cursor_row;
let hit = if backwards {
crate::merge::prev_conflict(&blocks, from)
} else {
crate::merge::next_conflict(&blocks, from)
};
let Some((idx, row)) = hit else {
return;
};
self.editor.clear_selection();
self.editor.cursor_row = row;
self.editor.cursor_col = 0;
self.editor.scroll_col = 0;
self.editor.ensure_cursor_col_visible();
self.status = format!("Conflict {} of {}", idx + 1, blocks.len());
}
fn open_merge_conflict_picker(&mut self) {
use crate::widgets::list_picker::{ListPicker, ListPurpose, ListRow};
let rows = vec![
ListRow {
id: String::from("current"),
label: String::from("Accept Current Change"),
},
ListRow {
id: String::from("incoming"),
label: String::from("Accept Incoming Change"),
},
ListRow {
id: String::from("both"),
label: String::from("Accept Both Changes"),
},
];
self.open_list_picker(
ListPicker::new(ListPurpose::MergeConflict, "Resolve Merge Conflict", rows),
"No merge conflict at the cursor",
);
}
/// Resolve the merge conflict at the cursor, reporting VS Code's
/// wording in the status line. Backs both the palette's Merge Conflict
/// commands and the Quick Fix picker rows.
fn resolve_merge_at_cursor(&mut self, res: crate::merge::Resolution) {
// Palette commands reach here on any tab; a non-text view (image,
// sheet, diff) must refuse rather than consult the conflict cache.
if !self.editor_is_text() {
self.status = String::from("Merge conflict actions need a text file");
return;
}
let row = self.editor.cursor_row;
if !self.editor.resolve_conflict_at(row, res) {
self.status = String::from("No merge conflict at the cursor");
return;
}
let accepted = match res {
crate::merge::Resolution::Current => "Accepted current change",
crate::merge::Resolution::Incoming => "Accepted incoming change",
crate::merge::Resolution::Both => "Accepted both changes",
};
self.status = if self.editor.conflicts().is_empty() {
format!(
"{accepted} — all conflicts resolved; \"Merge: Complete Merge\" stages the file"
)
} else {
format!("{accepted} — {} left", self.editor.conflicts().len())
};
}
/// VS Code's "Accept All Current / Incoming": resolve every block in the
/// buffer the same way, back to front so each replacement is one undo
/// step and earlier block indices stay valid.
fn resolve_all_merge(&mut self, res: crate::merge::Resolution) {
if !self.editor_is_text() {
self.status = String::from("Merge conflict actions need a text file");
return;
}
let total = self.editor.conflicts().len();
if total == 0 {
self.status = String::from("No merge conflicts in this file");
return;
}
while let Some(block) = self.editor.conflicts().last().copied() {
if !self.editor.resolve_conflict_at(block.ours_start, res) {
break;
}
}
let side = match res {
crate::merge::Resolution::Current => "current",
crate::merge::Resolution::Incoming => "incoming",
crate::merge::Resolution::Both => "both sides",
};
self.status = format!(
"Accepted {side} for {total} conflict{} — \"Merge: Complete Merge\" stages the file",
if total == 1 { "" } else { "s" }
);
}
/// VS Code's "Complete Merge": once every block is resolved, persist the
/// buffer and stage the file so it leaves MERGE CONFLICTS and rejoins the
/// ordinary commit flow. Refuses while conflicts remain.
fn complete_merge(&mut self) {
if !self.editor_is_text() {
self.status = String::from("Merge conflict actions need a text file");
return;
}
// Merge editor (#253): the Result has no markers, so the gate is
// the tracked regions, not the marker scan below.
if self.editor.merge.is_some() {
self.merge_view_sync();
let unresolved = self
.editor
.merge
.as_ref()
.map(|mv| mv.unresolved_count())
.unwrap_or(0);
if unresolved > 0 {
self.status = format!(
"{unresolved} conflict{} still unresolved — F7 jumps to the next one",
if unresolved == 1 { "" } else { "s" }
);
return;
}
}
let left = self.editor.conflicts().len();
if left > 0 {
self.status = format!(
"{left} conflict{} still unresolved — F7 jumps to the next one",
if left == 1 { "" } else { "s" }
);
return;
}
let Some(path) = self.editor.path.clone() else {
self.status = String::from("No file open");
return;
};
if self.editor.dirty {
self.save();
}
// Canonicalize before the relative-path strip: a workspace under
// a symlink (macOS /var → /private/var) otherwise falls back to
// the absolute path, which reads wrong in the status and would
// refuse in stricter git contexts.
let merge_root = self
.roots
.owning_root(&path)
.unwrap_or_else(|| self.roots.primary())
.to_path_buf();
let canon_root = std::fs::canonicalize(&merge_root).unwrap_or_else(|_| merge_root.clone());
let canon_path = std::fs::canonicalize(&path).unwrap_or_else(|_| path.clone());
let rel = canon_path
.strip_prefix(&canon_root)
.map(|p| p.to_string_lossy().into_owned())
.unwrap_or_else(|_| self.status_path(&path));
match crate::git::stage_path(&canon_root, &rel) {
Ok(()) => {
self.refresh_source_control();
self.status = format!("Merge complete: staged {rel}");
}
Err(e) => self.status = format!("Stage failed: {e}"),
}
}
/// Open the three-way merge editor (#253) for `path`. Inputs come
/// from the git index stages (`:1:` base, `:2:` ours, `:3:` theirs)
/// when the path is unmerged; otherwise the sides are synthesized
/// from conflict markers in the file itself, so the editor also
/// works on a plain marker file outside any merge. The tab is opened
/// through the normal text route first (language, LSP, undo all
/// attach), then the buffer is transformed into the initial Result
/// in one undo step — the marker text stays one Undo away.
fn open_merge_editor_for(&mut self, path: &Path) -> bool {
// Stage specs are repo-toplevel-relative (#139): see `repo_rel`.
let root = self.scm_root();
let canon_root = std::fs::canonicalize(&root).unwrap_or_else(|_| root.clone());
let rel = self.repo_rel(path);
let to_lines = |s: String| -> Vec<String> { s.lines().map(str::to_string).collect() };
let ours = crate::git::read_file_at_stage(&canon_root, &rel, 2).map(to_lines);
let theirs = crate::git::read_file_at_stage(&canon_root, &rel, 3).map(to_lines);
let sides = match (ours, theirs) {
// Neither stage exists: the path is not unmerged in git at
// all — fall through to marker synthesis below.
(Err(_), Err(_)) => None,
// Unmerged: a missing single stage is a deleted side (DU/UD)
// and a missing base is added-by-both (AA) — both mean "that
// side is empty", not an error.
(o, t) => {
let base = crate::git::read_file_at_stage(&canon_root, &rel, 1)
.map(&to_lines)
.unwrap_or_default();
Some((base, o.unwrap_or_default(), t.unwrap_or_default()))
}
};
let built = match sides {
Some((base, ours, theirs)) => Some(crate::merge_editor::MergeView::new(
base, ours, theirs, false,
)),
None => std::fs::read_to_string(path).ok().and_then(|text| {
let lines: Vec<String> = text.lines().map(str::to_string).collect();
crate::merge_editor::view_from_markers(&lines)
}),
};
let Some((mut mv, result)) = built else {
self.status = format!("{rel} has no merge conflicts");
return false;
};
if let Err(e) = self.editor.open_pinned(path) {
self.status = format!("Open failed: {e}");
return false;
}
self.focus_pane(Pane::Editor);
let end = self.editor.lines.len();
self.editor.splice_result_rows(0, end, result);
mv.synced_len = self.editor.lines.len();
mv.synced_seq = self.editor.edit_seq;
let n = mv.conflicts.len();
let first = mv.conflicts.first().map(|c| c.result_start);
mv.anchor_panes_on(0);
self.editor.merge = Some(mv);
if let Some(row) = first {
self.editor.clear_selection();
self.editor.cursor_row = row.min(self.editor.lines.len().saturating_sub(1));
self.editor.cursor_col = 0;
self.editor.ensure_cursor_col_visible();
}
self.status = format!(
"Merge editor: {n} conflict{} — F7 jumps, checkboxes or Merge commands accept, \"Reopen as Text\" for the marker flow",
if n == 1 { "" } else { "s" }
);
true
}
/// `path` relative to the repo toplevel, both sides canonicalized —
/// a workspace under a symlink (macOS /var → /private/var) otherwise
/// fails the strip and yields an absolute "relative" path, which git
/// stage specs refuse and status messages shouldn't show.
fn repo_rel(&self, path: &Path) -> String {
let root = self.scm_root();
let canon_root = std::fs::canonicalize(&root).unwrap_or_else(|_| root.clone());
let canon_path = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
canon_path
.strip_prefix(&canon_root)
.map(|p| p.to_string_lossy().into_owned())
.unwrap_or_else(|_| self.status_path(path))
}
/// Reconcile the merge view's tracked regions with any buffer edit it
/// has not seen yet (the render loop does this each frame; command
/// paths call it first so they also work headless, e.g. under test).
fn merge_view_sync(&mut self) {
let (len, seq, row) = (
self.editor.lines.len(),
self.editor.edit_seq,
self.editor.merge_edit_row,
);
if let Some(mv) = self.editor.merge.as_mut() {
mv.sync_with_buffer(len, seq, row);
}
}
/// The conflict an accept action targets: the one under the cursor,
/// else the one navigation last landed on.
fn merge_target_conflict(&self) -> Option<usize> {
let mv = self.editor.merge.as_ref()?;
mv.conflict_at_result_row(self.editor.cursor_row)
.or_else(|| (mv.active < mv.conflicts.len()).then_some(mv.active))
}
/// Set conflict `idx` to `state`, splicing its replacement into the
/// Result as one undo step and updating the tracked regions.
fn merge_set_conflict(&mut self, idx: usize, state: crate::merge_editor::ConflictState) {
self.merge_view_sync();
let Some(mv) = self.editor.merge.as_ref() else {
return;
};
let Some(c) = mv.conflicts.get(idx) else {
return;
};
let (start, end) = (c.result_start, c.result_start + c.result_len);
let repl = c.replacement(state);
let new_len = repl.len();
self.editor.splice_result_rows(start, end, repl);
let (len, seq) = (self.editor.lines.len(), self.editor.edit_seq);
let mv = self.editor.merge.as_mut().expect("checked above");
mv.note_accept(idx, new_len, state, len, seq);
let (resolved, total) = (mv.resolved_count(), mv.conflicts.len());
self.status = format!(
"Conflict {} of {total}: {} ({resolved}/{total} resolved)",
idx + 1,
match state {
crate::merge_editor::ConflictState::Current => "accepted current",
crate::merge_editor::ConflictState::Incoming => "accepted incoming",
crate::merge_editor::ConflictState::Both => "accepted both (current first)",
crate::merge_editor::ConflictState::BothReverse => "accepted both (incoming first)",
crate::merge_editor::ConflictState::Base => "kept base",
crate::merge_editor::ConflictState::Unresolved => "back to unresolved",
crate::merge_editor::ConflictState::Manual => "manual",
}
);
}
/// Accept-action entry for the palette commands: target the cursor's
/// conflict (falling back to the active one).
fn merge_apply(&mut self, state: crate::merge_editor::ConflictState) {
self.merge_view_sync();
match self.merge_target_conflict() {
Some(idx) => self.merge_set_conflict(idx, state),
None => self.status = String::from("No conflict at the cursor — F7 jumps to one"),
}
}
/// Accept every remaining unresolved conflict as `state` (the
/// Accept-All commands in the merge editor).
fn merge_accept_all(&mut self, state: crate::merge_editor::ConflictState) {
self.merge_view_sync();
let Some(mv) = self.editor.merge.as_ref() else {
return;
};
// Back-to-front so earlier indices' spans stay valid inside each
// splice's own bookkeeping (note_accept shifts only later ones).
let targets: Vec<usize> = (0..mv.conflicts.len())
.rev()
.filter(|&i| !mv.conflicts[i].state.resolved())
.collect();
let n = targets.len();
for idx in targets {
self.merge_set_conflict(idx, state);
}
let total = self
.editor
.merge
.as_ref()
.map(|m| m.conflicts.len())
.unwrap_or(0);
self.status = format!(
"Accepted {n} conflict{} ({total} total)",
if n == 1 { "" } else { "s" }
);
}
/// Checkbox click: toggle one side's inclusion, VS Code's model —
/// both checked is Accept Combination, neither reverts to base.
fn merge_toggle_side(&mut self, idx: usize, side: crate::merge_editor::CheckSide) {
use crate::merge_editor::{CheckSide, ConflictState as S};
let Some(mv) = self.editor.merge.as_ref() else {
return;
};
let Some(c) = mv.conflicts.get(idx) else {
return;
};
let (mut cur, mut inc) = match c.state {
S::Current => (true, false),
S::Incoming => (false, true),
S::Both | S::BothReverse => (true, true),
S::Unresolved | S::Base | S::Manual => (false, false),
};
match side {
CheckSide::Current => cur = !cur,
CheckSide::Incoming => inc = !inc,
}
let state = match (cur, inc) {
(true, false) => S::Current,
(false, true) => S::Incoming,
(true, true) => S::Both,
(false, false) => S::Unresolved,
};
self.merge_set_conflict(idx, state);
}
/// F7 / Shift+F7 in the merge editor: hop conflicts in the Result and
/// re-anchor every source pane on the same conflict.
fn merge_jump(&mut self, backwards: bool) {
self.merge_view_sync();
let row = self.editor.cursor_row;
let Some(mv) = self.editor.merge.as_mut() else {
return;
};
let Some(idx) = mv.next_conflict(row, backwards) else {
self.status = String::from("No conflicts");
return;
};
mv.anchor_panes_on(idx);
let target = mv.conflicts[idx].result_start;
let total = mv.conflicts.len();
self.editor.clear_selection();
self.editor.cursor_row = target.min(self.editor.lines.len().saturating_sub(1));
self.editor.cursor_col = 0;
self.editor.ensure_cursor_col_visible();
self.status = format!("Conflict {} of {total}", idx + 1);
}
fn start_code_action(&mut self) {
if self.editor.has_non_text_view() {
return;
}
// A merge conflict at the cursor takes the Quick Fix over LSP code
// actions, like VS Code's Accept Current / Incoming / Both lenses:
// resolving markers is what the user wants there, and it needs no
// server round-trip.
let cursor_row = self.editor.cursor_row;
if crate::merge::conflict_containing(self.editor.conflicts(), cursor_row).is_some() {
self.open_merge_conflict_picker();
return;
}
let Some(path) = self.editor.path.clone() else {
self.status = String::from("No file open");
return;
};
// `row`/`col` go to the server, so the column must be UTF-16;
// `diagnostics_in_line_range` takes a plain row and is unaffected.
let (row, col) = self
.editor
.pos_to_utf16(self.editor.cursor_row, self.editor.cursor_col);
let diagnostics = self.editor.diagnostics_in_line_range(row, row);
let Some(lsp) = self.lsp.as_mut() else {
self.status = String::from("No language server for this file");
return;
};
let id = lsp.request_code_action(path, row, col, row, col, diagnostics);
self.code_action_request_id = Some(id);
self.code_action_pending_resolve = false;
self.status = String::from("Finding quick fixes");
}
pub fn drain_lsp_code_actions(&mut self) -> bool {
let mut arrived = false;
let mut items: Option<Vec<crate::lsp::manager::CodeActionItem>> = None;
let mut unsupported = false;
{
let Some(lsp) = self.lsp.as_ref() else {
return false;
};
while let Some(result) = lsp.drain_code_action() {
if Some(result.request_id) != self.code_action_request_id {
continue;
}
arrived = true;
items = result.items;
unsupported = result.unsupported;
}
}
if !arrived {
return false;
}
self.code_action_request_id = None;
let was_resolve = std::mem::take(&mut self.code_action_pending_resolve);
if unsupported {
// No code-action server, but a seated navigator can still take
// the diagnostic under the caret (#374).
if self.navigator_fix_candidate().is_some() {
self.open_code_action_picker(Vec::new());
} else {
self.status = String::from("No quick fixes: no code-action server for this file");
}
return true;
}
// A resolve reply carries the one action the user already chose, now with
// its edit filled in: apply it directly instead of re-opening a menu.
if was_resolve {
match items.and_then(|mut v| v.pop()) {
Some(item) => self.apply_resolved_code_action(item),
None => self.status = String::from("Quick fix could not be resolved"),
}
return true;
}
match items {
Some(items) if items.len() == 1 && items[0].needs_resolve => {
// A single resolve-only action (e.g. a deferred auto-import):
// resolve it straight away rather than popping a one-row menu.
self.resolve_and_apply_code_action(items.into_iter().next().unwrap());
}
Some(items) if !items.is_empty() => self.open_code_action_picker(items),
// Nothing from the server: the navigator entry alone, when a
// diagnostic sits under the caret (#374).
_ if self.navigator_fix_candidate().is_some() => {
self.open_code_action_picker(Vec::new());
}
_ => self.status = String::from("No quick fixes available here"),
}
true
}
/// Present the available code actions in the shared list picker, tagging
/// each row with its index into `pending_code_actions`. When a diagnostic
/// sits under the caret, one more row follows the server's: Fix with
/// Navigator (#374), at index `items.len()`, offered whether or not a
/// navigator is seated (the action says so if none is).
fn open_code_action_picker(&mut self, items: Vec<crate::lsp::manager::CodeActionItem>) {
use crate::widgets::list_picker::{ListPicker, ListPurpose, ListRow};
let mut rows: Vec<ListRow> = items
.iter()
.enumerate()
.map(|(i, item)| ListRow {
id: i.to_string(),
label: if item.is_preferred {
format!("{} (preferred)", item.title)
} else {
item.title.clone()
},
})
.collect();
if self.navigator_fix_candidate().is_some() {
rows.push(ListRow {
id: String::from("navigator"),
label: String::from("Fix with Navigator"),
});
}
self.pending_code_actions = items;
self.open_list_picker(
ListPicker::new(ListPurpose::CodeAction, "Quick Fix", rows),
"No quick fixes available here",
);
}
/// Apply the chosen code action: edits first (as one undo step, like rename),
/// then any command. A resolve-only action is sent for resolution first; its
/// resolved edit/command arrives back through [`Self::drain_lsp_code_actions`].
fn apply_code_action(&mut self, item: crate::lsp::manager::CodeActionItem) {
if item.needs_resolve {
self.resolve_and_apply_code_action(item);
return;
}
self.apply_resolved_code_action(item);
}
/// Apply an action that already carries its edit / command (the leaf of both
/// the direct and the post-resolve paths). Never re-resolves, so a server
/// that returns a still-edit-less action after resolve can't loop.
fn apply_resolved_code_action(&mut self, item: crate::lsp::manager::CodeActionItem) {
let mut applied = false;
if !item.edits.is_empty() {
match self.apply_rename_edits(&item.edits) {
Ok((files, occ)) => {
applied = true;
self.status = format!(
"{}: changed {occ} edit(s) across {files} file(s)",
item.title
);
}
Err(e) => {
self.status = format!("Quick fix failed: {e}");
return;
}
}
}
if let Some(cmd) = item.command
&& let (Some(path), Some(lsp)) = (self.editor.path.clone(), self.lsp.as_mut())
{
lsp.execute_command(path, cmd.command, cmd.arguments);
applied = true;
self.status = format!("Applied quick fix: {}", item.title);
}
if !applied {
self.status = format!("Quick fix had no effect: {}", item.title);
}
}
/// Send a resolve-only action for `codeAction/resolve`; the resolved item
/// comes back as a single-item reply that the drain applies.
fn resolve_and_apply_code_action(&mut self, item: crate::lsp::manager::CodeActionItem) {
let Some(action) = item.resolve_action else {
self.status = format!("Quick fix cannot be resolved: {}", item.title);
return;
};
let Some(path) = self.editor.path.clone() else {
return;
};
let Some(lsp) = self.lsp.as_mut() else {
return;
};
let id = lsp.request_code_action_resolve(path, item.server, action);
self.code_action_request_id = Some(id);
self.code_action_pending_resolve = true;
self.status = String::from("Resolving quick fix");
}
/// Route the key through the completion popup when one is open.
/// Up/Down navigate, Enter/Tab accept and replace the typed prefix
/// with the chosen completion's full text, Esc dismisses. Printable
/// chars and Backspace pass through to the editor and refresh the
/// popup's filter prefix in place; if no items match the new prefix
/// the popup dismisses on the next tick.
fn handle_completion_popup_key(&mut self, key: KeyEvent) -> bool {
if self.completion_popup.is_none() {
return false;
}
match key.code {
KeyCode::Up => {
if let Some(p) = self.completion_popup.as_mut() {
p.move_up();
}
true
}
KeyCode::Down => {
if let Some(p) = self.completion_popup.as_mut() {
p.move_down();
}
true
}
KeyCode::Enter | KeyCode::Tab => {
let prefix_len = self
.completion_popup
.as_ref()
.map(|p| p.prefix.chars().count())
.unwrap_or(0);
let text = self
.completion_popup
.as_ref()
.and_then(|p| p.selected_label());
let is_snippet = self
.completion_popup
.as_ref()
.is_some_and(|p| p.selected_is_snippet());
self.completion_popup = None;
self.completion_request_id = None;
if let Some(t) = text {
if is_snippet {
// The body carries $1/$0 tab stops; expand_snippet
// removes the typed prefix itself and drives the caret.
self.editor.expand_snippet(&t, prefix_len);
} else {
for _ in 0..prefix_len {
self.editor.backspace();
}
// An accepted completion is the SERVER's text, not
// the user's: they picked it from a list rather than
// writing it (#349).
self.editor
.insert_str_as(&t, crate::provenance::Seat::Generated);
}
}
true
}
KeyCode::Esc => {
self.completion_popup = None;
self.completion_request_id = None;
true
}
KeyCode::Backspace => {
self.editor.backspace();
self.refresh_completion_prefix();
true
}
KeyCode::Char(c) => {
if key.modifiers.contains(KeyModifiers::CONTROL)
|| key.modifiers.contains(KeyModifiers::ALT)
|| key.modifiers.contains(KeyModifiers::SUPER)
{
self.completion_popup = None;
self.completion_request_id = None;
return false;
}
self.editor.insert_char(c);
self.refresh_completion_prefix();
if !is_word_continuation(c) {
self.completion_popup = None;
self.completion_request_id = None;
}
if is_signature_help_trigger(c) {
self.trigger_signature_help();
}
true
}
_ => {
self.completion_popup = None;
self.completion_request_id = None;
false
}
}
}
fn refresh_completion_prefix(&mut self) {
let prefix = self.editor.word_before_cursor();
let Some(popup) = self.completion_popup.as_mut() else {
return;
};
popup.set_prefix(prefix);
if popup.visible_is_empty() {
self.completion_popup = None;
self.completion_request_id = None;
}
}
fn drain_fs_events(&mut self) -> bool {
let init_changed = self.try_install_pending_init();
let mut drain = self.fs_watch.drain(&mut self.tree, &self.editor);
for w in &mut self.fs_watch_extra {
let d = w.drain(&mut self.tree, &self.editor);
drain.got_any |= d.got_any;
drain.touched_open_file |= d.touched_open_file;
drain.dirs_changed |= d.dirs_changed;
drain.finder_relevant |= d.finder_relevant;
// A secondary root's writes are an agent's writes too: dropping
// them here would silently give a multi-root workspace an empty
// review queue for every folder but the first (#345).
drain.changed_files.extend(d.changed_files);
drain.rescan_dropped_events |= d.rescan_dropped_events;
}
if drain.dirs_changed {
self.refresh_git_status_debounced();
if drain.finder_relevant {
self.kick_file_finder_index_rebuild();
}
}
// `touched_open_file` only tracks the ACTIVE tab; a background tab's
// file change still arrives as a watcher event (got_any), so sweep
// every tab whenever any event lands. The sweep is stamp-based, so
// a benign Access/Metadata event that didn't move mtime+len is a
// no-op and won't clobber selection or reload spuriously.
if drain.got_any {
self.reload_open_file_after_external_change();
// An open diff view follows the file the same way a buffer does
// (#471): an agent rewriting the working file, or a save from a
// sibling tab, re-diffs it in place.
self.refresh_open_diff_views(false, &[], &drain.changed_files);
}
// Attribute the writes to whichever agents were working when they
// landed (#345). Done after the reload so an agent's write to the
// ACTIVE tab is hashed from the content the user is about to see.
if !drain.changed_files.is_empty()
&& self.attribute_writes_to_working_agents(&drain.changed_files)
{
// Only when the ledger actually moved: the Explorer's dots must
// match it, and a decoration that lags is worse than none.
self.sync_agent_lane_decorations();
}
// A rescan means the watcher dropped events, so the queue is a
// LOWER BOUND from here until it is emptied (#345). Recorded in the
// ledger rather than only announced: a status line the next
// keystroke clears would leave a partial queue looking complete.
// Unconditional on whether an agent is working right now — the
// dropped writes may have landed a moment ago, while the pane's
// sampled status has since flipped to idle.
if drain.rescan_dropped_events {
self.agent_ledger.note_dropped_events();
if !self.working_agents().is_empty() {
self.status = String::from(
"File watcher overflowed: some agent changes may be missing from the review queue",
);
}
}
let polled = self.poll_filesystem_changes();
drain.got_any || init_changed || polled
}
fn cycle_focus(&mut self) {
// Skip hidden panes when cycling.
let mut next = self.focus;
for _ in 0..3 {
next = match next {
Pane::Tree => Pane::Editor,
Pane::Editor => Pane::Terminal,
Pane::Terminal => Pane::Tree,
};
if self.pane_visible(next) {
break;
}
}
// Through `focus_pane`, never a bare assignment: every route into a
// pane shares its guarantees (terminal find/copy-mode teardown, and
// restoring the editor from under a maximized terminal).
self.focus_pane(next);
}
/// Returns true exactly once after the welcome OSC-1337 image has been
/// emitted and the editor pane has stopped being blank (i.e. a file is
/// now open). The caller — the main draw loop — must respond by
/// invalidating the prev buffer so ratatui repaints every cell on the
/// next draw, wiping iTerm's image cache for the welcome region.
pub fn consume_welcome_image_clear(&mut self) -> bool {
let opened_file = !self.editor.is_blank_initial();
self.overlays.welcome.consume_clear_or(opened_file)
}
fn render_welcome(&mut self, frame: &mut ratatui::Frame, outer_area: Rect) {
if outer_area.width == 0 || outer_area.height == 0 {
return;
}
// In iTerm2 image mode we let the iTerm session bg (forced to
// sRGB(EDITOR_BG_RGB) by `SetColors=bg=srgb:…` at startup) show
// through the welcome cells via SGR 49 (default bg). The OSC-1337
// PNG canvas is filled with the same sRGB hex, so both surfaces
// display the same physical pixel — no Generic-RGB vs sRGB seam.
// Outside iTerm we fall back to explicit truecolor since there's
// no PNG to match against.
let bg = if crate::iterm2_inline::detect_iterm2_inline_support() {
Style::default().bg(Color::Reset)
} else {
Style::default().bg(self.theme.editor_bg())
};
// Paint a full bordered box around the welcome area so the editor
// pane has the same visible envelope as when a file is open
// (Borders::ALL on the editor widget). Without this, the welcome
// bg bleeds into the tree, the terminal, and the window edge with
// no perceptible seam — and the sidebar splitter looks
// unreachable. The bg style is applied to the same block so the
// inside is filled in one pass. The welcome content then renders
// into `block.inner(outer_area)` so a tall recents list can never
// paint over the border rows.
let outer_block = ratatui::widgets::Block::default()
.borders(ratatui::widgets::Borders::ALL)
.border_style(Style::default().fg(Color::DarkGray))
.style(bg);
let area = outer_block.inner(outer_area);
frame.render_widget(outer_block, outer_area);
if area.width == 0 || area.height == 0 {
return;
}
// Layout-control icons at the welcome screen's top-right, inside the
// border row — same controls as the editor tab strip (placement A).
let icon_row = Rect {
x: outer_area.x + 1,
y: outer_area.y,
width: outer_area.width.saturating_sub(2),
height: 1,
};
self.paint_layout_icons(frame, icon_row);
// Layout regions, top-to-bottom:
// [logo + version badge]
// [tagline]
// [gradient box: header + release highlights]
// [footer chevron line]
let block_left = area.x + area.width / 8;
let block_right = area.x + area.width - area.width / 8;
let block_w = block_right.saturating_sub(block_left);
let has_recent_panel = self.welcome.has_recent_panel();
let recents_inner_h =
welcome_recents_height(self.welcome.notes(), welcome_card_inner_width(block_w));
let tagline_h = 1u16;
let footer_h = 1u16;
// Gaps: blank row after logo, after tagline, after box.
let gaps_h = 3u16;
let logo_max_w = (area.width as u32).saturating_sub(4) as u16;
let logo_w_cells = logo_max_w.clamp(8, 48);
// Box content needs at least the 4-cell border+inset envelope to be
// worth drawing.
let desired_box_h = if has_recent_panel {
recents_inner_h.saturating_add(4)
} else {
0
};
// Size the card first, then give the logo whatever remains (still
// capped to its 4..14 band, so the stack can never overrun the
// fixed-size ratatui buffer). The release note is the panel's
// information and the logo is decoration: in a height-starved
// welcome area (a 40-row window with the terminal panel open) the
// old logo-first order kept a full 14-row logo above a card that
// was clipped mid-sentence or dropped entirely (#99).
let logo_h_cells = area
.height
.saturating_sub(tagline_h + footer_h + gaps_h)
.saturating_sub(desired_box_h)
.clamp(4, 14);
let used_above_box = logo_h_cells + 1 + tagline_h + 1; // logo, gap, tagline, gap
let used_below_box = 1 + footer_h; // gap, footer
let max_box_h = area
.height
.saturating_sub(used_above_box)
.saturating_sub(used_below_box);
let box_h = desired_box_h.min(max_box_h);
let total_h = used_above_box + box_h + used_below_box;
let block_top = area.y + area.height.saturating_sub(total_h) / 2;
let logo_x = area.x + area.width.saturating_sub(logo_w_cells) / 2;
let logo_y = block_top;
let area_max_y = area.y + area.height;
let desired = WelcomeLayout {
cell_x: logo_x,
cell_y: logo_y,
cell_w: logo_w_cells,
cell_h: logo_h_cells,
};
// Re-bake the OSC-1337 image whenever the layout shifts (resize,
// sidebar toggle, font size change). The canvas is filled with the
// raw `EDITOR_BG_RGB` bytes interpreted as sRGB (iTerm2 decodes
// PNG bytes as sRGB by default). The pane's SGR-painted cells use
// `Color::Reset` so they fall back to the iTerm session bg, which
// we force to the same sRGB hex via `SetColors=bg=srgb:…` at
// startup. Both surfaces therefore display the same physical
// pixel pair-for-pair.
if !self.overlays.welcome.layout_matches(&desired) {
self.overlays.welcome.request_clear_if_displayed();
if let Some((cw, ch)) = self.cell_pixel {
let canvas_w = (logo_w_cells as u32) * cw;
let canvas_h = (logo_h_cells as u32) * ch;
let bg = self.theme_bg_pixel();
let protocol = self.inline_protocol;
// On a light background the asset's white "cr"/"ft"
// letters would vanish; the ink recolor turns just those
// pixels dark while the orange/teal strokes pass through.
let ink = self.theme.is_light().then_some((0x3b_u8, 0x3b_u8, 0x3b_u8));
if let Ok(baked) = crate::iterm2_inline::fit_image_with_ink(
crate::iterm2_inline::WELCOME_LOGO_PNG,
canvas_w,
canvas_h,
bg,
ink,
) && let Some(raw) = crate::iterm2_inline::build_inline_image(
protocol,
&baked,
logo_w_cells,
logo_h_cells,
false,
crate::iterm2_inline::KITTY_ID_WELCOME,
) {
let osc = crate::iterm2_inline::maybe_tmux_wrap(
protocol,
crate::iterm2_inline::detect_tmux(),
raw,
);
self.overlays.welcome.set_image(osc);
}
}
self.overlays.welcome.set_layout(desired);
self.overlays.welcome.mark_dirty();
}
if !self.overlays.welcome.has_image() {
// Text fallback for non-iTerm2 terminals.
let label = " croft ";
let lx = logo_x
.saturating_add(logo_w_cells.saturating_sub(label.chars().count() as u16) / 2);
let ly = logo_y + logo_h_cells / 2;
frame.buffer_mut().set_string(
lx,
ly,
label,
Style::default()
.fg(self.theme.ui(Color::Rgb(0x9d, 0xa5, 0xb4)))
.add_modifier(Modifier::BOLD),
);
}
// Version badge to the right of the wordmark (the wordmark sits
// in the lower portion of the logo PNG; the badge tracks that row).
// Plain `vX.Y.Z` (#282). The hash told two builds of one version
// apart; the drift banner already does that, with an actionable
// message, at the moment it matters.
let version_label = format!(" v{} ", env!("CARGO_PKG_VERSION"));
let version_w = version_label.chars().count() as u16;
let badge_x = logo_x + logo_w_cells + 1;
let badge_y = logo_y + (logo_h_cells * 5) / 6;
if badge_x + version_w + 2 <= area.x + area.width && badge_y + 2 < area_max_y {
let badge_style = Style::default()
.fg(self.theme.ui(rgb_color(GRAD_TL)))
.add_modifier(Modifier::BOLD);
frame
.buffer_mut()
.set_string(badge_x, badge_y, "\u{256d}", badge_style);
for i in 0..version_w {
frame
.buffer_mut()
.set_string(badge_x + 1 + i, badge_y, "\u{2500}", badge_style);
}
frame.buffer_mut().set_string(
badge_x + 1 + version_w,
badge_y,
"\u{256e}",
badge_style,
);
frame
.buffer_mut()
.set_string(badge_x, badge_y + 1, "\u{2502}", badge_style);
frame.buffer_mut().set_string(
badge_x + 1,
badge_y + 1,
&version_label,
Style::default()
.fg(self.theme.ui(Color::White))
.add_modifier(Modifier::BOLD),
);
frame.buffer_mut().set_string(
badge_x + 1 + version_w,
badge_y + 1,
"\u{2502}",
badge_style,
);
frame
.buffer_mut()
.set_string(badge_x, badge_y + 2, "\u{2570}", badge_style);
for i in 0..version_w {
frame.buffer_mut().set_string(
badge_x + 1 + i,
badge_y + 2,
"\u{2500}",
badge_style,
);
}
frame.buffer_mut().set_string(
badge_x + 1 + version_w,
badge_y + 2,
"\u{256f}",
badge_style,
);
}
// Tagline.
let tagline_y = logo_y + logo_h_cells + 1;
let tagline_w = WELCOME_TAGLINE.chars().count() as u16;
let tagline_x = area.x + area.width.saturating_sub(tagline_w) / 2;
if tagline_y < area_max_y && tagline_w <= area.width {
frame.buffer_mut().set_string(
tagline_x,
tagline_y,
WELCOME_TAGLINE,
Style::default().fg(self.theme.ui(Color::Rgb(0x88, 0xc0, 0xd0))),
);
}
let box_y = tagline_y + tagline_h + 1;
if has_recent_panel && box_h >= 4 && block_w >= 4 && box_y + box_h <= area_max_y {
let box_rect = Rect {
x: block_left,
y: box_y,
width: block_w,
height: box_h,
};
if self.theme.is_light() {
// The brand gradient's teal leg washes out on white; paint
// the card border in the light widget-border grey instead.
let border = Style::default().fg(self.theme.ui(Color::Rgb(0x3b, 0x42, 0x52)));
let b = frame.buffer_mut();
for x in box_rect.x..box_rect.x + box_rect.width {
b.set_string(x, box_rect.y, "\u{2500}", border);
b.set_string(x, box_rect.y + box_rect.height - 1, "\u{2500}", border);
}
for y in box_rect.y..box_rect.y + box_rect.height {
b.set_string(box_rect.x, y, "\u{2502}", border);
b.set_string(box_rect.x + box_rect.width - 1, y, "\u{2502}", border);
}
b.set_string(box_rect.x, box_rect.y, "\u{256d}", border);
b.set_string(
box_rect.x + box_rect.width - 1,
box_rect.y,
"\u{256e}",
border,
);
b.set_string(
box_rect.x,
box_rect.y + box_rect.height - 1,
"\u{2570}",
border,
);
b.set_string(
box_rect.x + box_rect.width - 1,
box_rect.y + box_rect.height - 1,
"\u{256f}",
border,
);
} else {
paint_gradient_box(frame.buffer_mut(), box_rect);
}
// Inner content area: 1-cell inset from each border. The width
// comes from the same helper the height measure used, so the
// wrap below reproduces exactly the line count the card
// reserved rows for (#99).
let inner_x = box_rect.x + 2;
let inner_y = box_rect.y + 1;
let inner_w_actual = welcome_card_inner_width(box_rect.width);
let row_style = Style::default().fg(self.theme.ui(Color::Rgb(0xc5, 0xcd, 0xd9)));
// Header row: "> IN THIS RELEASE (vX.Y.Z)". The leading chevron
// echoes the cr<>ft wordmark's bracket. The highlights below are
// hand-curated data baked into this build (see
// `crate::release_notes`), so the heading names the exact version.
let header_y = inner_y;
frame.buffer_mut().set_string(
inner_x,
header_y,
"> ",
Style::default()
.fg(self.theme.ui(rgb_color(GRAD_TR)))
.add_modifier(Modifier::BOLD),
);
frame.buffer_mut().set_string(
inner_x + 2,
header_y,
format!("IN THIS RELEASE (v{})", env!("CARGO_PKG_VERSION")),
Style::default()
.fg(self.theme.ui(Color::White))
.add_modifier(Modifier::BOLD),
);
// Each highlight: a kind glyph in the gutter (rocket = new feature,
// bug = fix) tinted by kind, then the wrapped one-line summary.
// Continuation lines align under the summary, leaving the gutter
// clear so the glyph reads as a single bullet.
let summary_x = inner_x + WELCOME_NOTE_GUTTER;
let summary_w = inner_w_actual.saturating_sub(WELCOME_NOTE_GUTTER);
let last_row = box_rect.y + box_rect.height - 1;
let mut row_y = header_y + 2;
for note in self.welcome.notes() {
if row_y >= last_row {
break;
}
frame.buffer_mut().set_string(
inner_x,
row_y,
note.kind.icon(),
Style::default()
.fg(note.kind.color())
.add_modifier(Modifier::BOLD),
);
let lines = wrapped_welcome_note_summary(note, inner_w_actual);
for (line_idx, line) in lines.iter().enumerate() {
let line_y = row_y + line_idx as u16;
if line_y >= last_row {
break;
}
let clipped: String = line.chars().take(summary_w as usize).collect();
frame
.buffer_mut()
.set_string(summary_x, line_y, clipped, row_style);
}
row_y = row_y.saturating_add(lines.len().max(1) as u16);
}
}
}
/// Render the secondary side bar (VS Code's auxiliary bar): the active
/// file's Outline, on the edge opposite the primary side bar. Reuses the
/// single `OutlinePanel`, forced expanded for this dedicated panel; its
/// collapse state is saved/restored so the Explorer's own OUTLINE section
/// (which may render the same widget afterward) keeps its toggle.
fn render_secondary_side_bar(&mut self, frame: &mut ratatui::Frame, area: Option<Rect>) {
let Some(area) = area else {
return;
};
if area.width == 0 || area.height == 0 {
return;
}
// A left border + bg fill so the panel reads as a distinct column,
// like the primary side bar's seam against the editor.
let block = ratatui::widgets::Block::default()
.borders(ratatui::widgets::Borders::LEFT)
.border_style(Style::default().fg(self.theme.ui(Color::Rgb(0x2b, 0x2b, 0x2b))))
.style(Style::default().bg(self.theme.editor_bg()));
let inner = block.inner(area);
frame.render_widget(block, area);
let saved_collapsed = self.outline.collapsed;
self.outline.collapsed = false;
self.outline.theme = self.theme;
self.outline.focus_gradient = self.theme.gradient();
self.outline.focused = false;
self.outline.hover_pointer = self.pointer_cell;
frame.render_widget(&mut self.outline, inner);
self.outline.collapsed = saved_collapsed;
}
/// Paint the three layout-control icons (Toggle Primary Side Bar, Toggle
/// Panel, Customize Layout) right-aligned on the single-row `row` — the top
/// of the editor tab strip, or the welcome screen's top edge. croft's
/// analog of VS Code's title-bar layout controls (placement A). Records the
/// hit rects in `self.layout_icon_areas`.
fn paint_layout_icons(&mut self, frame: &mut ratatui::Frame, row: Rect) {
self.layout_icon_areas = LayoutIconAreas::default();
let w = LAYOUT_ICON_CELLS_W;
let stride = w + 1; // one-column gap between icons
// Three icons + a one-column right pad.
let needed = stride * 3;
if row.height == 0 || row.width < needed {
return;
}
let y = row.y;
let right = row.x + row.width;
let cust_x = right.saturating_sub(w + 1); // 1-col right pad
let panel_x = cust_x.saturating_sub(stride);
let side_x = panel_x.saturating_sub(stride);
if side_x < row.x {
return;
}
let rect = |x: u16| Rect {
x,
y,
width: w,
height: LAYOUT_ICON_CELLS_H,
};
self.layout_icon_areas = LayoutIconAreas {
toggle_side_bar: rect(side_x),
toggle_panel: rect(panel_x),
customize: rect(cust_x),
};
// On an image-capable terminal the post-draw flush paints crisp 2× PNG
// icons at these cells (see `pending_activity_image_overlays`); the text
// path below is only the fallback for terminals without inline images.
if self.overlays.activity.has_images() {
return;
}
let pointer = self.pointer_cell;
// The codicon shape carries the on/off state (filled vs. hollow), like
// VS Code; colour brightens to the accent on hover. Glyphs sit centred
// in the 4-wide slot.
let base = self.theme.ui(Color::Rgb(0xcc, 0xcc, 0xcc));
let accent = self.theme.ui(Color::Rgb(0x4e, 0x9a, 0xff));
let mut paint = |x: u16, glyph: char| {
let hovered = pointer.is_some_and(|(px, py)| py == y && px >= x && px < x + w);
let color = if hovered { accent } else { base };
frame.buffer_mut().set_string(
x + w / 2,
y,
glyph.to_string(),
Style::default().fg(color),
);
};
let side_glyph = if self.show_tree {
crate::icons::LAYOUT_SIDEBAR_ON
} else {
crate::icons::LAYOUT_SIDEBAR_OFF
};
let panel_glyph = if self.show_terminal {
crate::icons::LAYOUT_PANEL_ON
} else {
crate::icons::LAYOUT_PANEL_OFF
};
paint(side_x, side_glyph);
paint(panel_x, panel_glyph);
paint(cust_x, crate::icons::LAYOUT_CUSTOMIZE);
}
fn render_activity_bar(&mut self, frame: &mut ratatui::Frame, area: Rect) {
if area.width == 0 || area.height == 0 {
return;
}
// Keep the per-frame activity badges current before the post-draw flush
// emits them. Both are count-gated, so a frame with no churn is a cheap
// no-op. (The SCM badge refreshes off the git worker instead.)
self.refresh_explorer_unsaved_badge();
self.refresh_remote_ports_badge();
self.refresh_testing_badge();
self.refresh_problems_badge();
// In images mode the activity bar inherits the iTerm session bg
// (forced to sRGB(EDITOR_BG_RGB) via SetColors), matching the rest
// of the panes. The glyph-fallback path keeps a solid bg for
// terminals that can't render OSC-1337.
let bg = if self.overlays.activity.has_images() {
Style::default().bg(Color::Reset)
} else {
Style::default().bg(self.theme.editor_bg())
};
// In images mode the icon PNG owns the entire activity-bar block —
// background, codicon, and active pill are baked in. Rendering a bg
// block here would force a per-cell diff every frame, which in turn
// would force us to re-emit the OSC-1337 images on every draw. Both
// are visible to the user. So in images mode we leave the cells
// untouched and let the post-draw OSC writer paint them once.
if !self.overlays.activity.has_images() {
frame.render_widget(ratatui::widgets::Block::default().style(bg), area);
}
let active_bar = self.theme.activity_icon_pill();
let bg_color = bg.bg.unwrap_or(Color::Reset);
let explorer_block = activity_explorer_block(area);
let search_block = activity_search_block(area);
let source_control_block = activity_source_control_block(area);
let remote_block = activity_remote_block(area);
let run_debug_block = activity_run_debug_block(area);
let extensions_block = activity_extensions_block(area);
let testing_block = activity_testing_block(area);
let settings_block = activity_settings_block(area);
let explorer_active = self.sidebar_view == SidebarView::Explorer;
let search_active = self.sidebar_view == SidebarView::Search;
let source_control_active = self.sidebar_view == SidebarView::SourceControl;
let remote_active = self.sidebar_view == SidebarView::Remote;
let run_debug_active = self.sidebar_view == SidebarView::RunDebug;
let extensions_active = self.sidebar_view == SidebarView::Extensions;
let testing_active = self.sidebar_view == SidebarView::Testing;
let settings_active = self.settings_menu_active();
// Hover brightens the glyph (like active) but draws no selection pill,
// mirroring the image path's hovered variant. Selected wins over hover.
let hov = self.hovered_activity_icon;
let explorer_hovered = hov == Some(ActivityIcon::Explorer);
let search_hovered = hov == Some(ActivityIcon::Search);
let source_control_hovered = hov == Some(ActivityIcon::SourceControl);
let remote_hovered = hov == Some(ActivityIcon::Remote);
let run_debug_hovered = hov == Some(ActivityIcon::RunDebug);
let extensions_hovered = hov == Some(ActivityIcon::Extensions);
let testing_hovered = hov == Some(ActivityIcon::Testing);
let settings_hovered = hov == Some(ActivityIcon::Settings);
// Same palette the baked icons use, so an image-less terminal renders
// the bar in the same colors as an image-capable one instead of a
// second, slightly-off set of greys.
let active_color = self.theme.activity_icon_active();
let inactive_color = self.theme.activity_icon_inactive();
let glyph_x = activity_icon_glyph_x(area);
let render_glyph = |frame: &mut ratatui::Frame,
block: Rect,
glyph: char,
is_active: bool,
is_hovered: bool| {
let mid = block.y + block.height.saturating_sub(1) / 2;
if is_active {
let pill = Rect {
x: block.x,
y: mid,
width: 1,
height: 1,
};
frame.render_widget(
ratatui::widgets::Paragraph::new("▎")
.style(Style::default().fg(active_bar).bg(bg_color)),
pill,
);
}
let cell = Rect {
x: glyph_x,
y: mid,
width: 1,
height: 1,
};
let color = if is_active || is_hovered {
active_color
} else {
inactive_color
};
frame.render_widget(
ratatui::widgets::Paragraph::new(glyph.to_string()).style(
Style::default()
.fg(color)
.bg(bg_color)
.add_modifier(Modifier::BOLD),
),
cell,
);
};
// Text analogue of the baked count badge for image-less terminals: an
// accent cell with the count at the icon's bottom-right corner.
let badge_bg = self.theme.accent();
let render_count_badge = |frame: &mut ratatui::Frame, block: Rect, count: usize| {
if count == 0 {
return;
}
let label = if count > 9 {
String::from("9+")
} else {
count.to_string()
};
let w = label.chars().count() as u16;
frame.render_widget(
ratatui::widgets::Paragraph::new(label).style(
Style::default()
.fg(Color::White)
.bg(badge_bg)
.add_modifier(Modifier::BOLD),
),
Rect {
x: block.x + block.width.saturating_sub(w),
y: block.y + block.height.saturating_sub(1),
width: w,
height: 1,
},
);
};
if !self.overlays.activity.has_images() {
// Glyph fallback path: render the codicon and a separate active
// pill on the leftmost column. iTerm2's image path bakes the
// pill into the PNG itself, so this branch is only used on
// terminals that can't render OSC-1337.
render_glyph(
frame,
explorer_block,
crate::icons::ACTIVITY_EXPLORER,
explorer_active,
explorer_hovered,
);
render_count_badge(frame, explorer_block, self.unsaved_count());
render_glyph(
frame,
search_block,
crate::icons::ACTIVITY_SEARCH,
search_active,
search_hovered,
);
render_glyph(
frame,
source_control_block,
crate::icons::ACTIVITY_SOURCE_CONTROL,
source_control_active,
source_control_hovered,
);
let scm_count = if self.scm_worker().status().in_repo {
self.source_control.changes_count()
} else {
0
};
render_count_badge(frame, source_control_block, scm_count);
render_glyph(
frame,
remote_block,
crate::icons::ACTIVITY_REMOTE,
remote_active,
remote_hovered,
);
render_count_badge(frame, remote_block, self.ports.forwarded_count());
render_glyph(
frame,
run_debug_block,
crate::icons::ACTIVITY_RUN_DEBUG,
run_debug_active,
run_debug_hovered,
);
render_glyph(
frame,
extensions_block,
crate::icons::ACTIVITY_EXTENSIONS,
extensions_active,
extensions_hovered,
);
render_glyph(
frame,
testing_block,
crate::icons::ACTIVITY_TESTING,
testing_active,
testing_hovered,
);
render_count_badge(frame, testing_block, self.testing.failed_count());
if settings_block.width > 0 {
render_glyph(
frame,
settings_block,
crate::icons::ACTIVITY_SETTINGS,
settings_active,
settings_hovered,
);
}
}
self.sidebar_areas.explorer_icon = explorer_block;
self.sidebar_areas.search_icon = search_block;
self.sidebar_areas.source_control_icon = source_control_block;
self.sidebar_areas.remote_icon = remote_block;
self.sidebar_areas.run_debug_icon = run_debug_block;
self.sidebar_areas.extensions_icon = extensions_block;
self.sidebar_areas.testing_icon = testing_block;
self.sidebar_areas.settings_icon = settings_block;
}
fn set_sidebar_view(&mut self, view: SidebarView) {
// Choosing a sidebar view is a deliberate sidebar action, so it must
// reveal under auto-hide (#260). No pin is needed: every arm below
// focuses Pane::Tree, and auto-hide only collapses on a move to the
// editor or a terminal, so the reveal is not at risk from its own
// focus move.
if self.sidebar_view != view {
self.overlays.activity.mark_dirty();
// Leaving Search while a scan is in flight: send an
// empty-query request so the worker cancels the live walker
// threads instead of letting them keep saturating every core
// until the scan finishes. The user's hits stay populated for
// when they come back; only the live work is dropped.
if self.sidebar_view == SidebarView::Search && view != SidebarView::Search {
let _ = self
.search_query_tx
.send(SearchRequest::Query(String::new(), self.search.opts));
}
// Leaving Run-Debug after the headline icon was on screen:
// arm a one-shot `terminal.clear()` so iTerm2 evicts the
// cached OSC-1337 image cells. Plain SGR overwrites do not
// reliably evict those cells, but `\x1b[2J` (which
// `terminal.clear()` emits) does — same gate the welcome
// wordmark and editor preview pipelines use. The post-draw
// flush function is silent on the non-Run-Debug path, so
// nothing stomps the freshly-drawn next sidebar.
if self.sidebar_view == SidebarView::RunDebug
&& view != SidebarView::RunDebug
&& self.overlays.run_debug.was_emitted()
{
self.overlays.run_debug.request_clear();
}
// Same eviction trick for the Source Control no-repo hero
// PNG: leaving Source Control after the image was painted
// would otherwise leave the cached PNG under whatever
// sidebar replaces it.
if self.sidebar_view == SidebarView::SourceControl && view != SidebarView::SourceControl
{
self.overlays.hero.request_clear_if_displayed();
}
// The Source Control commit dropdown is anchored to that view;
// close it on any view change so it can't linger over the next
// sidebar.
self.commit_menu_open = false;
}
self.sidebar_view = view;
if self.sidebar_view == SidebarView::Remote && self.remote.refresh_if_config_changed() {
self.status = String::from("Reloaded SSH remotes");
}
if !self.show_tree {
self.show_tree = true; // ensure the side panel is open when switching
}
match view {
SidebarView::Explorer => self.focus_pane(Pane::Tree),
SidebarView::Search => {
self.focus_pane(Pane::Tree); // tree pane = side panel; dispatch by view
self.search.select_all_query();
}
SidebarView::SourceControl => {
self.refresh_source_control();
self.focus_pane(Pane::Tree);
}
SidebarView::Remote => self.focus_pane(Pane::Tree),
SidebarView::RunDebug => {
self.refresh_run_debug();
self.focus_pane(Pane::Tree);
}
SidebarView::Extensions => {
self.refresh_extensions();
self.focus_pane(Pane::Tree);
}
SidebarView::Testing => self.focus_pane(Pane::Tree),
}
}
/// Rebuild the Extensions panel's row list from the bundled + user manifests,
/// stamping each with its live enabled state from prefs. Called whenever the
/// view is shown or a toggle flips, so the list always reflects the manifests
/// on disk and the current disable set.
fn refresh_extensions(&mut self) {
let mut vscode: Vec<String> = self
.roots
.iter()
.flat_map(crate::vscode_extensions::workspace_recommendations)
.collect();
vscode.extend(self.vscode_listed.iter().cloned());
let compared = crate::vscode_extensions::compare(vscode);
let items = build_extension_items(&self.disabled_extensions, &compared);
self.extensions.set_items(items);
}
/// Extensions: Compare with VS Code (#352). Lists what VS Code has
/// installed (one `code --list-extensions`, which is why it is a command
/// and not a refresh), merges it with the workspace's recommendations,
/// and shows the panel with the FROM VS CODE group filled in.
fn compare_extensions_with_vscode(&mut self) {
self.vscode_listed = crate::vscode_extensions::installed_via_code();
self.refresh_extensions();
self.set_sidebar_view(SidebarView::Extensions);
let n = self
.extensions
.items()
.iter()
.filter(|it| it.vscode)
.count();
self.status = if self.vscode_listed.is_empty() {
format!(
"{n} VS Code extension{} from this workspace's recommendations; `code` was not found on PATH, so the installed list is not included",
if n == 1 { "" } else { "s" }
)
} else {
format!(
"{n} VS Code extension{} compared under FROM VS CODE",
if n == 1 { "" } else { "s" }
)
};
}
fn pane_visible(&self, p: Pane) -> bool {
match p {
Pane::Tree => self.show_tree,
Pane::Terminal => self.show_terminal,
Pane::Editor => true,
}
}
fn toggle_terminal(&mut self) {
self.show_terminal = !self.show_terminal;
// Hiding the terminal must also clear the maximize flag, otherwise
// the next time the user reopens the terminal it would still hide
// the editor — which is surprising because Ctrl+J is the user's
// mental "show my normal layout again" key.
if !self.show_terminal {
self.terminal_maximized = false;
}
// If we just hid the terminal while it was focused, fall back to editor.
if !self.show_terminal && self.focus == Pane::Terminal {
self.focus_pane(Pane::Editor);
}
// If we just showed the terminal, optionally jump focus to it for quick use.
if self.show_terminal {
self.focus_pane(Pane::Terminal);
}
}
/// `Ctrl+Shift+J`: flip the maximize-terminal flag. When turning ON,
/// also ensure the terminal pane is visible and focused so the user
/// can start typing immediately. When turning OFF, re-arm the welcome
/// wordmark so it re-paints in the restored editor area.
fn toggle_terminal_maximize(&mut self) {
self.terminal_maximized = !self.terminal_maximized;
if self.terminal_maximized {
if !self.show_terminal {
self.show_terminal = true;
}
self.focus_pane(Pane::Terminal);
self.overlays.welcome.request_clear_if_displayed();
} else {
self.overlays.welcome.mark_dirty();
}
}
pub fn terminal(&self) -> &PtyTerminal {
&self.terminals[self.active_terminal]
}
pub fn terminal_mut(&mut self) -> &mut PtyTerminal {
&mut self.terminals[self.active_terminal]
}
/// Spawn a new PTY-backed terminal next to the existing ones and make
/// it the active one. The pane becomes visible if it was hidden. The
/// new terminal's cwd is the *live* cwd of the active terminal's shell
/// (so a `cd somewhere` inside the user's prompt is reflected), with
/// the workspace root as a fallback if we can't resolve it.
///
/// The new terminal lands immediately to the right of the currently
/// active one, not at the far end of the strip, so the user's mental
/// model of "the new tab sits next to where I was" matches what they
/// see. Inserting at the end would scatter related splits across the
/// row whenever the active terminal wasn't already on the right edge.
pub fn split_terminal(&mut self) -> Result<()> {
self.insert_terminal(
PtyTerminal::new(&self.next_terminal_cwd()).context("spawning terminal")?,
);
Ok(())
}
/// Open a new pane running a specific shell (a terminal profile) instead of
/// `$SHELL`. Same placement and focus behaviour as [`split_terminal`].
pub fn split_terminal_with_shell(&mut self, shell_path: &str) -> Result<()> {
let cwd = self.next_terminal_cwd();
self.insert_terminal(
PtyTerminal::new_shell(shell_path, &cwd).context("spawning terminal")?,
);
Ok(())
}
/// The cwd a new terminal should inherit: the active terminal's live
/// directory if it has one, else the workspace root.
fn next_terminal_cwd(&self) -> PathBuf {
// The shell's own OSC 7 report (shell integration) beats sampling
// the process table — it is exact and free of proc-inspection
// races — but only when the REPORTING host is this machine: an
// in-pane ssh session names a remote path that would silently
// resolve to the wrong local directory whenever it exists here.
self.terminal()
.local_shell_cwd()
.filter(|p| p.is_dir())
.or_else(|| {
self.terminal()
.pid()
.and_then(cwd_of_pid)
.filter(|p| p.is_dir())
})
.unwrap_or_else(|| self.workspace_root().to_path_buf())
}
/// Insert `term` just after the active pane, make it active, and reveal the
/// terminal pane.
fn insert_terminal(&mut self, term: PtyTerminal) {
let target = self.active_terminal + 1;
self.terminals.insert(target, term);
self.active_terminal = target;
if !self.show_terminal {
self.show_terminal = true;
}
self.focus_pane(Pane::Terminal);
self.save_terminal_session();
}
/// Set a structural-change status, keeping any latched session-store
/// failure visible beside it (#158 review: plain assignments right
/// after a failed save silently hid the persistence error).
fn terminal_status(&mut self, msg: String) {
self.status = match &self.terminal_store_error {
Some(e) => format!("{msg} — session not saved: {e}"),
None => msg,
};
}
/// Snapshot the terminal panel (pane order, cwds, names, focus) into
/// the per-workspace session store. Called on structural changes and at
/// quit; the default single-pane layout prunes the record instead.
pub fn save_terminal_session(&mut self) {
let root = self.workspace_root().display().to_string();
let triggers = self.triggers.clone();
let panes = self
.terminals
.iter()
.map(|t| crate::terminal_session::PaneRecord {
cwd: t
.local_shell_cwd()
.filter(|p| p.is_dir())
.or_else(|| t.pid().and_then(cwd_of_pid).filter(|p| p.is_dir()))
.unwrap_or_else(|| self.workspace_root().to_path_buf())
.display()
.to_string(),
name: t.manual_name().map(str::to_string),
lane: self.lane_panes.get(&t.uid()).cloned(),
// The pane's own output, so a restored pane shows what you
// were doing instead of a blank grid (#249). Trailing blank
// rows are dropped: a mostly-empty screen would otherwise
// restore as a wall of nothing.
transcript: if t.alt_screen() {
// A full-screen program's frame is not scrollback: the
// alternate screen exists precisely so its contents
// vanish on exit. Persisting vim's tildes or htop's
// meters and replaying them as inert text above a fresh
// prompt would be worse than restoring nothing.
// `grid_lines` is the one grid reader here without an
// ALT_SCREEN guard of its own, so the check lives here.
Vec::new()
} else {
let (lines, _) = t.grid_lines();
let end = lines
.iter()
.rposition(|l| !l.trim().is_empty())
.map_or(0, |i| i + 1);
let start = end.saturating_sub(crate::terminal_session::TRANSCRIPT_LINES);
// Persisted to disk and replayed next launch: every
// redact rule applies (#360), as for the dump.
lines[start..end]
.iter()
.map(|l| crate::triggers::mask_text(l, &triggers, false))
.collect()
},
})
.collect();
let record = crate::terminal_session::SessionRecord {
panes,
active: self.active_terminal,
};
// A corrupt store is refused, never replaced (#157). The error is
// LATCHED, not just put in the status line: the structural-change
// call sites set their own success statuses right after this
// returns, which silently clobbered a transient message (#158
// review) — terminal_status() re-attaches it to whatever they say.
self.terminal_store_error =
crate::terminal_session::save_for_root(&self.terminal_session_path, &root, record)
.err();
}
/// Resurrect this workspace's terminal panel from the session store:
/// each recorded pane comes back as a fresh shell in its directory
/// (with its name), and focus returns to the pane that had it. Called
/// once at startup, replacing the default lone pane. A recorded
/// directory that no longer exists falls back to the workspace root; a
/// pane whose shell fails to spawn is skipped.
pub fn restore_terminal_session(&mut self) {
let map = crate::terminal_session::load(&self.terminal_session_path);
let Some(rec) = map.get(&self.workspace_root().display().to_string()) else {
return;
};
let mut terms = Vec::new();
let mut lanes = std::collections::BTreeMap::new();
for p in &rec.panes {
// A lane pane belongs in its worktree, whatever cwd its shell
// had drifted to at save time (#348): the launch line below is
// typed into THIS shell, so the directory and the lane are
// decided together. Deciding them apart seated the agent where
// the shell had wandered, or, when that cwd was gone, in the
// PRIMARY repo the fallback names, which is the one directory a
// lane exists to keep the agent out of. A lane whose worktree
// is gone is an ordinary pane now.
let lane = p.lane.as_ref().filter(|l| Path::new(&l.path).is_dir());
let dir = match lane {
Some(l) => PathBuf::from(&l.path),
None => {
let dir = PathBuf::from(&p.cwd);
if dir.is_dir() {
dir
} else {
self.workspace_root().to_path_buf()
}
}
};
// The transcript is painted during the spawn, not after it: a
// replay that follows the constructor races the new shell's
// first prompt for the same grid (#249).
if let Ok(mut t) = PtyTerminal::new_with_transcript(&dir, &p.transcript) {
t.set_manual_name(p.name.clone());
// The agent is seated again, from the row's CURRENT launch
// line, so an edited row applies.
if let Some(lane) = lane {
if let Some(cmd) = lane
.agent
.as_deref()
.and_then(|a| self.agents.launch_line(a))
{
t.write_input(lane_launch_input(cmd).as_bytes());
}
lanes.insert(t.uid(), lane.clone());
}
terms.push(t);
}
}
if terms.is_empty() {
return;
}
self.lane_panes = lanes;
// The restored panes are brand-new PtyTerminals, but everything
// bound to a pane of the OUTGOING panel is keyed by pane index —
// copy mode, find, quick-select — which an identical index in the
// restored panel would wrongly satisfy, applying stale grid
// coordinates to a grid that never produced them. The undo-close
// park would likewise resurrect an outgoing workspace's PTY into
// the restored panel. Drop them all before the swap.
self.close_terminal_copy_mode();
self.close_terminal_find();
self.close_terminal_quick_select();
self.closed_terminals.clear();
self.terminals = terms;
self.active_terminal = rec.active.min(self.terminals.len() - 1);
self.sync_focus_flags();
self.status = format!("Restored terminal session ({} panes)", self.terminals.len());
}
/// Available terminal profiles as `(shell_path, label)`: the shells in
/// `/etc/shells`, with the user's current `$SHELL` ensured present
/// (prepended) so the default is always an option even on a box with no
/// `/etc/shells`.
fn terminal_profiles(&self) -> Vec<(String, String)> {
let contents = std::fs::read_to_string("/etc/shells").unwrap_or_default();
let mut shells = crate::widgets::terminal::parse_shells(&contents);
if let Ok(current) = std::env::var("SHELL")
&& !current.is_empty()
{
let base = std::path::Path::new(¤t)
.file_name()
.and_then(|s| s.to_str())
.unwrap_or(¤t)
.to_string();
if !shells.iter().any(|(_, b)| *b == base) {
shells.insert(0, (current, base));
}
}
shells
}
/// Where the profile dropdown hangs: under the `⌄` caret of the pane it was
/// opened from, with the menu auto-clamping up/left to stay on screen.
/// Anchoring on the first caret in the vec is wrong twice over — hidden
/// panes hold `Rect::default()` placeholders so a button's position names
/// its terminal, and side by side every pane has a live caret, so every
/// pane's dropdown would hang under the leftmost one. Falls back to the
/// toolbar's top-right corner before the caret has been painted.
fn terminal_caret_origin(&self, pane: usize) -> (u16, u16) {
self.terminal_profile_buttons
.get(pane)
.filter(|c| c.width > 0)
.map(|c| (c.x, c.y.saturating_add(1)))
.unwrap_or((self.last_frame_area.width.saturating_sub(20), 1))
}
/// Open the terminal-profile dropdown (VS Code's `⌄` next to `+`): a compact
/// context menu anchored under the caret, one row per shell. Picking a row
/// opens a new pane running that shell.
fn open_terminal_profile_picker(&mut self, pane: usize) {
let items: Vec<MenuEntry> = self
.terminal_profiles()
.into_iter()
.map(|(path, label)| MenuEntry::Item {
label,
action: MenuAction::NewTerminalWithProfile(path),
})
.collect();
if items.is_empty() {
self.status = String::from("No terminal profiles found");
return;
}
let origin = self.terminal_caret_origin(pane);
// The dropdown is anchored under the `⌄` caret in the terminal
// toolbar and grows downward into the terminal panel — it never
// overlaps the editor's welcome logo, so the cached OSC-1337 image
// is left intact rather than evicted (evicting it left the logo
// blank, since the welcome emit is gated off while a menu is open).
self.context_menu = Some(ContextMenu {
origin,
items,
selected: 0,
open_submenu: None,
submenu_selected: 0,
target_dir: self.tree.root.clone(),
});
}
/// Clear the terminal at `idx`'s screen and scrollback (Cmd+K K / menu).
fn clear_terminal_at(&mut self, idx: usize) {
if let Some(t) = self.terminals.get_mut(idx) {
t.clear_screen_and_scrollback();
// The cleared grid invalidates find's state on this pane: the
// anchored match names content that no longer exists (and the
// clear can kill the scroll clock's tracer), so navigation
// restarts from scratch and the count reflects the empty grid.
if self.terminal_find.is_some() && self.terminal_find_pane == idx {
self.terminal_find_match = None;
self.terminals[idx].set_current_match(None, 0);
let (lines, _top) = self.terminals[idx].grid_lines();
if let Some(state) = self.terminal_find.as_mut() {
state.set_match_count(
crate::widgets::editor_find::count_matches(
&lines,
&state.query,
state.opts,
),
false,
);
state.match_index = None;
}
}
self.status = String::from("Cleared terminal");
}
}
/// Open a prompt to rename the terminal pane at `idx` (Cmd+K R / menu),
/// pre-filled with its current label.
fn begin_rename_terminal(&mut self, idx: usize) {
let Some(t) = self.terminals.get(idx) else {
return;
};
let current = t.label().to_string();
self.prompt = Some(Prompt {
label: String::from("Rename Terminal"),
buffer: current,
kind: PromptKind::RenameTerminal(idx),
target_dir: PathBuf::new(),
error: None,
});
}
/// Cmd+K N: open the annotation prompt for the active pane's selection
/// (its first line's span). When the span overlaps an existing
/// annotation, the prompt edits that note instead.
fn begin_annotate_terminal(&mut self) {
let pane = self.active_terminal;
// Selection and clock from ONE snapshot: separate reads let PTY
// output land in between, pairing a pre-output line with a
// post-output clock and pinning the note to the wrong row.
let (sel, clock) = self.terminals[pane].selection_and_clock();
let Some(sel) = sel.filter(|s| s.has_area()) else {
self.status = String::from("Annotate: select some output first (drag or copy mode)");
return;
};
let (sr, sc, er, ec) = sel.normalised();
let (_, _, cols, _) = self.terminals[pane].grid_bounds();
let end = if er > sr { cols.saturating_sub(1) } else { ec };
let (start, len) = (sc, end.saturating_sub(sc) + 1);
// Translate the existing annotations at the SAME captured clock as
// the selection, or output scrolling in between shifts them off the
// fixed `sr` and the same span duplicates instead of editing.
let current = self.terminals[pane].annotations_at_clock(clock);
let existing = current
.iter()
.position(|&(l, s0, ln, _)| l == sr && s0 < start + len && start < s0 + ln);
let buffer = existing
.and_then(|i| current.get(i).map(|a| a.3.clone()))
.unwrap_or_default();
self.prompt = Some(Prompt {
label: String::from("Annotate Selection"),
buffer,
kind: PromptKind::AnnotateTerminal {
pane,
line: sr,
clock,
start,
len,
existing,
},
target_dir: PathBuf::new(),
error: None,
});
}
/// Cmd+K Shift+N: drop every annotation whose span intersects the
/// selection's first line span.
fn delete_terminal_annotations_in_selection(&mut self) {
let pane = self.active_terminal;
let Some(sel) = self.terminals[pane].selection().filter(|s| s.has_area()) else {
self.status = String::from("Delete annotation: select over the note first");
return;
};
let (sr, sc, er, ec) = sel.normalised();
let (_, _, cols, _) = self.terminals[pane].grid_bounds();
let end = if er > sr { cols.saturating_sub(1) } else { ec };
let hits: Vec<usize> = self.terminals[pane]
.annotations_current()
.iter()
.enumerate()
.filter(|&(_, &(l, s0, ln, _))| l == sr && s0 <= end && sc < s0 + ln)
.map(|(i, _)| i)
.collect();
if hits.is_empty() {
self.status = String::from("No annotation under the selection");
return;
}
for i in hits.into_iter().rev() {
self.terminals[pane].remove_annotation(i);
}
self.status = String::from("Deleted annotation");
}
/// Drop the terminal at `idx`. Returns false (and does nothing) when
/// only one terminal is left or `idx` is out of range. Hiding the pane
/// is the user's job (Ctrl+J), not ours, so the last terminal stays.
/// The active index shifts so the same logical terminal remains active
/// when an inactive pane is closed; closing the active pane reseats the
/// focus on the neighbour to the left (or the new last if we removed
/// the right edge).
///
/// The pane is not dropped (which would kill its child): it parks in
/// `closed_terminals` for [`UNDO_CLOSE_GRACE`] so Cmd+K ⇧T can bring it
/// back, process and scrollback intact. The tick reaps expired entries.
pub fn close_terminal_at(&mut self, idx: usize) -> bool {
if self.terminals.len() <= 1 || idx >= self.terminals.len() {
return false;
}
let term = self.terminals.remove(idx);
// A lane pane closed by any route stops being the lane's (#348): the
// map is keyed by uid, and an undo-close brings the pane back as an
// ordinary one rather than re-seating an agent nobody asked for.
self.lane_panes.remove(&term.uid());
self.closed_terminals.push(ClosedTerminal {
term,
idx,
closed_at: std::time::Instant::now(),
});
if self.active_terminal == idx {
if self.active_terminal >= self.terminals.len() {
self.active_terminal = self.terminals.len() - 1;
}
} else if self.active_terminal > idx {
self.active_terminal -= 1;
}
// Closing the only expanded pane would leave the row nothing but
// strips; the collapse gesture refuses that from its own side and
// this closes the other route to it.
self.ensure_a_terminal_pane_is_expanded();
// A lone terminal has nothing to maximize against; the rail would be
// empty, so the split view is the honest state.
if self.terminals.len() <= 1 {
self.terminal_pane_maximized = false;
// Safety: never keep broadcast armed against a single pane —
// the next split would silently start receiving mirrored input.
if self.broadcast_input {
self.broadcast_input = false;
self.status = String::from("Broadcast input off (one pane left)");
}
}
self.sync_focus_flags();
self.save_terminal_session();
true
}
/// Toggle maximize mode for the active terminal pane (Cmd+K M / the
/// pane's `⛶` button): one pane spans the panel's width and the other
/// terminals move to the right rail, where clicking a row hands it the
/// maximized pane. Orthogonal to `toggle_terminal_maximize`
/// (Ctrl+Shift+J), which grows the panel over the editor: this
/// reapportions the panel's width, not the window's rows.
pub fn toggle_terminal_pane_maximize(&mut self) {
if self.terminal_pane_maximized {
self.terminal_pane_maximized = false;
// The rail lists folded panes too, so the pane that held the
// maximized view may be a strip once the split comes back. The
// invariant lives in `sync_focus_flags` and this is the gesture
// that re-enters its scope.
self.sync_focus_flags();
self.terminal_status(String::from("Restored terminal split"));
} else if self.terminals.len() > 1 {
self.terminal_pane_maximized = true;
self.status = String::from("Maximized terminal");
} else {
self.status = String::from("Only one terminal open");
}
}
/// Serve one accepted `croft view` client: bound the socket, read the
/// request, apply it, and answer. Returns the reply and whether anything
/// was opened (so the caller can redraw).
///
/// Split out of the accept loop so a test can hand it a stream and observe
/// the REPLY. The previous test for the blocking-mode fix accepted a
/// connection, called `set_nonblocking(false)` itself, and then asserted
/// the flag it had just set - it could not fail on any platform, which is
/// the false-green shape this repo's own guidance names. Given this seam a
/// test can hand in a deliberately NON-blocking stream and assert the
/// reply is `Ok`, which fails everywhere if the call below is dropped.
fn answer_view_client(
&mut self,
mut stream: std::os::unix::net::UnixStream,
deadline: std::time::Instant,
) -> (crate::view_ipc::ViewReply, bool) {
// An accepted socket's flags are not portably inherited: Linux's
// accept(2) says the new socket does NOT inherit O_NONBLOCK and that
// portable programs must set flags explicitly, while BSD (so macOS,
// croft's primary platform) does inherit them. Inherited, every read
// returns EAGAIN before any timeout applies and every `croft view`
// comes back "unreadable request: Resource temporarily unavailable"
// while Linux CI stays green.
let _ = stream.set_nonblocking(false);
// `read_request` re-arms its own read timeout from the deadline on
// every recv, so none is set here. The WRITE bound is armed below,
// after the read, from whatever the read left — and it exists because
// the reply embeds the client-supplied path, so a client that sends a
// valid long request and never reads can block `write_all` on a full
// socket buffer. Not reproducible on Linux, whose default unix-socket
// buffer is far larger than any legal reply, which is why it is set
// rather than tested.
let reply = match crate::view_ipc::read_request(&stream, deadline) {
Ok(req) => self.apply_view_request(&req.to_path()),
Err(e) => crate::view_ipc::ViewReply::Err {
message: format!("unreadable request: {e}"),
},
};
// Armed AFTER the read, from what the read left: computing it before
// gives a client that spent the whole budget reading a fresh window to
// spend writing, so one client could cost the frame loop twice the
// documented 20ms.
//
// The floor is 1ms and the write's result is discarded, which is worth
// being explicit about rather than leaving as an accident. If that
// 1ms ever fired on an `Ok`, the file is open in the editor while the
// client's shell exits 1 saying croft closed without replying: the
// reply is 16 bytes to a socket with a reader already waiting, so it
// is unreachable in practice, and the alternative (dropping the reply
// rather than the timeout) trades a wrong message for no message.
let left = deadline
.saturating_duration_since(std::time::Instant::now())
.max(std::time::Duration::from_millis(1));
let _ = stream.set_write_timeout(Some(left));
let opened = matches!(reply, crate::view_ipc::ViewReply::Ok);
let _ = crate::view_ipc::write_reply(&mut stream, &reply);
(reply, opened)
}
/// Paint a collapsed pane's one-column strip (#313) and return its hit
/// rect: the expand chevron on the header row, then the pane's name set
/// vertically down the column.
///
/// A strip rather than hiding the pane outright. A pane that vanishes is
/// indistinguishable from one that was closed, and croft already has
/// closing, with its own undo window; the strip keeps the pane counted,
/// named and clickable, which is what makes folding it obviously
/// reversible.
fn paint_terminal_collapsed_strip(
&mut self,
frame: &mut ratatui::Frame,
area: Rect,
idx: usize,
) -> Rect {
if area.width == 0 || area.height == 0 {
return Rect::default();
}
let hovered = self.pointer_cell.is_some_and(|(px, py)| {
px >= area.x && px < area.x + area.width && py >= area.y && py < area.y + area.height
});
frame.render_widget(
ratatui::widgets::Block::default().style(Style::default().bg(self.theme.editor_bg())),
area,
);
let chevron = crate::widgets::header_pill::action_style(self.theme, hovered);
let name = crate::widgets::header_pill::action_style(self.theme, false);
let label = self.terminals[idx].label().to_string();
let buf = frame.buffer_mut();
buf.set_string(area.x, area.y, TERMINAL_EXPAND_GLYPH.to_string(), chevron);
// The name runs down the strip so a folded pane is still identifiable
// without unfolding it. Only single-width characters are placed: a CJK
// glyph or an emoji is two cells wide and would paint over the pane
// next door, which is one column away.
for (row, ch) in label
.chars()
.filter_map(|c| match unicode_width::UnicodeWidthChar::width(c) {
Some(1) => Some(c),
// Wide: keep the position, lose the glyph.
Some(w) if w > 1 => Some(TERMINAL_STRIP_WIDE_STANDIN),
// Zero-width — a combining mark or a control character —
// has nothing to stand in for and no cell of its own.
_ => None,
})
.take(area.height.saturating_sub(1) as usize)
.enumerate()
{
buf.set_string(area.x, area.y + 1 + row as u16, ch.to_string(), name);
}
area
}
/// Collapse the pane at `idx` to a strip, or give a collapsed one its
/// width back (#313). The `‹` header button, the strip, the right-click
/// entry and the palette command all land here.
///
/// Collapsing the LAST expanded pane is refused: folding every pane away
/// leaves a row of strips with nothing in it, and croft already has
/// Ctrl+J for putting the panel away entirely (Ctrl+Shift+J is the
/// opposite gesture, growing it over the editor). The refusal says so
/// on the status line rather than swallowing the click, so the button
/// never reads as broken.
pub fn toggle_terminal_collapse(&mut self, idx: usize) {
let Some(pane) = self.terminals.get(idx) else {
return;
};
if pane.collapsed {
self.terminals[idx].collapsed = false;
self.active_terminal = idx;
self.focus_pane(Pane::Terminal);
let msg = format!("Expanded terminal {}", self.terminals[idx].label());
self.terminal_status(msg);
return;
}
if self.terminals.iter().filter(|t| !t.collapsed).count() <= 1 {
self.status = String::from("Cannot collapse the last expanded terminal");
return;
}
self.terminals[idx].collapsed = true;
// Focus cannot stay on a pane that is now one column wide: it shows no
// cursor, so the keystrokes would go somewhere the user cannot see
// them arrive. `sync_focus_flags` owns that rule for every path, this
// one included - a second copy of the nearest-expanded walk here would
// be dead weight AND a tie-break that can drift out of step with the
// one that matters.
self.sync_focus_flags();
let msg = format!("Collapsed terminal {}", self.terminals[idx].label());
self.terminal_status(msg);
}
/// Fold the active pane, unless maximize owns the panel (#313).
///
/// The `‹` button is not painted while maximized and the right-click entry
/// is suppressed there, but the chord and the palette command reached
/// `toggle_terminal_collapse` directly and so had no such guard. Because
/// collapsing reassigns `active_terminal` and the maximize branch hands
/// the panel to whatever that is, the effect was to swap the maximized
/// pane for a neighbour while the status line announced a collapse that
/// was invisible until you left maximize.
pub fn collapse_active_terminal_pane(&mut self) {
if self.terminal_pane_maximized {
self.status = String::from("Collapse is unavailable while a pane is maximized");
return;
}
self.toggle_terminal_collapse(self.active_terminal);
}
/// Make the pane at `idx` the active one AND visible (#313).
///
/// For callers that deliberately TARGET a pane by index - jump to a
/// captured line, run a task in its own pane, run a fenced block, focus an
/// agent's pane - rather than for a gesture that merely moves focus.
///
/// The distinction is load-bearing. `sync_focus_flags` walks focus OFF a
/// folded pane, which is right for a drifting gesture and wrong here: it
/// silently redirected these callers to a neighbour, so a task command was
/// written into a pane that is never rendered while the status line
/// reported it running. Reaching for a pane by index is a request to see
/// it, which is the rationale `undo_close_terminal` already applies when
/// it force-expands a reopened pane.
fn reveal_terminal_pane(&mut self, idx: usize) {
if let Some(t) = self.terminals.get_mut(idx) {
t.collapsed = false;
}
self.active_terminal = idx;
}
/// Give every collapsed pane its width back (Cmd+K `]`): the issue's
/// "maximise the terminals back to the same equal-sized terminal
/// windows", which has to be one gesture rather than one per pane.
pub fn restore_all_terminal_panes(&mut self) {
// The mirror of the guard on `collapse_active_terminal_pane`. Without
// it, Cmd+K ] while maximized cleared every flag and announced it, for
// a change the user cannot see until they leave maximize: the same
// silent-state-change this pair already refuses in the other
// direction.
if self.terminal_pane_maximized {
self.terminal_status(String::from(
"Restore is unavailable while a pane is maximized",
));
return;
}
let folded = self.terminals.iter().filter(|t| t.collapsed).count();
if folded == 0 {
self.terminal_status(String::from("No collapsed terminal panes"));
return;
}
for t in self.terminals.iter_mut() {
t.collapsed = false;
}
self.terminal_status(format!(
"Restored {folded} terminal pane{}",
if folded == 1 { "" } else { "s" }
));
}
/// Keep at least one pane expanded after a pane leaves the row (#313).
///
/// [`Self::toggle_terminal_collapse`] refuses to fold the last expanded
/// pane, but CLOSING reaches the same state from the other side: two
/// panes with one collapsed, close the expanded one, and the panel is a
/// single strip with nothing behind it. Expanding the pane that is now
/// active, rather than all of them, keeps the rest of the user's
/// folding intact.
fn ensure_a_terminal_pane_is_expanded(&mut self) {
if self.terminals.is_empty() || self.terminals.iter().any(|t| !t.collapsed) {
return;
}
let idx = self.active_terminal.min(self.terminals.len() - 1);
self.terminals[idx].collapsed = false;
}
/// Drop the rail's hit rects and its column. Both must go together: a
/// stale area would keep swallowing the wheel after the rail left screen.
fn clear_terminal_rail(&mut self) {
self.terminal_rail_rects.clear();
self.terminal_rail_area = Rect::default();
}
/// Paint the maximize-mode rail: one row per terminal down the panel's
/// right edge — the active one highlighted, the rest hover-lit — so the
/// user can shuffle between maximized terminals. Records one hit rect
/// per row in `terminal_rail_rects`, index-aligned with `terminals`.
fn paint_terminal_rail(&mut self, frame: &mut ratatui::Frame, rail: Rect) {
self.terminal_rail_area = rail;
if rail.width == 0 || rail.height == 0 {
return;
}
let brand = self.theme.gradient();
// Same selected-row treatment as the OPEN EDITORS list, so the rail
// reads as the same family of chrome in both themes.
let sel_bg = if brand {
crate::gradient::rgb_color(crate::gradient::POPUP_SEL_BG)
} else {
self.theme.ui(Color::Rgb(0x09, 0x4d, 0x77))
};
// With more terminals than rows the rail is a window over the list,
// scrolled by the wheel — the panel floors at 3 rows, so four panes
// are enough to reach this. Switching panes scrolls the new one into
// view so its highlight is never off-screen, but only on the frame the
// active pane CHANGES: revealing every frame would pin the window
// whenever the active pane sits at either end and make the wheel inert.
let rows = rail.height as usize;
let max_scroll = self.terminals.len().saturating_sub(rows);
let mut scroll = self.terminal_rail_scroll.min(max_scroll);
if self.terminal_rail_revealed != Some(self.active_terminal) {
if self.active_terminal < scroll {
scroll = self.active_terminal;
} else if self.active_terminal >= scroll + rows {
scroll = self.active_terminal + 1 - rows;
}
self.terminal_rail_revealed = Some(self.active_terminal);
}
self.terminal_rail_scroll = scroll;
for i in 0..self.terminals.len() {
// Rows outside the window still push a placeholder, so a rect's
// position in the vec keeps naming its terminal. `rect_contains`
// rejects empty rects, so they can never phantom-match a click.
if i < scroll || i >= scroll + rows {
self.terminal_rail_rects.push(Rect::default());
continue;
}
let y = rail.y + (i - scroll) as u16;
let row = Rect {
x: rail.x,
y,
width: rail.width,
height: 1,
};
let active = i == self.active_terminal;
let bg = if active {
Some(sel_bg)
} else {
crate::widgets::hover::row_hover_bg(row, self.pointer_cell, self.theme)
};
if let Some(bg) = bg {
frame.buffer_mut().set_style(row, Style::default().bg(bg));
}
let label = self.terminals[i].label().to_string();
let room = TERMINAL_RAIL_LABEL_W as usize;
let shown: String = label.chars().take(room).collect();
let fg = if active {
Style::default()
.fg(self.theme.ui(Color::White))
.add_modifier(Modifier::BOLD)
} else {
Style::default()
};
// `set_string` clips at the buffer edge, not the rail's, so a
// label wider than a clamped rail would paint its tail over the
// panel to the right. Clip to the rail's own width.
frame.buffer_mut().set_stringn(
row.x,
y,
format!(" {TERMINAL_RAIL_ICON} {shown}"),
row.width as usize,
fg,
);
self.terminal_rail_rects.push(row);
}
}
/// Move the terminal at `from` so it sits at slot `to`, keeping
/// `active_terminal` pointing at the same terminal it did before. Drives
/// the drag-reorder of side-by-side panes and maximize-mode rail rows.
pub fn move_terminal(&mut self, from: usize, to: usize) {
if from == to || from >= self.terminals.len() || to >= self.terminals.len() {
return;
}
// `last_area` is a SLOT's geometry, but it lives on the terminal
// object and so travels with it. The panes do not actually move on
// screen until the next frame, and the drag hit-tests `last_area`
// between frames — the main loop drains the whole queued mouse burst
// before drawing. Re-seat the rects in slot order so the next motion
// report over the same cell resolves to the pane now sitting there
// instead of swapping the two straight back, which made the final
// order the parity of however many motion reports arrived.
let slot_rects: Vec<Rect> = self.terminals.iter().map(|t| t.last_area).collect();
let t = self.terminals.remove(from);
self.terminals.insert(to, t);
self.active_terminal = match self.active_terminal {
a if a == from => to,
a if from < a && a <= to => a - 1,
a if to <= a && a < from => a + 1,
a => a,
};
if self.terminal_pane_maximized {
// Maximize mode has exactly one live rect, and it belongs to
// whichever pane was active at the LAST PAINT — not to the dragged
// terminal, since the press and the drag are drained together. So
// neither positional rule works here: find the live rect and hand
// it to the pane the drag leaves active, which is the one that will
// own the panel on the next frame.
let pane = slot_rects
.iter()
.copied()
.find(|r| r.width > 0)
.unwrap_or_default();
let active = self.active_terminal;
for (i, term) in self.terminals.iter_mut().enumerate() {
term.last_area = if i == active { pane } else { Rect::default() };
}
} else {
for (term, rect) in self.terminals.iter_mut().zip(slot_rects) {
// A folded pane is not painted in whatever slot the drag left
// it in, so it must not inherit that slot's geometry (#313):
// the rest of the drained mouse burst hit-tests these rects,
// and a live rect over an unpainted pane resolves clicks to a
// pane that is not there.
term.last_area = if term.collapsed {
Rect::default()
} else {
rect
};
}
}
self.terminal_session_dirty = true;
}
/// Write the pane session if a reorder marked it pending. Called once per
/// tick so a drag costs one write instead of one per motion report.
pub fn flush_terminal_session(&mut self) {
if std::mem::take(&mut self.terminal_session_dirty) {
self.save_terminal_session();
}
}
/// Drop the currently-active terminal. Thin wrapper kept for the
/// keyboard shortcut and existing callers.
pub fn close_active_terminal(&mut self) -> bool {
self.close_terminal_at(self.active_terminal)
}
/// Cmd+K ⇧T: bring back the most recently closed terminal pane while it
/// is still inside the undo-close grace window. The pane returns to the
/// slot it occupied (clamped if the layout shrank) and takes focus; its
/// child process and scrollback were never touched.
pub fn undo_close_terminal(&mut self) {
let Some(parked) = self.closed_terminals.pop() else {
self.status = String::from("No recently closed terminals");
return;
};
let idx = parked.idx.min(self.terminals.len());
self.terminals.insert(idx, parked.term);
// Reopening is a request to see the pane, so it comes back expanded
// whatever it was when it was closed: a restore that put a strip on
// screen would read as the reopen having failed.
self.terminals[idx].collapsed = false;
self.active_terminal = idx;
if !self.show_terminal {
self.show_terminal = true;
}
self.focus_pane(Pane::Terminal);
self.sync_focus_flags();
self.save_terminal_session();
let msg = format!("Restored terminal {}", self.terminals[idx].label());
self.terminal_status(msg);
}
/// Drop parked closed panes whose grace window lapsed (their Drop kills
/// the child). Called from the drain tick.
fn reap_closed_terminals(&mut self) {
self.closed_terminals
.retain(|p| p.closed_at.elapsed() <= UNDO_CLOSE_GRACE);
}
/// Record the focused group's tab at `idx` as reopenable (Cmd+K ⇧W).
/// Scratch buffers with no backing file are not recorded. Must run
/// BEFORE the close mutates the tab list. Tabs that merely move (into a
/// new window) or whose file was just trashed are deliberately never
/// recorded by their callers.
fn record_closed_tab_at(&mut self, idx: usize) {
let Some(ed) = self.editor.editors.get(idx) else {
return;
};
let Some(path) = ed.path.clone() else {
return;
};
self.closed_tabs.push(ClosedTab {
path,
pinned: ed.pinned,
cursor: (ed.cursor_row, ed.cursor_col),
scroll: ed.scroll,
});
if self.closed_tabs.len() > CLOSED_TAB_STACK_CAP {
self.closed_tabs.remove(0);
}
}
/// Record every tab the bulk closes (Close Others / Close to the Right)
/// are about to drop: the unpinned, file-backed ones `pred` selects, in
/// tab order so the reopen stack pops most-recent-first.
fn record_closed_tabs_where(&mut self, pred: impl Fn(usize, &Editor) -> bool) {
let picks: Vec<usize> = self
.editor
.editors
.iter()
.enumerate()
.filter(|(i, ed)| pred(*i, ed))
.map(|(i, _)| i)
.collect();
for i in picks {
self.record_closed_tab_at(i);
}
}
/// Cmd+K ⇧W: reopen the most recently closed editor tab (VS Code
/// "Reopen Closed Editor"), restoring its pin state, cursor, and
/// scroll. Entries whose file has vanished since the close are skipped,
/// falling through to the next reopenable one.
pub fn reopen_closed_tab(&mut self) {
while let Some(t) = self.closed_tabs.pop() {
if !t.path.exists() {
continue;
}
let opened = if t.pinned {
self.editor.open_pinned(&t.path)
} else {
self.editor.open_preview(&t.path)
};
match opened {
Ok(()) => {
self.sync_open_file_poll_mtime();
let rows = self.editor.lines.len();
self.editor.cursor_row = t.cursor.0.min(rows.saturating_sub(1));
let max_col = self
.editor
.lines
.get(self.editor.cursor_row)
.map(|l| l.chars().count())
.unwrap_or(0);
self.editor.cursor_col = t.cursor.1.min(max_col);
self.editor.scroll = t.scroll.min(rows.saturating_sub(1));
self.editor.ensure_cursor_col_visible();
self.tree.reveal_path(&t.path);
self.focus_pane(Pane::Editor);
self.poke_cursor();
self.status = format!("Reopened {}", self.status_path(&t.path));
}
Err(e) => {
self.status = format!("Reopen failed: {e}");
}
}
return;
}
self.status = String::from("No closed tabs to reopen");
}
/// Swap the per-host accent rules (config.json reload, and tests).
pub fn set_host_accents(&mut self, rules: &[crate::prefs::HostAccentRule]) {
self.host_accents = compile_host_accents(rules);
}
/// Settings / palette "Terminal: Toggle Secret Redaction" (#360): the
/// built-in key and token rules leave or rejoin the trigger set; the
/// user's own `redact` rows in triggers.json are unaffected.
pub fn toggle_secret_redaction(&mut self) {
self.secret_redaction = !self.secret_redaction;
self.triggers = load_trigger_set(self.secret_redaction);
self.status = String::from(if self.secret_redaction {
"Secret redaction: on"
} else {
"Secret redaction: off"
});
if !cfg!(test) {
let _ = crate::prefs::save_disable_secret_redaction(!self.secret_redaction);
}
}
/// Palette "Terminal: Reveal Redacted Secrets for 10s": every mask on
/// every pane paints as its real text for ten seconds, then masks
/// again. Announced so a screen share sees it happen.
pub fn reveal_redacted_secrets(&mut self) {
self.redaction_reveal_until =
Some(std::time::Instant::now() + std::time::Duration::from_secs(10));
self.status = String::from("Redacted secrets revealed for 10s");
}
/// Whether a reveal window is open right now.
fn redactions_revealed(&self) -> bool {
self.redaction_reveal_until
.is_some_and(|until| std::time::Instant::now() < until)
}
/// Main-loop tick: when the reveal window closes, drop it and ask for
/// a redraw so the masks come back without waiting for other input.
pub fn tick_redaction_reveal(&mut self) -> bool {
if self.redaction_reveal_until.is_some() && !self.redactions_revealed() {
self.redaction_reveal_until = None;
self.status = String::from("Redacted secrets masked again");
return true;
}
false
}
/// Masks on screen across every pane, as painted last frame.
fn redacted_on_screen(&self) -> usize {
self.terminals.iter().map(|t| t.redacted_on_screen).sum()
}
/// The current index of the pane a forwarded left press went to (#474),
/// or `None` once that pane has been closed. Looked up by uid on every
/// event of the gesture because a close or reorder while the button is
/// held renumbers the vector under a stored index.
fn forwarded_pane_index(&self, fp: ForwardedPointer) -> Option<usize> {
self.terminals.iter().position(|t| t.uid() == fp.pane)
}
/// The clipboard's view of terminal text: rules marked `copy: masked`
/// keep their mask, everything else copies as typed (#360).
fn terminal_text_for_copy(&self, text: String) -> String {
crate::triggers::mask_text(&text, &self.triggers, true)
}
/// Palette "Terminal: Toggle Timestamps": show / hide the per-row
/// arrival-clock gutter on every pane.
pub fn toggle_terminal_timestamps(&mut self) {
self.show_terminal_timestamps = !self.show_terminal_timestamps;
for t in self.terminals.iter_mut() {
t.show_timestamps = self.show_terminal_timestamps;
}
self.status = String::from(if self.show_terminal_timestamps {
"Terminal timestamps on"
} else {
"Terminal timestamps off"
});
}
/// Cmd+K I: toggle broadcast input. Turning it ON goes through a confirm
/// popup (iTerm2 warns the same way); turning it OFF is immediate.
fn toggle_broadcast_input(&mut self) {
if self.broadcast_input {
self.broadcast_input = false;
self.status = String::from("Broadcast input off");
return;
}
if self.terminals.len() < 2 {
self.status =
String::from("Broadcast input needs at least two terminal panes (Cmd+T splits)");
return;
}
self.pending_broadcast_enable = true;
}
fn confirm_pending_broadcast(&mut self) {
self.pending_broadcast_enable = false;
self.broadcast_input = true;
let receiving = self
.terminals
.iter()
.filter(|t| !t.broadcast_excluded)
.count();
self.status = format!(
"Broadcast input ON: keystrokes go to {receiving} panes (Cmd+K I to stop, Cmd+K Shift+I excludes a pane)"
);
}
fn cancel_pending_broadcast(&mut self) {
self.pending_broadcast_enable = false;
self.status = String::from("Broadcast input cancelled");
}
/// Cmd+K Shift+I: toggle whether the active pane receives broadcast
/// input. The focused pane always gets its own typing; exclusion only
/// mutes the mirrored copy while it is unfocused.
fn toggle_broadcast_exclusion(&mut self) {
let idx = self.active_terminal;
let Some(t) = self.terminals.get_mut(idx) else {
return;
};
t.broadcast_excluded = !t.broadcast_excluded;
let label = t.label().to_string();
self.status = if self.terminals[idx].broadcast_excluded {
format!("{label} excluded from broadcast input")
} else {
format!("{label} receives broadcast input again")
};
}
/// Paste counterpart of [`Self::write_terminal_key`] (bracketed-paste
/// aware per pane): normally just the active pane, mirrored to every
/// non-excluded pane while broadcast is on (the focused pane always
/// receives its own input).
fn paste_terminal_input(&mut self, payload: &[u8]) {
if self.broadcast_input {
let active = self.active_terminal;
for (i, t) in self.terminals.iter_mut().enumerate() {
if i == active || !t.broadcast_excluded {
t.paste_input(payload);
}
}
} else {
self.terminal_mut().paste_input(payload);
}
}
/// Cycle the active terminal forward to the next pane the user can
/// actually see, wrapping at the end.
///
/// Collapsed panes are stepped over (#313). A folded pane is one column
/// wide and is never rendered, so it paints no cursor and no focus
/// border: cycling onto one would send every keystroke into a pane the
/// user cannot see receiving them. `toggle_terminal_collapse` defends
/// that same invariant on its own path; this is the other way in, and it
/// predated the flag.
pub fn cycle_terminal(&mut self) {
self.step_active_terminal(true);
}
/// Cycle the active terminal backward, wrapping at the front. Mirror of
/// `cycle_terminal` for the Cmd+[ binding, folded panes skipped alike.
pub fn cycle_terminal_back(&mut self) {
self.step_active_terminal(false);
}
/// Walk `active_terminal` one visible pane in either direction.
///
/// The loop is bounded by the pane count and at least one pane is always
/// expanded (`toggle_terminal_collapse` refuses to fold the last one and
/// `ensure_a_terminal_pane_is_expanded` closes the other route), so it
/// always terminates on a pane that is painted. If that invariant were
/// ever broken the walk falls through without moving, which is inert
/// rather than a hang.
fn step_active_terminal(&mut self, forward: bool) {
let n = self.terminals.len();
if n <= 1 {
return;
}
for step in 1..=n {
let cand = if forward {
(self.active_terminal + step) % n
} else {
(self.active_terminal + n - (step % n)) % n
};
if !self.terminals[cand].collapsed {
self.active_terminal = cand;
break;
}
}
self.sync_focus_flags();
}
/// OR-fold dirty flags across all terminals while clearing each. Use `|`
/// (not `||`) so every terminal's flag is consumed even after the first
/// dirty one is found.
pub fn drain_terminals_dirty(&mut self) -> bool {
let dirty = self
.terminals
.iter()
.fold(false, |acc, t| acc | t.take_dirty());
// A recording captures the SCREEN, not the byte stream (#356). The
// PTY bytes are consumed by the grid before the app sees them, so
// there is no text stream left to tee — and a cast of screens is
// what a player replays anyway. Sampled here because this fires
// exactly when something changed, so an idle session records
// nothing rather than a frame per tick.
if dirty && self.recording.is_some() {
self.record_active_screen();
}
dirty
}
/// Write a resize event to the open recording (#356).
fn record_resize(&mut self, cols: u16, rows: u16) {
use std::io::Write as _;
let Some((rec, file, started)) = self.recording.as_mut() else {
return;
};
let line = rec.line(&crate::asciicast::Event::Resize {
at: started.elapsed().as_secs_f64(),
cols,
rows,
});
if writeln!(file, "{line}").is_err() {
self.recording = None;
self.status = String::from("Recording stopped: could not write to the cast file");
}
}
/// Write the active terminal's current screen to the open recording.
///
/// Clear-and-redraw rather than a delta: `\u{1b}[H\u{1b}[2J` then the
/// rows. A delta would need the previous screen and a diff that agrees
/// with the terminal's own scroll behaviour, and a cast that drifts a
/// row from reality is the kind of bug nobody notices until the demo is
/// published.
///
/// **The recording is monochrome, and the cursor is not restored.**
/// `grid_lines` returns plain `String`s — the cell attributes are in the
/// grid but not in that view — so a cast records the TEXT of a session
/// and not its colour. That is a real limit rather than an oversight:
/// carrying attributes means re-emitting SGR per run of cells, which is
/// the byte stream this deliberately does not tap. Named here so nobody
/// files it as a bug and so the follow-on knows what it costs.
fn record_active_screen(&mut self) {
// Read everything the frame needs from the pane in ONE borrow, then
// write. The two writes below both take `&mut self`, so interleaving
// them with pane reads would need the pane borrowed twice around
// them — which compiles but reads as an accident rather than as a
// decision.
let Some((size, lines)) = self.terminals.get(self.active_terminal).map(|t| {
let (mut all, top) = t.grid_lines();
// The VISIBLE screen only. `grid_lines` starts at
// `topmost_line()`, which is negative scrollback — up to
// 5000 rows. Writing all of it after a clear scrolls the
// live screen straight off the top, so the cast shows the
// tail of the history rather than what the user was looking
// at, at ~400 KB per frame.
let visible = all.split_off((-top).max(0) as usize);
((t.last_inner.width, t.last_inner.height), visible)
}) else {
return;
};
// The resize goes FIRST, so a player has the new geometry before the
// frame drawn at it — the other order renders one frame wrapped at
// the old width.
if size != self.recorded_size && size.0 > 0 && size.1 > 0 {
self.recorded_size = size;
self.record_resize(size.0, size.1);
}
let mut frame = String::from("\u{1b}[H\u{1b}[2J");
frame.push_str(&lines.join("\r\n"));
self.record_terminal_output(&frame);
}
/// Like `drain_terminals_dirty` but does not clear the underlying flags.
/// The main loop uses this to decide whether to coalesce a PTY-only
/// redraw without losing the signal if it chooses to skip.
pub fn peek_terminals_dirty(&self) -> bool {
self.terminals.iter().any(|t| t.peek_dirty())
}
/// Total bytes the PTY reader threads have advanced into their grids
/// since the last redraw. The main loop uses this to bypass the PTY
/// redraw cap for small interactive echo while keeping bulk streams
/// capped. Peeks without clearing; `drain_terminals_dirty` resets it.
pub fn peek_terminals_pending_bytes(&self) -> usize {
self.terminals.iter().map(|t| t.peek_pending_bytes()).sum()
}
fn terminal_at_pos(&self, col: u16, row: u16) -> Option<usize> {
self.terminals
.iter()
.position(|t| rect_contains(t.last_area, col, row))
}
/// Run `f` with auto-hide suppressed, for focus moves the user did not
/// ask for. `focus_pane` cannot tell intent apart on its own: an async
/// MCP result, a launch-time file open, and Enter on a sidebar row all
/// look identical to it, and collapsing on those is the flapping #260
/// set out to prevent.
fn without_auto_hide<R>(&mut self, f: impl FnOnce(&mut Self) -> R) -> R {
let prev = std::mem::replace(&mut self.sidebar_auto_hide_suspended, true);
let out = f(self);
self.sidebar_auto_hide_suspended = prev;
out
}
/// Whether a modal overlay owns the screen right now. The same eleven-way
/// check was repeated verbatim at three overlay-flush sites; auto-hide
/// (#260) needs it too, so it lives here once.
fn modal_overlay_open(&self) -> bool {
self.shortcuts_modal.is_some()
|| self.file_finder.is_some()
|| self.command_palette.is_some()
|| self.go_to_symbol.is_some()
|| self.workspace_symbols.is_some()
|| self.process_picker.is_some()
|| self.zoxide_jump.is_some()
|| self.command_history_popup.is_some()
|| self.branch_picker.is_some()
|| self.input_prompt.is_some()
|| self.list_picker.is_some()
}
/// Whether auto-hide may collapse the sidebar RIGHT NOW. Every reason to
/// hold it open lives here rather than being scattered through the call
/// sites, so the interaction rules are one readable list and a new
/// suppression case has exactly one place to go.
/// Whether a STRUCTURAL suppression is in force: one that no passage of
/// time lifts, only a deliberate chrome change by the user.
///
/// Split out from [`Self::sidebar_auto_hide_allowed`] because the tick has
/// to treat the two kinds differently and the combined predicate cannot
/// say which it declined for. A transient suppression (seam drag, open
/// palette, modal) ends in moments, so the dwell stays armed and retries.
/// A structural one can last the session, and a dwell left armed across it
/// fires on the frame it lifts — a collapse for a focus move the user made
/// an hour ago. Cancelling at the ARM site instead would make the retry
/// unreachable, which is the recovery path for the transient case.
fn sidebar_structurally_suppressed(&self) -> bool {
!self.activity_bar_visible || self.zen_mode
}
/// Whether auto-hide may collapse the sidebar RIGHT NOW. Every reason to
/// hold it open lives here rather than being scattered through the call
/// sites, so the interaction rules are one readable list and a new
/// suppression case has exactly one place to go.
fn sidebar_auto_hide_allowed(&self) -> bool {
if !self.sidebar_auto_hide || !self.show_tree {
return false;
}
// A focus move nobody asked for is not a reason to hide chrome.
if self.sidebar_auto_hide_suspended {
return false;
}
// NOTE: the one-shot reveal pin is deliberately NOT checked here. It is
// the caller's concern (`tick_sidebar_auto_hide_at`), because this
// predicate must stay answerable while a pin is banked: the tick asks
// "would this collapse otherwise fire?" precisely so it can decide
// whether spending the pin is warranted. Checking the pin here made
// that question unanswerable and the pin unspendable.
// Mid-drag on the sidebar seam: the pointer is over the editor by
// definition, and collapsing under the cursor is the flapping the
// issue calls out.
if self.splitter_drag.is_some() {
return false;
}
// Anything modal may be anchored over sidebar space, and several are
// sidebar-targeting flows (branch picker, connect dialog) that are
// their own fields rather than `Prompt`s — checking only `prompt`
// would have missed exactly those.
if self.prompt.is_some()
|| self.context_menu.is_some()
|| self.connect_dialog.is_some()
|| self.modal_overlay_open()
{
return false;
}
// An Explorer drag is a drag over the sidebar the user is dragging
// FROM; `splitter_drag` does not cover it.
if self.tree_drag.is_some() {
return false;
}
// With no activity bar there is no on-screen way back to a collapsed
// sidebar (hover-to-reveal is not implemented yet), so a mouse-only
// user would be stranded.
if !self.activity_bar_visible {
return false;
}
// Zen Mode already owns chrome visibility; it wins, as it does today.
if self.zen_mode {
return false;
}
true
}
/// Flip auto-hide and persist it. Both routes (palette command and the
/// Customize Layout row) funnel here so they cannot drift in what they
/// set, what they report, or whether the choice survives a restart.
fn toggle_sidebar_auto_hide(&mut self) {
self.sidebar_auto_hide = !self.sidebar_auto_hide;
// Best-effort, like every other pref write: a read-only config must
// not break the in-session toggle. Skipped under test, mirroring the
// write-skip in `apply_theme` — `save_*` resolves the developer's real
// ~/.config/croft/config.json, and a test has no business rewriting
// it (nor leaving the next test to read what it wrote).
if !cfg!(test) {
let _ = crate::prefs::save_sidebar_auto_hide(self.sidebar_auto_hide);
}
// Turning it ON with the sidebar open takes effect at the next focus
// move rather than retroactively yanking it away here — which means
// dropping any collapse already pending. A dwell armed before the
// setting was touched belongs to the old state: leaving it armed lets
// an idle tick collapse the sidebar after the user turns the feature
// off and on again, with no focus move of their own in between.
//
// The pin goes for the same reason, and the fourth boundary to say so.
// `toggle_side_bar` refuses to bank one while the feature is off,
// because "a pin set while the feature is off would sit unconsumed and
// silently eat the first collapse after they turn it on" — and a pin
// banked BEFORE the user disables auto-hide reaches that same state by
// the other route. Main cleared it incidentally by taking the pin on
// every focus move; consuming at fire time is correct but leaves each
// boundary to say so.
self.sidebar_dwell.disarm();
self.sidebar_pinned_open = false;
self.status = format!(
"Auto-hide side bar {}",
if self.sidebar_auto_hide { "on" } else { "off" }
);
}
/// Arm the grace delay before collapsing. Called on focus moves INTO the
/// editor or a terminal.
///
/// #294 collapsed right here, which meant a click *passing through* the
/// panel on its way to the editor took the panel out from under the
/// pointer. The collapse now waits `AUTO_HIDE_DWELL` (#302) and fires from
/// `tick_sidebar_auto_hide`, so a click that lands back on the sidebar
/// inside the window cancels it.
///
/// Note what is deliberately NOT done here: the one-shot pin is not
/// consumed. Arming is no longer the same event as collapsing, and eating
/// the exemption on an attempt the dwell then cancels would silently strip
/// a deliberate reveal of the protection it was granted. It is consumed
/// where the collapse actually happens.
fn maybe_auto_hide_sidebar(&mut self) {
// Cheap pre-check only. The real decision is re-made when the timer
// fires, because every suppression here can change during the window.
//
// `sidebar_auto_hide_suspended` is the exception and MUST be read here:
// it is scoped to a `without_auto_hide` closure and restored the moment
// that closure returns, so by tick time it is always false. Deferring
// it would silently un-suppress every programmatic focus move — the
// async MCP result, the launch-time file open, Enter on a sidebar row —
// which is the #260 flapping this flag exists to prevent. Arming is
// what has to be refused; there is nothing left to consult later.
//
// The STRUCTURAL suppressions (Zen Mode, hidden activity bar) are NOT
// checked here, and that is deliberate. Refusing to arm under them
// looks right and strands the feature: the tick stays armed through a
// decline and fires once the suppression lifts, so that retry IS the
// recovery path, and nothing that fails to arm can ever use it. Zen
// survives such a refusal only because Zen exit restores the pre-Zen
// snapshot and closes the sidebar, forcing a fresh reveal; a hidden
// activity bar restores nothing, focus is already on the editor, and
// production will not call `focus_pane` again for a pane that already
// has focus — so auto-hide would stay dead for the rest of the session
// with nothing on screen to explain it.
//
// The structural/transient distinction is drawn at FIRE time instead,
// where the state is actually known and no future suppression needs its
// own boundary hook. See `tick_sidebar_auto_hide_at`.
if self.sidebar_auto_hide && self.show_tree && !self.sidebar_auto_hide_suspended {
self.sidebar_dwell.arm(std::time::Instant::now());
}
}
/// Tear down the popups a click invalidates, for press paths that return
/// early and so miss the teardown every other path runs.
///
/// A fired binding changes the state underneath these popups, and leaving
/// them up paints a hover, a tab tooltip or a button hint describing what
/// was there before the command ran. Shared by the matched-gesture
/// dispatch and the double-click-prefix swallow: both return early, and
/// having two copies is how the swallow branch came to skip it entirely.
fn dismiss_click_overlays(&mut self, m: MouseEvent) {
if !matches!(m.kind, MouseEventKind::Up(_)) {
self.hover_popup = None;
self.hover_diagnostic = None;
}
self.tab_tooltip = None;
self.tab_hover.clear();
self.tab_hover_idx = None;
self.ui_tooltip = None;
self.ui_hover.clear();
self.ui_tooltip_label = None;
self.hover.clear();
}
/// Fire a pending auto-hide collapse once its grace delay elapses.
///
/// Returns `true` when the sidebar collapsed, so the frame redraws.
pub fn tick_sidebar_auto_hide(&mut self) -> bool {
self.tick_sidebar_auto_hide_at(std::time::Instant::now())
}
/// `tick_sidebar_auto_hide` with the clock injected, so the grace delay is
/// testable without sleeping — the same posture as `HoverDwell::due`.
pub(crate) fn tick_sidebar_auto_hide_at(&mut self, now: std::time::Instant) -> bool {
if !self.sidebar_dwell.armed() {
return false;
}
// Focus came back to the sidebar, or it is already closed: the pending
// collapse is moot. Leave the pin alone — it was never spent.
if self.focus == Pane::Tree || !self.show_tree {
self.sidebar_dwell.disarm();
return false;
}
if !self.sidebar_dwell.due(now, AUTO_HIDE_DWELL) {
return false;
}
// The window has elapsed and focus stayed away. Before spending
// anything, ask whether a collapse would fire at all: a tick stopped by
// a seam drag, an open palette or a modal is not the collapse the pin
// was banked for, and burning it there loses an exemption the user
// never saw honoured. Every earlier decline already leaves the pin
// alone; this makes the late one behave the same way.
//
// Stay ARMED on that decline, and disarm only once a collapse is
// actually due. These suppressions are transient — a drag ends, a
// palette closes — and nothing re-arms the dwell but a fresh focus
// move into the editor or terminal. Disarming here would drop the
// pending collapse for good, so a user whose palette happened to be
// open during the grace window would keep a sidebar that never
// auto-hides again. Retrying costs nothing: `main_loop` ticks on an
// 8ms cadence, so the collapse lands as soon as the suppression lifts.
// A STRUCTURAL suppression DEFERS and re-stamps. Cancelling here was
// the round-two defect: `main_loop` ticks every 8ms unconditionally, so
// a cancel-on-suppressed-tick fires 8ms after arming and is
// indistinguishable from refusing to arm at all — which strands the
// feature, because nothing re-arms once a hidden activity bar returns
// (focus never moved, and production will not re-focus a pane that
// already has focus).
//
// Re-stamping is what makes deferral safe. The complaint against
// deferral was that Zen can last an hour and the collapse would land on
// the frame it exits, for a focus move the user has long forgotten.
// Anchoring to the moment the suppression LIFTS answers that exactly:
// the user then gets the same AUTO_HIDE_DWELL grace they would get from
// a fresh focus move, measured from a moment they can actually perceive
// — the chrome coming back.
if self.sidebar_structurally_suppressed() {
self.sidebar_dwell.restamp(now);
return false;
}
if !self.sidebar_auto_hide_allowed() {
return false;
}
self.sidebar_dwell.disarm();
// A real collapse is now due, so this IS the moment the one-shot
// exemption is spent — whether or not it is what stops us.
//
// Semantics: the pin is spent by the next collapse that would genuinely
// have fired, not by the next tick — so a tick stopped by a TRANSIENT
// suppression (seam drag, palette, modal) spends nothing and the pin
// survives to do its job a moment later.
//
// Structural suppressions are decided HERE, above, not at the sites
// that enter them. Entry hooks cannot see the case where the dwell is
// armed while the suppression is ALREADY in force — Cmd+B works inside
// Zen, so no transition occurs and no hook fires. This tick is asked to
// distinguish a suppression that lasts a moment from one that lasts the
// session precisely because it is the one place that always runs.
let exempt = std::mem::take(&mut self.sidebar_pinned_open);
if !exempt {
self.show_tree = false;
return true;
}
false
}
fn focus_pane(&mut self, p: Pane) {
// Leaving the terminal closes its find bar so a stale match highlight
// never lingers on the grid once input goes elsewhere. Quick-select
// labels are torn down for the same reason.
if p != Pane::Terminal && self.terminal_find.is_some() {
self.close_terminal_find();
}
if p != Pane::Terminal && self.terminal_quick_select.is_some() {
self.close_terminal_quick_select();
}
if p != Pane::Terminal && self.terminal_copy_mode.is_some() {
self.close_terminal_copy_mode();
}
// A maximized terminal gives the editor zero rows; focusing the
// editor is always an intent to use it, so restore it (VS Code's
// convention when a file is revealed over a maximized panel).
// `terminal_pane_maximized` (width, among terminal panes) is
// unrelated and stays.
if p == Pane::Editor && self.terminal_maximized {
self.terminal_maximized = false;
}
// Auto-hide (#260): moving into the editor or a terminal collapses
// the sidebar; moving INTO the sidebar releases the pin a reveal
// command took, so the next move out can collapse it again.
match p {
Pane::Tree => {
self.sidebar_pinned_open = false;
// Focus came back inside the grace window: the click was
// passing through, or landed here. Cancel the pending
// collapse (#302) rather than letting it fire under the user.
self.sidebar_dwell.disarm();
}
Pane::Editor | Pane::Terminal => self.maybe_auto_hide_sidebar(),
}
self.focus = p;
self.sync_focus_flags();
if self.editor.focused {
self.poke_cursor();
}
// Group focus changes the active FILE without opening anything and
// without a path (#369): `focus_editor_group` and
// `move_active_editor` swap another group into `self.editor`, so
// neither the open-based sync nor a path-argument guard sees them.
// Every focus change lands here, so this is the one place that does.
self.drop_symbol_tab_if_file_changed();
}
fn sync_focus_flags(&mut self) {
// Focus must never rest on a COLLAPSED pane (#313). A folded pane is
// one column wide and is never rendered, so it paints no cursor and no
// focus border: the user would be typing into a pane they cannot see
// receiving it.
//
// Enforced HERE rather than at each gesture. The first attempt guarded
// `cycle_terminal` alone, which left closing the pane beside a folded
// one, the maximize rail, and a right-click on a strip - the last of
// which that same round OPENED, since making a strip right-clickable
// also made it focusable. A fix at the call site closes the path you
// were looking at; a fix at the invariant closes the ones you were not.
//
// Two things this function does NOT do, contrary to an earlier
// version of this comment. It is not called per frame - there are
// eleven call sites, none in a render path - and it is not on every
// path that moves `active_terminal`: `activate_terminal_pane` and
// `move_terminal` both assign without calling it. Those two are safe
// for reasons of their own (the first takes its index from
// `terminal_at_pos`, which cannot name a folded pane because its
// `last_area` is cleared; the second keeps the active pane pointed at
// its own terminal), so the invariant's totality rests on those
// reasons rather than on this being a universal funnel. A change to
// what feeds `terminal_at_pos` would break it silently.
//
// And this is the rule for focus that DRIFTS. A caller deliberately
// choosing a pane by index wants it made visible instead, which is
// `reveal_terminal_pane`.
//
// Skipped while a pane is maximized: the flags are deliberately
// ignored there and the active pane is painted full width whatever it
// holds, so moving focus would fight the user's own selection. Leaving
// maximize calls back through here, which is where it is repaired.
if !self.terminal_pane_maximized
&& self
.terminals
.get(self.active_terminal)
.is_some_and(|t| t.collapsed)
&& let Some(next) = self
.terminals
.iter()
.enumerate()
.filter(|(_, t)| !t.collapsed)
.min_by_key(|(candidate, _)| candidate.abs_diff(self.active_terminal))
.map(|(candidate, _)| candidate)
{
self.active_terminal = next;
}
// Quick-select is bound to the pane it opened on; this per-frame
// invariant covers every gesture that can move `active_terminal`
// (clicks, chords, pane closes shifting indices) in one place, so
// stale labels never survive a pane switch to hijack the new pane.
if self
.terminal_quick_select
.as_ref()
.is_some_and(|st| st.pane != self.active_terminal)
{
self.close_terminal_quick_select();
}
// Terminal find is pane-bound the same way.
if self.terminal_find.is_some() && self.terminal_find_pane != self.active_terminal {
self.close_terminal_find();
}
self.tree.focused = self.focus == Pane::Tree && self.sidebar_view == SidebarView::Explorer;
self.search.focused = self.focus == Pane::Tree && self.sidebar_view == SidebarView::Search;
self.source_control.focused =
self.focus == Pane::Tree && self.sidebar_view == SidebarView::SourceControl;
self.remote.focused = self.focus == Pane::Tree && self.sidebar_view == SidebarView::Remote;
self.run_debug.focused =
self.focus == Pane::Tree && self.sidebar_view == SidebarView::RunDebug;
self.extensions.focused =
self.focus == Pane::Tree && self.sidebar_view == SidebarView::Extensions;
self.editor.focused = self.focus == Pane::Editor;
// Inactive groups are by definition NOT the focused editor group, so
// their borders never light up even while the editor pane holds focus.
// `editor` (the active group) carries the highlight.
for group in self.editor_layout.inactive_groups_mut() {
group.focused = false;
}
let focused_pane = self.focus == Pane::Terminal;
let active = self.active_terminal;
for (i, t) in self.terminals.iter_mut().enumerate() {
t.focused = focused_pane && i == active;
}
// Only the Black theme dresses the focused pane in the gradient
// border; Croft Dark keeps the historical solid-blue highlight.
let gradient = self.theme.gradient();
// Every editor in both groups, not just the active one (deref would
// only hit the active editor): a tab switch or the split group must
// not resurrect the legacy navy active-tab chip between syncs.
// The bundled PDF / CSV viewers are gated by the Extensions panel:
// when disabled, the editor opens those file types as plain text.
let pdf_on = self.is_extension_enabled("pdf");
let csv_on = self.is_extension_enabled("csv");
for ed in self.editor.editors.iter_mut() {
ed.focus_gradient = gradient;
ed.theme = self.theme;
ed.pdf_viewer_enabled = pdf_on;
ed.csv_viewer_enabled = csv_on;
ed.show_indent_guides = self.indent_guides_enabled;
ed.show_bracket_colors = self.bracket_colors_enabled;
ed.provenance_overlay = self.provenance_overlay;
ed.whitespace_mode = self.whitespace_mode;
ed.diff_ws_default = self.diff_ws_default;
}
for group in self.editor_layout.inactive_groups_mut() {
for ed in group.editors.iter_mut() {
ed.focus_gradient = gradient;
ed.theme = self.theme;
ed.pdf_viewer_enabled = pdf_on;
ed.csv_viewer_enabled = csv_on;
ed.show_indent_guides = self.indent_guides_enabled;
ed.show_bracket_colors = self.bracket_colors_enabled;
ed.provenance_overlay = self.provenance_overlay;
ed.whitespace_mode = self.whitespace_mode;
ed.diff_ws_default = self.diff_ws_default;
ed.diff_ws_default = self.diff_ws_default;
}
}
self.tree.focus_gradient = gradient;
self.tree.theme = self.theme;
self.search.focus_gradient = gradient;
self.search.theme = self.theme;
self.source_control.focus_gradient = gradient;
self.source_control.theme = self.theme;
self.refresh_scm_repositories();
self.run_debug.focus_gradient = gradient;
self.run_debug.theme = self.theme;
let explorer_focused =
self.focus == Pane::Tree && self.sidebar_view == SidebarView::Explorer;
self.outline.focus_gradient = gradient;
self.outline.theme = self.theme;
self.outline.focused = explorer_focused;
self.open_editors.focus_gradient = gradient;
self.open_editors.theme = self.theme;
self.open_editors.focused = explorer_focused;
self.timeline.focus_gradient = gradient;
self.timeline.theme = self.theme;
self.timeline.focused = explorer_focused;
self.commit_graph.focus_gradient = gradient;
self.commit_graph.theme = self.theme;
self.commit_graph.focused =
self.focus == Pane::Tree && self.sidebar_view == SidebarView::SourceControl;
self.dependencies.focus_gradient = gradient;
self.dependencies.theme = self.theme;
self.dependencies.focused = explorer_focused;
self.remote.focus_gradient = gradient;
self.remote.theme = self.theme;
self.extensions.theme = self.theme;
self.problems.focus_gradient = gradient;
self.problems.theme = self.theme;
self.problems.focused = self.focus == Pane::Terminal;
self.problems.hover_pointer = self.pointer_cell;
self.problems.fix_glyph = match self.problems_fix_started {
Some(t) => update_spinner_frame(t.elapsed().as_millis()),
None => "",
};
self.output.focus_gradient = gradient;
self.output.theme = self.theme;
self.output.focused = self.focus == Pane::Terminal;
self.output.hover_pointer = self.pointer_cell;
self.output.sync();
self.ports.focus_gradient = gradient;
self.ports.theme = self.theme;
self.ports.focused = self.focus == Pane::Terminal;
self.ports.hover_pointer = self.pointer_cell;
for t in self.terminals.iter_mut() {
t.show_timestamps = self.show_terminal_timestamps;
}
self.captures.focus_gradient = gradient;
self.captures.theme = self.theme;
self.captures.focused = self.focus == Pane::Terminal;
self.captures.hover_pointer = self.pointer_cell;
for t in self.terminals.iter_mut() {
t.focus_gradient = gradient;
t.theme = self.theme;
t.set_palette(self.theme.ansi());
}
self.dress_host_accents();
}
/// Host accents: each pane's shell-reported OSC 7 host against the prefs
/// rules (first match wins). Cleared the moment the host stops matching
/// (an in-pane SSH session ends). Runs from `sync_focus_flags` AND at the
/// top of `render`: the OSC 7 host arrives on a PTY reader thread with no
/// input event behind it, so the PTY-dirty redraw is the only wakeup —
/// dressing must not wait for the next key or click.
fn dress_host_accents(&mut self) {
for t in self.terminals.iter_mut() {
let dress = t.shell_host().and_then(|h| {
self.host_accents
.iter()
.find(|(m, _, _)| m.is_match(&h))
.map(|(_, c, b)| (*c, b.clone()))
});
match dress {
Some((c, b)) => {
t.accent = Some(c);
t.accent_badge = b;
}
None => {
t.accent = None;
t.accent_badge = None;
}
}
}
}
/// Whether popups/menus/tooltips should wear the orange→green gradient
/// border and the muted dark-teal selection fill instead of the legacy
/// bright-blue accent. Gated on the Black theme to mirror the focused-pane
/// border, so Croft Dark keeps its coherent all-blue look.
fn popup_gradient(&self) -> bool {
self.theme.gradient()
}
/// Paint the bottom panel group's tab strip (PROBLEMS / TERMINAL) across
/// `strip` (its top row) and record each tab's hit rect. The active tab is
/// bright/bold; the inactive one is dim, mirroring VS Code's panel tabs. A
/// non-zero problem count rides the PROBLEMS label as a badge.
fn paint_panel_tabs(&mut self, frame: &mut ratatui::Frame, strip: Rect) {
use ratatui::widgets::Block;
let strip_bg = self.theme.editor_bg();
frame.render_widget(Block::default().style(Style::default().bg(strip_bg)), strip);
let brand = self.theme.gradient();
let active_fg = if brand {
crate::gradient::rgb_color(crate::gradient::PANEL_TITLE_FG)
} else {
self.theme.ui(Color::White)
};
let inactive_fg = self.theme.ui(Color::Rgb(0x80, 0x88, 0x98));
let right = strip.x + strip.width;
let count = self.problems.total_count();
let pointer = self.pointer_cell;
let orange = crate::gradient::rgb_color(crate::gradient::GRAD_TR);
let badge_fg = self.theme.ui(Color::Rgb(0x1a, 0x12, 0x0a));
let active = self.bottom_panel_tab;
self.problems_tab_rect = Rect::default();
self.output_tab_rect = Rect::default();
self.ports_tab_rect = Rect::default();
self.captures_tab_rect = Rect::default();
self.terminal_tab_rect = Rect::default();
// In images mode the count rides as an orange circle (the same raster
// badge as the activity bar), emitted post-frame; recompute its anchor
// each paint. Glyph-fallback terminals keep the powerline-cap pill.
let images = self.overlays.activity.has_images();
self.problems_badge_cell = None;
// VS Code panel-group order: PROBLEMS, OUTPUT, TERMINAL, PORTS. PROBLEMS
// alone carries the orange count badge after its label.
let tabs = [
(BottomPanelTab::Problems, " PROBLEMS "),
(BottomPanelTab::Output, " OUTPUT "),
(BottomPanelTab::Terminal, " TERMINAL "),
(BottomPanelTab::Ports, " PORTS "),
(BottomPanelTab::Captures, " CAPTURES "),
];
// Lay each tab out left to right, recording its hit rect (which, for
// PROBLEMS, spans the label and the pill together).
let mut placed: Vec<(BottomPanelTab, &str, Rect, u16)> = Vec::with_capacity(tabs.len());
let mut x = strip.x + 1;
for (tab, label) in tabs {
if x >= right {
break;
}
let badge_w = if tab == BottomPanelTab::Problems && count > 0 {
if images {
crate::iterm2_inline::count_badge_cells_w(count)
} else {
format!("{count}").chars().count() as u16 + 2
}
} else {
0
};
let w = label.chars().count() as u16 + badge_w;
let rect = Rect {
x,
y: strip.y,
width: w.min(right.saturating_sub(x)),
height: 1,
};
match tab {
BottomPanelTab::Problems => self.problems_tab_rect = rect,
BottomPanelTab::Output => self.output_tab_rect = rect,
BottomPanelTab::Ports => self.ports_tab_rect = rect,
BottomPanelTab::Captures => self.captures_tab_rect = rect,
BottomPanelTab::Terminal => self.terminal_tab_rect = rect,
}
placed.push((tab, label, rect, badge_w));
x = x.saturating_add(w + 1);
}
let buf = frame.buffer_mut();
for (tab, label, rect, badge_w) in &placed {
let is_active = *tab == active;
// Active tab: brand fg + bold (and underlined below). Hover brightens
// an inactive tab; the rest stay dim.
let style = if is_active {
Style::default()
.fg(active_fg)
.bg(strip_bg)
.add_modifier(Modifier::BOLD)
} else if crate::widgets::hover::row_hover_bg(*rect, pointer, self.theme).is_some() {
Style::default().fg(active_fg).bg(strip_bg)
} else {
Style::default().fg(inactive_fg).bg(strip_bg)
};
if rect.x < right {
buf.set_stringn(
rect.x,
rect.y,
label,
right.saturating_sub(rect.x) as usize,
style,
);
}
// Orange count badge after PROBLEMS. In images mode it's a raster
// circle (matching the activity-bar badges) emitted post-frame, so
// the cells stay blank strip_bg and we just record the anchor.
// Otherwise the powerline-cap pill is drawn as text.
if *badge_w > 0 {
let bx = rect.x + label.chars().count() as u16;
if images {
if bx < right {
self.problems_badge_cell = Some((bx, rect.y));
}
} else {
let badge_text = format!("{count}");
let cap_style = Style::default().fg(orange).bg(strip_bg);
if bx < right {
buf.set_string(bx, rect.y, "\u{e0b6}", cap_style);
}
let inner_start = bx + 1;
if inner_start < right {
buf.set_stringn(
inner_start,
rect.y,
&badge_text,
right.saturating_sub(inner_start) as usize,
Style::default()
.fg(badge_fg)
.bg(orange)
.add_modifier(Modifier::BOLD),
);
}
let cap_r = inner_start + badge_text.chars().count() as u16;
if cap_r < right {
buf.set_string(cap_r, rect.y, "\u{e0b4}", cap_style);
}
}
}
// The active-tab underline (VS Code's indicator) hugs the word only,
// stopping before the padding spaces and the pill.
if is_active {
let leading = label.chars().take_while(|c| *c == ' ').count() as u16;
let word_len = label.trim().chars().count() as u16;
let start = rect.x + leading;
for ux in start..(start + word_len).min(right) {
buf[(ux, rect.y)].modifier.insert(Modifier::UNDERLINED);
}
}
}
}
/// Switch the bottom panel group's active tab, ensuring the panel is
/// visible and the panel pane is focused so the new view is usable at once.
fn set_bottom_panel_tab(&mut self, tab: BottomPanelTab) {
self.bottom_panel_tab = tab;
if !self.show_terminal {
self.show_terminal = true;
}
self.focus_pane(Pane::Terminal);
}
/// Split the editor into two side-by-side columns (`Cmd+\`). The new
/// group duplicates the active file (re-opens its path, copies the
/// cursor/scroll position) and takes focus, landing in the right
/// column. No-op if already split or the active tab has no path on
/// disk (a blank/unsaved buffer has nothing to mirror).
/// "Split Editor Right": split the active group side by side, the new
/// focused duplicate to the right. The default split, on `Cmd+\`.
fn split_editor(&mut self) {
self.split_editor_dir(editor_layout::SplitDir::Horizontal, true);
}
/// Split the active group, duplicating its file into a new focused group
/// placed in the direction the caller asks for. `dir` chooses the seam's
/// orientation (Horizontal = side by side, Vertical = stacked) and
/// `new_after` whether the NEW group sits after the existing one (right /
/// below) or before it (left / above) — the four VS Code Split commands:
/// Right = (H, after), Left = (H, before), Down = (V, after), Up = (V,
/// before). Splitting is offered only from an unsplit editor for now.
fn split_editor_dir(&mut self, dir: editor_layout::SplitDir, new_after: bool) {
let Some(path) = self.editor.path.clone() else {
self.status = String::from("Cannot split: save the file first");
return;
};
// A fresh EditorTabs starts blank-initial; `open_preview` reuses
// that placeholder tab so the new group holds exactly the file
// (not a stray blank tab beside it). Opening it as the PREVIEW
// slot - not pinned - means the next file the user opens in this
// column swaps straight into it (clean "left = A, right = B"
// comparison) rather than stacking a second tab. Editing or
// double-clicking pins it, as everywhere else.
let mut group = EditorTabs::default();
if group.open_preview(&path).is_err() {
self.status = String::from("Cannot split: failed to open file");
return;
}
// Mirror the source view state (caret + scroll, incl. the wrap
// sub-line offset) so the duplicate opens exactly where the
// source was rather than at the top of the file.
group.copy_view_position_from(&self.editor);
// The new focused group (now in `self.editor`, always the active leaf)
// takes the active slot; the existing group settles into the sibling.
let existing = std::mem::replace(&mut self.editor, group);
self.editor_layout.split_active(existing, dir, new_after);
self.focus_pane(Pane::Editor);
}
/// VS Code "Move Editor into <dir> Group": relocate the active tab to the
/// group adjacent in `dir`. If a neighbour exists there the tab moves into
/// it (the source collapses when its last tab leaves); otherwise a new group
/// is created in that direction holding the moved tab. Moving the only tab
/// of a single group with no neighbour is a no-op (nowhere to move to).
fn move_active_editor(&mut self, dir: editor_layout::Dir) {
// A nominal area: seam adjacency is scale-invariant, so the exact pane
// size doesn't matter for finding the directional neighbour.
let synth = ratatui::layout::Rect::new(0, 0, 10_000, 10_000);
match self.editor_layout.neighbor_leaf_in_dir(synth, 1, dir) {
Some(target) => {
let moved = self.editor.take_active_editor();
let source_emptied = self.editor.is_blank_initial();
let reduced = std::mem::take(&mut self.editor);
self.editor = self.editor_layout.refocus_to_dfs(reduced, target);
self.editor.push_editor(moved);
if source_emptied {
self.editor_layout
.prune_blank_inactive(|t| t.is_blank_initial());
}
self.focus_pane(Pane::Editor);
}
None => {
if self.editor.tab_count() <= 1 {
self.status = String::from("Move: the editor is already a single group");
return;
}
let moved = self.editor.take_active_editor();
let mut group = EditorTabs::default();
group.push_editor(moved);
let existing = std::mem::replace(&mut self.editor, group);
self.editor_layout
.split_active(existing, dir.split_dir(), dir.places_new_after());
self.focus_pane(Pane::Editor);
}
}
}
/// VS Code "Split in Group": open a second view of the active file beside
/// it. A TUI has no true in-group sub-view, so the observable equivalent is
/// a side-by-side split duplicating the active file — the same result as
/// Split Right.
fn split_in_group(&mut self) {
self.split_editor_dir(editor_layout::SplitDir::Horizontal, true);
}
/// Move keyboard focus to the editor group in the given physical
/// column (`true` = left, `false` = right). Hoists the active group
/// through `editor_layout` so the focused group is always `editor`, keeping
/// the physical columns fixed. No-op when not split or already focused
/// there.
fn focus_editor_group(&mut self, want_left: bool) {
if !self.editor_layout.is_split() {
return;
}
// Physical columns map to depth-first leaf order: leftmost = 0,
// rightmost = last. Hoist the active group out and pull the target
// leaf's group into `self.editor` so the invariant holds.
let target = if want_left {
0
} else {
self.editor_layout.leaf_count() - 1
};
if self.editor_layout.active_dfs_index() == target {
// Already focused there; the chord still doubles as "focus editor".
if self.focus != Pane::Editor {
self.focus_pane(Pane::Editor);
}
return;
}
let current = std::mem::take(&mut self.editor);
self.editor = self.editor_layout.refocus_to_dfs(current, target);
self.focus_pane(Pane::Editor);
}
/// The seam (if any) the cell `(col, row)` lands on, using the same
/// two-cell hit-zone as the sidebar/terminal seams. Returns a clone so an
/// in-flight drag can hold the boundary across frames.
fn seam_at(&self, col: u16, row: u16) -> Option<editor_layout::Seam> {
self.editor_seams
.iter()
.find(|s| match s.dir {
editor_layout::SplitDir::Horizontal => {
(col == s.pos || col == s.pos.saturating_sub(1))
&& row >= s.cross_start
&& row < s.cross_end
}
editor_layout::SplitDir::Vertical => {
(row == s.pos || row == s.pos.saturating_sub(1))
&& col >= s.cross_start
&& col < s.cross_end
}
})
.cloned()
}
/// After a tab close, collapse the split if the focused group ran out
/// of real tabs. The surviving (other) group becomes the sole editor.
fn collapse_split_if_empty(&mut self) {
// While a full-screen window is open, `editor` is the window and the
// grid is parked out of the tree — collapsing here would fold the
// parked grid into the window. The window's own emptiness is handled by
if !self.editor_layout.is_split() || !self.editor.is_blank_initial() {
return;
}
// The focused group is empty; drop it and promote a surviving group to
// become the new active editor. Evict the right slot's image so it
// can't ghost after the column disappears.
self.editor = self.editor_layout.collapse_active();
self.editor_seams.clear();
self.disable_editor_image(1);
// Focus stays on the editor pane; just re-light the promoted
// group's border. (No `focus_pane` so this is safe to call from
// any close path without re-poking the cursor mid-frame.)
self.sync_focus_flags();
}
/// VS Code "Move into New Window": open the tab at `idx` in a brand-new
/// window of the host terminal (a real, separate window running croft on the
/// same workspace with the file open), then close the tab here — the file
/// has moved to the new window. The current window is otherwise untouched.
fn move_into_new_window(&mut self, idx: usize) {
if !self.open_tab_in_new_window(idx) {
return;
}
// The file now lives in the new window; drop it from this one. Mirrors
// MenuAction::CloseTab so the split collapses if this was its last tab.
let label = self.editor.tab_display_label(idx);
if self.editor.close_tab(idx) {
self.sync_open_file_poll_mtime();
self.poke_cursor();
self.collapse_split_if_empty();
}
self.status = format!("{label}: moved into a new window");
}
/// VS Code "Copy into New Window" (⌘K O): open the tab at `idx` in a
/// brand-new OS terminal window, leaving the original tab exactly where it
/// is. The current window is not touched at all.
fn copy_into_new_window(&mut self, idx: usize) {
if !self.open_tab_in_new_window(idx) {
return;
}
let label = self.editor.tab_display_label(idx);
self.status = format!("{label}: copied into a new window");
}
/// Spawn a new OS terminal window running croft on the current workspace
/// with the tab at `idx` opened. Returns false (and sets a status) when the
/// action can't run: an unsaved/path-less buffer, a remote session (no
/// local window server on the headless host), or a spawn failure. Shared by
/// Move and Copy into New Window — the only difference is what the caller
/// does to the source tab afterwards.
fn open_tab_in_new_window(&mut self, idx: usize) -> bool {
// A new croft process opens a file by path, so an untitled buffer has
// nothing to hand off.
let Some(path) = self.editor.tab_path(idx) else {
self.status = String::from("New Window: save the file first");
return false;
};
// A new OS window only exists where croft can talk to a window server:
// the local machine. Over SSH croft runs on the headless host.
if self.is_remote {
self.status = String::from("New Window: not available over SSH");
return false;
}
match spawn_new_window(&self.tree.root, &path) {
Ok(()) => true,
Err(e) => {
self.status = format!("New Window failed: {e}");
false
}
}
}
fn render(&mut self, frame: &mut ratatui::Frame) {
let size = frame.area();
self.last_frame_area = size;
// Redaction reveal is app state; each pane paints from its own copy.
let reveal = self.redactions_revealed();
for t in self.terminals.iter_mut() {
t.reveal_redactions = reveal;
}
// Hit rects must describe the frame being painted, not the last
// frame that happened to include a section. A section that stops
// rendering (Explorer's OPEN EDITORS / TIMELINE / DEPENDENCIES /
// OUTLINE after a switch to Source Control) otherwise keeps its
// stale rect, and `handle_mouse`'s containment checks swallow every
// click the current view paints in those cells — the COMMITS graph
// sits exactly there and its clicks went dead (#103). Zero them all
// up front; each section's render re-records the live ones this
// frame (the OSK does the same for its collapsed band).
for rect in [
&mut self.open_editors.last_area,
&mut self.open_editors.last_scrollbar,
&mut self.timeline.last_area,
&mut self.timeline.last_scrollbar,
&mut self.dependencies.last_area,
&mut self.dependencies.last_scrollbar,
&mut self.outline.last_area,
&mut self.outline.last_scrollbar,
&mut self.commit_graph.last_area,
&mut self.commit_graph.last_scrollbar,
] {
*rect = Rect::default();
}
self.dress_host_accents();
self.expire_ssh_offer();
self.sync_lane_root_badges();
// Theme background, whole frame. croft's chrome (the sidebar panels,
// explorer sections, activity bar, gaps) mostly paints `Color::Reset`
// and leans on the iTerm2 `SetColors` session bg to color it. Ghostty /
// Kitty / sixel ignore `SetColors`, so those Reset cells fall through to
// the host terminal's own background (black), leaving only the surfaces
// that fill an explicit bg (editor, terminal) themed. Prefilling the
// frame with the theme bg colors every unfilled cell; widgets that set
// their own bg override it (ratatui patches bg only when `Some`). Gated
// to exactly the hosts where `SetColors` is NOT emitted (see
// `apply_theme`): on iTerm2 the session bg already handles this and a
// full-frame fill would force the OSC-1337 activity images to re-emit
// every frame.
if !crate::iterm2_inline::detect_iterm2_inline_support() {
frame.render_widget(
ratatui::widgets::Block::default()
.style(Style::default().bg(self.theme.editor_bg())),
size,
);
}
// The on-screen keyboard docks as a band between the panes and the
// status bar, scaling its keys to thumb size on tall frames; frames
// too short to host it keep it collapsed so the workspace can't be
// squeezed into nothing.
let osk_h = if self.osk.is_some() && size.height >= OSK_MIN_FRAME_HEIGHT {
crate::widgets::osk::band_height(size.height)
} else {
0
};
// The bottom status bar can be hidden (Customize Layout / Zen Mode),
// reclaiming its row for the workspace.
let status_h: u16 = if self.status_bar_visible { 1 } else { 0 };
let outer = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Min(1),
Constraint::Length(osk_h),
Constraint::Length(status_h),
])
.split(size);
let main_area = outer[0];
// Reserve the activity bar (when shown) and the secondary side bar,
// then clamp the primary side bar so the editor keeps RIGHT_PANE_MIN.
let activity_w = if self.activity_bar_visible {
ACTIVITY_BAR_WIDTH
} else {
0
};
let secondary_w = if self.secondary_side_bar_visible {
SECONDARY_SIDEBAR_WIDTH
} else {
0
};
let max_sidebar = main_area
.width
.saturating_sub(activity_w)
.saturating_sub(secondary_w)
.saturating_sub(RIGHT_PANE_MIN);
let sidebar_w = self
.sidebar_width
.clamp(SIDEBAR_WIDTH_MIN, max_sidebar.max(SIDEBAR_WIDTH_MIN));
// Persist the clamped value so subsequent drags start from where
// the user can actually see the splitter.
self.sidebar_width = sidebar_w;
// Panel Alignment = Justify spans the panel across the full content
// width (under the side bar): carve it off the bottom of `main` BEFORE
// the horizontal chrome split, so the side bars sit above it.
let justify_panel = self.show_terminal
&& !self.terminal_maximized
&& osk_h == 0
&& self.panel_alignment == PanelAlignment::Justify;
let (chrome_area, justify_terminal) = if justify_panel {
let total_h = main_area.height;
let max_h = total_h
.saturating_sub(EDITOR_HEIGHT_MIN)
.max(TERMINAL_HEIGHT_MIN);
let term_h = self
.terminal_height
.unwrap_or(total_h / 3)
.clamp(TERMINAL_HEIGHT_MIN, max_h);
self.terminal_height = Some(term_h);
let rows = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Min(EDITOR_HEIGHT_MIN),
Constraint::Length(term_h),
])
.split(main_area);
(rows[0], Some(rows[1]))
} else {
(main_area, None)
};
// Pure horizontal split of the workspace chrome (honors activity-bar
// visibility, side bar position, and the secondary side bar).
let chrome = compute_chrome_layout(
chrome_area,
self.activity_bar_visible,
self.show_tree,
self.secondary_side_bar_visible,
self.side_bar_position,
sidebar_w,
SECONDARY_SIDEBAR_WIDTH,
);
let activity_area = chrome.activity;
let side_area = chrome.primary_side;
let secondary_area = chrome.secondary_side;
let right_area = chrome.right;
// Remember the Explorer column so the zoxide jump popup can anchor
// over it instead of centering on the whole frame.
self.last_sidebar_area = side_area;
self.sidebar_splitter_x = chrome.sidebar_splitter_x;
self.last_content_width = right_area.width;
self.last_content_height = right_area.height;
// Editor ↔ terminal split within the editor column. `terminal_band` is
// the full bottom strip; `terminal_area` is where the terminals draw
// (narrower than the band under Left/Right alignment).
let (editor_area, terminal_area, terminal_band) = if let Some(jt) = justify_terminal {
// The panel was already carved full-width from `main`; the editor
// fills the rest of its column and the splitter sits at the seam.
self.terminal_splitter_y = Some(jt.y);
(right_area, Some(jt), Some(jt))
} else if osk_h > 0 && self.focus == Pane::Terminal && self.show_terminal {
let zero_editor = Rect {
x: right_area.x,
y: right_area.y,
width: right_area.width,
height: 0,
};
self.terminal_splitter_y = None;
(zero_editor, Some(right_area), Some(right_area))
} else if osk_h > 0 {
self.terminal_splitter_y = None;
(right_area, None, None)
} else if self.show_terminal {
if self.terminal_maximized {
// Editor / welcome collapses; terminal fills the entire
// right column next to the Explorer. Splitter is hidden
// because there is nothing to drag against.
let zero_editor = Rect {
x: right_area.x,
y: right_area.y,
width: right_area.width,
height: 0,
};
self.terminal_splitter_y = None;
(zero_editor, Some(right_area), Some(right_area))
} else {
let total_h = right_area.height;
let pinned = self.terminal_height.map(|h| {
h.clamp(
TERMINAL_HEIGHT_MIN,
total_h
.saturating_sub(EDITOR_HEIGHT_MIN)
.max(TERMINAL_HEIGHT_MIN),
)
});
let rows = if let Some(term_h) = pinned {
self.terminal_height = Some(term_h);
Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Min(EDITOR_HEIGHT_MIN),
Constraint::Length(term_h),
])
.split(right_area)
} else {
Layout::default()
.direction(Direction::Vertical)
.constraints([Constraint::Percentage(65), Constraint::Percentage(35)])
.split(right_area)
};
self.terminal_splitter_y = Some(rows[1].y);
let band = rows[1];
// Left/Right alignment hugs the panel to that half of the band.
let term = panel_band_rect(band, self.panel_alignment);
(rows[0], Some(term), Some(band))
}
} else {
self.terminal_splitter_y = None;
(right_area, None, None)
};
if let Some(activity_area) = activity_area {
self.render_activity_bar(frame, activity_area);
} else {
// Hidden activity bar: zero the icon hit-rects so clicks and the
// post-draw OSC image flush both treat it as absent (no ghosting).
self.sidebar_areas = SidebarAreas::default();
}
// Secondary side bar: the active file's Outline, on the edge opposite
// the primary side bar.
self.render_secondary_side_bar(frame, secondary_area);
if let Some(area) = side_area {
let usable_area = area;
// Feed the render-time pointer cell to every side panel so the row
// under the cursor (and the remote header pills) can light up,
// mirroring the editor tab strip and terminal pane buttons.
let panel_pointer = self.pointer_cell;
self.tree.hover_pointer = panel_pointer;
self.search.hover_pointer = panel_pointer;
self.source_control.hover_pointer = panel_pointer;
self.remote.hover_pointer = panel_pointer;
self.outline.hover_pointer = panel_pointer;
self.open_editors.hover_pointer = panel_pointer;
self.timeline.hover_pointer = panel_pointer;
self.dependencies.hover_pointer = panel_pointer;
self.extensions.hover_pointer = panel_pointer;
self.commit_graph.hover_pointer = panel_pointer;
// Explorer stacks its toggled sub-views (Open Editors / Folders /
// Outline / Timeline / Dependencies) inside the usable strip.
// Every other sidebar view fills it with its single activity widget.
match self.sidebar_view {
SidebarView::Explorer => self.render_explorer_sections(frame, usable_area),
SidebarView::Search => frame.render_widget(&mut self.search, usable_area),
SidebarView::SourceControl => {
// The COMMITS graph section docks under the change list,
// capped at half the strip (like the Explorer sub-views).
// Hidden entirely while the repo empty-state hero shows.
let graph_h = if self.source_control.status.in_repo {
self.commit_graph
.desired_height(usable_area.height)
.min(usable_area.height.saturating_sub(6))
} else {
0
};
let scm_area = Rect {
height: usable_area.height - graph_h,
..usable_area
};
frame.render_widget(&mut self.source_control, scm_area);
if graph_h > 0 {
let graph_area = Rect {
y: usable_area.y + usable_area.height - graph_h,
height: graph_h,
..usable_area
};
frame.render_widget(&mut self.commit_graph, graph_area);
} else {
self.commit_graph.last_area = Rect::default();
}
}
SidebarView::Remote => frame.render_widget(&mut self.remote, usable_area),
SidebarView::RunDebug => frame.render_widget(&mut self.run_debug, usable_area),
SidebarView::Extensions => frame.render_widget(&mut self.extensions, usable_area),
SidebarView::Testing => frame.render_widget(&mut self.testing, usable_area),
}
}
if !self.editor_layout.is_split() && self.editor.is_blank_initial() {
self.render_welcome(frame, editor_area);
// The previous frame may have rendered an image-preview tab
// whose OSC-1337 pixels are still cached in iTerm's image
// store. Closing that tab brings us here, but ratatui's diff
// alone doesn't tell iTerm to drop the image — flag it so the
// main loop wipes the screen on the next pass. Both slots, in
// case a split was just collapsed back to the welcome screen.
self.disable_editor_image(0);
self.disable_editor_image(1);
// The welcome screen has no minimap (no document to preview).
self.disable_minimap_image();
self.editor_seams.clear();
// Keep the editor's hit-test rectangles fresh so the activity-bar
// / tree click logic still works even though we skipped the
// EditorTabs widget this frame.
self.editor.last_full_area = editor_area;
self.editor.last_area = Rect {
x: editor_area.x,
y: editor_area.y,
width: editor_area.width,
height: 0,
};
} else {
// The editor just overdrew whatever cells the welcome image
// occupied; if the user reopens the welcome screen we'll need
// to re-emit it.
self.overlays.welcome.mark_dirty();
// Feed the render-time pointer cell to every editor group so the
// tab strip can light the hovered tab body / close-cross pill,
// mirroring the terminal pane buttons' hover affordance.
let pointer = self.pointer_cell;
self.editor.hover_pointer = pointer;
// Breadcrumb bar: recompute the path + symbol trail for the active
// file each frame so it tracks caret moves and outline updates.
self.editor.breadcrumbs = self.build_breadcrumbs();
// Sticky scroll: recompute the pinned scope headers from the top
// visible line each frame so they track scrolling.
self.editor.sticky_lines = self.build_sticky_lines();
// Multiplayer ghost carets: other participants' parked carets in
// the active file, in their colors. The current typist's caret is
// the live cursor, so it never ghosts; departed participants drop
// out with the roster.
self.editor.ghost_carets = match self.editor.path.clone() {
Some(path) if !self.session_carets.is_empty() => self
.session_carets
.iter()
.filter(|(id, parked)| {
Some(**id) != self.session_typist
&& parked.path == path
&& self.session_participants.iter().any(|p| p.id == **id)
})
.map(|(id, parked)| (parked.row, parked.col, participant_color(*id)))
.collect(),
_ => Vec::new(),
};
// Collab peers' carets (Phase D independent viewports): same
// ghost rendering, keyed by workspace-relative file, plus a name
// tag while the caret is inside its fade window. The seated
// navigator's caret wears its identity accent.
self.editor.ghost_caret_labels.clear();
if !self.collab_carets.is_empty()
&& let Some(active) = self
.editor
.path
.as_ref()
.and_then(|p| collab_file_key(&self.tree.root, p))
{
let navigator_sites = self
.pair_host
.as_ref()
.map(|h| h.caret_sites())
.unwrap_or_default();
let now = std::time::Instant::now();
for (site, c) in &self.collab_carets {
if c.file != active {
continue;
}
let color = collab_caret_color(&navigator_sites, *site);
self.editor.ghost_carets.push((c.row, c.col, color));
if !c.name.is_empty() && now.duration_since(c.last_moved) < CARET_LABEL_FADE {
self.editor
.ghost_caret_labels
.push((c.row, c.col, c.name.clone(), color));
}
}
}
// Gutter stop button for an AI stream into the active file; the
// hoisted group is the only one that shows it (clear the rest so
// a group swap never leaves a stale button behind).
self.editor.stream_stop_line = self.stream_stop_row();
// The navigator's comment boxes for the active file, same
// hoisting rule (rows come from poll_pair's per-tick snapshot).
let author = self
.pair_host
.as_ref()
.map(|h| h.name().to_string())
.unwrap_or_default();
self.editor.comment_boxes = self
.editor
.path
.as_ref()
.and_then(|p| collab_file_key(&self.tree.root, p))
.and_then(|file| self.navigator_notes.get(&file))
.map(|notes| {
notes
.iter()
.map(|(id, row, body)| crate::widgets::editor::CommentBox {
id: *id,
line: *row,
author: author.clone(),
body: body.clone(),
})
.collect()
})
.unwrap_or_default();
// Review threads (#366) join the navigator's rather than
// replacing them: both are comments on the same lines, and a
// reviewer reading a PR with a navigator session open wants
// both. Appended after, so a navigator note and a review
// comment on one line keep a stable order.
if let Some((path, threads)) = &self.review_boxes
&& self.editor.path.as_deref() == Some(path.as_path())
{
let lines = self.editor.lines.len();
self.editor.comment_boxes.extend(threads.iter().map(|t| {
crate::widgets::editor::CommentBox {
id: t.id,
line: t.box_line(lines),
author: t.title_for(lines),
body: t.body.clone(),
}
}));
}
// A focused box that vanished (ignored elsewhere, cleared, or
// re-anchored away) releases the keyboard back to the buffer.
if let Some(focus) = &self.editor.comment_focus
&& !self.editor.comment_boxes.iter().any(|b| b.id == focus.id)
{
self.editor.comment_focus = None;
}
for group in self.editor_layout.inactive_groups_mut() {
for ed in &mut group.editors {
ed.stream_stop_line = None;
ed.comment_boxes.clear();
ed.comment_focus = None;
}
}
// Render the editor group layout tree. The active group is hoisted
// into `self.editor`; every other group lives in `editor_layout`.
// Lay the leaves out and paint each at its rect (depth-first order),
// reporting the active group's rect so popups anchor there.
let rects = self.editor_layout.leaf_rects(editor_area, EDITOR_SPLIT_MIN);
let active_idx = self.editor_layout.active_dfs_index();
let focused_area = if self.editor_layout.is_split() {
let active_area = rects[active_idx];
frame.render_widget(&mut self.editor, active_area);
let inactive_rects: Vec<Rect> = rects
.iter()
.enumerate()
.filter(|(i, _)| *i != active_idx)
.map(|(_, r)| *r)
.collect();
for (group, rect) in self
.editor_layout
.inactive_groups_mut()
.into_iter()
.zip(inactive_rects)
{
group.hover_pointer = pointer;
frame.render_widget(group, rect);
}
// Every boundary in the grid is a draggable seam (one per
// internal child edge of every split node, any depth).
self.editor_seams = self.editor_layout.seams(editor_area, EDITOR_SPLIT_MIN);
// Image overlays stay keyed by physical column (0 = left).
if rects.len() == 2 {
self.update_editor_image_overlay(0, rects[0]);
self.update_editor_image_overlay(1, rects[1]);
} else {
self.update_editor_image_overlay(0, active_area);
self.disable_editor_image(1);
}
// ponytail: no minimap while the editor is split; per-group
// minimaps when someone asks for them.
self.disable_minimap_image();
active_area
} else if let Some((ed_rect, full_strip, img_rect)) = self.carve_minimap(editor_area) {
// Bg-fill the whole strip column so no stale cells show
// through, then paint the editor into the narrowed rect and
// bake the minimap raster into the text-aligned sub-rect.
frame.render_widget(
ratatui::widgets::Block::default()
.style(Style::default().bg(self.theme.editor_bg())),
full_strip,
);
frame.render_widget(&mut self.editor, ed_rect);
self.editor_seams.clear();
self.update_editor_image_overlay(0, ed_rect);
self.disable_editor_image(1);
self.update_minimap_overlay(img_rect);
ed_rect
} else {
frame.render_widget(&mut self.editor, editor_area);
self.editor_seams.clear();
self.update_editor_image_overlay(0, editor_area);
// No right pane: make sure its slot can't ghost an image.
self.disable_editor_image(1);
self.disable_minimap_image();
editor_area
};
if self.focus == Pane::Editor
&& self.completion_popup.is_some()
&& let Some((cx, cy)) = self.editor.cursor_screen_pos()
{
if let Some(popup) = self.completion_popup.as_mut() {
popup.anchor = (cx, cy);
popup.theme = self.theme;
}
let popup_ref = self.completion_popup.as_ref().unwrap();
let area = popup_ref.area_for(focused_area);
if area.width > 0 && area.height > 0 {
frame.render_widget(popup_ref, area);
}
}
// Parameter hints sit ABOVE the caret, so they coexist with the
// completion popup below it.
if self.focus == Pane::Editor
&& self.signature_help_popup.is_some()
&& let Some((cx, cy)) = self.editor.cursor_screen_pos()
{
if let Some(popup) = self.signature_help_popup.as_mut() {
popup.anchor = (cx, cy);
popup.theme = self.theme;
}
let popup_ref = self.signature_help_popup.as_ref().unwrap();
let area = popup_ref.area_for(focused_area);
if area.width > 0 && area.height > 0 {
frame.render_widget(popup_ref, area);
}
}
if let Some(popup) = self.tab_tooltip.as_mut() {
popup.theme = self.theme;
let area = popup.area_for(focused_area);
if area.width > 0 && area.height > 0 {
frame.render_widget(&*popup, area);
}
}
// Layout-control icons at the top-right of the editor tab strip.
let strip_row = Rect {
x: editor_area.x,
y: editor_area.y,
width: editor_area.width,
height: 1,
};
self.paint_layout_icons(frame, strip_row);
}
if let Some(area) = terminal_area {
// Left/Right panel alignment narrows the terminal to one half of
// its band; paint the leftover strip with the editor background so
// the vacated cells don't ghost the previous frame.
if let Some(band) = terminal_band
&& (band.width != area.width || band.x != area.x)
{
frame.render_widget(
ratatui::widgets::Block::default()
.style(Style::default().bg(self.theme.editor_bg())),
band,
);
}
// The panel group's tab strip (PROBLEMS / TERMINAL) takes the top
// row; the active tab's view fills the rest. Mirrors VS Code's
// bottom-panel tab bar.
let strip = Rect {
x: area.x,
y: area.y,
width: area.width,
height: 1,
};
let content = if area.height > 1 {
Rect {
x: area.x,
y: area.y + 1,
width: area.width,
height: area.height - 1,
}
} else {
area
};
self.paint_panel_tabs(frame, strip);
match self.bottom_panel_tab {
BottomPanelTab::Terminal => {
let n = self.terminals.len().max(1);
let multi = self.terminals.len() > 1;
let maximized = self.terminal_pane_maximized && multi;
self.clear_terminal_rail();
// Maximize mode: the active pane owns the panel's width
// minus a right rail listing every terminal (VS Code's
// terminal-tabs list); hidden panes drop their hit rects
// so clicks can't phantom-match. Otherwise: even split.
let cols: Vec<Rect> = if maximized {
// The rail is a fixed, very narrow switcher column:
// icon + 4 label characters, nothing adaptive.
let rail_w = TERMINAL_RAIL_W.min(content.width.saturating_sub(20));
let pane = Rect {
x: content.x,
y: content.y,
width: content.width - rail_w,
height: content.height,
};
let rail = Rect {
x: content.x + pane.width,
y: content.y,
width: rail_w,
height: content.height,
};
self.paint_terminal_rail(frame, rail);
(0..n)
.map(|i| {
if i == self.active_terminal {
pane
} else {
Rect::default()
}
})
.collect()
} else {
// Collapsed panes (#313) keep a one-column strip and
// the rest divide what is left. Read off the panes
// rather than a list held here, so a reorder or a
// close can never leave the flags naming the wrong
// terminal.
let collapsed: Vec<bool> = (0..n)
.map(|i| self.terminals.get(i).is_some_and(|t| t.collapsed))
.collect();
Layout::default()
.direction(Direction::Horizontal)
.constraints(terminal_pane_constraints(&collapsed))
.split(content)
.to_vec()
};
// Theme the terminal background like VS Code's integrated
// terminal: prefill each pane with the theme bg before the
// grid paints. Shell-colored cells override it; default-bg
// cells (Style bg = None) keep the fill. On iTerm2 this
// matches the SetColors session bg; on Ghostty/Kitty (which
// ignores SetColors) it's what makes the terminal follow the
// theme at all instead of showing the host's own bg.
let term_bg = self.theme.editor_bg();
for (i, t) in self.terminals.iter_mut().enumerate() {
// A collapsed pane is not rendered, and that is what
// keeps its shell intact: rendering is what resizes
// the PTY, and reflowing a running shell into one
// column would mangle everything already on its
// screen. It keeps the geometry it had, so expanding
// brings the pane back as it was rather than as a
// column of broken wrapping. Its `last_area` is
// cleared so a click on the strip cannot land in a
// grid that is no longer painted there.
if cols[i].width == 0 || (t.collapsed && !maximized) {
t.last_area = Rect::default();
// `last_inner` too (#510): it anchors the image
// overlay's raw CUP write, so a stale rect sends
// the payload outside the pane with nothing to
// catch it. The other terminal-pane clears below
// need no counterpart - the overlay returns early
// when the panel is hidden or off the Terminal
// tab, which is what makes them unreachable for
// it. A consumer that drops that guard inherits
// this obligation.
t.last_inner = Rect::default();
t.redacted_on_screen = 0;
} else {
frame.render_widget(
ratatui::widgets::Block::default()
.style(Style::default().bg(term_bg)),
cols[i],
);
frame.render_widget(t, cols[i]);
}
}
let show_close = multi;
self.terminal_add_buttons.clear();
self.terminal_profile_buttons.clear();
self.terminal_close_buttons.clear();
self.terminal_max_buttons.clear();
self.terminal_label_rects.clear();
self.terminal_collapse_buttons.clear();
self.terminal_strip_rects.clear();
for (i, col) in cols.iter().enumerate().take(self.terminals.len()) {
// Hidden panes still push placeholders so a button's
// position in each vec names its terminal index.
if col.width == 0 {
self.terminal_add_buttons.push(Rect::default());
self.terminal_profile_buttons.push(Rect::default());
self.terminal_close_buttons.push(Rect::default());
self.terminal_max_buttons.push(Rect::default());
self.terminal_label_rects.push(Rect::default());
self.terminal_collapse_buttons.push(Rect::default());
self.terminal_strip_rects.push(Rect::default());
continue;
}
// A collapsed pane's whole chrome is its strip: no
// header buttons fit in one column, and the only
// gesture it offers is the way back out.
if self.terminals[i].collapsed && !maximized {
let strip = self.paint_terminal_collapsed_strip(frame, *col, i);
self.terminal_add_buttons.push(Rect::default());
self.terminal_profile_buttons.push(Rect::default());
self.terminal_close_buttons.push(Rect::default());
self.terminal_max_buttons.push(Rect::default());
self.terminal_label_rects.push(Rect::default());
self.terminal_collapse_buttons.push(Rect::default());
self.terminal_strip_rects.push(strip);
continue;
}
self.terminal_strip_rects.push(Rect::default());
let buttons = paint_terminal_pane_buttons(
frame,
*col,
show_close,
maximized,
self.theme,
self.pointer_cell,
);
self.terminal_add_buttons
.push(buttons.add.unwrap_or_default());
self.terminal_profile_buttons
.push(buttons.profile.unwrap_or_default());
self.terminal_close_buttons
.push(buttons.close.unwrap_or_default());
self.terminal_max_buttons
.push(buttons.max.unwrap_or_default());
self.terminal_collapse_buttons
.push(buttons.collapse.unwrap_or_default());
// Auto/manual pane label at top-left, only with 2+ panes
// (a lone pane needs no name). Kept clear of the buttons.
// The painted pill doubles as the drag-reorder handle,
// so its rect is recorded index-aligned with the pane.
let mut label_rect = Rect::default();
if multi {
let label = self.terminals[i].label().to_string();
// The pill is painted AFTER the header buttons and
// wins the shared cells, so its budget has to
// clear the button strip plus the pill's own
// widest decoration (a leading `⚠` or `⇶` and the
// two spaces every pill carries).
let room =
col.width.saturating_sub(TERMINAL_BUTTON_STRIP_W + 4) as usize;
// While broadcast input is on, every pane that
// receives the mirrored keystrokes wears an
// unmissable red pill with a ⇶ marker
// (Terminator's role colouring); excluded panes
// keep the normal pill. The marker paints even
// while the pane's auto-label is still empty.
let receiving = self.broadcast_input
&& (i == self.active_terminal
|| !self.terminals[i].broadcast_excluded);
// An agent pane wears its badge in the pill
// (`◆ claude ◐`, #344); the badge takes the room
// first and the label is clipped to what is left.
let badge = self.terminals[i]
.agent()
.map(|a| format!("\u{25c6} {} {}", a.name, a.status.glyph()));
let label = match &badge {
Some(b) if label.is_empty() => b.clone(),
Some(b) => format!("{b} {label}"),
None => label,
};
if (!label.is_empty() || receiving) && room >= 3 {
let shown: String = label.chars().take(room).collect();
let mut text = if receiving && shown.is_empty() {
String::from(" \u{21f6} ")
} else if receiving {
format!(" \u{21f6} {shown} ")
} else {
format!(" {shown} ")
};
// A live OSC 9;4 percent joins the pill (the
// border gauge is the primary drawing; this
// keeps unfocused panes glanceable). The
// indeterminate state has no number to show.
if let Some((state, pct)) = self.terminals[i].progress()
&& state != 3
&& text.chars().count() + 6 <= room
{
text = format!("{}\u{b7} {pct}% ", text);
}
let accent = self.terminals[i].accent;
let text = if accent.is_some() && !receiving {
format!(" \u{26a0}{text}")
} else {
text
};
let style = if receiving {
Style::default()
.fg(Color::Black)
.bg(self.theme.ui(Color::Rgb(0xe7, 0x70, 0x70)))
.add_modifier(Modifier::BOLD)
} else if let Some((r, g, b)) = accent {
Style::default()
.fg(Color::Black)
.bg(Color::Rgb(r, g, b))
.add_modifier(Modifier::BOLD)
} else {
crate::widgets::header_pill::action_style(self.theme, false)
};
// `room` bounds how much of the name is worth
// showing, but it counts CHARACTERS while the
// buffer advances by display CELLS, so a CJK
// or emoji name is twice as wide as its budget
// and would still reach the buttons. Clip the
// paint to the cells before the button strip —
// `set_stringn` measures grapheme width, which
// is the same clamp the rail rows use — and
// take the drag handle's width from what was
// actually painted.
let budget =
col.width.saturating_sub(TERMINAL_BUTTON_STRIP_W) as usize;
let (end_x, _) = frame
.buffer_mut()
.set_stringn(col.x, col.y, text, budget, style);
label_rect = Rect {
x: col.x,
y: col.y,
width: end_x.saturating_sub(col.x),
height: 1,
};
}
}
self.terminal_label_rects.push(label_rect);
}
}
BottomPanelTab::Problems => {
// The terminals are hidden behind the PROBLEMS view; drop
// their hit rects so a click never phantom-matches a pane
// that isn't painted (mirrors the hidden-panel reset).
self.terminal_add_buttons.clear();
self.terminal_profile_buttons.clear();
self.terminal_close_buttons.clear();
self.terminal_max_buttons.clear();
self.terminal_label_rects.clear();
self.terminal_collapse_buttons.clear();
self.terminal_strip_rects.clear();
self.clear_terminal_rail();
for t in self.terminals.iter_mut() {
t.last_area = Rect::default();
t.redacted_on_screen = 0;
}
frame.render_widget(&mut self.problems, content);
}
BottomPanelTab::Output => {
// Same hidden-terminal reset as PROBLEMS: the OUTPUT view
// covers the panes, so their hit rects must not linger.
self.terminal_add_buttons.clear();
self.terminal_profile_buttons.clear();
self.terminal_close_buttons.clear();
self.terminal_max_buttons.clear();
self.terminal_label_rects.clear();
self.terminal_collapse_buttons.clear();
self.terminal_strip_rects.clear();
self.clear_terminal_rail();
for t in self.terminals.iter_mut() {
t.last_area = Rect::default();
t.redacted_on_screen = 0;
}
frame.render_widget(&mut self.output, content);
}
BottomPanelTab::Ports => {
// Same hidden-terminal reset: the PORTS view covers the
// panes, so their hit rects must not linger.
self.terminal_add_buttons.clear();
self.terminal_profile_buttons.clear();
self.terminal_close_buttons.clear();
self.terminal_max_buttons.clear();
self.terminal_label_rects.clear();
self.terminal_collapse_buttons.clear();
self.terminal_strip_rects.clear();
self.clear_terminal_rail();
for t in self.terminals.iter_mut() {
t.last_area = Rect::default();
t.redacted_on_screen = 0;
}
frame.render_widget(&mut self.ports, content);
}
BottomPanelTab::Captures => {
// Same hidden-terminal reset as the PORTS arm above.
self.terminal_add_buttons.clear();
self.terminal_profile_buttons.clear();
self.terminal_close_buttons.clear();
self.terminal_max_buttons.clear();
self.terminal_label_rects.clear();
self.terminal_collapse_buttons.clear();
self.terminal_strip_rects.clear();
self.clear_terminal_rail();
for t in self.terminals.iter_mut() {
t.last_area = Rect::default();
t.redacted_on_screen = 0;
}
frame.render_widget(&mut self.captures, content);
}
}
} else {
self.terminal_add_buttons.clear();
self.terminal_profile_buttons.clear();
self.terminal_close_buttons.clear();
self.terminal_max_buttons.clear();
self.terminal_label_rects.clear();
self.terminal_collapse_buttons.clear();
self.terminal_strip_rects.clear();
self.clear_terminal_rail();
self.problems_tab_rect = Rect::default();
self.output_tab_rect = Rect::default();
self.ports_tab_rect = Rect::default();
self.captures_tab_rect = Rect::default();
self.terminal_tab_rect = Rect::default();
// A hidden terminal must not keep stale hit rects alive, or
// `terminal_at_pos` would phantom-match clicks meant for
// whatever now occupies those cells (mirrors the SYSTEM
// panel's hidden-state reset).
for t in self.terminals.iter_mut() {
t.last_area = Rect::default();
t.redacted_on_screen = 0;
}
}
// Owned snapshot: the spans borrow the status, and borrowing it
// through scm_worker() would pin all of &self for the whole render.
let scm_status = self.scm_worker().status().clone();
let mut spans: Vec<Span> = Vec::with_capacity(20);
spans.extend(brand_spans(self.theme));
let redacted = self.redacted_on_screen();
if redacted > 0 || self.redactions_revealed() {
// How much of what is on screen is masked right now (#360): a
// screen-share host wants to know the count is non-zero, and
// that a reveal window is open.
let (label, bg) = if self.redactions_revealed() {
(
format!(" \u{1f441} {redacted} revealed "),
Color::Rgb(0xc0, 0x39, 0x2b),
)
} else {
(
format!(" \u{2022} {redacted} redacted "),
Color::Rgb(0x3a, 0x3f, 0x4b),
)
};
spans.push(Span::styled(
label,
Style::default()
.bg(self.theme.ui(bg))
.fg(Color::White)
.add_modifier(Modifier::BOLD),
));
}
if let Some(span) = self.perf.status_span() {
spans.push(span);
}
if self.any_update_ready() {
spans.push(Span::styled(
" ⟳ Update ready - F9 to relaunch ",
Style::default()
.bg(self.theme.ui(Color::Rgb(0x1f, 0x7a, 0x33)))
.fg(Color::White)
.add_modifier(Modifier::BOLD),
));
}
if let Some(current) = self.local_drift.as_ref()
&& self.update_status == UpdateStatus::Idle
&& self.self_install.is_none()
// The same latch as `f9_update_armed`: while the staged release
// builds, F9 is not a rebuild, so the hint must not say so.
&& self.staged_status != UpdateStatus::InProgress
&& self.staged_install.is_none()
{
// Amber, persistent: the binary predates its own source tree
// (#242). One keypress rebuilds it in the background.
spans.push(Span::styled(
format!(
" ⟳ croft {} < repo {current} - F9 to rebuild ",
env!("CROFT_GIT_HASH")
),
Style::default()
.bg(self.theme.ui(Color::Rgb(0x8a, 0x60, 0x00)))
.fg(Color::White)
.add_modifier(Modifier::BOLD),
));
}
if self.any_update_in_progress() {
// Red + a spinning circular-arrow glyph to draw the eye to the
// in-progress background update.
spans.push(Span::styled(
format!(
" {} Updating croft in the background ",
self.update_spinner_glyph()
),
Style::default()
.fg(self.theme.ui(Color::Rgb(0xff, 0x45, 0x4d)))
.add_modifier(Modifier::BOLD),
));
}
if let Some(progress) = self.lsp_progress_status() {
// A busy language server (rust-analyzer priming its crate graph,
// etc.) is otherwise invisible: hover/completion just return empty
// until it finishes. Surfacing "rust-analyzer: Indexing " tells
// the user to wait rather than assume the server is dead.
spans.push(Span::styled(
format!(" ⟳ {progress} "),
Style::default()
.fg(self.theme.ui(Color::Rgb(0x4e, 0x9a, 0xff)))
.add_modifier(Modifier::BOLD),
));
}
if let Some(label) = &self.mcp_busy_label {
// An in-flight extension command (install + tool call on a worker
// thread) is otherwise invisible; an animated badge says it's working.
spans.push(Span::styled(
format!(" {} {label} ", self.mcp_spinner_glyph()),
Style::default()
.fg(self.theme.ui(Color::Rgb(0x2d, 0xd4, 0xbf)))
.add_modifier(Modifier::BOLD),
));
}
if let Some(rec) = &self.macro_recording {
// Recording is state a user can forget they left on, so it gets a
// filled red badge rather than a dim hint (#255). A named register
// shows which one, since vim users keep several.
let label = match rec.register {
Some(r) => format!(" ● REC @{r} "),
None => String::from(" ● REC "),
};
spans.push(Span::styled(
label,
Style::default()
.bg(self.theme.ui(Color::Rgb(0xc0, 0x2b, 0x2b)))
.fg(Color::White)
.add_modifier(Modifier::BOLD),
));
spans.push(Span::raw(" "));
}
if self.vim.enabled {
let (text, bg) = match self.vim.command_line() {
Some(cmd) => (
format!(" {cmd} "),
self.theme.ui(Color::Rgb(0x33, 0x33, 0x33)),
),
None => {
let label = self.vim.mode_label().unwrap_or("NORMAL");
let bg = match self.vim.mode() {
crate::vim::VimMode::Insert => self.theme.ui(Color::Rgb(0x1f, 0x7a, 0x33)),
crate::vim::VimMode::Visual | crate::vim::VimMode::VisualLine => {
self.theme.ui(Color::Rgb(0x8a, 0x4f, 0xbf))
}
_ => self.theme.ui(Color::Rgb(0x4e, 0x9a, 0xff)),
};
(format!(" {label} "), bg)
}
};
spans.push(Span::styled(
text,
Style::default()
.bg(bg)
.fg(Color::White)
.add_modifier(Modifier::BOLD),
));
spans.push(Span::raw(" "));
}
// Hairline zone divider (│): fences the brand/git zone, the
// diagnostics cluster, and the transient message off from each other
// so the bar reads as segments instead of one run of text. Quiet on
// both the navy and near-black bars.
let zone_div = Style::default().fg(self.theme.ui(Color::Rgb(0x3a, 0x41, 0x50)));
let scm_spans = git_status_spans(&scm_status);
// The wordmark already ends in a space; the git spans don't, so buy
// the divider one cell of air only when the branch segment painted.
let scm_present = !scm_spans.is_empty();
spans.extend(scm_spans);
spans.push(Span::styled(
if scm_present { " \u{2502}" } else { "\u{2502}" },
zone_div,
));
// Persistent orange badge for a remote session with no dtach: it can't
// survive a transport drop, so flag it for the whole session (rendered
// before the transient status so a status update never hides it).
if let Some(warning) = self.persistence_warning {
spans.push(Span::styled(
format!(" \u{26a0} {warning} "),
Style::default()
.bg(self.theme.ui(Color::Rgb(0xff, 0x9d, 0x2f)))
.fg(self.theme.ui(Color::Rgb(0x10, 0x13, 0x1a)))
.add_modifier(Modifier::BOLD),
));
spans.push(Span::raw(" "));
}
// Multiplayer roster badge: how many clients are attached to this
// persistent session, painted only when someone else is here
// (manage them via Session: Participants, Cmd+K A).
if self.session_participants.len() > 1 {
spans.push(Span::styled(
format!(" \u{f0c0} {} attached ", self.session_participants.len()),
Style::default()
.bg(self.theme.ui(Color::Rgb(0x2f, 0x6f, 0xd0)))
.fg(self.theme.ui(Color::Rgb(0xff, 0xff, 0xff)))
.add_modifier(Modifier::BOLD),
));
spans.push(Span::raw(" "));
}
// AI-stream badge: a pilot is streaming an edit into a shared file;
// orange like the persistence warning (attention, not decoration),
// naming the cancel chord so the stop path is one glance away.
if let Some(stream) = &self.collab_stream {
spans.push(Span::styled(
format!(
" \u{23f9} {} streaming into {} (Cmd+K X to stop) ",
stream.name, stream.file
),
Style::default()
.bg(self.theme.ui(Color::Rgb(0xff, 0x9d, 0x2f)))
.fg(self.theme.ui(Color::Rgb(0x10, 0x13, 0x1a)))
.add_modifier(Modifier::BOLD),
));
spans.push(Span::raw(" "));
} else if let Some(host) = &self.pair_host {
// Resident navigator seated and idle: presence, not attention —
// the stream badge above takes over whenever it is typing.
spans.push(Span::styled(
format!(" \u{25c6} {} seated ", host.title()),
Style::default()
.bg(self.theme.ui(Color::Rgb(0x3c, 0x41, 0x4f)))
.fg(self.theme.ui(Color::Rgb(0xff, 0x9d, 0x2f)))
.add_modifier(Modifier::BOLD),
));
spans.push(Span::raw(" "));
}
// Diagnostics counts (click → PROBLEMS), VS Code-style, after git.
// Always shown so the bar reads as a health indicator at a glance.
let err_count = self.problems.error_count();
let warn_count = self.problems.warning_count();
let diag_start_col: u16 = spans.iter().map(|s| s.content.chars().count() as u16).sum();
// One cell between the counts, not three: the errors and warnings
// read as a single health cluster (they already share one hit rect).
// diag_len is measured from the very strings that render, so the hit
// rect can never drift from the visible text.
let err_text = format!(" \u{ea87} {err_count}");
let warn_text = format!(" \u{ea6c} {warn_count} ");
let diag_len = (err_text.chars().count() + warn_text.chars().count()) as u16;
spans.push(Span::styled(
err_text,
Style::default().fg(self.theme.ui(Color::Rgb(0xf1, 0x4c, 0x4c))),
));
spans.push(Span::styled(
warn_text,
Style::default().fg(self.theme.ui(Color::Rgb(0xcc, 0xa7, 0x00))),
));
// Transient status message (e.g. "Saved editor.rs"), no keybinding
// cheat-sheet — those live in F1 / the Command Palette now. Fenced
// behind a divider and dimmed so commentary reads apart from the
// clickable clusters around it.
if !self.status.is_empty() {
spans.push(Span::styled("\u{2502} ", zone_div));
spans.push(Span::styled(
self.status.clone(),
Style::default().fg(self.theme.ui(Color::Rgb(0x9a, 0xa4, 0xb8))),
));
}
if let Some(osk) = self.osk.as_mut() {
if osk_h > 0 {
crate::widgets::osk::render_osk(osk, outer[1], frame.buffer_mut(), self.theme);
} else {
// Collapsed (frame too short): zero the hit rect so the
// invisible band can't swallow clicks.
osk.last_area = Rect::default();
}
}
let status_rect = outer[2];
// The F1 cheat-sheet is gone; F1 / the palette still open Shortcuts.
self.shortcuts_hit_rect = None;
// Diagnostics hit rect (left group), for click-to-PROBLEMS.
self.status_diag_rect = if status_h > 0 {
Rect {
x: status_rect.x.saturating_add(diag_start_col),
y: status_rect.y,
width: diag_len.min(status_rect.width.saturating_sub(diag_start_col)),
height: 1,
}
} else {
Rect::default()
};
// ---- Right cluster: document facts, right-justified. Indentation /
// encoding / EOL / language are clickable to change (hit rects recorded
// below). A hairline │ marks each seam so the segments read as
// separate controls, one shade brighter than the transient message so
// controls and commentary stop sharing a costume; the clickable ones
// take a hover fill under the pointer (spans are built after `rx` is
// known, below, so hover can be computed against this frame's rects).
let mut seg_texts: Vec<String> = vec![
format!(
" Ln {}, Col {} ",
self.editor.cursor_row + 1,
self.editor.cursor_col + 1
),
format!(" {} ", self.editor.indent_style().label()),
format!(" {} ", self.editor.encoding.name()),
format!(" {} ", self.editor.eol.label()),
format!(" {} ", self.editor.language_label()),
];
// `2 agents · 1 waiting` (#344), only while an agent is seated; a
// click focuses the waiting pane.
let (seated, waiting) = self.agent_counts();
// The review queue rides the same chip (#345): a file an agent
// changed while you were looking elsewhere is the thing you most
// need to be told about, and it outlives the agent's own pane.
// The set the Explorer is drawing, not a fresh count off the ledger:
// this is the per-frame render path, and `unreviewed_files` clones
// every path to build a set it then throws away. Reading the cache
// also makes the chip and the dots the SAME number by construction
// rather than by two code paths agreeing.
let unreviewed = self.tree.agent_touched.len();
if seated > 0 || unreviewed > 0 {
// With nothing seated the agent half would read "0 agents",
// which is not what the chip is reporting any more: the queue
// outlives the pane, so the chip becomes the queue's.
let agents_part = if seated > 0 {
format!(
"{seated} agent{}{}",
if seated == 1 { "" } else { "s" },
if waiting > 0 {
format!(" \u{b7} {waiting} waiting")
} else {
String::new()
}
)
} else {
String::new()
};
let review_part = if unreviewed > 0 {
// A "+" when the watcher dropped events: the count is a
// floor, and a bare number would read as a total.
format!(
"{unreviewed}{} to review",
if self.agent_ledger.may_be_incomplete() {
"+"
} else {
""
}
)
} else {
String::new()
};
let joined = match (agents_part.is_empty(), review_part.is_empty()) {
(false, false) => format!("{agents_part} \u{b7} {review_part}"),
(false, true) => agents_part,
_ => review_part,
};
seg_texts.push(format!(" \u{25c6} {joined} "));
}
let widths: Vec<u16> = seg_texts.iter().map(|s| s.chars().count() as u16).collect();
let right_total: u16 = widths.iter().sum::<u16>() + (seg_texts.len() as u16 - 1);
// The right cluster paints OVER the left paragraph, so an over-long
// transient loses exactly its tail — for "Opened <deep path>" that
// was the filename, the one informative part (#100). Middle-elide
// the transient (always the last span) into the room that survives.
if !self.status.is_empty() {
let left_fixed: u16 = spans
.iter()
.take(spans.len().saturating_sub(1))
.map(|s| s.content.chars().count() as u16)
.sum();
let avail = status_rect
.width
.saturating_sub(right_total)
.saturating_sub(left_fixed)
.saturating_sub(1);
if let Some(last) = spans.last_mut()
&& last.content.chars().count() as u16 > avail
{
// Keep the message's dim style through the elision so a
// truncated transient doesn't suddenly brighten.
*last = Span::styled(elide_middle(&self.status, avail as usize), last.style);
}
}
// Black theme: drop the navy status strip to a near-black seam (a hair
// lighter than the #000000 editor so the bar still reads as distinct),
// matching VS Code's OLED themes. Croft Dark keeps the navy band.
let status_bg = if self.popup_gradient() {
self.theme.ui(Color::Rgb(0x18, 0x18, 0x18))
} else {
self.theme.ui(Color::Rgb(0x1e, 0x3a, 0x6e))
};
// Left fills the whole bar (background + left text); the right cluster
// overwrites the right portion.
frame.render_widget(
Paragraph::new(Line::from(spans)).style(Style::default().bg(status_bg)),
status_rect,
);
// Reset clickable rects; re-record only when the right cluster fits.
self.status_indent_rect = Rect::default();
self.status_encoding_rect = Rect::default();
self.status_eol_rect = Rect::default();
self.status_language_rect = Rect::default();
self.status_agents_rect = Rect::default();
if status_h > 0 && right_total > 0 && right_total <= status_rect.width {
let rx = status_rect.right() - right_total;
// The right cluster paints OVER the left paragraph, so the
// diagnostics hit rect must stop where it starts. Clipped only to
// the frame edge, it went on answering for cells that now read
// "Ln 1, Col 1" — opening PROBLEMS from a click on the position
// readout, with the counts it claimed not even on screen.
if self.status_diag_rect.x >= rx {
// Entirely behind the cluster: not on screen, so not a target.
self.status_diag_rect = Rect::default();
} else if self.status_diag_rect.right() > rx {
self.status_diag_rect.width = rx - self.status_diag_rect.x;
}
// Build the spans now that x positions are known: segment fg one
// shade up from the transient's dim gray, │ dividers between, and
// a hover fill on the clickable segments (indices 1..=5) when the
// pointer rests on them — same affordance as the activity bar.
// Ln/Col (index 0) is a readout, not a control, so it never
// hovers. Hit rects recorded in the same pass.
let seg_style = Style::default().fg(self.theme.ui(Color::Rgb(0xc9, 0xd2, 0xe3)));
let hover_style = Style::default()
.bg(self.theme.ui(Color::Rgb(0x2a, 0x31, 0x40)))
.fg(self.theme.ui(Color::White));
let mut right: Vec<Span> = Vec::with_capacity(seg_texts.len() * 2 - 1);
let mut cx = rx;
for (i, text) in seg_texts.iter().enumerate() {
if i > 0 {
right.push(Span::styled("\u{2502}", zone_div));
cx = cx.saturating_add(1);
}
let r = Rect {
x: cx,
y: status_rect.y,
width: widths[i],
height: 1,
};
let hovered = i > 0
&& self
.pointer_cell
.is_some_and(|(pc, pr)| rect_contains(r, pc, pr));
right.push(Span::styled(
text.clone(),
if hovered { hover_style } else { seg_style },
));
match i {
1 => self.status_indent_rect = r,
2 => self.status_encoding_rect = r,
3 => self.status_eol_rect = r,
4 => self.status_language_rect = r,
5 => self.status_agents_rect = r,
_ => {}
}
cx = cx.saturating_add(widths[i]);
}
frame.render_widget(
Paragraph::new(Line::from(right)).style(Style::default().bg(status_bg)),
Rect {
x: rx,
y: status_rect.y,
width: right_total,
height: status_rect.height,
},
);
}
// Overlays render last so they sit on top of everything else. The port
// toast goes first so modals/menus paint above it.
//
// The hover note popup (editor symbol hover / terminal annotation
// note) renders here against the WHOLE frame, not the editor's
// focused_area: its anchor may sit in the terminal panel, and the
// welcome screen skips the editor-tabs branch entirely, which used to
// drop a terminal annotation's note without painting it at all.
if let Some(popup) = self.peek_popup.as_mut() {
popup.theme = self.theme;
let area = popup.area_for(frame.area());
if area.width > 0 && area.height > 0 {
frame.render_widget(&*popup, area);
}
}
if let Some(popup) = self.hover_popup.as_mut() {
popup.theme = self.theme;
let area = popup.area_for(frame.area());
if area.width > 0 && area.height > 0 {
frame.render_widget(&*popup, area);
}
}
self.render_port_toast(frame);
self.render_update_toast(frame);
self.render_context_menu(frame);
self.render_commit_dropdown(frame);
self.render_prompt(frame);
self.render_local_open_confirm(frame);
self.render_discard_confirm(frame);
self.render_revert_hunk_confirm(frame);
self.render_discard_all_confirm(frame);
self.render_replace_all_confirm(frame);
self.render_broadcast_confirm(frame);
self.render_run_block_confirm(frame);
// Terminal-pane inline image: sync after the panes have painted so
// last_inner and the scroll offset are this frame's (all gating —
// hidden panel, alt screen, off-screen anchor — is inside).
self.update_terminal_image_overlay();
self.update_markdown_image_overlay();
self.render_editor_find(frame);
self.render_terminal_find(frame);
self.render_file_finder(frame);
self.render_command_palette(frame);
self.render_go_to_symbol(frame);
self.render_workspace_symbols(frame);
self.render_process_picker(frame);
self.render_zoxide_jump(frame);
self.render_command_history_popup(frame);
self.render_branch_picker(frame);
self.render_scm_menu(frame);
self.render_input_prompt(frame);
self.render_list_picker(frame);
self.render_shortcuts_modal(frame);
self.render_connect_dialog(frame);
// The startup unsupported-terminal nudge renders last so it sits above
// every other overlay until the user dismisses it.
self.render_terminal_warning(frame);
// Chrome button-hint tooltip. Rendered at the top level against the
// whole frame (not the editor's `focused_area`) because the controls it
// labels live in the activity bar and sidebar, outside the editor pane;
// clamping it to the editor area would yank it away from the control or,
// on the welcome screen, drop it entirely.
let mut tooltip_area = None;
if let Some(popup) = self.ui_tooltip.as_mut() {
popup.theme = self.theme;
let full = frame.area();
let mut area = popup.area_for(full);
// Keep the box clear of the activity bar's inline-image column. Those
// codicon glyphs are a terminal graphics layer that always composites
// ABOVE text cells, so any overlap would paint over (hide) the left of
// the tooltip. Shift it to the right of the bar instead, like VS Code
// floats an activity-icon hint beside the icon.
if area.x < ACTIVITY_BAR_WIDTH {
area.x = ACTIVITY_BAR_WIDTH;
area.width = area.width.min(full.width.saturating_sub(area.x));
}
if area.width > 0 && area.height > 0 {
frame.render_widget(&*popup, area);
tooltip_area = Some(area);
}
}
// Record the box so the post-draw flush can RE-PAINT it on top of any
// sidebar OSC-1337 illustration (the no-repo hero / SSH empty-state).
// Those images are emitted after ratatui's text and would otherwise
// composite over the tooltip; re-emitting the box last wins the cell.
self.ui_tooltip_area = tooltip_area;
// Show the host terminal's hardware caret only when the editor is
// focused and has no modal overlay. The DECSCUSR style is set to
// BlinkingBar at startup, so the terminal blinks a thin vertical
// line over the cursor cell without replacing its character.
if self.focus == Pane::Editor
&& self.context_menu.is_none()
&& self.prompt.is_none()
&& self.cursor_visible_phase()
{
let pos = if self.editor.diff.is_some() {
self.editor.diff_caret_screen_pos()
} else {
self.editor.cursor_screen_pos()
};
if let Some((cx, cy)) = pos {
frame.set_cursor_position((cx, cy));
}
}
// Source-control commit-message caret. Same software-blink rule:
// the user can't see where they're typing in the message box
// without a visible caret, since `set_string` just lays the text
// flat with no native caret cell.
if self.focus == Pane::Tree
&& self.sidebar_view == SidebarView::SourceControl
&& self.context_menu.is_none()
&& self.prompt.is_none()
&& self.cursor_visible_phase()
&& let Some((cx, cy)) = self.source_control.cursor_screen_pos()
{
frame.set_cursor_position((cx, cy));
}
// Search-panel field caret and Extensions filter caret. Same software
// blink as the commit box so all three side-panel inputs share one
// blinking hardware caret instead of a static block (Search) or no
// caret at all (Extensions).
if self.focus == Pane::Tree
&& self.sidebar_view == SidebarView::Search
&& self.context_menu.is_none()
&& self.prompt.is_none()
&& self.cursor_visible_phase()
&& let Some((cx, cy)) = self.search.cursor_screen_pos()
{
frame.set_cursor_position((cx, cy));
}
if self.focus == Pane::Tree
&& self.sidebar_view == SidebarView::Extensions
&& self.context_menu.is_none()
&& self.prompt.is_none()
&& self.cursor_visible_phase()
&& let Some((cx, cy)) = self.extensions.cursor_screen_pos()
{
frame.set_cursor_position((cx, cy));
}
}
fn render_context_menu(&self, frame: &mut ratatui::Frame) {
let Some(menu) = &self.context_menu else {
return;
};
// `menu_rect` already clamps against `last_frame_area`, so the
// rect we draw here is the same rect `menu_item_at` hit-tests
// against. Keeping the two in lock-step is what prevents the
// off-by-N row dispatch when the menu has to shift up to fit.
let Some(clipped) = self.menu_rect() else {
return;
};
let grad = self.popup_gradient();
// The top-level panel; the open submenu's parent row stays highlighted.
self.render_menu_panel(frame, clipped, &menu.items, menu.selected, grad);
// Float the open submenu's panel beside its parent.
if let Some(sub_rect) = self.submenu_rect()
&& let Some(MenuEntry::Submenu { items, .. }) =
menu.open_submenu.and_then(|p| menu.items.get(p))
{
self.render_menu_panel(frame, sub_rect, items, menu.submenu_selected, grad);
}
}
/// Paint one bordered menu panel of `entries` into `rect`, highlighting row
/// `selected`. Items show a right-aligned shortcut hint, submenu parents a
/// `▸`, and separators a divider rule. Shared by the main menu and the
/// floating submenu.
fn render_menu_panel(
&self,
frame: &mut ratatui::Frame,
rect: Rect,
entries: &[MenuEntry],
selected: usize,
grad: bool,
) {
// Black theme: orange→green gradient border + muted dark-teal
// selection. Croft Dark keeps the legacy bright-blue accent so the
// menu stays coherent with that theme's blue focus border.
let border_blue = self.theme.ui(Color::Rgb(0x4e, 0x9a, 0xff));
let block = ratatui::widgets::Block::default()
.borders(ratatui::widgets::Borders::ALL)
.border_style(Style::default().fg(border_blue))
.style(Style::default().bg(self.theme.ui(Color::Rgb(0x1e, 0x1e, 0x1e))));
frame.render_widget(ratatui::widgets::Clear, rect);
frame.render_widget(block, rect);
if grad {
paint_gradient_box(frame.buffer_mut(), rect);
}
let sel_bg = if grad {
rgb_color(POPUP_SEL_BG)
} else {
border_blue
};
let sel_fg = if grad { Color::White } else { Color::Black };
let inner = Rect {
x: rect.x + 1,
y: rect.y + 1,
width: rect.width.saturating_sub(2),
height: rect.height.saturating_sub(2),
};
for (i, entry) in entries.iter().enumerate() {
if i as u16 >= inner.height {
break;
}
let row = Rect {
x: inner.x,
y: inner.y + i as u16,
width: inner.width,
height: 1,
};
if let MenuEntry::Separator = entry {
let rule = "\u{2500}".repeat(inner.width as usize);
frame.buffer_mut().set_string(
inner.x,
row.y,
&rule,
Style::default().fg(self.theme.ui(Color::Rgb(0x45, 0x45, 0x45))),
);
continue;
}
if let MenuEntry::Header(label) = entry {
// Dimmed, non-selectable section label (VS Code's group titles
// like "Side Bar Position").
frame.buffer_mut().set_string(
inner.x,
row.y,
format!(" {label}"),
Style::default()
.fg(self.theme.ui(Color::Rgb(0x7a, 0x82, 0x90)))
.add_modifier(Modifier::BOLD),
);
continue;
}
let is_sel = i == selected;
let row_style = if is_sel {
Style::default().fg(sel_fg).bg(sel_bg)
} else {
Style::default().fg(self.theme.ui(Color::White))
};
let (label, right_hint) = match entry {
MenuEntry::Item { label, action } => {
(label.as_str(), shortcut_for(action).map(str::to_string))
}
// A submenu parent shows the ▸ where a shortcut would sit.
MenuEntry::Submenu { label, .. } => {
(label.as_str(), Some(String::from("\u{25b8}")))
}
MenuEntry::Separator | MenuEntry::Header(_) => {
unreachable!("handled above")
}
};
let line = ratatui::text::Line::from(format!(" {label}"));
frame.render_widget(ratatui::widgets::Paragraph::new(line).style(row_style), row);
if let Some(hint) = right_hint {
let hint_w = hint.chars().count() as u16;
if hint_w + 2 <= inner.width {
let hint_x = inner.x + inner.width - hint_w - 1;
let hint_style = if is_sel {
Style::default().fg(sel_fg).bg(sel_bg)
} else {
Style::default().fg(self.theme.ui(Color::Rgb(0x9d, 0xa5, 0xb4)))
};
frame
.buffer_mut()
.set_string(hint_x, row.y, &hint, hint_style);
}
}
}
}
fn render_commit_dropdown(&mut self, frame: &mut ratatui::Frame) {
use crate::widgets::source_control::CommitMenuItem;
// The dropdown belongs to the Source Control view only. Gate on it
// so a stale `commit_menu_open` flag can never paint the menu over
// another sidebar view (e.g. Run-Debug) after a view switch.
if !self.commit_menu_open || self.sidebar_view != SidebarView::SourceControl {
self.source_control.commit_menu_item_areas.clear();
return;
}
let caret = self.source_control.last_commit_caret_area;
let main = self.source_control.last_button_area;
if caret.width == 0 || main.width == 0 {
return;
}
let default_branch = self
.default_branch_label
.clone()
.unwrap_or_else(|| "default".to_string());
let items: Vec<(CommitMenuItem, String)> = CommitMenuItem::ALL
.iter()
.map(|item| (*item, item.label(&default_branch)))
.collect();
// Row layout: [pad][icon][gap][label][pad]. The icon occupies one
// cell at item_x+1; the label starts two cells later at item_x+3.
const ICON_PAD: u16 = 3;
let label_w = items
.iter()
.map(|(_, l)| l.chars().count() as u16 + ICON_PAD + 1)
.max()
.unwrap_or(0);
let item_w: u16 = label_w.max(caret.width);
let item_x = (caret.x + caret.width).saturating_sub(item_w).max(main.x);
let item_y_top = caret.y + caret.height;
let menu_rect = Rect {
x: item_x,
y: item_y_top,
width: item_w,
height: items.len() as u16,
};
let bg = self.theme.ui(Color::Rgb(0x25, 0x2b, 0x37));
let fg = self.theme.ui(Color::White);
let style = Style::default().fg(fg).bg(bg);
frame.render_widget(ratatui::widgets::Clear, menu_rect);
self.source_control.commit_menu_item_areas.clear();
for (i, (item, label)) in items.into_iter().enumerate() {
let row_y = item_y_top + i as u16;
let row_rect = Rect {
x: item_x,
y: row_y,
width: item_w,
height: 1,
};
for rx in 0..row_rect.width {
frame.buffer_mut()[(row_rect.x + rx, row_rect.y)]
.set_symbol(" ")
.set_style(style);
}
// Leading codicon, colored per action: push glyphs in blue,
// diff/compare glyphs in purple, mirroring VS Code's SCM accents.
let icon_color = match item {
CommitMenuItem::CommitAndPush => self.theme.ui(Color::Rgb(0x9a, 0xa4, 0xb2)),
CommitMenuItem::Push | CommitMenuItem::Pull | CommitMenuItem::Sync => {
self.theme.ui(Color::Rgb(0x6c, 0xb6, 0xff))
}
CommitMenuItem::CheckoutBranch => self.theme.ui(Color::Rgb(0x88, 0xc0, 0xd0)),
CommitMenuItem::Stash | CommitMenuItem::StashPop => {
self.theme.ui(Color::Rgb(0xeb, 0xcb, 0x8b))
}
CommitMenuItem::ViewStagedDiff
| CommitMenuItem::ViewPreviousCommitDiff
| CommitMenuItem::ViewDefaultBranchDiff => {
self.theme.ui(Color::Rgb(0xc0, 0xa4, 0xf5))
}
};
frame.buffer_mut().set_string(
row_rect.x + 1,
row_rect.y,
item.icon().to_string(),
Style::default().fg(icon_color).bg(bg),
);
frame
.buffer_mut()
.set_string(row_rect.x + 3, row_rect.y, &label, style);
self.source_control
.commit_menu_item_areas
.push((row_rect, item));
}
}
fn dispatch_commit_menu_item(&mut self, item: crate::widgets::source_control::CommitMenuItem) {
use crate::widgets::source_control::CommitMenuItem;
match item {
CommitMenuItem::CommitAndPush => self.commit_and_push_source_control(),
CommitMenuItem::Push => self.push_source_control(),
CommitMenuItem::Pull => self.pull_source_control(),
CommitMenuItem::Sync => self.sync_source_control(),
CommitMenuItem::CheckoutBranch => self.open_branch_picker(),
CommitMenuItem::Stash => self.stash_source_control(),
CommitMenuItem::StashPop => self.stash_pop_source_control(),
CommitMenuItem::ViewStagedDiff => self.view_staged_diff_source_control(),
CommitMenuItem::ViewPreviousCommitDiff => {
self.view_previous_commit_diff_source_control()
}
CommitMenuItem::ViewDefaultBranchDiff => self.view_default_branch_diff_source_control(),
}
}
fn render_discard_confirm(&self, frame: &mut ratatui::Frame) {
let Some(pd) = self.pending_discard.as_ref() else {
return;
};
let area = frame.area();
let width = area.width.saturating_sub(8).clamp(50, 96);
let height: u16 = 8;
let x = (area.width.saturating_sub(width)) / 2 + area.x;
let y = (area.height.saturating_sub(height)) / 2 + area.y;
let rect = Rect {
x,
y,
width,
height,
};
let warn = self.theme.ui(Color::Rgb(0xe7, 0x70, 0x70));
let block = ratatui::widgets::Block::default()
.borders(ratatui::widgets::Borders::ALL)
.border_style(Style::default().fg(warn))
.style(Style::default().bg(self.theme.ui(Color::Rgb(0x1e, 0x1e, 0x1e))))
.title(ratatui::text::Span::styled(
" DISCARD CHANGES? ",
Style::default()
.fg(Color::White)
.bg(warn)
.add_modifier(Modifier::BOLD),
));
frame.render_widget(ratatui::widgets::Clear, rect);
frame.render_widget(block, rect);
let inner = Rect {
x: rect.x + 2,
y: rect.y + 1,
width: rect.width.saturating_sub(4),
height: rect.height.saturating_sub(2),
};
let warn_text = if pd.untracked {
"This will permanently delete the file from disk."
} else {
"This will overwrite your local changes from HEAD."
};
let body = ratatui::text::Text::from(vec![
ratatui::text::Line::from(ratatui::text::Span::styled(
warn_text,
Style::default().fg(self.theme.ui(Color::White)),
)),
ratatui::text::Line::from(""),
ratatui::text::Line::from(ratatui::text::Span::styled(
truncate_for_display(&pd.rel_path, inner.width as usize),
Style::default().fg(self.theme.ui(Color::Rgb(0xeb, 0xcb, 0x8b))),
)),
ratatui::text::Line::from(""),
ratatui::text::Line::from(vec![
ratatui::text::Span::styled(
"[Y]",
Style::default().fg(Color::Red).add_modifier(Modifier::BOLD),
),
ratatui::text::Span::raw("es, discard "),
ratatui::text::Span::styled(
"[N]",
Style::default()
.fg(Color::Green)
.add_modifier(Modifier::BOLD),
),
ratatui::text::Span::raw("o / Esc"),
]),
]);
frame.render_widget(ratatui::widgets::Paragraph::new(body), inner);
}
/// Confirmation modal for Revert Hunk: destroys the uncommitted edit
/// under the diff caret, so it gets the same red Y/N gate as discard.
fn render_revert_hunk_confirm(&self, frame: &mut ratatui::Frame) {
let Some(pr) = self.pending_revert_hunk.as_ref() else {
return;
};
let area = frame.area();
let width = area.width.saturating_sub(8).clamp(50, 96);
let height: u16 = 8;
let x = (area.width.saturating_sub(width)) / 2 + area.x;
let y = (area.height.saturating_sub(height)) / 2 + area.y;
let rect = Rect {
x,
y,
width,
height,
};
let warn = self.theme.ui(Color::Rgb(0xe7, 0x70, 0x70));
let block = ratatui::widgets::Block::default()
.borders(ratatui::widgets::Borders::ALL)
.border_style(Style::default().fg(warn))
.style(Style::default().bg(self.theme.ui(Color::Rgb(0x1e, 0x1e, 0x1e))))
.title(ratatui::text::Span::styled(
" REVERT HUNK? ",
Style::default()
.fg(Color::White)
.bg(warn)
.add_modifier(Modifier::BOLD),
));
frame.render_widget(ratatui::widgets::Clear, rect);
frame.render_widget(block, rect);
let inner = Rect {
x: rect.x + 2,
y: rect.y + 1,
width: rect.width.saturating_sub(4),
height: rect.height.saturating_sub(2),
};
let body = ratatui::text::Text::from(vec![
ratatui::text::Line::from(ratatui::text::Span::styled(
"This will undo the change hunk under the cursor on disk.",
Style::default().fg(self.theme.ui(Color::White)),
)),
ratatui::text::Line::from(""),
ratatui::text::Line::from(ratatui::text::Span::styled(
truncate_for_display(&pr.rel_path, inner.width as usize),
Style::default().fg(self.theme.ui(Color::Rgb(0xeb, 0xcb, 0x8b))),
)),
ratatui::text::Line::from(""),
ratatui::text::Line::from(vec![
ratatui::text::Span::styled(
"[Y]",
Style::default().fg(Color::Red).add_modifier(Modifier::BOLD),
),
ratatui::text::Span::raw("es, revert "),
ratatui::text::Span::styled(
"[N]",
Style::default()
.fg(Color::Green)
.add_modifier(Modifier::BOLD),
),
ratatui::text::Span::raw("o / Esc"),
]),
]);
frame.render_widget(ratatui::widgets::Paragraph::new(body), inner);
}
/// The Replace All confirmation modal (#123): counts up front, commits
/// on Enter/Y, cancels on Esc/N — the discard-all popup's shape.
fn render_replace_all_confirm(&self, frame: &mut ratatui::Frame) {
let Some((occurrences, files, skipped)) = self.pending_replace_all else {
return;
};
let area = frame.area();
let width = area.width.saturating_sub(8).clamp(50, 96);
let prompt = format!(
"Replace {occurrences} occurrence(s) across {files} file(s) with \"{}\"?",
self.search.replace
);
// The prompt interpolates arbitrary user text: derive the height
// from its wrapped row count so the Enter/Esc hint can never fall
// below the border (#124 review).
let inner_w = width.saturating_sub(2);
let prompt_rows = wrap_cells_variable_width(&prompt, inner_w, inner_w).len() as u16;
let skipped_rows = u16::from(skipped > 0);
let height: u16 = 6 + prompt_rows + skipped_rows;
let rect = Rect {
x: (area.width.saturating_sub(width)) / 2 + area.x,
y: (area.height.saturating_sub(height)) / 2 + area.y,
width,
height,
};
let warn = self.theme.ui(Color::Rgb(0xe7, 0xa7, 0x3c));
let block = ratatui::widgets::Block::default()
.borders(ratatui::widgets::Borders::ALL)
.border_style(Style::default().fg(warn))
.style(Style::default().bg(self.theme.ui(Color::Rgb(0x1e, 0x1e, 0x1e))))
.title(ratatui::text::Span::styled(
" REPLACE ALL? ",
Style::default()
.fg(Color::Black)
.bg(warn)
.add_modifier(Modifier::BOLD),
));
frame.render_widget(ratatui::widgets::Clear, rect);
let inner = block.inner(rect);
frame.render_widget(block, rect);
let mut lines = vec![
Line::from(prompt),
Line::from(""),
Line::from("Files are rewritten on disk."),
];
if skipped > 0 {
lines.push(Line::from(format!(
"{skipped} open file(s) with unsaved changes will be skipped."
)));
}
lines.push(Line::from(""));
lines.push(Line::from(Span::styled(
"Enter / Y replaces \u{00b7} Esc cancels",
Style::default().fg(self.theme.ui(Color::Rgb(0x9a, 0xa4, 0xb8))),
)));
frame.render_widget(
Paragraph::new(lines).wrap(ratatui::widgets::Wrap { trim: false }),
inner,
);
}
/// Confirmation modal for "Discard All Changes" — reverts every tracked
/// edit to HEAD, so it gets the same red Y/N gate as a single discard.
fn render_discard_all_confirm(&self, frame: &mut ratatui::Frame) {
if !self.pending_discard_all {
return;
}
let area = frame.area();
let width = area.width.saturating_sub(8).clamp(50, 96);
let height: u16 = 7;
let rect = Rect {
x: (area.width.saturating_sub(width)) / 2 + area.x,
y: (area.height.saturating_sub(height)) / 2 + area.y,
width,
height,
};
let warn = self.theme.ui(Color::Rgb(0xe7, 0x70, 0x70));
let block = ratatui::widgets::Block::default()
.borders(ratatui::widgets::Borders::ALL)
.border_style(Style::default().fg(warn))
.style(Style::default().bg(self.theme.ui(Color::Rgb(0x1e, 0x1e, 0x1e))))
.title(ratatui::text::Span::styled(
" DISCARD ALL CHANGES? ",
Style::default()
.fg(Color::White)
.bg(warn)
.add_modifier(Modifier::BOLD),
));
frame.render_widget(ratatui::widgets::Clear, rect);
frame.render_widget(block, rect);
let inner = Rect {
x: rect.x + 2,
y: rect.y + 1,
width: rect.width.saturating_sub(4),
height: rect.height.saturating_sub(2),
};
let body = ratatui::text::Text::from(vec![
ratatui::text::Line::from(ratatui::text::Span::styled(
"This reverts every tracked file to HEAD. Untracked files are kept.",
Style::default().fg(self.theme.ui(Color::White)),
)),
ratatui::text::Line::from(""),
ratatui::text::Line::from(vec![
ratatui::text::Span::styled(
"[Y]",
Style::default().fg(Color::Red).add_modifier(Modifier::BOLD),
),
ratatui::text::Span::raw("es, discard all "),
ratatui::text::Span::styled(
"[N]",
Style::default()
.fg(Color::Green)
.add_modifier(Modifier::BOLD),
),
ratatui::text::Span::raw("o / Esc"),
]),
]);
frame.render_widget(ratatui::widgets::Paragraph::new(body), inner);
}
/// Confirmation modal for enabling broadcast input: the classic footgun
/// is typing a destructive command into panes you forgot were listening,
/// so switching it on gets the same red Y/N gate iTerm2 shows.
fn render_broadcast_confirm(&self, frame: &mut ratatui::Frame) {
if !self.pending_broadcast_enable {
return;
}
let area = frame.area();
let width = area.width.saturating_sub(8).clamp(50, 96);
let height: u16 = 7;
let rect = Rect {
x: (area.width.saturating_sub(width)) / 2 + area.x,
y: (area.height.saturating_sub(height)) / 2 + area.y,
width,
height,
};
let warn = self.theme.ui(Color::Rgb(0xe7, 0x70, 0x70));
let block = ratatui::widgets::Block::default()
.borders(ratatui::widgets::Borders::ALL)
.border_style(Style::default().fg(warn))
.style(Style::default().bg(self.theme.ui(Color::Rgb(0x1e, 0x1e, 0x1e))))
.title(ratatui::text::Span::styled(
" BROADCAST INPUT TO ALL PANES? ",
Style::default()
.fg(Color::White)
.bg(warn)
.add_modifier(Modifier::BOLD),
));
frame.render_widget(ratatui::widgets::Clear, rect);
frame.render_widget(block, rect);
let inner = Rect {
x: rect.x + 2,
y: rect.y + 1,
width: rect.width.saturating_sub(4),
height: rect.height.saturating_sub(2),
};
let receiving = self
.terminals
.iter()
.filter(|t| !t.broadcast_excluded)
.count()
.max(1);
let body = ratatui::text::Text::from(vec![
ratatui::text::Line::from(ratatui::text::Span::styled(
format!(
"Every keystroke and paste will go to {receiving} terminal panes at once (red \u{21f6} pills mark them). Cmd+K I stops it; Cmd+K Shift+I excludes a pane."
),
Style::default().fg(self.theme.ui(Color::White)),
)),
ratatui::text::Line::from(""),
ratatui::text::Line::from(vec![
ratatui::text::Span::styled(
"[Y]",
Style::default().fg(Color::Red).add_modifier(Modifier::BOLD),
),
ratatui::text::Span::raw("es, broadcast "),
ratatui::text::Span::styled(
"[N]",
Style::default()
.fg(Color::Green)
.add_modifier(Modifier::BOLD),
),
ratatui::text::Span::raw("o / Esc"),
]),
]);
frame.render_widget(
ratatui::widgets::Paragraph::new(body).wrap(ratatui::widgets::Wrap { trim: true }),
inner,
);
}
/// The confirm popup for a runnable fence (#353): the whole block, the
/// pane and directory it would run in, red when it looks destructive.
fn render_run_block_confirm(&self, frame: &mut ratatui::Frame) {
let Some(block) = self.pending_run_block.as_ref() else {
return;
};
let area = frame.area();
let width = area.width.saturating_sub(8).clamp(50, 96);
let inner_w = width.saturating_sub(4) as usize;
let shown: Vec<String> = block
.code
.lines()
.take(8)
// A line wider than the popup is cut with a visible mark: what
// the popup hides must never look complete.
.map(|l| {
if l.chars().count() > inner_w {
let mut cut: String = l.chars().take(inner_w.saturating_sub(1)).collect();
cut.push('\u{2026}');
cut
} else {
l.to_string()
}
})
.collect();
let more = block.code.lines().count().saturating_sub(shown.len());
let height =
(shown.len() as u16 + 6 + u16::from(more > 0)).min(area.height.saturating_sub(2));
let rect = Rect {
x: (area.width.saturating_sub(width)) / 2 + area.x,
y: (area.height.saturating_sub(height)) / 2 + area.y,
width,
height,
};
let (title, accent) = if block.destructive {
(
" RUN THIS BLOCK? IT LOOKS DESTRUCTIVE ",
self.theme.ui(Color::Rgb(0xe7, 0x70, 0x70)),
)
} else {
(" RUN THIS BLOCK? ", self.theme.accent())
};
let popup = ratatui::widgets::Block::default()
.borders(ratatui::widgets::Borders::ALL)
.border_style(Style::default().fg(accent))
.style(Style::default().bg(self.theme.ui(Color::Rgb(0x1e, 0x1e, 0x1e))))
.title(ratatui::text::Span::styled(
title,
Style::default()
.fg(Color::White)
.bg(accent)
.add_modifier(Modifier::BOLD),
));
frame.render_widget(ratatui::widgets::Clear, rect);
frame.render_widget(popup, rect);
let inner = Rect {
x: rect.x + 2,
y: rect.y + 1,
width: rect.width.saturating_sub(4),
height: rect.height.saturating_sub(2),
};
let mut lines: Vec<ratatui::text::Line> =
vec![ratatui::text::Line::from(ratatui::text::Span::styled(
format!("in pane {} at {}", block.pane_name, block.cwd.display()),
Style::default().fg(self.theme.ui(Color::Rgb(0xCC, 0xCC, 0xCC))),
))];
for l in &shown {
lines.push(ratatui::text::Line::from(ratatui::text::Span::styled(
l.clone(),
Style::default().fg(self.theme.ui(Color::White)),
)));
}
if more > 0 {
lines.push(ratatui::text::Line::from(ratatui::text::Span::styled(
format!("… {more} more line(s)"),
Style::default().fg(self.theme.ui(Color::Rgb(0x88, 0x88, 0x88))),
)));
}
lines.push(ratatui::text::Line::from(""));
lines.push(ratatui::text::Line::from(vec![
ratatui::text::Span::styled(
"[Y]",
Style::default().fg(Color::Red).add_modifier(Modifier::BOLD),
),
ratatui::text::Span::raw("es, run "),
ratatui::text::Span::styled(
"[N]",
Style::default()
.fg(Color::Green)
.add_modifier(Modifier::BOLD),
),
ratatui::text::Span::raw("o / Esc"),
]));
frame.render_widget(
ratatui::widgets::Paragraph::new(ratatui::text::Text::from(lines)),
inner,
);
}
fn render_terminal_warning(&self, frame: &mut ratatui::Frame) {
if !self.pending_terminal_warning {
return;
}
let area = frame.area();
// The lower clamp bound must never beat the frame itself: on a
// terminal narrower than 50 columns the modal used to come out
// WIDER than the buffer and the paint panicked at launch (#192).
let width = area.width.saturating_sub(8).clamp(50, 96).min(area.width);
let height: u16 = 11u16.min(area.height);
let x = (area.width.saturating_sub(width)) / 2 + area.x;
let y = (area.height.saturating_sub(height)) / 2 + area.y;
let rect = Rect {
x,
y,
width,
height,
};
let warn = self.theme.ui(Color::Rgb(0xff, 0xa5, 0x00));
let accent = self.theme.ui(Color::Rgb(0x4e, 0x9a, 0xff));
let block = ratatui::widgets::Block::default()
.borders(ratatui::widgets::Borders::ALL)
.border_style(Style::default().fg(warn))
.style(Style::default().bg(self.theme.ui(Color::Rgb(0x1e, 0x1e, 0x1e))))
.title(ratatui::text::Span::styled(
" UNSUPPORTED TERMINAL ",
Style::default()
.fg(Color::Black)
.bg(warn)
.add_modifier(Modifier::BOLD),
));
frame.render_widget(ratatui::widgets::Clear, rect);
frame.render_widget(block, rect);
let inner = Rect {
x: rect.x + 2,
y: rect.y + 1,
width: rect.width.saturating_sub(4),
height: rect.height.saturating_sub(2),
};
let current = std::env::var("TERM_PROGRAM")
.ok()
.filter(|s| !s.is_empty())
.or_else(|| std::env::var("TERM").ok().filter(|s| !s.is_empty()))
.unwrap_or_else(|| String::from("this terminal"));
let body = ratatui::text::Text::from(vec![
Line::from(Span::styled(
"Croft draws its icons and images with inline-image protocols",
Style::default().fg(self.theme.ui(Color::White)),
)),
Line::from(Span::styled(
format!("that {current} does not support, so the activity bar and"),
Style::default().fg(self.theme.ui(Color::White)),
)),
Line::from(Span::styled(
"file icons stay blank. Croft still runs; for the full UI use:",
Style::default().fg(self.theme.ui(Color::White)),
)),
Line::from(""),
Line::from(vec![
Span::raw(" macOS: "),
Span::styled(
"iTerm2",
Style::default().fg(accent).add_modifier(Modifier::BOLD),
),
Span::raw(" or "),
Span::styled(
"Ghostty",
Style::default().fg(accent).add_modifier(Modifier::BOLD),
),
]),
Line::from(vec![
Span::raw(" Linux: "),
Span::styled(
"Ghostty",
Style::default().fg(accent).add_modifier(Modifier::BOLD),
),
]),
Line::from(""),
Line::from(vec![
Span::styled(
"[any key]",
Style::default()
.fg(Color::Green)
.add_modifier(Modifier::BOLD),
),
Span::raw(" dismiss "),
Span::styled(
"[D]",
Style::default()
.fg(Color::Green)
.add_modifier(Modifier::BOLD),
),
Span::raw("on't show again"),
]),
]);
frame.render_widget(ratatui::widgets::Paragraph::new(body), inner);
}
fn render_local_open_confirm(&self, frame: &mut ratatui::Frame) {
let Some(url) = &self.pending_local_open else {
return;
};
let area = frame.area();
let width = area.width.saturating_sub(8).clamp(50, 96);
let height: u16 = 8;
let x = (area.width.saturating_sub(width)) / 2 + area.x;
let y = (area.height.saturating_sub(height)) / 2 + area.y;
let rect = Rect {
x,
y,
width,
height,
};
let block = ratatui::widgets::Block::default()
.borders(ratatui::widgets::Borders::ALL)
.border_style(Style::default().fg(self.theme.ui(Color::Rgb(0xff, 0xa5, 0x00))))
.style(Style::default().bg(self.theme.ui(Color::Rgb(0x1e, 0x1e, 0x1e))))
.title(ratatui::text::Span::styled(
" OPEN ON LOCAL MAC? ",
Style::default()
.fg(Color::Black)
.bg(self.theme.ui(Color::Rgb(0xff, 0xa5, 0x00)))
.add_modifier(Modifier::BOLD),
));
frame.render_widget(ratatui::widgets::Clear, rect);
frame.render_widget(block, rect);
let inner = Rect {
x: rect.x + 2,
y: rect.y + 1,
width: rect.width.saturating_sub(4),
height: rect.height.saturating_sub(2),
};
let body = ratatui::text::Text::from(vec![
ratatui::text::Line::from(ratatui::text::Span::styled(
"This URL will open in YOUR LOCAL MAC's browser via the croft relay.",
Style::default().fg(self.theme.ui(Color::White)),
)),
ratatui::text::Line::from(""),
ratatui::text::Line::from(ratatui::text::Span::styled(
truncate_for_display(url, inner.width as usize),
Style::default().fg(self.theme.ui(Color::Rgb(0x4e, 0x9a, 0xff))),
)),
ratatui::text::Line::from(""),
ratatui::text::Line::from(vec![
ratatui::text::Span::styled(
"[Y]",
Style::default()
.fg(Color::Green)
.add_modifier(Modifier::BOLD),
),
ratatui::text::Span::raw("es once "),
ratatui::text::Span::styled(
"[A]",
Style::default()
.fg(Color::Green)
.add_modifier(Modifier::BOLD),
),
ratatui::text::Span::raw("lways for this session "),
ratatui::text::Span::styled(
"[N]",
Style::default().fg(Color::Red).add_modifier(Modifier::BOLD),
),
ratatui::text::Span::raw("o / Esc"),
]),
]);
frame.render_widget(ratatui::widgets::Paragraph::new(body), inner);
}
/// Paint the transient port-detection toast in the bottom-right corner and
/// record its clickable action-button rects. Click-only: it never captures
/// keystrokes, so it can't interfere with terminal typing.
fn render_port_toast(&mut self, frame: &mut ratatui::Frame) {
let Some(toast) = self.port_toast.as_ref() else {
return;
};
let port = toast.port;
let origin_remote = toast.origin_remote;
let proc = toast.process.clone().unwrap_or_default();
let accent = self.theme.accent();
let btn_bg = self.theme.button();
let actions: Vec<(String, PortToastAction)> = if origin_remote {
vec![
(
" Forward & Open ".to_string(),
PortToastAction::ForwardAndOpen,
),
(" Forward ".to_string(), PortToastAction::ForwardOnly),
(" \u{2715} ".to_string(), PortToastAction::Dismiss),
]
} else {
vec![
(" Open ".to_string(), PortToastAction::Open),
(" \u{2715} ".to_string(), PortToastAction::Dismiss),
]
};
let buttons_w: u16 = actions
.iter()
.map(|(l, _)| l.chars().count() as u16 + 1)
.sum::<u16>()
+ 1;
let title_line = format!("\u{25cf} port {port} {proc}");
let inner_w = buttons_w.max(title_line.chars().count() as u16);
let area = frame.area();
let width = (inner_w + 4).min(area.width.saturating_sub(2));
let height: u16 = 4;
let status_h: u16 = if self.status_bar_visible { 1 } else { 0 };
if area.width < width + 2 || area.height < height + status_h + 1 {
return;
}
let rect = Rect {
x: area.x + area.width - width - 2,
y: area.y + area.height - height - status_h - 1,
width,
height,
};
let block = ratatui::widgets::Block::default()
.borders(ratatui::widgets::Borders::ALL)
.border_style(Style::default().fg(accent))
.style(Style::default().bg(self.theme.editor_bg()))
.title(ratatui::text::Span::styled(
" PORT DETECTED ",
Style::default().fg(accent).add_modifier(Modifier::BOLD),
));
frame.render_widget(ratatui::widgets::Clear, rect);
frame.render_widget(block, rect);
let inner = Rect {
x: rect.x + 2,
y: rect.y + 1,
width: rect.width.saturating_sub(4),
height: rect.height.saturating_sub(2),
};
let buf = frame.buffer_mut();
buf.set_stringn(
inner.x,
inner.y,
&title_line,
inner.width as usize,
Style::default().fg(self.theme.ui(Color::Rgb(0xCC, 0xCC, 0xCC))),
);
let mut bx = inner.x;
let by = inner.y + 1;
let mut rects: Vec<(Rect, PortToastAction)> = Vec::new();
for (label, action) in &actions {
let w = label.chars().count() as u16;
if bx + w > inner.x + inner.width {
break;
}
buf.set_stringn(
bx,
by,
label,
w as usize,
Style::default()
.fg(Color::White)
.bg(btn_bg)
.add_modifier(Modifier::BOLD),
);
rects.push((
Rect {
x: bx,
y: by,
width: w,
height: 1,
},
*action,
));
bx += w + 1;
}
if let Some(t) = self.port_toast.as_mut() {
t.buttons = rects;
}
}
/// Paint the update-available popup in the bottom-LEFT corner (the
/// port toast owns the right) and record its button rects. Click-only,
/// like the port toast: it never captures keystrokes (#333).
fn render_update_toast(&mut self, frame: &mut ratatui::Frame) {
let Some(toast) = self.update_toast.as_ref() else {
return;
};
let version = toast.version.clone();
let ready = toast.ready;
let staging = self.staged_status == UpdateStatus::InProgress && !ready;
let accent = self.theme.accent();
let btn_bg = self.theme.button();
let actions: Vec<(String, UpdateToastAction)> = if ready {
vec![(" Relaunch ".to_string(), UpdateToastAction::Relaunch)]
} else if staging {
Vec::new()
} else {
vec![
(" Update ".to_string(), UpdateToastAction::Update),
(" Later ".to_string(), UpdateToastAction::Later),
]
};
let title_line = if ready {
format!("\u{27f3} croft v{version} is ready - relaunch to update")
} else if staging {
format!(
"{} building croft v{version} in the background",
self.update_spinner_glyph()
)
} else {
format!(
"\u{27f3} croft v{version} is available (you have v{})",
env!("CARGO_PKG_VERSION")
)
};
let buttons_w: u16 = actions
.iter()
.map(|(l, _)| l.chars().count() as u16 + 1)
.sum::<u16>()
+ 1;
let inner_w = buttons_w.max(title_line.chars().count() as u16);
let area = frame.area();
let width = (inner_w + 4).min(area.width.saturating_sub(2));
let height: u16 = 4;
let status_h: u16 = if self.status_bar_visible { 1 } else { 0 };
// The port toast owns the bottom-right band; at ordinary widths
// this popup's title reaches into it, so stack above it instead.
let stack: u16 = if self.port_toast.is_some() { height } else { 0 };
if area.width < width + 2 || area.height < height + status_h + 1 + stack {
return;
}
let rect = Rect {
x: area.x + 1,
y: area.y + area.height - height - status_h - 1 - stack,
width,
height,
};
let block = ratatui::widgets::Block::default()
.borders(ratatui::widgets::Borders::ALL)
.border_style(Style::default().fg(accent))
.style(Style::default().bg(self.theme.editor_bg()))
.title(ratatui::text::Span::styled(
" UPDATE ",
Style::default().fg(accent).add_modifier(Modifier::BOLD),
));
frame.render_widget(ratatui::widgets::Clear, rect);
frame.render_widget(block, rect);
let inner = Rect {
x: rect.x + 2,
y: rect.y + 1,
width: rect.width.saturating_sub(4),
height: rect.height.saturating_sub(2),
};
let buf = frame.buffer_mut();
buf.set_stringn(
inner.x,
inner.y,
&title_line,
inner.width as usize,
Style::default().fg(self.theme.ui(Color::Rgb(0xCC, 0xCC, 0xCC))),
);
let mut bx = inner.x;
let by = inner.y + 1;
let mut rects: Vec<(Rect, UpdateToastAction)> = Vec::new();
for (label, action) in &actions {
let w = label.chars().count() as u16;
if bx + w > inner.x + inner.width {
break;
}
buf.set_stringn(
bx,
by,
label,
w as usize,
Style::default()
.fg(Color::White)
.bg(btn_bg)
.add_modifier(Modifier::BOLD),
);
rects.push((
Rect {
x: bx,
y: by,
width: w,
height: 1,
},
*action,
));
bx += w + 1;
}
if let Some(t) = self.update_toast.as_mut() {
t.buttons = rects;
}
}
fn render_prompt(&self, frame: &mut ratatui::Frame) {
let Some(p) = &self.prompt else { return };
let area = frame.area();
let width = area.width.saturating_sub(8).clamp(40, 80);
let height = if p.error.is_some() { 6 } else { 5 };
let x = (area.width.saturating_sub(width)) / 2 + area.x;
let y = (area.height.saturating_sub(height)) / 2 + area.y;
let rect = Rect {
x,
y,
width,
height,
};
let grad = self.popup_gradient();
let cursor_fg = if grad {
rgb_color(GRAD_TL)
} else {
self.theme.ui(Color::Rgb(0x4e, 0x9a, 0xff))
};
let title_bg = if grad {
rgb_color(POPUP_SEL_BG)
} else {
self.theme.ui(Color::Rgb(0x1e, 0x3a, 0x6e))
};
let title = ratatui::text::Span::styled(
format!(" {} ", p.label),
Style::default()
.fg(self.theme.ui(Color::White))
.bg(title_bg)
.add_modifier(Modifier::BOLD),
);
let block = ratatui::widgets::Block::default()
.borders(ratatui::widgets::Borders::ALL)
.border_style(Style::default().fg(self.theme.ui(Color::Rgb(0x4e, 0x9a, 0xff))))
.style(Style::default().bg(self.theme.ui(Color::Rgb(0x1e, 0x1e, 0x1e))))
.title(title.clone());
frame.render_widget(ratatui::widgets::Clear, rect);
frame.render_widget(block, rect);
// Black theme: overpaint the solid border with the gradient, then
// re-stamp the title the gradient top edge just covered.
if grad {
paint_gradient_box(frame.buffer_mut(), rect);
frame
.buffer_mut()
.set_span(rect.x + 1, rect.y, &title, title.width() as u16);
}
let inner = Rect {
x: rect.x + 2,
y: rect.y + 1,
width: rect.width.saturating_sub(4),
height: rect.height.saturating_sub(2),
};
let (top_line, hint_text) = match &p.kind {
PromptKind::Create(_) => (
ratatui::text::Line::from(vec![
ratatui::text::Span::raw("> "),
ratatui::text::Span::styled(
p.buffer.as_str(),
Style::default().fg(self.theme.ui(Color::White)),
),
ratatui::text::Span::styled("█", Style::default().fg(cursor_fg)),
]),
"Enter to create, Esc to cancel",
),
PromptKind::Rename(_) => (
ratatui::text::Line::from(vec![
ratatui::text::Span::raw("> "),
ratatui::text::Span::styled(
p.buffer.as_str(),
Style::default().fg(self.theme.ui(Color::White)),
),
ratatui::text::Span::styled("█", Style::default().fg(cursor_fg)),
]),
"Enter to rename, Esc to cancel",
),
PromptKind::RenameSymbol { .. } => (
ratatui::text::Line::from(vec![
ratatui::text::Span::raw("> "),
ratatui::text::Span::styled(
p.buffer.as_str(),
Style::default().fg(self.theme.ui(Color::White)),
),
ratatui::text::Span::styled("█", Style::default().fg(cursor_fg)),
]),
"Enter to rename symbol, Esc to cancel",
),
PromptKind::RenameTerminal(_) => (
ratatui::text::Line::from(vec![
ratatui::text::Span::raw("> "),
ratatui::text::Span::styled(
p.buffer.as_str(),
Style::default().fg(self.theme.ui(Color::White)),
),
ratatui::text::Span::styled("█", Style::default().fg(cursor_fg)),
]),
"Enter to rename, Esc to cancel (blank clears the name)",
),
PromptKind::AnnotateTerminal { existing, .. } => (
ratatui::text::Line::from(vec![
ratatui::text::Span::raw("> "),
ratatui::text::Span::styled(
p.buffer.as_str(),
Style::default().fg(self.theme.ui(Color::White)),
),
ratatui::text::Span::styled("█", Style::default().fg(cursor_fg)),
]),
if existing.is_some() {
"Enter to update the note, Esc to cancel (blank deletes it)"
} else {
"Enter to pin the note to the selection, Esc to cancel"
},
),
PromptKind::BreakpointCondition { .. } => (
ratatui::text::Line::from(vec![
ratatui::text::Span::raw("> "),
ratatui::text::Span::styled(
p.buffer.as_str(),
Style::default().fg(self.theme.ui(Color::White)),
),
ratatui::text::Span::styled("█", Style::default().fg(cursor_fg)),
]),
"Enter to set condition (blank for a plain breakpoint), Esc to cancel",
),
PromptKind::Logpoint { .. } => (
ratatui::text::Line::from(vec![
ratatui::text::Span::raw("> "),
ratatui::text::Span::styled(
p.buffer.as_str(),
Style::default().fg(self.theme.ui(Color::White)),
),
ratatui::text::Span::styled("█", Style::default().fg(cursor_fg)),
]),
"Enter to set the log message, {expr} interpolates (blank for a plain breakpoint), Esc to cancel",
),
};
frame.render_widget(
ratatui::widgets::Paragraph::new(top_line),
Rect {
x: inner.x,
y: inner.y,
width: inner.width,
height: 1,
},
);
let hint = ratatui::widgets::Paragraph::new(ratatui::text::Line::from(hint_text))
.style(Style::default().fg(Color::DarkGray));
frame.render_widget(
hint,
Rect {
x: inner.x,
y: inner.y + 2,
width: inner.width,
height: 1,
},
);
if let Some(err) = &p.error {
let line = ratatui::widgets::Paragraph::new(ratatui::text::Line::from(format!(
"Error: {err}"
)))
.style(Style::default().fg(self.theme.ui(Color::Rgb(0xe8, 0x27, 0x4b))));
frame.render_widget(
line,
Rect {
x: inner.x,
y: inner.y + 3,
width: inner.width,
height: 1,
},
);
}
}
/// Dispatch the second key of a `Cmd+K`-prefixed chord (VS Code's two-key
/// model). Returns `true` if the key completed a chord and was consumed,
/// `false` if it matched nothing (the caller then processes it normally).
/// The second key reaches us as ordinary input, so `Cmd` on the trailing
/// key (e.g. `Cmd+K Cmd+T`) is accepted but not required.
fn handle_cmd_k_chord(&mut self, key: KeyEvent) -> bool {
let plain = !key.modifiers.contains(KeyModifiers::ALT);
let shifted = key.modifiers.contains(KeyModifiers::SHIFT);
match key.code {
// Cmd+K ⇧C / ⇧S / ⇧R with the terminal focused: the keyboard
// forms of the decoration-menu actions, applied to the LAST
// finished command (VS Code's copyLastCommandOutput family).
// Must precede the case-insensitive C/S/R editor arms below.
KeyCode::Char('C' | 'S' | 'R') if shifted && plain && self.focus == Pane::Terminal => {
let KeyCode::Char(c) = key.code else {
return false;
};
let Some(d) = self.last_command_decoration() else {
self.status = String::from("No finished commands yet");
return true;
};
let idx = self.active_terminal;
match c {
'C' => self.copy_command_output(idx, d),
'S' => self.select_command_output(idx, d),
_ => self.rerun_command(idx, d),
}
true
}
// Cmd+K Shift+T: reopen the most recently closed terminal pane
// (the browser reopen-tab convention under the Cmd+K leader).
// Must precede the case-insensitive T theme arm below.
KeyCode::Char('T') if shifted && plain => {
self.undo_close_terminal();
true
}
// Cmd+K Shift+W: reopen the most recently closed editor tab
// (VS Code "Reopen Closed Editor"; ⇧W pairs with Cmd+W the way
// ⇧T pairs with the terminal close). Matched case-insensitively
// because CSI-u hosts report Shift+W as `Char('w') + SHIFT`
// while iTerm2's forwarder delivers `Char('W')`. Must precede
// any case-insensitive W arm.
KeyCode::Char(c) if shifted && plain && c.eq_ignore_ascii_case(&'w') => {
self.reopen_closed_tab();
true
}
// Cmd+K Shift+N with the terminal focused: delete the
// annotation(s) under the selection. Must precede any
// case-insensitive N arm.
KeyCode::Char('N') if shifted && plain && self.focus == Pane::Terminal => {
self.delete_terminal_annotations_in_selection();
true
}
// Cmd+K N with the terminal focused: pin a note to the selected
// output span (iTerm2's annotations); over an existing note it
// edits in place.
KeyCode::Char(c)
if plain && c.eq_ignore_ascii_case(&'n') && self.focus == Pane::Terminal =>
{
self.begin_annotate_terminal();
true
}
// Cmd+K Cmd+T / Cmd+K T: open the Color Theme picker.
KeyCode::Char(c) if plain && c.eq_ignore_ascii_case(&'t') => {
self.open_theme_picker();
true
}
// Cmd+K A: who is attached to this multiplayer session
// (Session: Participants).
KeyCode::Char(c) if plain && c.eq_ignore_ascii_case(&'a') => {
self.open_participants_picker();
true
}
// Cmd+K X: cancel the AI stream (croft pair) — the keyboard
// form of the gutter stop button; the pilot reverts the
// streamed text.
KeyCode::Char(c) if plain && c.eq_ignore_ascii_case(&'x') => {
self.collab_cancel_stream();
true
}
// Cmd+K Cmd+Q: Go to Last Edit Location (VS Code's chord; the
// second key carries Cmd, which keeps it distinct from the
// navigator's plain Cmd+K Q below).
KeyCode::Char(c)
if c.eq_ignore_ascii_case(&'q') && key.modifiers.contains(KeyModifiers::SUPER) =>
{
self.goto_last_edit_location();
true
}
// Cmd+K Q: ask the navigator about the caret line, or the
// selected lines when a selection is active (Q for question).
KeyCode::Char(c) if plain && c.eq_ignore_ascii_case(&'q') => {
let (range, selection) = match self.editor.selection_rows() {
Some(rows) => (rows, self.editor.selection_text()),
None => {
let row = self.editor.cursor_row;
((row, row), String::new())
}
};
self.open_ask_navigator(range, selection);
true
}
// Cmd+K Y: yield the turn — the navigator reviews the active
// file comment-only; its say lands as gutter diamonds and
// OUTPUT commentary, never as edits.
KeyCode::Char(c) if plain && c.eq_ignore_ascii_case(&'y') => {
self.yield_to_navigator();
true
}
// Cmd+K Shift+Cmd+\: open a second view of the active file beside it
// ("Split in Group"). Must precede the plain Cmd+\ (Split Up) arm,
// which ignores Shift. Shift+\ may arrive as '|' on some layouts.
KeyCode::Char('\\' | '|') if key.modifiers.contains(KeyModifiers::SHIFT) => {
self.split_in_group();
true
}
// Cmd+K Cmd+\ (or Cmd+K \): split the active group UP (stacked, the
// new group above). Plain Cmd+\ already splits Right.
KeyCode::Char('\\') if plain => {
self.split_editor_dir(editor_layout::SplitDir::Vertical, false);
true
}
// Cmd+K →: close the editors to the right of the active tab.
KeyCode::Right if plain => {
let from = self.editor.active_index();
self.record_closed_tabs_where(|i, ed| i > from && !ed.pinned);
let removed = self.editor.close_to_right(from);
if removed > 0 {
self.sync_open_file_poll_mtime();
self.status = if removed == 1 {
String::from("Closed 1 tab to the right")
} else {
format!("Closed {removed} tabs to the right")
};
self.poke_cursor();
}
true
}
// Cmd+K S: mark the active file as the compare anchor.
KeyCode::Char(c) if plain && c.eq_ignore_ascii_case(&'s') => {
if let Some(path) = self.editor.path.clone() {
let label = path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| path.display().to_string());
self.compare_anchor = Some(path);
self.status = format!("Selected {label} for compare");
} else {
self.status = String::from("Select for Compare: no active file");
}
true
}
// Cmd+K C: diff the active file against the compare anchor.
KeyCode::Char(c) if plain && c.eq_ignore_ascii_case(&'c') => {
match (self.compare_anchor.clone(), self.editor.path.clone()) {
(Some(anchor), Some(other)) => match self.editor.open_diff(&anchor, &other) {
Ok(()) => {
self.focus_pane(Pane::Editor);
self.compare_anchor = None;
self.sync_open_file_poll_mtime();
let l = anchor
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| anchor.display().to_string());
let r = other
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| other.display().to_string());
self.status = format!("Diff: {l} \u{2194} {r}");
}
Err(e) => self.status = format!("Diff failed: {e}"),
},
(None, _) => {
self.status = String::from("Compare with Selected: nothing selected yet")
}
(_, None) => {
self.status = String::from("Compare with Selected: no active file")
}
}
true
}
// Cmd+K W: close all editor tabs.
KeyCode::Char(c) if plain && c.eq_ignore_ascii_case(&'w') => {
self.close_all_tabs();
true
}
// Cmd+K U: close all saved (non-dirty) editor tabs.
KeyCode::Char(c) if plain && c.eq_ignore_ascii_case(&'u') => {
self.close_saved_tabs();
true
}
// Cmd+K E: reveal the active file in the Explorer tree.
KeyCode::Char(c) if plain && c.eq_ignore_ascii_case(&'e') => {
if let Some(path) = self.editor.path.clone() {
self.reveal_in_explorer(path);
} else {
self.status = String::from("Reveal in Explorer View: no active file");
}
true
}
// Cmd+K Shift+H: outgoing calls (what does this call?). Must
// precede the case-insensitive H arm below.
KeyCode::Char('H') if shifted && plain => {
self.request_call_hierarchy_at_cursor(false);
true
}
// Cmd+K G: accept the ssh-pane workspace offer (#364) — "go to
// the host". The same remote flow the palette command runs; the
// offer only saves the reaching.
KeyCode::Char(c) if plain && c.eq_ignore_ascii_case(&'g') => {
match self.accept_ssh_offer() {
Some(host) => self.request_remote_launch(host, None),
None => {
self.status = String::from(
"No ssh workspace offer is open (it appears when a pane connects to a host in ~/.ssh/config)",
);
}
}
true
}
// Cmd+K H: incoming calls — who calls the symbol at the caret
// (VS Code's call Hierarchy, peek replaced by croft's picker).
KeyCode::Char(c) if plain && c.eq_ignore_ascii_case(&'h') => {
self.request_call_hierarchy_at_cursor(true);
true
}
// Cmd+K P: pin / unpin the active tab. This chord was Cmd+K
// Shift+Enter (and Keep Open bare Cmd+K Enter) — both silently
// SHADOWED the later, documented Cmd+K Enter run-test-at-cursor
// arms below, so the Enter family now belongs to Testing alone.
// Cmd+K ⇧P: keep the active preview tab open (sibling of the pin
// chord below). Must precede the case-insensitive 'p' arm, which
// would swallow the shifted press.
KeyCode::Char('P') if shifted && plain => {
if self.editor.keep_open(self.editor.active_index()) {
self.status = String::from("Kept tab open");
self.poke_cursor();
}
true
}
KeyCode::Char(c) if plain && c.eq_ignore_ascii_case(&'p') => {
let idx = self.editor.active_index();
let pinned = self.editor.toggle_pin(idx);
self.status = String::from(if pinned { "Pinned tab" } else { "Unpinned tab" });
self.poke_cursor();
true
}
// Cmd+K Shift+O: move the active tab into a new window. Must precede
// the plain Cmd+K O (Copy) arm, which ignores Shift.
KeyCode::Char(c)
if c.eq_ignore_ascii_case(&'o') && key.modifiers.contains(KeyModifiers::SHIFT) =>
{
self.move_into_new_window(self.editor.active_index());
true
}
// Cmd+K O: copy the active tab into a new window (VS Code's binding).
KeyCode::Char(c) if plain && c.eq_ignore_ascii_case(&'o') => {
self.copy_into_new_window(self.editor.active_index());
true
}
// Cmd+K Z: toggle Zen Mode (VS Code's binding).
KeyCode::Char(c) if plain && c.eq_ignore_ascii_case(&'z') => {
self.toggle_zen_mode();
true
}
// Cmd+K Cmd+F (SUPER/CTRL held on the second key): Format
// Selection, VS Code's binding (#254). Must precede the plain
// Cmd+K F arm, which keeps croft's format-on-save toggle.
KeyCode::Char(c)
if plain
&& c.eq_ignore_ascii_case(&'f')
&& (key.modifiers.contains(KeyModifiers::SUPER)
|| key.modifiers.contains(KeyModifiers::CONTROL)) =>
{
self.format_selection();
true
}
// Cmd+K F: toggle Format on Save (croft binding; VS Code leaves this
// preference unbound, but every croft action carries an accelerator).
KeyCode::Char(c) if plain && c.eq_ignore_ascii_case(&'f') => {
self.toggle_format_on_save();
true
}
// Cmd+K K: clear the active terminal (VS Code clears with Cmd+K).
KeyCode::Char(c) if plain && c.eq_ignore_ascii_case(&'k') => {
if !self.show_terminal {
self.show_terminal = true;
}
self.clear_terminal_at(self.active_terminal);
true
}
// Cmd+K R: rename the active terminal pane.
KeyCode::Char(c) if plain && c.eq_ignore_ascii_case(&'r') => {
if !self.show_terminal {
self.show_terminal = true;
}
self.begin_rename_terminal(self.active_terminal);
true
}
// Cmd+K M: maximize the active terminal pane / restore the even
// split (croft binding; VS Code leaves its panel-maximize
// relative unbound, and every croft action carries an
// accelerator).
KeyCode::Char(c) if plain && c.eq_ignore_ascii_case(&'m') => {
if !self.show_terminal {
self.show_terminal = true;
}
self.toggle_terminal_pane_maximize();
true
}
// Cmd+K [ / Cmd+K ]: fold the active terminal pane to a strip,
// and give every folded pane its width back (#313). VS Code binds
// its own fold / unfold pair to ⌘K ⌘[ and ⌘K ⌘], so the gesture
// keeps the keys it already has elsewhere.
//
// NOT ⌘K E, which the design proposal had picked as "even": that
// is croft's reveal-in-Explorer and the arm would never have been
// reached, since an earlier `e` arm in this same match wins.
// NOT ⌘K -, either: `-` is close, on the button and here.
//
// Cmd+K M (pane-maximize) is untouched: maximize and collapse are
// orthogonal and compose.
KeyCode::Char('[') if plain => {
if !self.show_terminal {
self.show_terminal = true;
}
self.collapse_active_terminal_pane();
true
}
KeyCode::Char(']') if plain => {
if !self.show_terminal {
self.show_terminal = true;
}
self.restore_all_terminal_panes();
true
}
// Cmd+K D: dump the active terminal's scrollback into a scratch
// editor tab (kitty's show_scrollback, with the editor as the
// pager: find, vim mode, save, and path:line jumps come free).
KeyCode::Char(c) if plain && c.eq_ignore_ascii_case(&'d') => {
self.open_scrollback_in_editor();
true
}
// Cmd+K B: show the Testing view (B for the beaker icon). Cmd+Shift+T
// — VS Code's Testing-ish chord — is already croft's focus-Terminal
// chord, so the Cmd+K leader hosts this the way it hosts Zen (Cmd+K Z).
KeyCode::Char(c) if plain && c.eq_ignore_ascii_case(&'b') => {
self.open_testing_view();
true
}
// Cmd+K Shift+I: toggle whether the active pane receives
// broadcast input (iTerm2's per-session broadcast-domain
// toggle). Must precede the case-insensitive I arm below.
KeyCode::Char('I') if shifted && plain => {
self.toggle_broadcast_exclusion();
true
}
// Cmd+K I: toggle broadcast input — type into every terminal
// pane at once (iTerm2's Cmd+Opt+I; I for Input). Enabling is
// gated on a confirm popup.
KeyCode::Char(c) if plain && c.eq_ignore_ascii_case(&'i') => {
self.toggle_broadcast_input();
true
}
// Cmd+K Shift+Enter: debug the test the caret sits in (checked
// before the plain-Enter run arm, which also matches this chord).
KeyCode::Enter if key.modifiers.contains(KeyModifiers::SHIFT) => {
self.debug_test_at_cursor();
true
}
// Cmd+K Enter: run the test the editor caret sits in. Enter already
// means "run" in the Testing view (runs all), so it carries over as
// the run verb under the Cmd+K leader (no new terminal registration).
KeyCode::Enter => {
self.run_test_at_cursor();
true
}
// Cmd+K Cmd+0 / Cmd+K 0: collapse every fold (VS Code "Fold All").
KeyCode::Char('0') if plain => {
self.editor.fold_all();
self.poke_cursor();
true
}
// Cmd+K Cmd+J / Cmd+K J: expand every fold (VS Code "Unfold All").
KeyCode::Char(c) if plain && c.eq_ignore_ascii_case(&'j') => {
self.editor.unfold_all();
self.poke_cursor();
true
}
// Cmd+K Shift+L: Agent: New Worktree Lane (#348). Matched
// case-insensitively for the same CSI-u / iTerm2 split as ⇧W,
// and so it must precede the case-insensitive L arm below.
KeyCode::Char(c) if shifted && plain && c.eq_ignore_ascii_case(&'l') => {
self.open_new_lane_prompt();
true
}
// Cmd+K Cmd+L / Cmd+K L: toggle the fold at the cursor line
// (VS Code "Toggle Fold").
KeyCode::Char(c) if plain && c.eq_ignore_ascii_case(&'l') => {
let row = self.editor.cursor_row;
self.editor.toggle_fold(row);
self.poke_cursor();
true
}
// Cmd+K Cmd+/ : collapse every comment block (VS Code
// "Fold All Block Comments", #254).
KeyCode::Char('/') if plain => {
self.editor
.fold_all_of_kind(crate::lsp::manager::FoldRangeKind::Comment);
self.poke_cursor();
true
}
// Cmd+K Cmd+8 / Cmd+K Cmd+9: fold / unfold every #region
// (VS Code "Fold/Unfold All Regions", #254).
KeyCode::Char('8') if plain => {
self.editor
.fold_all_of_kind(crate::lsp::manager::FoldRangeKind::Region);
self.poke_cursor();
true
}
KeyCode::Char('9') if plain => {
self.editor
.unfold_all_of_kind(crate::lsp::manager::FoldRangeKind::Region);
self.poke_cursor();
true
}
_ => false,
}
}
/// Dispatch one key, capturing it into a live macro recording (#255).
///
/// The capture happens AFTER dispatch and only if recording was already
/// on both before and after: that is what keeps the gesture that ENDS a
/// recording (vim's closing `q`, the palette's stop command) out of the
/// macro it ends, and the gesture that STARTS one out of the macro it
/// opens. Keys are recorded rather than resolved commands because only
/// palette selections and user-rebound chords reach `run_command` — the
/// built-in defaults call their app methods directly, so a command-level
/// recorder would miss most of what a user does.
fn handle_key(&mut self, key: KeyEvent) -> Result<()> {
// Esc dismisses an open ssh-pane offer (#364) without being consumed:
// the offer is a status-bar hint, not a modal, so whatever Esc meant
// to the focused pane still happens.
if key.code == KeyCode::Esc
&& matches!(key.kind, KeyEventKind::Press | KeyEventKind::Repeat)
{
self.dismiss_ssh_offer();
}
let capture =
self.macro_recording.is_some() && !self.macro_replaying && self.focus == Pane::Editor;
let result = self.handle_key_inner(key);
// Focus is re-checked after dispatch too: a key that hands focus to
// the terminal would otherwise be recorded while everything after it
// is dropped, producing a macro that replays a focus change and then
// silently loses its payload.
if capture && self.macro_recording.is_some() {
if self.focus == Pane::Editor {
self.record_macro_key(key);
} else {
// The issue asks for skipped keys to be logged rather than
// vanishing: a macro that quietly stopped recording halfway
// is otherwise indistinguishable from one that recorded
// everything.
crate::output::push(
"Macros",
crate::output::OutputLevel::Info,
&format!("skipped {key:?}: recording captures the editor pane only"),
);
}
}
result
}
fn handle_key_inner(&mut self, key: KeyEvent) -> Result<()> {
// Peek Definition popup: Enter converts to the real jump, Esc
// closes, and any other key closes it and keeps its normal
// meaning — the popup is a glance, never a mode (#115). Gated on
// Press/Repeat like every other modal (the app-wide filter runs
// just below), so a key RELEASE never dismisses or jumps.
if self.peek_popup.is_some()
&& matches!(key.kind, KeyEventKind::Press | KeyEventKind::Repeat)
{
match key.code {
KeyCode::Enter => {
if let Some((path, line, col)) = self.peek_target.take() {
self.close_peek_popup();
self.go_to_definition(path, line, col);
}
return Ok(());
}
KeyCode::Esc => {
self.close_peek_popup();
return Ok(());
}
_ => self.close_peek_popup(),
}
}
if key.kind != KeyEventKind::Press && key.kind != KeyEventKind::Repeat {
return Ok(());
}
self.hover_popup = None;
self.hover_diagnostic = None;
self.hover_request_id = None;
// `Cmd+K` leader: if armed, this keystroke is the second half of a
// `Cmd+K`-prefixed chord. Consume the leader regardless; dispatch the
// chord if it matches and the window has not lapsed, otherwise fall
// through so the key keeps its normal meaning (e.g. Esc cancels).
if let Some(started) = self.cmd_k_leader.take() {
const CMD_K_LEADER_TIMEOUT: std::time::Duration =
std::time::Duration::from_millis(1500);
if started.elapsed() <= CMD_K_LEADER_TIMEOUT && self.handle_cmd_k_chord(key) {
return Ok(());
}
}
// Modal layer: the unsupported-terminal nudge sits on top of everything
// at startup. Any key dismisses it for this session; D also persists the
// dismissal so it never shows again. All keys are swallowed so the user
// can't accidentally type through into the UI below.
if self.pending_terminal_warning {
match key.code {
KeyCode::Char('d') | KeyCode::Char('D') => self.dismiss_terminal_warning(true),
_ => self.dismiss_terminal_warning(false),
}
return Ok(());
}
if self.connect_dialog.is_some() {
self.handle_connect_dialog_key(key);
return Ok(());
}
if self.shortcuts_modal.is_some() {
self.handle_shortcuts_modal_key(key);
return Ok(());
}
if self.file_finder.is_some() {
self.handle_file_finder_key(key);
return Ok(());
}
if self.command_palette.is_some() {
self.handle_command_palette_key(key);
return Ok(());
}
if self.workspace_symbols.is_some() {
self.handle_workspace_symbols_key(key);
return Ok(());
}
if self.go_to_symbol.is_some() {
self.handle_go_to_symbol_key(key);
return Ok(());
}
if self.process_picker.is_some() {
self.handle_process_picker_key(key);
return Ok(());
}
if self.zoxide_jump.is_some() {
self.handle_zoxide_jump_key(key);
return Ok(());
}
if self.command_history_popup.is_some() {
self.handle_command_history_key(key);
return Ok(());
}
if self.branch_picker.is_some() {
self.handle_branch_picker_key(key);
return Ok(());
}
if self.input_prompt.is_some() {
self.handle_input_prompt_key(key);
return Ok(());
}
if self.list_picker.is_some() {
self.handle_list_picker_key(key);
return Ok(());
}
if self.pending_replace_all.is_some() {
match key.code {
KeyCode::Char('y') | KeyCode::Char('Y') | KeyCode::Enter => {
self.confirm_pending_replace_all();
}
KeyCode::Char('n') | KeyCode::Char('N') | KeyCode::Esc => {
self.cancel_pending_replace_all();
}
_ => {}
}
return Ok(());
}
if self.pending_discard_all {
match key.code {
KeyCode::Char('y') | KeyCode::Char('Y') | KeyCode::Enter => {
self.confirm_pending_discard_all();
}
KeyCode::Char('n') | KeyCode::Char('N') | KeyCode::Esc => {
self.cancel_pending_discard_all();
}
_ => {}
}
return Ok(());
}
if self.pending_broadcast_enable {
match key.code {
KeyCode::Char('y') | KeyCode::Char('Y') | KeyCode::Enter => {
self.confirm_pending_broadcast();
}
KeyCode::Char('n') | KeyCode::Char('N') | KeyCode::Esc => {
self.cancel_pending_broadcast();
}
_ => {}
}
return Ok(());
}
if self.pending_run_block.is_some() {
match key.code {
KeyCode::Char('y') | KeyCode::Char('Y') | KeyCode::Enter => {
self.confirm_pending_run_block();
}
KeyCode::Char('n') | KeyCode::Char('N') | KeyCode::Esc => {
self.cancel_pending_run_block();
}
_ => {}
}
return Ok(());
}
// History scrubber (#371): arrows step, Home returns to the working
// tree, Esc closes.
//
// BELOW every modal guard above, deliberately. The scrubber is a view
// of the editor, not a mode over the window, so a palette, prompt or
// picker opened while scrubbing keeps its own arrows. Placing it here
// gets that by construction — each of those guards returns
// unconditionally, so a key only reaches this line when none of them
// wanted it. The alternative, a list of "overlays that take
// precedence", silently rots the next time someone adds a modal.
if self.scrubber.is_some()
&& matches!(key.kind, KeyEventKind::Press | KeyEventKind::Repeat)
&& self.handle_scrubber_key(key.code)
{
return Ok(());
}
if self.scm_menu.open && matches!(key.code, KeyCode::Esc) {
self.scm_menu.close();
return Ok(());
}
// Macro recording (#255) taps the key here: every modal above has
// already returned, so what reaches this point is editor work — the
// thing a macro is for. Capturing keys rather than resolved commands
// is deliberate: only palette selections and user-rebound chords
// reach `run_command`, while the built-in defaults (Cmd+S, Alt+Up,
// the debugger keys) call their app methods straight from here, so a
// command-level recorder would miss most of what a user does.
//
// Replay feeds keys back through `handle_key`, so it is re-entrant by
// construction — `replaying` keeps a replayed key from being recorded
// into the macro that is producing it.
// User keybindings (keybindings.json) win over the built-in chords, but
// only when the terminal is not focused (its raw control keys must pass
// through) and the chord carries a real modifier or is a function key
// (so plain typing and bare Enter/Tab/Esc keep their contextual meaning).
// This stands in for VS Code's `when: editorTextFocus` without a full
// context engine.
if self.focus != Pane::Terminal
&& !self.keymap.is_empty()
&& is_rebindable_chord(key)
&& let Some(cmd) = self.keymap.command_for(key)
{
self.run_command(cmd);
return Ok(());
}
// A focused comment-box reply field owns the keyboard: typing edits
// the draft, Enter sends, Esc leaves, F4 hops on. Sits below the
// real modals (palette, prompts) and above every editor key.
if self.editor.comment_focus.is_some() && self.focus == Pane::Editor {
self.handle_comment_focus_key(key);
return Ok(());
}
if matches!(key.code, KeyCode::F(1)) {
self.open_shortcuts_modal();
return Ok(());
}
if matches!(key.code, KeyCode::F(8)) {
self.perf.toggle();
return Ok(());
}
// Debugger chords (VS Code defaults). F5 start/continue, Shift+F5 stop,
// Shift+Cmd+F5 restart, Ctrl+F5 attach to a Python process, F9 toggle
// breakpoint, F10 step over, F11/Shift+F11 step in/out. Cmd is SUPER on
// macOS, Ctrl on Linux/Termux.
//
// A bare F5/F9/F10/F11 pressed while the terminal pane is focused and
// no debug session is live belongs to the app running in the shell
// (process-compose's F10 Quit, htop's F9 kill), so it falls through to
// the PTY instead of dying as a debugger no-op. Modified chords and a
// ready update's F9 re-exec keep their croft meaning everywhere.
let terminal_owns_fkeys = self.focus == Pane::Terminal
&& matches!(self.bottom_panel_tab, BottomPanelTab::Terminal)
&& self.dap_session.is_none()
&& key.modifiers.is_empty();
if matches!(key.code, KeyCode::F(5)) && !terminal_owns_fkeys {
let shift = key.modifiers.contains(KeyModifiers::SHIFT);
let cmd = key.modifiers.contains(KeyModifiers::SUPER)
|| key.modifiers.contains(KeyModifiers::CONTROL);
if shift && cmd {
self.debug_restart();
} else if key.modifiers.contains(KeyModifiers::CONTROL)
&& !shift
&& !key.modifiers.contains(KeyModifiers::SUPER)
&& !key.modifiers.contains(KeyModifiers::ALT)
{
self.open_attach_python_picker();
} else if shift {
self.debug_stop();
} else {
self.debug_start_or_continue();
}
return Ok(());
}
// F6 pauses a running program (VS Code's Pause key) ONLY while a debug
// session is live; with no session it falls through to its long-standing
// role as croft's cycle-focus key.
if matches!(key.code, KeyCode::F(6)) && self.dap_session.is_some() {
self.debug_pause();
return Ok(());
}
if matches!(key.code, KeyCode::F(9)) && !(terminal_owns_fkeys && !self.f9_update_armed()) {
if key.modifiers.contains(KeyModifiers::SHIFT)
&& key.modifiers.contains(KeyModifiers::ALT)
{
// Shift+Alt+F9: add or edit a logpoint at the cursor. Must
// precede the bare-Shift arm, which also matches this chord.
self.debug_edit_logpoint();
} else if key.modifiers.contains(KeyModifiers::SHIFT) {
// Shift+F9: add or edit a conditional breakpoint at the cursor.
self.debug_edit_condition();
} else if key.modifiers.contains(KeyModifiers::ALT) {
// Alt+F9: toggle break-on-raised-exceptions.
self.debug_toggle_raised_exceptions();
} else if self.any_update_ready() {
// A background update has landed (a staged release, the
// drift rebuild, or a remote install): bare F9 re-execs
// into it. `run()` swaps the staged binary in first when
// that is the one that landed.
self.pending_reexec = true;
self.quit = true;
} else if self.f9_update_armed() && self.update_status == UpdateStatus::Idle {
// The drift hint is armed (#242): bare F9 rebuilds and
// reinstalls the local croft in the background.
self.start_local_reinstall();
} else if self.self_install.is_some() {
// A rebuild is already in flight (second F9 of an input
// batch, or pressed again mid-install): swallow it -
// toggling a breakpoint here is never what was meant.
} else {
self.debug_toggle_breakpoint();
}
return Ok(());
}
if matches!(key.code, KeyCode::F(10)) && !terminal_owns_fkeys {
self.debug_step("next");
return Ok(());
}
if matches!(key.code, KeyCode::F(11)) && !terminal_owns_fkeys {
let cmd = if key.modifiers.contains(KeyModifiers::SHIFT) {
"stepOut"
} else {
"stepIn"
};
self.debug_step(cmd);
return Ok(());
}
// Arm the `Cmd+K` leader (VS Code's two-key chord prefix). The next
// keystroke is interpreted by `handle_cmd_k_chord`, checked at the top
// of this fn. Cmd is SUPER everywhere; Ctrl doubles as Cmd only on
// Termux — on desktop Linux a bare Ctrl+K stays the editor's
// kill-to-end-of-line (see `is_cmd_k_leader_key`).
if is_cmd_k_leader_key(key) {
self.cmd_k_leader = Some(std::time::Instant::now());
return Ok(());
}
if is_file_finder_key(key) {
self.open_file_finder();
return Ok(());
}
if is_command_palette_key(key) {
self.open_command_palette();
return Ok(());
}
if is_go_to_symbol_key(key) {
self.open_go_to_symbol();
return Ok(());
}
// Modal layer: prompt eats every key while it's open.
if self.prompt.is_some() {
self.handle_prompt_key(key);
return Ok(());
}
// Modal layer: local-browser confirmation eats every key.
if self.pending_local_open.is_some() {
self.handle_local_open_confirm_key(key);
return Ok(());
}
// Modal layer: discard-changes confirmation eats every key. Y/Enter
// discards; N/Esc cancels. Anything else is swallowed so the user
// can't accidentally type-through into the editor below.
if self.pending_discard.is_some() {
match key.code {
KeyCode::Char('y') | KeyCode::Char('Y') | KeyCode::Enter => {
self.confirm_pending_discard();
}
KeyCode::Char('n') | KeyCode::Char('N') | KeyCode::Esc => {
self.cancel_pending_discard();
}
_ => {}
}
return Ok(());
}
// Modal layer: revert-hunk confirmation, same contract as the
// discard modal above.
if self.pending_revert_hunk.is_some() {
match key.code {
KeyCode::Char('y') | KeyCode::Char('Y') | KeyCode::Enter => {
self.confirm_pending_revert_hunk();
}
KeyCode::Char('n') | KeyCode::Char('N') | KeyCode::Esc => {
self.cancel_pending_revert_hunk();
}
_ => {}
}
return Ok(());
}
// Modal layer: open context menu eats keyboard navigation.
if self.context_menu.is_some() {
self.handle_menu_key(key);
return Ok(());
}
// Cmd+E toggles native modal (vim) editing. Global (above the focus
// dispatch) so it works from any pane and even with no file open: the
// mode is a single app-wide flag that only affects the editor, but it
// can be pre-armed from the tree or terminal and stays on as you open
// and switch between files.
if is_vim_toggle_key(key) {
self.toggle_vim_mode();
return Ok(());
}
// App-wide shortcuts (priority). Skip Cmd+S when the Source
// Control pane is focused so the SC handler can use it as the
// stage shortcut — saving an editor file with no editor focus
// doesn't make sense anyway, and globally swallowing Cmd+S here
// is what made the user's first attempt feel inert.
let sc_focused =
self.focus == Pane::Tree && self.sidebar_view == SidebarView::SourceControl;
if is_save_key(key) && !sc_focused {
self.save();
return Ok(());
}
if is_terminal_toggle_key(key) {
self.toggle_terminal();
return Ok(());
}
if is_terminal_maximize_key(key) {
self.toggle_terminal_maximize();
return Ok(());
}
if is_editor_split_key(key) {
self.split_editor();
return Ok(());
}
if is_focus_group_left_key(key) {
self.focus_editor_group(true);
return Ok(());
}
if is_focus_group_right_key(key) {
self.focus_editor_group(false);
return Ok(());
}
if is_terminal_split_key(key) {
match self.split_terminal() {
Ok(()) => {
self.terminal_status(format!(
"Split terminal: {} active",
self.terminals.len()
));
}
Err(e) => {
self.status = format!("Split terminal failed: {e}");
}
}
return Ok(());
}
if is_terminal_focus_key(key) {
if !self.show_terminal {
self.show_terminal = true;
}
self.focus_pane(Pane::Terminal);
return Ok(());
}
if is_run_build_task_key(key) {
self.run_build_task();
return Ok(());
}
// Explorer-pane shortcuts get first refusal so Cmd+Shift+F creates
// a folder when the user is browsing the tree, rather than always
// jumping to Search. Outside Explorer the global Search-jump wins.
if self.is_explorer_focused() && self.handle_explorer_shortcut(key) {
return Ok(());
}
if is_search_jump_key(key) {
// Jumping to global Search supersedes the in-file find: tear the
// local find bar down first, otherwise its overlay keeps painting
// over the editor (render_editor_find only gates on editor_find
// being Some, not on focus) and shadows the global search input.
self.close_editor_find();
self.set_sidebar_view(SidebarView::Search);
return Ok(());
}
// Cmd+Shift+S jumps to Source Control from any pane — croft's Source
// Control gesture. There is no editor Save-As to collide with (Cmd+S
// alone saves), so it fires even while the editor is focused.
if is_source_control_jump_key(key) {
self.set_sidebar_view(SidebarView::SourceControl);
return Ok(());
}
if is_explorer_jump_key(key) {
self.show_tree = true;
self.set_sidebar_view(SidebarView::Explorer);
return Ok(());
}
if is_run_debug_jump_key(key) {
self.show_tree = true;
self.set_sidebar_view(SidebarView::RunDebug);
return Ok(());
}
if is_remote_jump_key(key) {
self.show_tree = true;
self.set_sidebar_view(SidebarView::Remote);
return Ok(());
}
if is_extensions_jump_key(key) {
self.show_tree = true;
self.set_sidebar_view(SidebarView::Extensions);
return Ok(());
}
if self.is_remote && is_drop_to_local_key(key) {
self.drop_to_local = true;
self.quit = true;
return Ok(());
}
if self.sidebar_view == SidebarView::Search
&& self.focus == Pane::Tree
&& is_search_editing_shortcut(key)
{
self.handle_search_key(key);
return Ok(());
}
if is_secondary_sidebar_toggle_key(key) {
self.toggle_secondary_side_bar();
return Ok(());
}
if is_minimap_toggle_key(key) {
self.toggle_minimap();
return Ok(());
}
// Ctrl+B while the terminal pane is focused belongs to the app in
// the shell, not to croft (#304). Claude Code backgrounds a running
// command with it and has no other route to that; croft's sidebar
// toggle has three (Cmd+B, the palette, the menu). The asymmetry is
// the argument: releasing costs a chord that is reachable three
// other ways, holding costs a chord that is reachable no other way.
//
// Same conditional shape as the bare F5/F9/F10/F11 rule above, and
// for the same reason -- it is a rule about when the chord is
// UNAMBIGUOUS, not a user preference, so it needs no setting and
// cannot drift out of step with a config. Cmd+B is untouched
// everywhere, which is what keeps the sidebar reachable from the
// terminal; only the Ctrl form is released, matching iTerm2 and
// Ghostty, which reserve Cmd and pass Ctrl through.
let terminal_owns_ctrl_b = self.focus == Pane::Terminal
&& matches!(self.bottom_panel_tab, BottomPanelTab::Terminal)
&& key.modifiers == KeyModifiers::CONTROL;
if is_sidebar_toggle_key(key) && !terminal_owns_ctrl_b {
self.toggle_side_bar();
return Ok(());
}
match (key.code, key.modifiers) {
(KeyCode::Char('q'), KeyModifiers::CONTROL) => {
self.quit = true;
return Ok(());
}
(KeyCode::F(6), _) => {
self.cycle_focus();
return Ok(());
}
_ => {}
}
match self.focus {
Pane::Tree => match self.sidebar_view {
SidebarView::Explorer => self.handle_tree_key(key),
SidebarView::Search => self.handle_search_key(key),
SidebarView::SourceControl => self.handle_source_control_key(key),
SidebarView::Remote => self.handle_remote_key(key),
SidebarView::RunDebug => self.handle_run_debug_key(key),
SidebarView::Extensions => self.handle_extensions_key(key),
SidebarView::Testing => self.handle_testing_key(key),
},
Pane::Editor => {
// A shared file is read-only until its bootstrap snapshot
// lands (a keystroke now would race the owner's canonical
// text). One gate at the dispatch covers every editor edit
// path; the window is the bootstrap round-trip.
if let Some(session) = self.collab.as_ref()
&& let Some(file) = self
.editor
.path
.as_ref()
.and_then(|p| collab_file_key(&self.tree.root, p))
{
if session.is_bootstrapping(&file) {
self.status = format!("{file}: joining the shared session, one moment");
return Ok(());
}
// Same gate for a not-yet-attached pane of a LIVE file
// (a fresh split or reopen holding stale disk text): a
// keystroke absorbed now would be silently wiped when
// the attach pass seeds the pane one tick later.
if session.is_live(&file) && self.editor.collab_doc_gen == 0 {
self.status = format!("{file}: syncing this pane, one moment");
return Ok(());
}
}
self.handle_editor_key(key);
self.poke_cursor();
}
Pane::Terminal => match self.bottom_panel_tab {
// The PROBLEMS / OUTPUT views own the panel pane while their tab
// is active, so keystrokes scroll the list instead of leaking
// into the hidden shell.
BottomPanelTab::Problems => self.handle_problems_key(key),
BottomPanelTab::Output => self.handle_output_key(key),
BottomPanelTab::Ports => self.handle_ports_key(key),
BottomPanelTab::Captures => self.handle_captures_key(key),
BottomPanelTab::Terminal => self.handle_terminal_key(key),
},
}
Ok(())
}
fn handle_search_key(&mut self, key: KeyEvent) {
use crate::widgets::search::SearchField;
// Reset the blink so the caret is solidly visible right after any key,
// matching the commit box; the panel is focused whenever this fires.
self.poke_cursor();
if is_search_paste_key(key) {
let text = (self.clipboard_reader)();
self.paste_clipboard_into_search(text.as_deref());
return;
}
if is_editor_select_all_key(key) {
self.search.select_all_active();
return;
}
if is_editor_copy_key(key) {
let text = self.search.active_selection_text();
if !text.is_empty() {
copy_to_clipboard(&text);
self.status = format!("Copied {} chars to clipboard", text.chars().count());
}
return;
}
if is_editor_cut_key(key) {
let text = self.search.active_selection_text();
if !text.is_empty() {
copy_to_clipboard(&text);
let n = text.chars().count();
self.search.backspace();
self.refresh_search_if_filtering();
self.status = format!("Cut {n} chars to clipboard");
}
return;
}
// Tab cycles through the visible inputs (Query → Replace → include →
// exclude → Query), mirroring VS Code. Shift+Tab is left to fall
// through to default since BackTab arrives as its own key code.
if key.code == KeyCode::Tab && key.modifiers.is_empty() {
self.search.focus_next_field();
return;
}
match key.code {
KeyCode::Esc => {
if self.search.active_text().is_empty() {
if self.search.field == SearchField::Query {
self.set_sidebar_view(SidebarView::Explorer);
} else {
self.search.focus_field(SearchField::Query);
}
} else {
let was_query = self.search.field == SearchField::Query;
self.search.active_text_mut_clear();
self.search.clear_active_selection();
if was_query {
self.search.hits.clear();
}
self.refresh_search_if_filtering();
}
}
KeyCode::Enter => {
// On the Replace field, Enter runs Replace All across the
// current results; elsewhere it opens the selected hit.
if self.search.field == SearchField::Replace {
self.run_search_replace_all();
} else if let Some(hit) = self.search.selected_hit().cloned() {
self.open_search_hit(&hit);
}
}
KeyCode::Backspace if self.search.backspace() => {
self.refresh_search_if_filtering();
}
KeyCode::Up => self.search.move_up(),
KeyCode::Down => self.search.move_down(),
KeyCode::Char(c) => {
if !key.modifiers.contains(KeyModifiers::CONTROL)
&& !key.modifiers.contains(KeyModifiers::ALT)
&& !key.modifiers.contains(KeyModifiers::SUPER)
{
self.search.type_char(c);
self.refresh_search_if_filtering();
} else if key.modifiers.contains(KeyModifiers::SUPER) {
self.status = format!("Search: unhandled Cmd+{c}");
} else if key.modifiers.contains(KeyModifiers::CONTROL) {
self.status = format!("Search: unhandled Ctrl+{c}");
}
}
_ => {}
}
}
/// Re-run the search after a field edit, but only when the edited field
/// actually affects the result set. Editing the Replace text changes
/// nothing about which files match, so it must not clear / re-scan.
fn refresh_search_if_filtering(&mut self) {
if self.search.field != crate::widgets::search::SearchField::Replace {
self.submit_search_query();
}
}
/// Replace every match in the current results with the Replace text, then
/// re-run the query so the (now stale) hit list refreshes.
fn run_search_replace_all(&mut self) {
if self.is_collab_guest() {
// Replace All writes hit files on disk directly; in a collab
// session only the owner writes (their croft offers the same
// action, and open shared files converge through the reload
// diff).
self.status = String::from("Replace All is owner-only in a shared session");
return;
}
if self.search.query.trim().is_empty() {
self.status = String::from("Replace All: enter a search term first");
return;
}
if !self.search.complete {
// Hits stream in batches; replacing before Done would silently
// miss files found after confirmation (#124 review).
self.status =
String::from("Replace All: search still running — retry when it finishes");
return;
}
// Count first, write only after the modal confirms: a workspace-wide
// disk rewrite is exactly what the confirm-destructive rule is for
// (#123 — Enter used to commit instantly). Dirty-open files are
// excluded from the count too: the confirmed action skips them, and
// counting them made the modal overpromise.
let dirty = self.dirty_open_paths();
let (occurrences, files) = self.search.count_replacements(&dirty);
let skipped = self
.search
.hits
.iter()
.map(|h| &h.path)
.filter(|p| dirty.contains(*p))
.collect::<std::collections::HashSet<_>>()
.len();
if occurrences == 0 && skipped == 0 {
self.status = String::from("Replace All: nothing to replace");
return;
}
self.pending_replace_all = Some((occurrences, files, skipped));
}
/// Every path open with unsaved edits, across the active group and all
/// inactive split leaves.
fn dirty_open_paths(&self) -> std::collections::HashSet<PathBuf> {
self.editor
.editors
.iter()
.chain(
self.editor_layout
.inactive_leaf_tabs()
.into_iter()
.flat_map(|tabs| tabs.editors.iter()),
)
.filter(|e| e.dirty)
.filter_map(|e| e.path.clone())
.collect()
}
/// The confirmed Replace All: writes every hit file EXCEPT ones open
/// with unsaved edits — a disk write under a dirty buffer forces that
/// tab into conflict divergence, so those are skipped and named.
fn confirm_pending_replace_all(&mut self) {
self.pending_replace_all = None;
let dirty = self.dirty_open_paths();
let (n, skipped) = self.search.replace_all_skipping(&dirty);
self.status = if skipped.is_empty() {
format!("Replace All: replaced {n} occurrence(s)")
} else {
let names: Vec<String> = skipped
.iter()
.take(2)
.map(|p| self.status_path(p))
.collect();
let more = skipped.len().saturating_sub(names.len());
let list = if more > 0 {
format!("{} and {more} more", names.join(", "))
} else {
names.join(", ")
};
format!(
"Replace All: replaced {n} occurrence(s); skipped {list} (unsaved changes — save first)"
)
};
self.submit_search_query();
}
fn cancel_pending_replace_all(&mut self) {
self.pending_replace_all = None;
self.status = String::from("Replace All cancelled");
}
fn handle_remote_key(&mut self, key: KeyEvent) {
let has_mod = key
.modifiers
.intersects(KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SUPER);
match key.code {
KeyCode::Up => self.remote.move_up(),
KeyCode::Down => self.remote.move_down(),
KeyCode::PageUp => self.remote.scroll_up(10),
KeyCode::PageDown => self.remote.scroll_down(10),
KeyCode::Backspace if !self.remote.filter.is_empty() => {
self.remote.pop_filter_char();
}
KeyCode::Char(' ') if has_mod => {}
KeyCode::Char(c) if !has_mod => {
self.remote.push_filter_char(c);
}
KeyCode::Enter => {
if let Some(target) = self.remote.selected_target().cloned() {
self.request_remote_launch(target.alias, None);
}
}
KeyCode::Esc if !self.remote.clear_filter() => {
self.set_sidebar_view(SidebarView::Explorer);
}
_ => {}
}
}
fn handle_source_control_key(&mut self, key: KeyEvent) {
if matches!(key.code, KeyCode::Esc) {
self.set_sidebar_view(SidebarView::Explorer);
return;
}
let cmd_or_ctrl = key.modifiers.contains(KeyModifiers::SUPER)
|| key.modifiers.contains(KeyModifiers::CONTROL);
// Ctrl+Enter: commit & push. We deliberately match ONLY Control
// here (not Super). iTerm2's default keymap binds Cmd+Enter to
// "Toggle Fullscreen" and never delivers the chord to the TUI,
// which made the original Cmd+Enter wiring feel inert; Ctrl is
// unintercepted across every terminal we target.
if key.modifiers.contains(KeyModifiers::CONTROL) && matches!(key.code, KeyCode::Enter) {
self.commit_and_push_source_control();
return;
}
// Cmd+A: select every entry row in the panel so a follow-up Cmd+S
// stages them all in one go. Distinct from the editor's Cmd+A
// (select-all text) which the user kept hitting in the SC pane
// and getting the wrong scope.
if cmd_or_ctrl && matches!(key.code, KeyCode::Char('a') | KeyCode::Char('A')) {
let n = self.source_control.select_all_changes();
self.status = format!("Selected {n} change(s)");
return;
}
// Cmd+S: stage the selected entry, or every entry in the
// multi-selection. Mirrors clicking the inline "+" icon but
// sweeps across the whole selection.
if cmd_or_ctrl && matches!(key.code, KeyCode::Char('s') | KeyCode::Char('S')) {
self.stage_selected_source_control_entries();
return;
}
if is_clipboard_paste_key(key) {
if let Some(text) = (self.clipboard_reader)() {
self.source_control.insert_str(&text);
self.poke_cursor();
}
return;
}
match key.code {
KeyCode::Backspace => {
self.source_control.backspace();
self.poke_cursor();
}
KeyCode::Delete => {
self.source_control.delete_char();
self.poke_cursor();
}
KeyCode::Left => {
self.source_control.move_cursor_left();
self.poke_cursor();
}
KeyCode::Right => {
self.source_control.move_cursor_right();
self.poke_cursor();
}
KeyCode::Home => {
self.source_control.home();
self.poke_cursor();
}
KeyCode::End => {
self.source_control.end();
self.poke_cursor();
}
KeyCode::Up => self.source_control.scroll_up(1),
KeyCode::Down => self.source_control.scroll_down(1),
KeyCode::Enter => self.commit_source_control(),
KeyCode::Char(c)
if !key.modifiers.contains(KeyModifiers::CONTROL)
&& !key.modifiers.contains(KeyModifiers::ALT)
&& !key.modifiers.contains(KeyModifiers::SUPER) =>
{
self.source_control.insert_char(c);
self.poke_cursor();
}
_ => {}
}
}
fn refresh_source_control(&mut self) {
// Non-blocking: post a StatusAndChanges request and let the worker
// reply via `git_response_rx`. The panel paints immediately from
// whatever entries the last drain installed (typically <400 ms
// old via the FS-watcher tick); the fresh state lands within one or
// two frames after the click. StatusAndChanges (not just Changes) so
// the branch sync counts (`↑1` / `↓N`) and dirty flag refresh too —
// a commit changes those without changing the file list. Still off
// the UI thread, so no synchronous `git status` stall.
let ws = self.active_scm_root.clone();
self.git_worker_for_root_mut(&ws)
.request_status_and_changes();
self.refresh_commit_graph();
}
/// Refetch the COMMITS graph off-thread: `git log --topo-order` plus the
/// pure lane layout both run on the fetch thread, and the finished rows
/// land in [`graph_rx`] tagged with the root they describe. The inflight
/// latch collapses a burst of triggers into one shell-out plus one
/// queued refetch: a trigger during flight is answering a question the
/// in-flight fetch predates (a Make Root, a newer HEAD), so it must
/// re-fire when the reply drains rather than be dropped — a root change
/// racing the fetch otherwise left the panel on "Loading" until HEAD
/// next moved.
fn refresh_commit_graph(&mut self) {
if self.graph_fetch_inflight {
self.graph_refetch_queued = true;
return;
}
self.graph_fetch_inflight = true;
// The COMMITS section follows the active repo (#149).
let root = self.active_scm_root.clone();
let revspec = self.graph_revspec.clone();
let tx = self.graph_tx.clone();
std::thread::spawn(move || {
let commits = match revspec.as_deref() {
Some(spec) => crate::git::branch_history_range(&root, spec, 400),
None => crate::git::commit_graph(&root, 400),
};
let rows = crate::widgets::commit_graph::layout_graph(commits);
let _ = tx.send((root, revspec, rows));
});
}
/// Open a commit's full patch (header, message, diffstat, diff) in a
/// read-only scratch tab — the graph's click-through, tig's enter key.
fn open_commit_patch(&mut self, hash: &str, short_hash: &str) {
match crate::git::show_commit(&self.scm_root(), hash) {
Ok(text) => {
let label = format!("commit {short_hash}");
match self.editor.open_text_buffer(Path::new(&label), &text) {
Ok(()) => {
self.focus_pane(Pane::Editor);
self.sync_open_file_poll_mtime();
self.status = format!("Opened commit {short_hash}");
}
Err(e) => self.status = format!("Open commit failed: {e}"),
}
}
Err(e) => self.status = format!("Show commit failed: {e}"),
}
}
fn handle_extensions_key(&mut self, key: KeyEvent) {
let has_mod = key
.modifiers
.intersects(KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SUPER);
// Keep the filter caret solid right after a key, like the commit box.
self.poke_cursor();
match key.code {
KeyCode::Up => self.extensions.move_up(),
KeyCode::Down => self.extensions.move_down(),
KeyCode::PageUp => self.extensions.scroll_up(10),
KeyCode::PageDown => self.extensions.scroll_down(10),
// Space / Enter flip the selected extension's toggle switch. Space is
// reserved for the toggle (per the panel's design), so the filter box
// takes every other printable character but never a space.
KeyCode::Char(' ') if !has_mod => self.toggle_selected_extension(),
KeyCode::Enter => self.toggle_selected_extension(),
// Delete uninstalls the selected installed extension (distinct from
// Backspace, which edits the filter). Reaches the app on both iTerm2
// and Ghostty as a plain key, so no chord forwarder is needed.
KeyCode::Delete => self.uninstall_selected_extension(),
KeyCode::Backspace if !self.extensions.filter_is_empty() => {
self.extensions.pop_filter_char()
}
KeyCode::Char(c) if !has_mod => self.extensions.push_filter_char(c),
// Esc clears an active filter first; a second Esc leaves the view.
KeyCode::Esc if !self.extensions.clear_filter() => {
self.set_sidebar_view(SidebarView::Explorer)
}
_ => {}
}
}
/// Flip the enabled state of the Extensions panel's selected row: update the
/// in-memory disabled set, persist it, rebuild the list (so the row's state
/// label and dim styling refresh), and apply any immediate feature gating
/// (e.g. closing a now-disabled viewer). LSP extensions only re-evaluate on
/// the next launch; the others gate live.
fn toggle_selected_extension(&mut self) {
let Some(id) = self.extensions.selected_id().map(str::to_string) else {
return;
};
// A FROM VS CODE row with nothing to install is an answer, not a
// control: say what croft has for it and stop.
if let Some(item) = self.extensions.selected_item()
&& item.vscode
&& item.install.is_none()
{
self.status = format!("{}: {}", item.id, item.description);
return;
}
// AVAILABLE catalog rows: the toggle "adds" (installs) rather than
// enables. Materialize the manifest into the user extensions dir, then
// refresh so it moves into INSTALLED (enabled by default). A FROM VS
// CODE row installs its croft equivalent, not its own (VS Code) id.
if self.extensions.selected_available() {
let id = self
.extensions
.selected_install_target()
.map(str::to_string)
.unwrap_or(id);
match crate::mcp::catalog::install(&id) {
Ok(_) => {
self.refresh_extensions();
self.status = format!(
"Added '{id}' — invoke it from the Command Palette (its server installs on first use)"
);
}
Err(e) => self.status = format!("Could not add '{id}': {e}"),
}
return;
}
let now_enabled = self.disabled_extensions.contains(&id);
if now_enabled {
self.disabled_extensions.remove(&id);
} else {
self.disabled_extensions.insert(id.clone());
}
let _ =
crate::prefs::save_disabled_extensions_in(&self.config_dir, &self.disabled_extensions);
self.refresh_extensions();
self.status = format!(
"{} extension '{id}'",
if now_enabled { "Enabled" } else { "Disabled" }
);
}
/// Uninstall the selected INSTALLED extension: delete its manifest from the
/// user extensions dir so it drops back to AVAILABLE on refresh. Restricted
/// to catalog-sourced ids — croft only removes what it added, never a
/// hand-dropped user manifest (which it can only disable). Reversible by
/// re-adding from the catalog with one keystroke, so no confirmation modal.
fn uninstall_selected_extension(&mut self) {
if !self.extensions.selected_removable() {
return;
}
let Some(id) = self.extensions.selected_id().map(str::to_string) else {
return;
};
if !crate::mcp::catalog::is_removable(&id) {
self.status =
format!("'{id}' is your own extension — croft won't delete it; disable it instead");
return;
}
// Confirm before removing: uninstall is destructive and must never fire
// from a single Delete keypress (or trash click) without asking. Enter in
// the popup performs it; Esc keeps the extension. (Seed a sentinel value
// so Enter on the empty field still submits — submit_value() ignores blanks.)
use crate::widgets::input_prompt::{InputPrompt, InputPurpose};
self.open_input_prompt(
InputPrompt::new(
InputPurpose::ExtensionUninstall { id: id.clone() },
format!("Uninstall '{id}'? It returns to Available."),
"Enter to uninstall · Esc to keep",
)
.with_value("uninstall"),
);
}
/// Perform the confirmed uninstall (the popup's Enter path). Removes the
/// catalog/index-installed manifest and refreshes the panel.
fn perform_extension_uninstall(&mut self, id: &str) {
match crate::mcp::catalog::uninstall_in(&self.config_dir.join("extensions"), id) {
Ok(()) => {
// Drop any stale disabled-state for the removed id so a later
// re-add starts enabled, matching a fresh install.
if self.disabled_extensions.remove(id) {
let _ = crate::prefs::save_disabled_extensions_in(
&self.config_dir,
&self.disabled_extensions,
);
}
// And its consent: a re-add is a program the user has not
// approved this time, so the first-run gate asks again.
self.forget_extension_consent(id);
self.refresh_extensions();
self.status = format!("Uninstalled '{id}' — it's back under AVAILABLE to re-add");
}
Err(e) => self.status = format!("Could not uninstall '{id}': {e}"),
}
}
/// Write a first-run consent for `ext_id` to prefs, after the caller has
/// put it in the session set both gates read. The session grant holds
/// either way; a prefs write that fails is said in the status rather
/// than swallowed, since the user would otherwise be asked again next
/// launch with no idea why.
fn persist_extension_consent(&mut self, ext_id: &str) {
if let Err(e) = crate::prefs::save_mcp_consent_in(&self.config_dir, ext_id) {
self.status = format!("Allowed {ext_id}, but the consent could not be saved: {e}");
}
}
/// Forget `id`'s first-run consent in the session set and in prefs.
fn forget_extension_consent(&mut self, id: &str) {
self.consented_extensions.remove(id);
let _ = crate::prefs::forget_mcp_consent_in(&self.config_dir, id);
}
/// Whether the extension `id` is currently enabled (not in the disabled set).
/// The single gate the bundled features consult before activating.
fn is_extension_enabled(&self, id: &str) -> bool {
!self.disabled_extensions.contains(id)
}
fn handle_run_debug_key(&mut self, key: KeyEvent) {
// While a session is live the panel is a REPL: text edits the prompt and
// Enter evaluates it. Esc always leaves the view.
if self.run_debug.debug_active {
match key.code {
KeyCode::Esc => self.set_sidebar_view(SidebarView::Explorer),
KeyCode::Enter => {
self.debug_repl_submit();
self.refresh_debug_panel();
}
KeyCode::Backspace => {
self.run_debug.repl_input.pop();
}
KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => {
self.run_debug.repl_input.push(c);
}
_ => {}
}
return;
}
match key.code {
KeyCode::Esc => self.set_sidebar_view(SidebarView::Explorer),
KeyCode::Enter => self.run_debug_button_action(),
_ => {}
}
}
/// Testing view keys: Enter runs all tests, `r` re-discovers, arrows scroll
/// the tree, Esc returns to the Explorer (mirrors the Run-and-Debug view).
fn handle_testing_key(&mut self, key: KeyEvent) {
match key.code {
KeyCode::Esc => self.set_sidebar_view(SidebarView::Explorer),
KeyCode::Enter => self.run_all_tests(),
KeyCode::Char('r' | 'R') => self.discover_tests(),
KeyCode::Up => self.testing.scroll_up(1),
KeyCode::Down => self.testing.scroll_down(1),
_ => {}
}
}
/// Whether an enabled runner extension claims this workspace. When none
/// does — no recognised project, or its runner toggled off in the
/// Extensions panel — every run gesture must refuse here: the worker's
/// fallback used to shell `cargo test` regardless, so a disabled Rust
/// runner still ran (and rebuilt) the workspace, and a disabled Python
/// runner ran cargo in a directory with no Cargo.toml.
fn testing_runner_available(&mut self) -> bool {
if crate::testing::worker::runner_for(&self.active_test_root).is_some() {
return true;
}
self.status = String::from(crate::testing::NO_RUNNER_STATUS);
false
}
/// Rebind the Testing stack to `root` — the focused file's workspace
/// folder (#151). Exactly the re-root rebind: the worker's epoch drops
/// in-flight results for the old root, the panel resets (its tree
/// described another project), a pending debug build is dropped, and
/// the front-of-view panel re-discovers immediately.
fn rebind_test_root(&mut self, root: PathBuf) {
self.active_test_root = root.clone();
self.test_worker.set_root(root);
self.testing.reset();
// The build this armed for is being dropped (#373).
self.disarm_failure_breakpoint();
self.pending_test_debug = None;
if self.sidebar_view == SidebarView::Testing {
self.discover_tests();
}
}
/// Kick off a full test run on the worker (no-op if a run/discovery is
/// already in flight) and reveal the Testing view so results stream in.
fn run_all_tests(&mut self) {
if self.testing.is_busy() || !self.testing_runner_available() {
return;
}
self.test_worker.run_all();
self.set_sidebar_view(SidebarView::Testing);
}
/// Run a single test by exact name (click-to-run from the tree). Marks just
/// that case Running and keeps the rest of the discovered list intact.
fn run_test(&mut self, name: String) {
if self.testing.is_busy() || !self.testing_runner_available() {
return;
}
self.testing.start_single(&name);
self.test_worker.run_one(name);
self.set_sidebar_view(SidebarView::Testing);
}
/// Jump the editor to a test's `fn` definition (Cmd/Opt+click in the tree).
/// `--list` carries no location, so we grep the source for the function —
/// a whole-workspace walk, so it runs on a background thread and the jump
/// lands via the drain in [`Self::sync_explorer_panels`].
fn jump_to_test_source(&mut self, name: String) {
let root = self.active_test_root.clone();
let tx = self.test_jump_tx.clone();
self.status = format!("Locating test {name}");
std::thread::spawn(move || {
let hit = crate::testing::locate::find_test_source(&root, &name);
let _ = tx.send((root, name, hit));
});
}
/// Run every test in a suite (click on its header in the tree). cargo's
/// filter and the panel's marking are substring matches, so the pattern is
/// anchored (`parse::`) to keep `parse` from sweeping `parse_utils::b`.
fn run_suite(&mut self, suite: String) {
if self.testing.is_busy() || !self.testing_runner_available() {
return;
}
self.testing
.start_filter(&crate::testing::suite_pattern(&suite));
self.test_worker.run_suite(suite);
self.set_sidebar_view(SidebarView::Testing);
}
/// Run the test the editor caret sits in (Cmd+K Enter / palette). Finds the
/// enclosing `fn` and runs it by name; results stream into the
/// Testing view like any other run.
fn run_test_at_cursor(&mut self) {
let Some(name) =
crate::testing::locate::enclosing_fn_name(&self.editor.lines, self.editor.cursor_row)
else {
self.status = String::from("Run Test at Cursor: no function at the caret");
return;
};
self.run_named_test(name);
}
/// Start the test `name` through the worker and reveal the Testing view —
/// the shared tail of run-at-cursor and the editor's gutter play glyph.
/// A leaf unique in the discovered tree resolves to its full name for an
/// exact run; otherwise cargo's substring filter is the best available.
fn run_named_test(&mut self, name: String) {
if self.testing.is_busy() || !self.testing_runner_available() {
return;
}
let (run, exact) = match self.testing.sole_case_with_leaf(&name) {
Some(full) => (full, true),
None => (name, false),
};
if exact {
self.testing.start_single(&run);
self.test_worker.run_one(run.clone());
} else {
self.testing.start_filter(&run);
self.test_worker.run_filter(run.clone());
}
self.set_sidebar_view(SidebarView::Testing);
self.status = format!("Running test {run}");
}
/// Debug the test the editor caret sits in (Cmd+K Shift+Enter, palette).
fn debug_test_at_cursor(&mut self) {
let Some(name) =
crate::testing::locate::enclosing_fn_name(&self.editor.lines, self.editor.cursor_row)
else {
self.status = String::from("Debug Test at Cursor: no function at the caret");
return;
};
self.debug_named_test(name);
}
/// Hand the test `name` to the debugger — the M6 wedge: pytest runs as a
/// debugpy module launch under the PROJECT's interpreter, a cargo test
/// binary launches under lldb-dap with the name as its libtest filter.
/// Shared by debug-at-cursor and Alt+click on the gutter play glyph.
fn debug_named_test(&mut self, name: String) {
use std::collections::BTreeMap;
if self.dap_session.is_some() {
self.status = String::from("A debug session is already running (Shift+F5 stops it)");
return;
}
let root = self.tree.root.clone();
// #373: if the last run of this test failed and named a place in
// the user's own code, break there — the whole point of "debug this
// test" is landing on the assertion without being asked to find it
// first. Set BEFORE the launch set is collected so it travels with
// the user's own breakpoints, and recorded so it can be taken back
// out when the session ends.
self.arm_failure_breakpoint(&name, &root);
let breakpoints: BTreeMap<PathBuf, Vec<crate::dap::session::SourceBreakpoint>> = self
.editor
.breakpoints
.iter()
.map(|(p, lines)| (p.clone(), self.editor.source_breakpoints(p, lines)))
.collect();
match crate::testing::worker::runner_for(&root) {
Some(crate::testing::worker::Runner::Pytest) => {
let adapter_py = match crate::dap::install::ensure_debug_venv() {
Ok(py) => py,
Err(e) => {
self.debug_error(format!("Debugger setup failed: {e}"));
return;
}
};
let project_py = project_python(&root);
let request =
crate::dap::session::pytest_debug_launch_request(&project_py, &root, &name);
let adapter_args = vec![String::from("-m"), String::from("debugpy.adapter")];
match crate::dap::session::DapSession::launch_with(
&adapter_py.to_string_lossy(),
&adapter_args,
&root,
request,
breakpoints,
) {
Ok(session) => {
self.dap_session = Some(session);
self.run_debug.feedback = Some(format!("Debugging test {name}"));
self.run_debug.feedback_is_error = false;
self.status = self.with_failure_note(format!(
"Debugging test {name} — F5 continue · F10 step over · Shift+F5 stop"
));
self.reveal_debug_view();
}
Err(e) => self.debug_error(format!("Failed to start debugger: {e}")),
}
}
Some(crate::testing::worker::Runner::Cargo) => {
if lldb_dap_path().is_none() {
self.debug_error(lldb_dap_missing_message());
return;
}
// The file the gesture happened in narrows the harness: a
// lib test and an integration test can share a bare fn name.
let source = self.editor.path.clone();
self.start_test_binary_build(root, name, source);
}
Some(crate::testing::worker::Runner::Vitest | crate::testing::worker::Runner::Jest) => {
// No session will start, so the armed breakpoint has nothing
// to be cleaned up by (#373).
self.disarm_failure_breakpoint();
self.status =
String::from("Debugging JS tests is not wired yet — the play glyph runs them");
}
None => {
self.disarm_failure_breakpoint();
self.status = String::from("No test runner detected in this workspace");
}
}
}
/// Kick off `cargo test --no-run` on a background thread and remember the
/// receiver: a cold build takes minutes, and running it on the UI thread
/// froze every pane — no keys, no redraw, no PTY pumping — while the
/// "Building…" status could never even paint before the launch overwrote
/// it. The drain launches the debugger when the binary arrives.
fn start_test_binary_build(&mut self, root: PathBuf, name: String, source: Option<PathBuf>) {
if self.pending_test_debug.is_some() {
// The launch this armed for is not happening (#373).
self.disarm_failure_breakpoint();
self.status = String::from("A test binary is already building");
return;
}
self.status = self.with_failure_note(format!("Building test binary for {name}"));
let (tx, rx) = std::sync::mpsc::channel();
{
let name = name.clone();
let root = root.clone();
std::thread::spawn(move || {
let _ = tx.send(
crate::testing::worker::build_test_binary(&root, &name, source.as_deref())
.map_err(|e| e.to_string()),
);
});
}
self.pending_test_debug = Some((rx, name, root));
}
/// Drain the background test-binary build: on success launch lldb-dap
/// (with the editor's breakpoints as they are NOW — the user may have set
/// more while the build ran), on failure surface the error. Returns true
/// when anything landed, for the redraw aggregate.
fn drain_pending_test_debug(&mut self) -> bool {
use std::sync::mpsc::TryRecvError;
let Some((rx, _, _)) = self.pending_test_debug.as_ref() else {
return false;
};
let result = match rx.try_recv() {
Ok(r) => r,
Err(TryRecvError::Empty) => return false,
Err(TryRecvError::Disconnected) => Err(String::from("the build thread died")),
};
let (_, name, build_root) = self.pending_test_debug.take().expect("checked above");
// Re-rooting the Explorer mid-build would otherwise launch the old
// workspace's binary with the new workspace's cwd and breakpoints.
if build_root != self.tree.root {
// No launch, so nothing will clean up after it (#373).
self.disarm_failure_breakpoint();
self.status = format!(
"Test binary for {name} finished, but the workspace changed — debug it again from its workspace"
);
return true;
}
match result {
Ok(binary) => self.launch_lldb_test_debug(&binary, &name),
Err(e) => self.debug_error(format!("Test build failed: {e}")),
}
true
}
/// The launch tail of debug-a-cargo-test, run from the drain once the
/// background build hands over the binary.
fn launch_lldb_test_debug(&mut self, binary: &Path, name: &str) {
use std::collections::BTreeMap;
if self.dap_session.is_some() {
// The build took minutes and the user started another session
// meanwhile: this launch is abandoned, so the breakpoint it
// armed has nothing to clean up after it (#373).
self.disarm_failure_breakpoint();
self.status = String::from("A debug session is already running (Shift+F5 stops it)");
return;
}
let Some(adapter) = lldb_dap_path() else {
self.debug_error(lldb_dap_missing_message());
return;
};
let root = self.tree.root.clone();
let breakpoints: BTreeMap<PathBuf, Vec<crate::dap::session::SourceBreakpoint>> = self
.editor
.breakpoints
.iter()
.map(|(p, lines)| (p.clone(), self.editor.source_breakpoints(p, lines)))
.collect();
// The bare name is libtest's substring filter (run-at-cursor has no
// full module path); --nocapture keeps output visible.
let args = vec![name.to_string(), String::from("--nocapture")];
let request = crate::dap::session::lldb_test_launch_request(binary, &args);
match crate::dap::session::DapSession::launch_with(
&adapter,
&[],
&root,
request,
breakpoints,
) {
Ok(session) => {
self.dap_session = Some(session);
self.run_debug.feedback = Some(format!("Debugging test {name} (lldb)"));
self.run_debug.feedback_is_error = false;
self.status = self.with_failure_note(format!(
"Debugging test {name} via lldb-dap — F5 continue · Shift+F5 stop"
));
self.reveal_debug_view();
}
Err(e) => self.debug_error(format!("Failed to start lldb-dap: {e}")),
}
}
/// List tests without running them (populate the tree). No-op while busy or
/// outside a recognised test project (Cargo or pytest) — the tool would
/// error with no manifest, and `cargo test -- --list` compiles the test
/// binary so we never auto-fire it per-keystroke.
fn discover_tests(&mut self) {
if self.testing.is_busy()
|| crate::testing::worker::runner_for(&self.active_test_root).is_none()
{
return;
}
self.test_worker.discover();
}
/// Reveal the Testing view (the user-open gesture: activity icon, Cmd+K B,
/// palette). Auto-discovers once when the tree is still empty so it
/// populates like VS Code, without recompiling on every subsequent open.
fn open_testing_view(&mut self) {
self.show_tree = true;
self.set_sidebar_view(SidebarView::Testing);
if self.testing.is_empty() {
self.discover_tests();
}
}
fn refresh_run_debug(&mut self) {
let path = self.editor.path.clone();
// Decide the button: scripts and executables are "Run" (terminal);
// compiled source (no script runner, but a debug adapter) is "Debug"
// (build + lldb). Files that are neither (e.g. `.git/config`) get no
// button. run_spec_for already covers executables (the +x bit), so a
// compiled binary is "Run" — run it directly.
let (runnable, is_debug) = match path.as_deref() {
Some(p) => {
let ext = p
.extension()
.and_then(|e| e.to_str())
.unwrap_or("")
.to_ascii_lowercase();
if Self::run_spec_for(
p,
self.roots
.owning_root(p)
.unwrap_or_else(|| self.roots.primary()),
)
.is_some()
{
(true, false)
} else if crate::dap::registry::adapter_for_extension(&ext).is_some() {
(true, true)
} else {
(false, false)
}
}
None => (false, false),
};
self.run_debug.runnable = runnable;
self.run_debug.run_is_debug = is_debug;
self.run_debug.set_active_file(path);
self.run_debug.feedback = None;
self.run_debug.feedback_is_error = false;
// The launch.json config row (#250): count + F5 selection. Discovery
// re-reads the same two small files once per helper — four reads — and
// this only runs on active-file changes.
// Compounds count too — the row is the documented route to the picker,
// and the picker lists them, so counting only configurations makes the
// row vanish for a compounds-only workspace and undercount otherwise.
//
// A HIDDEN compound is not listed (#318), so it must not be counted
// either: the row and the picker have to agree, or a workspace whose
// only entry is hidden advertises "1 debug entry" over a picker that
// offers nothing. Same filter as `open_debug_config_picker`.
let root = self.active_workspace_root();
// The same filter the picker applies, so the badge and the picker
// cannot disagree: a `presentation.hidden` entry of EITHER kind is
// absent from both (#318).
self.run_debug.config_count = crate::dap::configs::discover_configs(&root)
.iter()
.filter(|c| !c.hidden())
.count()
+ crate::dap::configs::discover_compounds(&root)
.iter()
.filter(|c| !c.hidden())
.count();
self.run_debug.selected_config = self.selected_debug_config.clone();
}
/// Resolve how to run `file`: which command line to feed the PTY and
/// which directory the PTY should `chdir` to. Returns `None` for
/// extensions we don't know how to run.
///
/// For Python files the resolver walks from the file's directory up to
/// (and including) `workspace_root`, picking the first `.venv/bin/python`,
/// `venv/bin/python`, or `.env/bin/python` it finds. The cwd is set to
/// the directory that owns the venv so relative imports, `.env` reads,
/// and any path-relative work the script does line up with how the user
/// would run it from their own shell. With no venv anywhere on the
/// path the resolver falls back to the system `python3` and the file's
/// own directory.
fn run_spec_for(file: &Path, workspace_root: &Path) -> Option<RunSpec> {
let ext = file
.extension()
.and_then(|e| e.to_str())
.unwrap_or("")
.to_ascii_lowercase();
let file_str = file.to_string_lossy().into_owned();
let file_dir = file.parent().unwrap_or(Path::new(".")).to_path_buf();
if matches!(ext.as_str(), "py" | "pyi" | "pyw") {
if let Some((py, venv_dir)) = find_python_venv(&file_dir, workspace_root) {
return Some(RunSpec {
program: py.to_string_lossy().into_owned(),
args: vec![file_str],
cwd: venv_dir,
});
}
return Some(RunSpec {
program: String::from("python3"),
args: vec![file_str],
cwd: file_dir,
});
}
let runner: &str = match ext.as_str() {
"js" | "mjs" | "cjs" => "node",
"ts" | "tsx" => "tsx",
"rb" => "ruby",
"lua" => "lua",
"php" => "php",
"pl" => "perl",
"sh" | "bash" => "bash",
"zsh" => "zsh",
"fish" => "fish",
_ => {
// No known script runner. If the file is itself an executable
// (a compiled binary, usually extensionless), run it directly.
if is_executable_file(file) {
return Some(RunSpec {
program: file_str,
args: vec![],
cwd: file_dir,
});
}
return None;
}
};
Some(RunSpec {
program: String::from(runner),
args: vec![file_str],
cwd: file_dir,
})
}
/// Spawn a fresh PTY at the resolved working directory, seed it with the
/// runner command for the active editor tab's file, and focus the
/// terminal pane so the user sees output immediately.
/// Drain the debug session each frame. Returns true if anything changed
/// (so the frame loop redraws). Mirrors the paused location into the
/// editor's stop-line, surfaces program output + stop reasons, and tears
/// the session down when the debuggee exits.
pub fn poll_dap(&mut self) -> bool {
use crate::dap::session::{DapEvent, SessionPhase};
if self.dap_session.is_none() {
return false;
}
let events = self
.dap_session
.as_mut()
.map(|s| s.poll())
.unwrap_or_default();
let mut changed = !events.is_empty();
for ev in events {
match ev {
// Route program output to the debug console (each embedded
// newline becomes its own line), but drop debugpy's own
// `telemetry` banner (the `ptvsd` / `debugpy` noise).
DapEvent::Output { category, text }
if crate::dap::session::output_is_user_visible(&category) =>
{
for line in text.split('\n') {
if !line.is_empty() {
self.debug_console_push(line.to_string());
}
}
}
// REPL submissions echo "❯ expr" then the result; watch/hover
// results are consumed elsewhere.
DapEvent::Evaluated {
context,
expression,
result,
..
} if context == "repl" => {
self.debug_console_push(format!("❯ {expression}"));
self.debug_console_push(result);
}
DapEvent::Evaluated {
context,
expression,
result,
success,
} if context == "watch" => {
self.watch_vals.insert(expression, (result, success));
}
// Fresh stack + frame selection just landed: this is the
// moment each watch expression re-evaluates against the new
// top frame (#112).
DapEvent::InspectionUpdated => {
self.refresh_watches();
self.refresh_inline_values();
changed = true;
}
DapEvent::Stopped { reason, .. } => {
self.run_debug.feedback = Some(format!("Paused ({reason})"));
self.run_debug.feedback_is_error = false;
self.watch_baseline_pending = true;
}
DapEvent::BreakpointsUpdated => {
// Mirror the adapter's unverified set into the editor so the
// gutter can hollow out inert breakpoints, and warn once if
// any failed to bind (the "I set a breakpoint and it just
// ran" case).
let unverified: std::collections::HashMap<
PathBuf,
std::collections::BTreeSet<usize>,
> = self
.dap_session
.as_ref()
.map(|s| s.unverified_breakpoints.clone().into_iter().collect())
.unwrap_or_default();
let total: usize = unverified.values().map(|s| s.len()).sum();
self.editor.unverified_breakpoints = unverified;
if total > 0 {
self.status = format!(
"{total} breakpoint(s) could not bind (no executable code on that line)"
);
}
}
_ => {}
}
}
let phase = self.dap_session.as_ref().map(|s| s.phase);
match phase {
Some(SessionPhase::Stopped) => {
self.debug_ever_stopped = true;
let loc = self
.dap_session
.as_ref()
.and_then(|s| s.current_location.clone());
if let Some(loc) = loc
&& self.editor.stop_line.as_ref() != Some(&loc)
{
self.editor.stop_line = Some(loc);
// A re-stop at the same location can re-arm the arrow
// without a fresh InspectionUpdated on this tick; rebuild
// the trailers here too so arrow and values never split
// (#136 review). Idempotent over already-fetched data.
self.refresh_inline_values();
changed = true;
}
}
Some(SessionPhase::Terminated) => {
self.editor.stop_line = None;
self.editor.unverified_breakpoints.clear();
// A session that ends on its own must take croft's own
// breakpoint with it, exactly as Shift+F5 does (#373):
// this is the path a passing test takes, so it is the
// common one, not the exceptional one.
self.disarm_failure_breakpoint();
self.reset_watch_runtime();
self.clear_inline_values();
// Reply to the adapter's own `terminated`/`exited` with the
// graceful `disconnect` handshake before dropping it. js-debug
// only retires its detached watchdog on this handshake, never on
// a SIGKILL of the server, so the natural-exit path used to leak
// the watchdog by dropping straight to a kill.
if let Some(session) = self.dap_session.as_mut() {
session.disconnect();
}
self.dap_session = None;
// The watchdog reparents to init the moment the server dies;
// sweep it (and any tree a crashed prior croft left behind)
// after a short grace so it has settled into the orphan state.
crate::dap::reaper::reap_orphaned_js_debug_async(std::time::Duration::from_millis(
REAPER_TEARDOWN_GRACE_MS,
));
let had_breakpoints = !self.editor.breakpoints.is_empty();
self.run_debug.feedback =
Some(debug_end_message(had_breakpoints, self.debug_ever_stopped).to_string());
self.run_debug.feedback_is_error = false;
// Keep `debug_console` so its output stays visible after the run;
// the panel renders it until the next session starts.
self.run_debug.session_ended = true;
changed = true;
}
_ => {
if self.editor.stop_line.take().is_some() {
// The trailers clear wherever the stop arrow clears
// (#136 review): this arm catches every phase change the
// four explicit resume sites don't, guarded the same way
// so ordinary Running ticks pay nothing.
self.clear_inline_values();
changed = true;
}
}
}
// Rebuild the Call Stack / Variables panel from the (now-updated) session.
self.refresh_debug_panel();
changed
}
/// Rebuild the Run & Debug panel's paused-state tree from the session, or
/// deactivate it when not paused. Cheap; called after each `poll_dap`.
fn refresh_debug_panel(&mut self) {
let (active, status, rows) = self.build_debug_view();
self.run_debug.debug_active = active;
if active {
self.run_debug.debug_status = status;
self.run_debug.debug_rows = rows;
let max_scroll = self.run_debug.debug_rows.len().saturating_sub(1);
if self.run_debug.debug_scroll > max_scroll {
self.run_debug.debug_scroll = max_scroll;
}
// Show the console tail (most recent output / REPL lines).
let n = self.debug_console.len();
self.run_debug.console_tail = self.debug_console[n.saturating_sub(50)..].to_vec();
} else {
self.run_debug.debug_rows.clear();
self.run_debug.debug_scroll = 0;
self.run_debug.repl_input.clear();
// Retain the just-ended session's console output until the next run;
// otherwise the idle Run panel shows nothing.
if self.run_debug.session_ended && !self.debug_console.is_empty() {
let n = self.debug_console.len();
self.run_debug.console_tail = self.debug_console[n.saturating_sub(50)..].to_vec();
} else {
self.run_debug.console_tail.clear();
}
}
}
/// Build the (active, status, rows) tuple for the debug panel from the
/// session. `&self` so it can borrow the session and expansion set without
/// conflicting with the `&mut self` assignment in `refresh_debug_panel`.
fn build_debug_view(&self) -> (bool, String, Vec<crate::widgets::run_debug::DebugRow>) {
use crate::dap::session::SessionPhase;
use crate::widgets::run_debug::{DebugRow, DebugRowKind};
let Some(session) = self.dap_session.as_ref() else {
return (false, String::new(), Vec::new());
};
// Active for any live session: while Running the tree is empty but the
// console still shows output; while Stopped the full tree is built.
if session.phase == SessionPhase::Terminated {
return (false, String::new(), Vec::new());
}
if session.phase != SessionPhase::Stopped {
let status = self
.run_debug
.feedback
.clone()
.unwrap_or_else(|| String::from("Running"));
return (true, status, Vec::new());
}
let mut rows = Vec::new();
rows.push(DebugRow {
indent: 0,
kind: DebugRowKind::Header {
title: String::from("CALL STACK"),
},
});
for f in &session.stack_frames {
let loc = f
.path
.as_ref()
.and_then(|p| p.file_name())
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
rows.push(DebugRow {
indent: 1,
kind: DebugRowKind::Frame {
id: f.id,
selected: Some(f.id) == session.selected_frame,
name: f.name.clone(),
location: format!("{loc}:{}", f.line),
},
});
}
rows.push(DebugRow {
indent: 0,
kind: DebugRowKind::Header {
title: String::from("VARIABLES"),
},
});
for scope in &session.scopes {
rows.push(DebugRow {
indent: 1,
kind: DebugRowKind::Scope {
name: scope.name.clone(),
},
});
if let Some(vars) = session.variables.get(&scope.variables_ref) {
push_variable_rows(&mut rows, session, &self.debug_expanded, vars, 2);
}
}
rows.push(DebugRow {
indent: 0,
kind: DebugRowKind::Header {
title: String::from("WATCH"),
},
});
for (widx, expr) in self.watch_exprs.iter().enumerate() {
let (value, available, pending) = match self.watch_vals.get(expr) {
Some((v, ok)) => (v.clone(), *ok, false),
None => (String::new(), true, true),
};
let changed = available
&& !pending
&& self.watch_prev.get(expr).is_some_and(|prev| prev != &value);
rows.push(DebugRow {
indent: 1,
kind: DebugRowKind::Watch {
index: widx,
expression: expr.clone(),
value,
available,
changed,
pending,
},
});
}
rows.push(DebugRow {
indent: 1,
kind: DebugRowKind::WatchAdd,
});
let status = self
.run_debug
.feedback
.clone()
.unwrap_or_else(|| String::from("Paused"));
(true, status, rows)
}
/// Re-evaluate every watch expression against the current stop. The
/// current values become the previous stop's baseline first, so the
/// changed-value highlight compares stop-to-stop (#112).
fn refresh_watches(&mut self) {
if self.watch_exprs.is_empty() {
return;
}
if std::mem::take(&mut self.watch_baseline_pending) {
self.watch_prev = self
.watch_vals
.drain()
.filter(|(_, (_, ok))| *ok)
.map(|(k, (v, _))| (k, v))
.collect();
}
if let Some(session) = self
.dap_session
.as_mut()
.filter(|s| s.phase == crate::dap::session::SessionPhase::Stopped)
{
for expr in &self.watch_exprs {
session.evaluate(expr, "watch");
}
}
}
/// Append a watch expression (palette or the panel's add row) and
/// evaluate it immediately when a session is paused.
fn add_watch_expression(&mut self, expr: String) {
let expr = expr.trim().to_string();
if expr.is_empty() {
self.status = String::from("Enter an expression to watch");
return;
}
if self.watch_exprs.contains(&expr) {
self.status = format!("Already watching {expr}");
return;
}
self.watch_exprs.push(expr.clone());
if let Some(session) = self
.dap_session
.as_mut()
.filter(|s| s.phase == crate::dap::session::SessionPhase::Stopped)
{
session.evaluate(&expr, "watch");
}
self.status = format!("Watching {expr}");
}
fn remove_watch_expression(&mut self, idx: usize) {
if idx < self.watch_exprs.len() {
let expr = self.watch_exprs.remove(idx);
self.watch_vals.remove(&expr);
self.watch_prev.remove(&expr);
self.status = format!("Stopped watching {expr}");
}
}
/// Append a line to the debug console, capping the backlog so a chatty
/// program can't grow it without bound.
fn debug_console_push(&mut self, line: String) {
const CAP: usize = 1000;
self.debug_console.push(line);
if self.debug_console.len() > CAP {
let overflow = self.debug_console.len() - CAP;
self.debug_console.drain(..overflow);
}
}
/// Submit the Run & Debug panel's REPL input: echo + evaluate it at the
/// selected frame. No-op on empty input or with no session.
fn debug_repl_submit(&mut self) {
let expr = self.run_debug.repl_input.trim().to_string();
self.run_debug.repl_input.clear();
if expr.is_empty() {
return;
}
match self.dap_session.as_mut() {
Some(session) => session.evaluate(&expr, "repl"),
None => self.debug_console_push(String::from("(no debug session)")),
}
}
/// Hover-to-evaluate: while a debug session is paused, return a popup string
/// for the identifier at `(line, c)` if it's a loaded local/global, else
/// None (so the normal LSP hover proceeds).
fn debug_hover_value(&self, line: usize, c: usize) -> Option<String> {
use crate::dap::session::SessionPhase;
let session = self.dap_session.as_ref()?;
if session.phase != SessionPhase::Stopped {
return None;
}
let word = self.editor.word_string_at(line, c)?;
let var = session.lookup_local(&word)?;
let ty = if var.type_name.is_empty() {
String::new()
} else {
format!(": {}", var.type_name)
};
Some(format!("{} = {}{ty}", var.name, var.value))
}
/// Act on a click of debug-panel row `idx`: select a call-stack frame (load
/// its scopes/variables) or toggle an expandable variable open/closed.
fn debug_panel_click(&mut self, idx: usize) {
use crate::widgets::run_debug::DebugRowKind;
let Some(row) = self.run_debug.debug_rows.get(idx) else {
return;
};
match row.kind.clone() {
DebugRowKind::Frame { id, .. } => {
if let Some(session) = self.dap_session.as_mut() {
session.load_frame(id);
}
// Collapse expansions: variable refs are frame-scoped.
self.debug_expanded.clear();
}
DebugRowKind::Variable {
reference,
expandable: true,
..
} => {
if self.debug_expanded.contains(&reference) {
self.debug_expanded.remove(&reference);
} else {
self.debug_expanded.insert(reference);
if let Some(session) = self.dap_session.as_mut() {
session.expand_variable(reference);
}
}
}
DebugRowKind::WatchAdd => {
self.open_add_watch_prompt();
}
_ => {}
}
self.refresh_debug_panel();
}
/// Cmd+F on a hex tab (#172): a single-line input popup, per croft's
/// inputs-in-popups rule. Hex byte pairs or literal ASCII.
fn open_hex_find_prompt(&mut self) {
use crate::widgets::input_prompt::{InputPrompt, InputPurpose};
if self.editor.hex.is_none() {
return;
}
self.open_input_prompt(InputPrompt::new(
InputPurpose::HexFind,
"Find in Hex",
"hex bytes (de ad be ef) or text",
));
}
/// The "+ Add Expression" affordance (panel row or palette): a single-line
/// input popup, per croft's inputs-in-popups rule.
fn open_add_watch_prompt(&mut self) {
use crate::widgets::input_prompt::{InputPrompt, InputPurpose};
self.open_input_prompt(InputPrompt::new(
InputPurpose::AddWatch,
"Add Watch Expression",
"expression",
));
}
/// The Run/Debug panel button action: debug compiled source (build + lldb),
/// or run scripts/executables in a terminal — matching the button's verb.
fn run_debug_button_action(&mut self) {
if self.run_debug.run_is_debug {
self.debug_start_or_continue();
} else {
self.run_active_file();
}
}
/// Open and focus the Run and Debug view so the call stack, variables,
/// console, and REPL are visible the instant a session starts (VS Code
/// reveals its debug view on launch the same way).
fn reveal_debug_view(&mut self) {
// A fresh session: drop the previous run's retained console + stop
// tracking so the "exited without hitting a breakpoint" hint and the
// console reflect only this run.
self.debug_console.clear();
self.debug_ever_stopped = false;
self.run_debug.session_ended = false;
self.show_tree = true;
self.set_sidebar_view(SidebarView::RunDebug);
self.focus_pane(Pane::Tree);
}
/// Surface a debug-start failure on BOTH the styled Run/Debug panel
/// feedback line AND the always-visible status bar. The panel line only
/// renders while the Run/Debug sidebar is the active view (`reveal_debug_view`
/// is reached only on success), so without the status-bar mirror F5 fails
/// silently whenever the user is looking at any other sidebar — which read
/// as "F5 does nothing" on a remote with no debug adapter installed.
fn debug_error(&mut self, msg: String) {
// A launch that never happened leaves no session to clean up after,
// so any breakpoint croft armed for it comes out here (#373) —
// otherwise it survives in the editor as if the user had set it.
self.disarm_failure_breakpoint();
self.run_debug.feedback = Some(msg.clone());
self.run_debug.feedback_is_error = true;
self.status = msg;
}
/// F5: start debugging the active file, or resume if already paused.
pub fn debug_start_or_continue(&mut self) {
use crate::dap::session::SessionPhase;
if let Some(session) = self.dap_session.as_mut() {
if session.phase == SessionPhase::Stopped {
session.continue_execution();
self.editor.stop_line = None;
self.clear_inline_values();
}
return;
}
self.start_selected_debug();
}
/// Start whatever F5 is pointed at: the selected launch.json
/// configuration when one is chosen, else the zero-config active file.
/// Configs are re-read here so an edited launch.json applies on the next
/// F5 without reopening the picker.
fn start_selected_debug(&mut self) {
if let Some(name) = self.selected_debug_config.clone() {
let root = self.active_workspace_root();
self.debug_configs = crate::dap::configs::discover_configs(&root);
if let Some(cfg) = self.debug_configs.iter().find(|c| c.name == name).cloned() {
self.launch_debug_config(&cfg);
return;
}
// The selection outlived its config (file edited/deleted): fall
// back to zero-config and say so rather than failing silently.
self.selected_debug_config = None;
self.run_debug.selected_config = None;
self.status = format!(
"Debug configuration \"{name}\" no longer exists — debugging the active file"
);
}
self.start_debug_session();
}
/// Debug: Select and Start Debugging — the launch.json configurations
/// plus the synthesized zero-config entry.
pub fn open_debug_config_picker(&mut self) {
use crate::widgets::list_picker::{ListPicker, ListPurpose, ListRow};
let root = self.active_workspace_root();
self.debug_configs = crate::dap::configs::discover_configs(&root);
self.debug_compounds = crate::dap::configs::discover_compounds(&root);
let mut rows = vec![ListRow {
id: String::from("active"),
label: String::from("Debug active file — no configuration"),
}];
// Configurations and compounds are ONE list to sort, which is what
// VS Code does: a config and a compound can name the same
// `presentation.group`, and sorting them separately would split that
// group in two no matter what the file asked for (#318).
//
// Every id is built BEFORE the sort, from `enumerate` over the full
// unsorted list, so `compound:{i}` and `{i}` keep naming the same
// entries however the rows move. Indexing the sorted sequence would
// launch a different configuration than the row says as soon as any
// entry declares a `presentation`.
let entries: Vec<(ListRow, Option<crate::dap::configs::Presentation>)> = self
.debug_configs
.iter()
.enumerate()
.map(|(i, c)| {
(
ListRow {
id: i.to_string(),
label: format!("{} — {} · {}", c.name, c.type_name, c.source),
},
c.presentation.clone(),
)
})
// Compounds are listed so a workspace's own launch.json is
// reflected honestly. Selecting one LAUNCHES it when it names a
// single configuration and carries no key croft cannot honour;
// otherwise it reports what is missing (#310) rather than
// launching a subset, which would debug something other than what
// was asked for.
.chain(self.debug_compounds.iter().enumerate().map(|(i, c)| {
(
ListRow {
id: format!("compound:{i}"),
label: format!(
"{} — compound of {}",
c.name,
c.configurations.join(", ")
),
},
c.presentation.clone(),
)
}))
.collect();
rows.extend(
crate::dap::configs::visible_and_sorted(entries, |(_, p)| p.as_ref())
.into_iter()
.map(|(row, _)| row),
);
self.open_list_picker(
ListPicker::new(ListPurpose::DebugConfig, "Debug Configuration", rows),
"No debug configurations (.croft/launch.json or .vscode/launch.json)",
);
}
/// Continue a parked launch whose `preLaunchTask` has finished.
///
/// Split from the terminal sweep so it can be driven directly: reaching it
/// through the sweep needs a pane emitting OSC 133 marks, and the branch
/// that matters most - a compound's task completing, then its MEMBER
/// starting (#318) - is invisible to every test that only checks the
/// launch parked.
fn resume_pending_launch(&mut self, exit: Option<i32>, step: PendingLaunchStep) {
if exit != Some(0) {
let code = exit.map_or_else(|| String::from("?"), |c| c.to_string());
self.debug_error(format!(
"preLaunchTask exited {code} — debug launch aborted (its pane has the output)"
));
return;
}
match step {
PendingLaunchStep::Resolved(rc) => self.launch_resolved_config(*rc),
// Back through the front door: the member may have a
// `preLaunchTask` of its own, and VS Code runs the compound's AND
// the member's. Calling the resolved-launch path here would
// silently skip the member's.
PendingLaunchStep::Member(cfg) => self.launch_debug_config(&cfg),
}
}
/// Run a COMPOUND's own `preLaunchTask`, then launch its single member
/// (#318).
///
/// Deliberately not folded into [`Self::launch_debug_config`]: that runs
/// the *config's* task as the last step before the adapter, while this one
/// runs before the member is even resolved. Keeping them separate is what
/// lets both fire for a compound whose member also declares a task, which
/// is what VS Code does.
///
/// Same failure contract as a config's task, because a user cannot tell
/// the two apart from the outside: a task the workspace does not declare
/// is an error rather than a silent skip, and a non-zero exit aborts the
/// launch instead of debugging whatever the build left behind.
fn launch_after_compound_task(
&mut self,
task_label: &str,
member: crate::dap::configs::DebugConfig,
) {
if self.dap_session.is_some() {
self.debug_stop();
}
self.pending_debug_launch = None;
let root = self.active_workspace_root();
let tasks = crate::tasks::discover_tasks(&root);
let Some(task) = tasks.into_iter().find(|t| t.label == task_label) else {
self.debug_error(format!(
"compound preLaunchTask \"{task_label}\" not found — Tasks: Run Task lists what the workspace declares"
));
return;
};
let command = task.command.clone();
let Some(pane) = self.run_project_task(task) else {
// run_project_task already reported why the pane failed.
return;
};
self.pending_debug_launch = Some(PendingDebugLaunch {
pane,
command,
step: PendingLaunchStep::Member(Box::new(member)),
started: std::time::Instant::now(),
});
self.run_debug.feedback = Some(format!("compound preLaunchTask \"{task_label}\" running…"));
self.run_debug.feedback_is_error = false;
self.status = format!(
"compound preLaunchTask \"{task_label}\" running — debug starts when it exits 0"
);
}
/// Resolve and launch one launch.json configuration: substitution against
/// the active editor state, then either straight to the adapter or parked
/// behind its `preLaunchTask`.
fn launch_debug_config(&mut self, cfg: &crate::dap::configs::DebugConfig) {
use crate::dap::configs;
if self.dap_session.is_some() {
self.debug_stop();
}
self.pending_debug_launch = None;
let root = self.active_workspace_root();
let ctx = configs::SubstCtx {
workspace_folder: root.clone(),
file: self.editor.path.clone(),
};
let rc = match configs::resolve(cfg, &ctx) {
Ok(rc) => rc,
Err(e) => {
self.debug_error(e);
return;
}
};
if let Some(task_label) = rc.pre_launch_task.clone() {
let tasks = crate::tasks::discover_tasks(&root);
let Some(task) = tasks.into_iter().find(|t| t.label == task_label) else {
self.debug_error(format!(
"preLaunchTask \"{task_label}\" not found — Tasks: Run Task lists what the workspace declares"
));
return;
};
let command = task.command.clone();
let Some(pane) = self.run_project_task(task) else {
// run_project_task already reported why the pane failed.
return;
};
self.pending_debug_launch = Some(PendingDebugLaunch {
pane,
command,
step: PendingLaunchStep::Resolved(Box::new(rc)),
started: std::time::Instant::now(),
});
self.run_debug.feedback = Some(format!("preLaunchTask \"{task_label}\" running…"));
self.run_debug.feedback_is_error = false;
self.status =
format!("preLaunchTask \"{task_label}\" running — debug starts when it exits 0");
return;
}
self.launch_resolved_config(rc);
}
/// Where the last run of `name` failed, if the runner named a place in
/// the user's own code (#373). Read back from the Test Runner output
/// channel, which already holds every line the run printed.
///
/// Scoped to the failing test's own block: a run of the whole suite
/// prints many failures, and breaking on another test's assertion would
/// stop the debugger somewhere the user did not ask about. The block
/// starts at the runner's "failures:"-style banner for this test and
/// ends at the next test's banner.
fn failure_site_of(&self, name: &str) -> Option<crate::testing::failure_site::FailureSite> {
use crate::testing::failure_site::is_failure_banner;
let lines = crate::output::snapshot(crate::output::CHANNEL_TESTS)?;
let texts: Vec<&str> = lines.iter().map(|l| l.text.as_str()).collect();
// Walk backwards to the most recent BANNER for this test, so a
// re-run's output wins over an earlier one in the same channel.
// Anchoring on the banner rather than on any mention is what makes
// this work against real output: libtest reprints every failing
// name in its trailing `failures:` summary, so "the last line
// mentioning the name" lands after every block and finds nothing.
let start = texts.iter().rposition(|t| is_failure_banner(t, name))?;
// The block runs to the next test's banner, or to the end.
let end = texts[start + 1..]
.iter()
.position(|t| {
(t.trim_start().starts_with("---- ")
|| t.trim_start().starts_with('_')
|| t.trim_start().starts_with('\u{25cf}'))
&& !is_failure_banner(t, name)
})
.map(|i| start + 1 + i)
.unwrap_or(texts.len());
crate::testing::failure_site::failure_site(&texts[start..end].join("\n"))
}
/// Set a TEMPORARY breakpoint at the assertion the last run of `name`
/// failed on (#373), unless the user already has one there.
///
/// Recorded in `debug_temp_breakpoint` so [`Self::disarm_failure_breakpoint`]
/// can take exactly this one back out: a breakpoint croft set and then
/// left behind would be indistinguishable from one the user set, and
/// would keep stopping them on a line they never chose.
fn arm_failure_breakpoint(&mut self, name: &str, root: &Path) {
self.disarm_failure_breakpoint();
let Some((file, line)) = self
.failure_site_of(name)
.and_then(|site| site.resolve(root))
else {
return;
};
let line = line as usize;
let lines = self.editor.breakpoints.entry(file.clone()).or_default();
// The user's own breakpoint there is left alone: it is theirs, it
// outlives the session, and removing it on stop would delete work.
if !lines.insert(line) {
return;
}
self.debug_temp_breakpoint = Some((file.clone(), line));
// Recorded for the caller to append to whatever message it shows:
// setting `status` here would be overwritten moments later by the
// launch's own ("Building test binary…"), so the user would never
// learn a breakpoint had been set for them.
self.debug_temp_note = Some(format!(
"breaking at {}:{line} where it last failed",
file.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default()
));
}
/// Append the armed-breakpoint note to `msg`, if one was armed (#373).
fn with_failure_note(&self, msg: String) -> String {
match &self.debug_temp_note {
Some(note) => format!("{msg} — {note}"),
None => msg,
}
}
/// Remove the breakpoint [`Self::arm_failure_breakpoint`] set, if it is
/// still ours. The user may have removed it themselves mid-session, in
/// which case there is nothing to take back.
fn disarm_failure_breakpoint(&mut self) {
self.debug_temp_note = None;
let Some((file, line)) = self.debug_temp_breakpoint.take() else {
return;
};
if let Some(lines) = self.editor.breakpoints.get_mut(&file) {
lines.remove(&line);
if lines.is_empty() {
self.editor.breakpoints.remove(&file);
}
}
}
/// The editor's breakpoints in launch shape, shared by every session
/// starter (zero-config and launch.json alike).
fn collect_editor_breakpoints(
&self,
) -> std::collections::BTreeMap<PathBuf, Vec<crate::dap::session::SourceBreakpoint>> {
self.editor
.breakpoints
.iter()
.map(|(p, lines)| (p.clone(), self.editor.source_breakpoints(p, lines)))
.collect()
}
/// Spawn the adapter for a resolved launch.json configuration and hand it
/// the built launch/attach request.
fn launch_resolved_config(&mut self, mut rc: crate::dap::configs::ResolvedConfig) {
use crate::dap::configs::{self, RequestKind};
use crate::dap::session::AdapterKind;
let breakpoints = self.collect_editor_breakpoints();
let cwd = rc
.cwd
.clone()
.unwrap_or_else(|| self.active_workspace_root());
let name = rc.name.clone();
let result = match rc.kind {
AdapterKind::Debugpy => {
if rc.request == RequestKind::Launch && rc.program.is_none() && rc.module.is_none()
{
self.debug_error(format!(
"config \"{name}\": a python launch needs a \"program\" or \"module\""
));
return;
}
match crate::dap::install::ensure_debug_venv() {
Ok(py) => {
let adapter_args =
vec![String::from("-m"), String::from("debugpy.adapter")];
crate::dap::session::DapSession::launch_with(
&py.to_string_lossy(),
&adapter_args,
&cwd,
configs::debugpy_request(&rc, &py),
breakpoints,
)
}
Err(e) => {
self.debug_error(format!("Debugger setup failed: {e}"));
return;
}
}
}
AdapterKind::LldbDap => {
let Some(adapter) = lldb_dap_path() else {
self.debug_error(lldb_dap_missing_message());
return;
};
match rc.request {
RequestKind::Launch => {
let Some(program) = rc.program.as_deref() else {
self.debug_error(format!(
"config \"{name}\": an lldb launch needs a \"program\" (the built binary)"
));
return;
};
match resolve_lldb_program(program, &cwd) {
Ok(resolved) => {
rc.program = Some(resolved.to_string_lossy().into_owned())
}
Err(e) => {
self.debug_error(format!("config \"{name}\": {e}"));
return;
}
}
}
RequestKind::Attach => {
if rc.process_id.is_none() {
self.debug_error(format!(
"config \"{name}\": an lldb attach needs a numeric \"processId\""
));
return;
}
}
}
crate::dap::session::DapSession::launch_with(
&adapter,
&[],
&cwd,
configs::lldb_request(&rc),
breakpoints,
)
}
AdapterKind::JsDebug => {
if rc.request == RequestKind::Launch && rc.program.is_none() {
self.debug_error(format!(
"config \"{name}\": a node launch needs a \"program\""
));
return;
}
if rc.request == RequestKind::Attach && rc.port.is_none() {
self.debug_error(format!("config \"{name}\": a node attach needs a \"port\""));
return;
}
let node = match crate::dap::install::node_program() {
Ok(n) => n,
Err(e) => {
self.debug_error(format!("{e}"));
return;
}
};
let server = match crate::dap::install::ensure_js_debug() {
Ok(s) => s,
Err(e) => {
self.debug_error(format!("Debugger setup failed: {e}"));
return;
}
};
crate::dap::session::DapSession::launch_js_with(
&node,
&server,
&cwd,
configs::js_request(&rc),
breakpoints,
)
}
};
match result {
Ok(session) => {
self.dap_session = Some(session);
let verb = match rc.request {
RequestKind::Launch => "Debugging",
RequestKind::Attach => "Attached:",
};
self.run_debug.feedback = Some(format!("{verb} {name}"));
self.run_debug.feedback_is_error = false;
self.status =
format!("{verb} {name} — F5 continue · F10 step over · Shift+F5 stop");
self.reveal_debug_view();
}
Err(e) => self.debug_error(format!("Failed to start debugger: {e}")),
}
}
/// Launch a debug session for the active file, choosing the adapter by file
/// type. Python (debugpy) is the verified path; other recognised compiled
/// languages route to lldb-dap.
fn start_debug_session(&mut self) {
use crate::dap::session::AdapterKind;
let Some(path) = self.editor.path.clone() else {
self.debug_error(String::from("Open a file to debug"));
return;
};
let ext = path
.extension()
.and_then(|e| e.to_str())
.unwrap_or("")
.to_ascii_lowercase();
match crate::dap::registry::adapter_for_extension(&ext) {
Some(AdapterKind::Debugpy) => {}
Some(AdapterKind::LldbDap) => {
self.start_lldb_debug_session(&path);
return;
}
Some(AdapterKind::JsDebug) => {
self.start_js_debug_session(&path);
return;
}
None => {
// An executable binary (e.g. a compiled `target/debug/app`) can
// be debugged directly by lldb-dap with no build step.
if is_executable_file(&path) {
self.launch_lldb(&path, &path);
} else if let Some(ext_id) = crate::dap::registry::disabled_extension_for(&ext) {
// A debugger exists for this file type but its extension is
// turned off — say so rather than claim none exists.
self.debug_error(format!(
"The {ext_id} debugger extension is disabled — enable it in Extensions"
));
} else {
self.debug_error(format!(
"No debugger for .{ext} files (Python, JS/TS, Rust, C/C++ are supported)"
));
}
return;
}
}
let py = match crate::dap::install::ensure_debug_venv() {
Ok(py) => py,
Err(e) => {
self.debug_error(format!("Debugger setup failed: {e}"));
return;
}
};
let breakpoints = self.collect_editor_breakpoints();
let adapter_args = vec![String::from("-m"), String::from("debugpy.adapter")];
let py_str = py.to_string_lossy().into_owned();
let debug_root = self
.roots
.owning_root(&path)
.unwrap_or_else(|| self.roots.primary())
.to_path_buf();
match crate::dap::session::DapSession::launch(
&py_str,
&adapter_args,
&debug_root,
&path,
&py,
breakpoints,
false,
) {
Ok(session) => {
self.dap_session = Some(session);
let name = path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
self.run_debug.feedback = Some(format!("Debugging {name}"));
self.run_debug.feedback_is_error = false;
self.status =
format!("Debugging {name} — F5 continue · F10 step over · Shift+F5 stop");
self.reveal_debug_view();
}
Err(e) => {
self.debug_error(format!("Failed to start debugger: {e}"));
}
}
}
/// Launch a vscode-js-debug session for a `.js`/`.ts` file run under Node.
/// Provisions the js-debug server on first use, then drives the shared DAP
/// session machinery (which transparently spawns the parent + child
/// connections js-debug requires). TypeScript binds via source maps.
fn start_js_debug_session(&mut self, path: &Path) {
let node = match crate::dap::install::node_program() {
Ok(n) => n,
Err(e) => {
self.debug_error(format!("{e}"));
return;
}
};
let server = match crate::dap::install::ensure_js_debug() {
Ok(s) => s,
Err(e) => {
self.debug_error(format!("Debugger setup failed: {e}"));
return;
}
};
let breakpoints = self.collect_editor_breakpoints();
let debug_root = self
.roots
.owning_root(path)
.unwrap_or_else(|| self.roots.primary())
.to_path_buf();
match crate::dap::session::DapSession::launch_js(
&node,
&server,
&debug_root,
path,
breakpoints,
false,
) {
Ok(session) => {
self.dap_session = Some(session);
let name = path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
self.run_debug.feedback = Some(format!("Debugging {name}"));
self.run_debug.feedback_is_error = false;
self.status =
format!("Debugging {name} — F5 continue · F10 step over · Shift+F5 stop");
self.reveal_debug_view();
}
Err(e) => {
self.debug_error(format!("Failed to start debugger: {e}"));
}
}
}
/// Launch lldb-dap on a Rust / C / C++ source file: build a debuggable
/// binary, then drive the same DAP session machinery as Python. The binary
/// build is the only language-specific step; breakpoints, stepping, call
/// stack, variables, and the REPL all flow through the shared session.
///
/// Note: lldb-dap requires a permitted `debugserver` (macOS gates this
/// behind code-signing / `DevToolsSecurity`); where that isn't granted the
/// process runs without binding breakpoints. croft surfaces the adapter's
/// own status rather than pretending otherwise.
fn start_lldb_debug_session(&mut self, path: &Path) {
if lldb_dap_path().is_none() {
self.debug_error(lldb_dap_missing_message());
return;
}
// Compiled source: build a debuggable binary first, then debug it.
let binary = match self.build_debuggable_binary(path) {
Ok(b) => b,
Err(e) => {
self.debug_error(format!("Build for debug failed: {e}"));
return;
}
};
self.launch_lldb(&binary, path);
}
/// Launch lldb-dap on an already-built `binary`, attributing status to
/// `label_path` (the source for a compiled language, or the binary itself
/// for a directly-debugged executable). Shared by the compiled-source path
/// and the executable-binary path so neither duplicates the launch plumbing.
fn launch_lldb(&mut self, binary: &Path, label_path: &Path) {
let Some(adapter) = lldb_dap_path() else {
self.debug_error(lldb_dap_missing_message());
return;
};
let breakpoints = self.collect_editor_breakpoints();
let cwd = label_path
.parent()
.unwrap_or(self.workspace_root())
.to_path_buf();
match crate::dap::session::DapSession::launch_with(
&adapter,
&[],
&cwd,
crate::dap::session::lldb_launch_request(binary, false),
breakpoints,
) {
Ok(session) => {
self.dap_session = Some(session);
let name = label_path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
self.run_debug.feedback = Some(format!("Debugging {name} (lldb)"));
self.run_debug.feedback_is_error = false;
self.status =
format!("Debugging {name} via lldb-dap — F5 continue · Shift+F5 stop");
self.reveal_debug_view();
}
Err(e) => {
self.debug_error(format!("Failed to start lldb-dap: {e}"));
}
}
}
/// Compile `path` to a debuggable binary (with debug info, no optimisation)
/// and return the binary path. C via `cc`, C++ via `c++`, Rust via `rustc`
/// for a single file. The binary lands next to the source as `<stem>.dbg`.
fn build_debuggable_binary(&self, path: &Path) -> std::io::Result<PathBuf> {
use std::process::Command;
let ext = path
.extension()
.and_then(|e| e.to_str())
.unwrap_or("")
.to_ascii_lowercase();
let out = path.with_extension("dbg");
let (program, args): (&str, Vec<String>) = match ext.as_str() {
"rs" => (
"rustc",
vec![
String::from("-g"),
String::from("-o"),
out.to_string_lossy().into_owned(),
path.to_string_lossy().into_owned(),
],
),
"c" | "h" | "m" => (
"cc",
vec![
String::from("-g"),
String::from("-O0"),
path.to_string_lossy().into_owned(),
String::from("-o"),
out.to_string_lossy().into_owned(),
],
),
_ => (
"c++",
vec![
String::from("-g"),
String::from("-O0"),
path.to_string_lossy().into_owned(),
String::from("-o"),
out.to_string_lossy().into_owned(),
],
),
};
// .output(), never .status(): the compiler must not inherit croft's
// TTY - a compile error would spray its diagnostics over the UI
// (same class as the pdftoppm trailer-dictionary spray).
let cmd_out = Command::new(program).args(&args).output()?;
if !cmd_out.status.success() {
let stderr = String::from_utf8_lossy(&cmd_out.stderr);
return Err(std::io::Error::other(format!(
"{program} exited with {}: {}",
cmd_out.status,
stderr.trim()
)));
}
Ok(out)
}
/// F9: toggle a breakpoint on the cursor line, pushing it live if a session
/// is running.
pub fn debug_toggle_breakpoint(&mut self) {
self.debug_toggle_breakpoint_line(self.editor.cursor_row + 1);
}
/// Toggle a breakpoint on an explicit 1-based `line`, then push the file's
/// breakpoints to a live session. Shared by F9 (cursor line) and the gutter
/// right-click menu (clicked line).
fn debug_toggle_breakpoint_line(&mut self, line: usize) {
match self.editor.toggle_breakpoint_line(line) {
Some((_, line, now_set)) => {
self.status = if now_set {
format!("Breakpoint set at line {line}")
} else {
format!("Breakpoint removed from line {line}")
};
}
None => {
self.status = String::from("Open a file to set a breakpoint");
return;
}
}
if let Some(path) = self.editor.path.clone() {
let specs = self
.editor
.breakpoints
.get(&path)
.map(|lines| self.editor.source_breakpoints(&path, lines))
.unwrap_or_default();
if let Some(session) = self.dap_session.as_mut() {
session.update_breakpoints(&path, &specs);
}
}
}
/// Open the breakpoint-condition editor for the cursor line, pre-filled with
/// any existing condition.
pub fn debug_edit_condition(&mut self) {
self.debug_edit_condition_line(self.editor.cursor_row + 1);
}
/// Open the breakpoint-condition editor for an explicit 1-based `line` as a
/// centered popup (`PromptKind::BreakpointCondition`), pre-filled with any
/// existing condition. Shared by the command-palette entry (cursor line)
/// and the gutter right-click menu (clicked line). The popup, not the
/// status line, captures the input; commit lives in [`App::commit_prompt`].
fn debug_edit_condition_line(&mut self, line: usize) {
let Some(path) = self.editor.path.clone() else {
self.status = String::from("Open a file to set a conditional breakpoint");
return;
};
let existing = self
.editor
.breakpoint_conditions
.get(&path)
.and_then(|c| c.get(&line))
.cloned()
.unwrap_or_default();
let label = if existing.is_empty() {
format!("Add Conditional Breakpoint · line {line}")
} else {
format!("Edit Condition · line {line}")
};
let target_dir = self.tree.root.clone();
self.prompt = Some(Prompt {
label,
buffer: existing,
kind: PromptKind::BreakpointCondition { path, line },
target_dir,
error: None,
});
}
/// Commit the breakpoint-condition popup: ensure a breakpoint exists on the
/// line, attach the typed expression (or clear it when blank), and push the
/// file's breakpoints to a live session.
fn commit_breakpoint_condition(&mut self, path: PathBuf, line: usize, expr: &str) {
self.editor
.breakpoints
.entry(path.clone())
.or_default()
.insert(line);
let cond = expr.trim();
if cond.is_empty() {
if let Some(c) = self.editor.breakpoint_conditions.get_mut(&path) {
c.remove(&line);
}
self.status = format!("Plain breakpoint at line {line}");
} else {
self.editor
.breakpoint_conditions
.entry(path.clone())
.or_default()
.insert(line, cond.to_string());
self.status = format!("Conditional breakpoint at line {line}");
}
let specs = self
.editor
.breakpoints
.get(&path)
.map(|l| self.editor.source_breakpoints(&path, l))
.unwrap_or_default();
if let Some(session) = self.dap_session.as_mut() {
session.update_breakpoints(&path, &specs);
}
}
/// Open the logpoint editor for the cursor line, pre-filled with any
/// existing message.
pub fn debug_edit_logpoint(&mut self) {
self.debug_edit_logpoint_line(self.editor.cursor_row + 1);
}
/// Open the logpoint editor for an explicit 1-based `line` as a centered
/// popup (`PromptKind::Logpoint`). Shared by the palette entry (cursor
/// line), Shift+Alt+F9, and the gutter right-click menu (clicked line).
fn debug_edit_logpoint_line(&mut self, line: usize) {
let Some(path) = self.editor.path.clone() else {
self.status = String::from("Open a file to set a logpoint");
return;
};
let existing = self
.editor
.breakpoint_logs
.get(&path)
.and_then(|m| m.get(&line))
.cloned()
.unwrap_or_default();
let label = if existing.is_empty() {
format!("Add Logpoint · line {line}")
} else {
format!("Edit Logpoint · line {line}")
};
let target_dir = self.tree.root.clone();
self.prompt = Some(Prompt {
label,
buffer: existing,
kind: PromptKind::Logpoint { path, line },
target_dir,
error: None,
});
}
/// Commit the logpoint popup: ensure a breakpoint exists on the line,
/// attach the typed message (or clear it when blank), and push the file's
/// breakpoints to a live session.
fn commit_logpoint(&mut self, path: PathBuf, line: usize, message: &str) {
self.editor
.breakpoints
.entry(path.clone())
.or_default()
.insert(line);
let msg = message.trim();
if msg.is_empty() {
if let Some(m) = self.editor.breakpoint_logs.get_mut(&path) {
m.remove(&line);
}
self.status = format!("Plain breakpoint at line {line}");
} else {
self.editor
.breakpoint_logs
.entry(path.clone())
.or_default()
.insert(line, msg.to_string());
self.status = format!("Logpoint at line {line}");
}
let specs = self
.editor
.breakpoints
.get(&path)
.map(|l| self.editor.source_breakpoints(&path, l))
.unwrap_or_default();
if let Some(session) = self.dap_session.as_mut() {
session.update_breakpoints(&path, &specs);
}
}
/// F10/F11/Shift+F11: step the paused thread (`next` / `stepIn` / `stepOut`).
pub fn debug_step(&mut self, command: &str) {
if let Some(session) = self.dap_session.as_mut() {
session.step(command);
self.editor.stop_line = None;
self.clear_inline_values();
}
}
/// Toggle "break on raised exceptions" for the active session. `uncaught` is
/// always kept on so unhandled exceptions still pause. No-op without a
/// session.
pub fn debug_toggle_raised_exceptions(&mut self) {
let Some(session) = self.dap_session.as_mut() else {
self.status = String::from("Start debugging first to set exception breakpoints");
return;
};
let raised = !session.has_exception_filter("raised");
let mut filters = vec![String::from("uncaught")];
if raised {
filters.push(String::from("raised"));
}
session.set_exception_filters(filters);
self.status = if raised {
String::from("Breaking on raised exceptions (and uncaught)")
} else {
String::from("Breaking on uncaught exceptions only")
};
}
/// F6: interrupt a running program so it stops at the current line.
pub fn debug_pause(&mut self) {
match self.dap_session.as_mut() {
Some(session) => {
session.pause();
self.status = String::from("Pausing");
}
None => self.status = String::from("No debug session to pause"),
}
}
/// Restart: tear down the current session and relaunch the active file with
/// the same breakpoints.
pub fn debug_restart(&mut self) {
if self.dap_session.is_some() {
self.debug_stop();
}
self.start_selected_debug();
}
/// A session ended: the expressions survive (they usually make sense for
/// the next run too), but the values, the changed-value baseline, and the
/// baseline latch are that session's — left in place they made every
/// watch flash "changed" on a fresh session's first stop.
fn reset_watch_runtime(&mut self) {
self.watch_vals.clear();
self.watch_prev.clear();
self.watch_baseline_pending = false;
}
/// Shift+F5: stop debugging and tear the session down.
pub fn debug_stop(&mut self) {
if let Some(session) = self.dap_session.as_mut() {
session.disconnect();
}
self.dap_session = None;
self.reset_watch_runtime();
// Sweep js-debug's detached watchdog (and any leftover tree) once it has
// reparented to init after the server dies. See the Terminated arm in
// `poll_dap` and `crate::dap::reaper`.
crate::dap::reaper::reap_orphaned_js_debug_async(std::time::Duration::from_millis(
REAPER_TEARDOWN_GRACE_MS,
));
self.editor.stop_line = None;
self.editor.unverified_breakpoints.clear();
// The breakpoint croft set at the failing assertion goes with the
// session that asked for it (#373).
self.disarm_failure_breakpoint();
self.clear_inline_values();
self.status = String::from("Debug session stopped");
// Clear the paused-state feedback ("Paused (breakpoint)") so the
// empty-state panel doesn't keep showing it under the Run button.
self.run_debug.feedback = None;
self.run_debug.feedback_is_error = false;
// Refresh now: `poll_dap` early-returns once the session is gone, so it
// would never deactivate the panel on its own — without this the Run &
// Debug panel keeps showing the stale "Paused" tree until the next event.
self.refresh_debug_panel();
}
pub fn run_active_file(&mut self) {
let Some(path) = self.editor.path.clone() else {
self.run_debug.feedback = Some(String::from("Open a file first"));
self.run_debug.feedback_is_error = true;
return;
};
let run_root = self
.roots
.owning_root(&path)
.unwrap_or_else(|| self.roots.primary())
.to_path_buf();
let Some(spec) = Self::run_spec_for(&path, &run_root) else {
self.run_debug.feedback = Some(format!(
"Don't know how to run {}",
path.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| path.display().to_string())
));
self.run_debug.feedback_is_error = true;
return;
};
match PtyTerminal::new_running(&spec.program, &spec.args, &spec.cwd) {
Ok(term) => {
let target = self.active_terminal + 1;
self.terminals.insert(target, term);
self.active_terminal = target;
if !self.show_terminal {
self.show_terminal = true;
}
self.focus_pane(Pane::Terminal);
self.run_debug.feedback = Some(format!(
"Running {}",
path.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| path.display().to_string())
));
self.run_debug.feedback_is_error = false;
}
Err(e) => {
self.run_debug.feedback = Some(format!("Failed to spawn terminal: {e}"));
self.run_debug.feedback_is_error = true;
}
}
}
/// Open the change at `entry_idx` in the editor pane: a side-by-side
/// diff against HEAD for Modified / StagedModified entries (the
/// VS Code Source Control click behaviour), or a plain file open
/// for everything else where the working tree IS the only version
/// (Untracked, StagedAdded) or HEAD doesn't carry the file
/// (Deleted). Selection state on the panel updates so the user can
/// see which entry the editor is bound to.
pub fn open_source_control_entry(&mut self, entry_idx: usize) {
use crate::git::ChangeKind;
let Some(entry) = self.source_control.entries.get(entry_idx).cloned() else {
return;
};
self.source_control.selected_change = Some(entry_idx);
// Porcelain paths are toplevel-relative (#139): join and HEAD-read
// against the repo root, never the workspace root.
let scm_root = self.scm_root();
let abs = scm_root.join(&entry.path);
let opened = match entry.kind {
// A conflicted entry opens the three-way MERGE EDITOR (#253)
// on the index stages — non-overlapping hunks pre-resolve,
// and "Reopen as Text" reaches the old in-buffer marker flow.
// If the stages are unreadable (e.g. binary), fall back to
// opening the working file with its markers, parked on the
// first conflict as before.
ChangeKind::Conflicted => {
if self.open_merge_editor_for(&abs) {
true
} else {
match self.editor.open_pinned(&abs) {
Ok(()) => {
self.focus_pane(Pane::Editor);
let n = self.editor.conflicts().len();
if let Some(block) = self.editor.conflicts().first().copied() {
self.editor.clear_selection();
self.editor.cursor_row = block.ours_start;
self.editor.cursor_col = 0;
self.editor.scroll_col = 0;
self.editor.ensure_cursor_col_visible();
}
self.status = format!(
"{n} conflict{} — F7 jumps, Cmd+. accepts, \"Merge: Complete Merge\" stages",
if n == 1 { "" } else { "s" }
);
true
}
Err(e) => {
self.status = format!("Open failed: {e}");
false
}
}
}
}
ChangeKind::Modified | ChangeKind::StagedModified => {
match crate::git::read_file_at_head(&scm_root, &entry.path) {
Ok(head_text) => {
let label = std::path::PathBuf::from(format!("{} (HEAD)", entry.path));
match self
.editor
.open_head_diff_with_text(label, &head_text, &abs, true)
{
Ok(()) => {
self.tag_open_diff(
crate::widgets::diff::DiffSource::HeadVsWorking {
root: scm_root.to_path_buf(),
rel: entry.path.clone(),
},
);
true
}
Err(e) => {
self.status = format!("Diff failed: {e}");
false
}
}
}
Err(e) => {
self.status = format!("git show HEAD failed: {e}");
// Fall back to plain open so the user still sees
// something rather than nothing.
if abs.is_file() {
self.editor.open_pinned(&abs).is_ok()
} else {
false
}
}
}
}
ChangeKind::Deleted | ChangeKind::StagedDeleted => {
// No working-tree file to diff against — show the HEAD
// blob as a one-sided unified diff so every removed
// line is visible in red, matching `git diff` output
// for a deletion.
match crate::git::read_file_at_head(&scm_root, &entry.path) {
Ok(head_text) => {
let label = std::path::PathBuf::from(&entry.path);
match self.editor.open_deleted_diff_with_text(&label, &head_text) {
Ok(()) => true,
Err(e) => {
self.status = format!("Open deletion view failed: {e}");
false
}
}
}
Err(e) => {
self.status = format!("git show HEAD failed: {e}");
false
}
}
}
_ => {
if abs.is_file() {
match self.editor.open_pinned(&abs) {
Ok(()) => true,
Err(e) => {
self.status = format!("Open failed: {e}");
false
}
}
} else {
false
}
}
};
if opened {
self.focus_pane(Pane::Editor);
self.sync_open_file_poll_mtime();
}
}
/// Open `path` as a pinned editor tab and focus the editor. Used at launch
/// for `croft <root> --open-file <path>` (the new window spawned by Move /
/// Copy into New Window opens the handed-off file this way). Best-effort: a
/// missing / unreadable file just leaves the editor on the welcome screen.
pub fn open_file_at_launch(&mut self, path: &Path) {
if self.editor.open_pinned(path).is_ok() {
// Launch is not a user focus gesture: collapsing here would hide
// the sidebar before the user has interacted at all (#260).
self.without_auto_hide(|app| app.focus_pane(Pane::Editor));
self.sync_open_file_poll_mtime();
}
}
fn initialize_repository(&mut self) {
match std::process::Command::new("git")
.arg("-C")
.arg(&self.tree.root)
.arg("init")
.output()
{
Ok(out) if out.status.success() => {
self.status = format!(
"Initialized empty Git repository in {}",
self.tree.root.display()
);
self.active_git_bypass_debounce();
self.refresh_git_status_debounced();
self.refresh_source_control();
}
Ok(out) => {
let err = String::from_utf8_lossy(&out.stderr).trim().to_string();
self.status = format!("git init failed: {err}");
}
Err(e) => {
self.status = format!("git init failed: {e}");
}
}
}
pub fn stage_selected_source_control_entries(&mut self) {
let indices: Vec<usize> = if self.source_control.multi_selection.is_empty() {
self.source_control
.selected_change
.iter()
.copied()
.collect()
} else {
self.source_control
.multi_selection
.iter()
.copied()
.collect()
};
if indices.is_empty() {
self.status = String::from("No change selected to stage");
return;
}
let paths: Vec<String> = indices
.iter()
.filter_map(|i| self.source_control.entries.get(*i))
.filter(|e| e.kind.section() != crate::git::ChangeSection::Staged)
.map(|e| e.path.clone())
.collect();
if paths.is_empty() {
self.status = String::from("Selection is already staged");
return;
}
match crate::git::stage_paths(&self.scm_root(), &paths) {
Ok(()) => {
self.status = if paths.len() == 1 {
format!("Staged {}", paths[0])
} else {
format!("Staged {} files", paths.len())
};
}
Err(err) => {
self.status = format!("Stage failed: {err}");
self.source_control.commit_feedback = Some(err);
self.source_control.commit_feedback_is_error = true;
}
}
self.active_git_bypass_debounce();
self.refresh_git_status_debounced();
self.refresh_source_control();
}
/// Push the current branch without committing. Sibling of
/// `commit_and_push_source_control`, called from the commit dropdown's
/// "Push" item so users can ship already-committed work without
/// having to type a no-op commit message first.
pub fn push_source_control(&mut self) {
match crate::git::push_current_branch(&self.scm_root()) {
Ok(summary) => {
self.source_control.commit_feedback = Some(if summary.is_empty() {
"pushed".to_string()
} else {
format!("pushed: {summary}")
});
self.source_control.commit_feedback_is_error = false;
self.status = format!("Pushed: {summary}");
}
Err(err) => {
self.source_control.commit_feedback = Some(format!("push failed: {err}"));
self.source_control.commit_feedback_is_error = true;
self.status = format!("Push failed: {err}");
}
}
self.active_git_bypass_debounce();
self.refresh_git_status_debounced();
}
/// Pull the current branch from its upstream. Sibling of
/// `push_source_control`, reached from the commit dropdown's "Pull".
pub fn pull_source_control(&mut self) {
match crate::git::pull_current_branch(&self.scm_root()) {
Ok(summary) => {
self.source_control.commit_feedback = Some(if summary.is_empty() {
"pulled".to_string()
} else {
format!("pulled: {summary}")
});
self.source_control.commit_feedback_is_error = false;
self.status = format!("Pulled: {summary}");
}
Err(err) => {
self.source_control.commit_feedback = Some(format!("pull failed: {err}"));
self.source_control.commit_feedback_is_error = true;
self.status = format!("Pull failed: {err}");
}
}
self.active_git_bypass_debounce();
self.refresh_git_status_debounced();
self.refresh_source_control();
}
/// Sync = pull then push, mirroring VS Code's sync button. A failed
/// pull short-circuits (we never push on top of an unmerged tree); a
/// successful pull followed by a failed push reports both halves.
pub fn sync_source_control(&mut self) {
let pull_summary = match crate::git::pull_current_branch(&self.scm_root()) {
Ok(s) => s,
Err(err) => {
self.source_control.commit_feedback = Some(format!("sync: pull failed: {err}"));
self.source_control.commit_feedback_is_error = true;
self.status = format!("Sync failed on pull: {err}");
self.active_git_bypass_debounce();
self.refresh_git_status_debounced();
self.refresh_source_control();
return;
}
};
match crate::git::push_current_branch(&self.scm_root()) {
Ok(push_summary) => {
self.source_control.commit_feedback = Some(format!(
"synced (pulled: {pull_summary} | pushed: {push_summary})"
));
self.source_control.commit_feedback_is_error = false;
self.status = String::from("Synced");
}
Err(err) => {
self.source_control.commit_feedback = Some(format!("pull ok; push failed: {err}"));
self.source_control.commit_feedback_is_error = true;
self.status = format!("Sync: pull ok; push failed: {err}");
}
}
self.active_git_bypass_debounce();
self.refresh_git_status_debounced();
self.refresh_source_control();
}
/// Stash the working tree (`git stash push`). Reached from the commit
/// dropdown's "Stash" item.
pub fn stash_source_control(&mut self) {
match crate::git::stash_push(&self.scm_root()) {
Ok(summary) => {
self.source_control.commit_feedback = Some(format!("stashed: {summary}"));
self.source_control.commit_feedback_is_error = false;
self.status = format!("Stashed: {summary}");
}
Err(err) => {
self.source_control.commit_feedback = Some(format!("stash failed: {err}"));
self.source_control.commit_feedback_is_error = true;
self.status = format!("Stash failed: {err}");
}
}
self.active_git_bypass_debounce();
self.refresh_git_status_debounced();
self.refresh_source_control();
}
/// Restore the most recent stash (`git stash pop`). A pop conflict is
/// surfaced verbatim so the user can resolve it.
pub fn stash_pop_source_control(&mut self) {
match crate::git::stash_pop(&self.scm_root()) {
Ok(summary) => {
self.source_control.commit_feedback = Some(format!("popped: {summary}"));
self.source_control.commit_feedback_is_error = false;
self.status = format!("Stash popped: {summary}");
}
Err(err) => {
self.source_control.commit_feedback = Some(format!("stash pop failed: {err}"));
self.source_control.commit_feedback_is_error = true;
self.status = format!("Stash pop failed: {err}");
}
}
self.active_git_bypass_debounce();
self.refresh_git_status_debounced();
self.refresh_source_control();
}
/// Unstage a single entry by index (the inline "−" icon on a staged
/// row). Mirror of `stage_source_control_entry`.
pub fn unstage_source_control_entry(&mut self, entry_idx: usize) {
let Some(entry) = self.source_control.entries.get(entry_idx).cloned() else {
return;
};
match crate::git::unstage_path(&self.scm_root(), &entry.path) {
Ok(()) => {
self.status = format!("Unstaged {}", entry.path);
self.active_git_bypass_debounce();
self.refresh_git_status_debounced();
self.refresh_source_control();
}
Err(err) => {
self.status = format!("Unstage failed: {err}");
self.source_control.commit_feedback = Some(err);
self.source_control.commit_feedback_is_error = true;
}
}
}
// --- Source Control "⋯" menu plumbing --------------------------------
/// Append a git command + its outcome to the rolling output log, which
/// the "Show Git Output" action surfaces read-only. Capped so a long
/// session can't grow it without bound.
fn log_git(&mut self, label: &str, outcome: &Result<String, String>) {
let body = match outcome {
Ok(s) if s.is_empty() => String::from("(ok)"),
Ok(s) => s.clone(),
Err(e) => format!("error: {e}"),
};
self.git_output_log.push(format!("$ git {label}\n{body}"));
const CAP: usize = 200;
if self.git_output_log.len() > CAP {
let excess = self.git_output_log.len() - CAP;
self.git_output_log.drain(0..excess);
}
}
/// Run an immediate git operation: log it, surface its summary or error
/// in the commit-feedback line, and refresh the panel. The single path
/// every "⋯"-menu leaf that acts now (vs. opening a modal) flows through.
fn run_scm_op(&mut self, label: &str, outcome: Result<String, String>, ok_prefix: &str) {
self.log_git(label, &outcome);
match outcome {
Ok(summary) => {
self.source_control.commit_feedback = Some(if summary.is_empty() {
ok_prefix.to_string()
} else {
format!("{ok_prefix}: {summary}")
});
self.source_control.commit_feedback_is_error = false;
self.status = format!("{ok_prefix}: {summary}");
}
Err(err) => {
self.source_control.commit_feedback = Some(format!("{ok_prefix} failed: {err}"));
self.source_control.commit_feedback_is_error = true;
self.status = format!("{ok_prefix} failed: {err}");
}
}
self.active_git_bypass_debounce();
self.refresh_git_status_debounced();
self.refresh_source_control();
}
pub fn stage_all_source_control(&mut self) {
let r = crate::git::stage_all(&self.scm_root());
self.run_scm_op("add -A", r, "Staged all");
}
pub fn unstage_all_source_control(&mut self) {
let r = crate::git::unstage_all(&self.scm_root());
self.run_scm_op("reset HEAD", r, "Unstaged all");
}
/// Arm the Discard All confirmation. Destructive (reverts every tracked
/// edit to HEAD), so it never acts until `confirm_pending_discard_all`.
pub fn request_discard_all_source_control(&mut self) {
self.pending_discard_all = true;
}
pub fn cancel_pending_discard_all(&mut self) {
self.pending_discard_all = false;
}
pub fn confirm_pending_discard_all(&mut self) {
if !self.pending_discard_all {
return;
}
self.pending_discard_all = false;
let r = crate::git::discard_all_tracked(&self.scm_root());
self.run_scm_op("checkout -- .", r, "Discarded all changes");
}
/// The commit message currently in the input box, trimmed, or an error
/// surfaced when it is empty (shared by the Commit submenu variants).
fn require_commit_message(&mut self) -> Option<String> {
let message = self.source_control.message.trim().to_string();
if message.is_empty() {
self.source_control.commit_feedback = Some(String::from("Empty commit message"));
self.source_control.commit_feedback_is_error = true;
return None;
}
Some(message)
}
fn commit_staged_source_control(&mut self) {
let Some(message) = self.require_commit_message() else {
return;
};
let r = crate::git::commit_staged(&self.scm_root(), &message);
if r.is_ok() {
self.source_control.clear_message();
}
self.run_scm_op("commit -m", r, "Committed staged");
}
fn commit_all_source_control(&mut self) {
let Some(message) = self.require_commit_message() else {
return;
};
if let Err(err) = crate::git::stage_all(&self.scm_root()) {
self.run_scm_op("add -A", Err(err), "Stage all");
return;
}
let r = crate::git::commit_staged(&self.scm_root(), &message);
if r.is_ok() {
self.source_control.clear_message();
}
self.run_scm_op("commit (all)", r, "Committed all");
}
fn commit_amend_source_control(&mut self) {
// Amend keeps the prior message when the box is empty, otherwise
// rewrites it — matching VS Code's amend.
let message = self.source_control.message.trim().to_string();
let r = if message.is_empty() {
crate::git::commit_amend_no_edit(&self.scm_root())
} else {
crate::git::commit_amend(&self.scm_root(), &message)
};
if r.is_ok() {
self.source_control.clear_message();
}
self.run_scm_op("commit --amend", r, "Amended commit");
}
fn commit_and_sync_source_control(&mut self) {
let Some(message) = self.require_commit_message() else {
return;
};
let commit = crate::git::commit_all_tracked(&self.scm_root(), &message);
self.log_git("commit -am", &commit);
if let Err(err) = commit {
self.source_control.commit_feedback = Some(err.clone());
self.source_control.commit_feedback_is_error = true;
self.status = format!("Commit failed: {err}");
return;
}
self.source_control.clear_message();
self.sync_source_control();
}
fn publish_branch_source_control(&mut self) {
let Some(branch) = self.source_control.status.branch.clone() else {
self.source_control.commit_feedback =
Some(String::from("Detached HEAD has no branch to publish"));
self.source_control.commit_feedback_is_error = true;
return;
};
let r = crate::git::publish_branch(&self.scm_root(), &branch);
self.run_scm_op("push -u origin", r, "Published");
}
/// Open the read-only "Git Output" log in an editor tab (VS Code's Git
/// output channel). Empty until croft has run an operation this session.
fn show_git_output(&mut self) {
let body = if self.git_output_log.is_empty() {
String::from("(no git operations run yet this session)")
} else {
self.git_output_log.join("\n\n")
};
let label = self.scratch_buffer_path("Git Output");
if let Err(err) = self.editor.open_text_buffer(&label, &body) {
self.status = format!("Could not open Git Output: {err}");
return;
}
self.focus_pane(Pane::Editor);
}
/// Open the branch picker with an explicit purpose (Checkout by default,
/// or one of the Branch-submenu verbs).
fn open_branch_picker_for(&mut self, purpose: BranchPurpose) {
self.branch_purpose = purpose;
self.open_branch_picker();
}
/// Open a single-line input modal for an SCM value (clone URL, branch
/// rename, …).
fn open_input_prompt(&mut self, prompt: crate::widgets::input_prompt::InputPrompt) {
self.scm_menu.close();
self.input_prompt = Some(prompt);
self.overlays.input_prompt_clear.request();
}
fn close_input_prompt(&mut self) {
if self.input_prompt.take().is_some() {
self.overlays.input_prompt_clear.request();
self.overlays.activity.mark_dirty();
self.overlays.welcome.mark_dirty();
self.overlays.hero.mark_dirty();
self.invalidate_editor_image_layouts();
self.status.clear();
}
}
/// Open a single-choice list picker (stashes, tags, remotes). Reports
/// the empty case instead of opening a useless box.
fn open_list_picker(
&mut self,
picker: crate::widgets::list_picker::ListPicker,
empty_msg: &str,
) {
self.scm_menu.close();
if picker.rows.is_empty() {
self.status = empty_msg.to_string();
return;
}
self.list_picker = Some(picker);
self.overlays.list_picker_clear.request();
}
fn close_list_picker(&mut self) {
if self.list_picker.take().is_some() {
self.overlays.list_picker_clear.request();
self.overlays.activity.mark_dirty();
self.overlays.welcome.mark_dirty();
self.overlays.hero.mark_dirty();
self.invalidate_editor_image_layouts();
self.status.clear();
}
}
/// Route every "⋯"-menu leaf to its handler. Immediate ops run now;
/// ops needing a value or a choice open a modal/picker.
pub fn dispatch_scm_action(&mut self, action: crate::widgets::scm_menu::ScmAction) {
use crate::widgets::input_prompt::{InputPrompt, InputPurpose};
use crate::widgets::list_picker::ListPurpose;
use crate::widgets::scm_menu::ScmAction;
self.scm_menu.close();
match action {
ScmAction::Pull => self.pull_source_control(),
ScmAction::Push => self.push_source_control(),
ScmAction::Clone => self.open_input_prompt(InputPrompt::new(
InputPurpose::CloneUrl,
"Clone Repository",
"Repository URL (https://… or git@…)",
)),
ScmAction::CheckoutTo => self.open_branch_picker_for(BranchPurpose::Checkout),
ScmAction::Fetch => {
let r = crate::git::fetch_all(&self.scm_root());
self.run_scm_op("fetch --all --prune", r, "Fetched");
}
ScmAction::ShowGitOutput => self.show_git_output(),
ScmAction::Commit => self.commit_source_control(),
ScmAction::CommitStaged => self.commit_staged_source_control(),
ScmAction::CommitAll => self.commit_all_source_control(),
ScmAction::CommitAmend => self.commit_amend_source_control(),
ScmAction::CommitAndPush => self.commit_and_push_source_control(),
ScmAction::CommitAndSync => self.commit_and_sync_source_control(),
ScmAction::StageAll => self.stage_all_source_control(),
ScmAction::UnstageAll => self.unstage_all_source_control(),
ScmAction::DiscardAll => self.request_discard_all_source_control(),
ScmAction::Sync => self.sync_source_control(),
ScmAction::PullRebase => {
let r = crate::git::pull_rebase(&self.scm_root());
self.run_scm_op("pull --rebase", r, "Pulled (rebase)");
}
ScmAction::PushTo => self.open_push_to_remote_picker(),
ScmAction::PushForce => {
let r = crate::git::push_force(&self.scm_root());
self.run_scm_op("push --force-with-lease", r, "Force-pushed");
}
ScmAction::PublishBranch => self.publish_branch_source_control(),
ScmAction::CreateBranch => self.open_branch_picker_for(BranchPurpose::Checkout),
ScmAction::CreateBranchFrom => self.open_branch_picker_for(BranchPurpose::CreateFrom),
ScmAction::RenameBranch => {
let seed = self
.source_control
.status
.branch
.clone()
.unwrap_or_default();
self.open_input_prompt(
InputPrompt::new(
InputPurpose::RenameBranch,
"Rename Branch",
"New branch name",
)
.with_value(seed),
);
}
ScmAction::DeleteBranch => self.open_branch_picker_for(BranchPurpose::Delete),
ScmAction::Merge => self.open_branch_picker_for(BranchPurpose::Merge),
ScmAction::Rebase => self.open_branch_picker_for(BranchPurpose::Rebase),
ScmAction::AddRemote => self.open_input_prompt(InputPrompt::new(
InputPurpose::AddRemoteName,
"Add Remote",
"Remote name (e.g. origin)",
)),
ScmAction::RemoveRemote => self.open_remote_picker(ListPurpose::RemoveRemote),
ScmAction::Stash => self.stash_source_control(),
ScmAction::StashIncludeUntracked => {
let r = crate::git::stash_push_untracked(&self.scm_root());
self.run_scm_op("stash push -u", r, "Stashed (incl. untracked)");
}
ScmAction::StashStaged => {
let r = crate::git::stash_push_staged(&self.scm_root());
self.run_scm_op("stash push --staged", r, "Stashed staged");
}
ScmAction::ApplyStash => self.open_stash_picker(ListPurpose::StashApply),
ScmAction::PopStashLatest => self.stash_pop_source_control(),
ScmAction::PopStashPick => self.open_stash_picker(ListPurpose::StashPop),
ScmAction::DropStash => self.open_stash_picker(ListPurpose::StashDrop),
ScmAction::CreateTag => self.open_input_prompt(InputPrompt::new(
InputPurpose::CreateTag,
"Create Tag",
"Tag name (e.g. v1.0.0)",
)),
ScmAction::DeleteTag => self.open_tag_picker(),
}
}
fn open_stash_picker(&mut self, purpose: crate::widgets::list_picker::ListPurpose) {
use crate::widgets::list_picker::{ListPicker, ListRow};
let rows: Vec<ListRow> = match crate::git::list_stashes(&self.scm_root()) {
Ok(stashes) => stashes
.into_iter()
.map(|s| ListRow {
id: s.index.to_string(),
label: format!("stash@{{{}}}: {}", s.index, s.message),
})
.collect(),
Err(err) => {
self.status = format!("Stashes: {err}");
return;
}
};
let title = match purpose {
crate::widgets::list_picker::ListPurpose::StashApply => "Apply Stash",
crate::widgets::list_picker::ListPurpose::StashDrop => "Drop Stash",
_ => "Pop Stash",
};
self.open_list_picker(
ListPicker::new(purpose, title, rows),
"No stashes to choose",
);
}
fn open_tag_picker(&mut self) {
use crate::widgets::list_picker::{ListPicker, ListPurpose, ListRow};
let rows: Vec<ListRow> = match crate::git::list_tags(&self.scm_root()) {
Ok(tags) => tags
.into_iter()
.map(|t| ListRow {
id: t.clone(),
label: t,
})
.collect(),
Err(err) => {
self.status = format!("Tags: {err}");
return;
}
};
self.open_list_picker(
ListPicker::new(ListPurpose::DeleteTag, "Delete Tag", rows),
"No tags to delete",
);
}
fn open_remote_picker(&mut self, purpose: crate::widgets::list_picker::ListPurpose) {
use crate::widgets::list_picker::{ListPicker, ListRow};
let rows: Vec<ListRow> = match crate::git::list_remotes(&self.scm_root()) {
Ok(remotes) => remotes
.into_iter()
.map(|r| ListRow {
id: r.name.clone(),
label: format!("{} {}", r.name, r.url),
})
.collect(),
Err(err) => {
self.status = format!("Remotes: {err}");
return;
}
};
self.open_list_picker(
ListPicker::new(purpose, "Remove Remote", rows),
"No remotes configured",
);
}
fn open_push_to_remote_picker(&mut self) {
use crate::widgets::list_picker::{ListPicker, ListPurpose, ListRow};
let rows: Vec<ListRow> = match crate::git::list_remotes(&self.scm_root()) {
Ok(remotes) => remotes
.into_iter()
.map(|r| ListRow {
id: r.name.clone(),
label: format!("{} {}", r.name, r.url),
})
.collect(),
Err(err) => {
self.status = format!("Remotes: {err}");
return;
}
};
self.open_list_picker(
ListPicker::new(ListPurpose::PushToRemote, "Push to Remote", rows),
"No remotes configured",
);
}
/// Apply the value submitted by the input modal to its purpose's git op.
fn submit_input_prompt(&mut self) {
use crate::widgets::input_prompt::{InputPrompt, InputPurpose};
let Some(prompt) = self.input_prompt.as_ref() else {
return;
};
let Some(value) = prompt.submit_value() else {
return; // blank: keep waiting
};
let purpose = prompt.purpose.clone();
match purpose {
InputPurpose::AddWatch => {
self.close_input_prompt();
self.add_watch_expression(value);
}
InputPurpose::MacroReplayCount => {
self.close_input_prompt();
match value.trim().parse::<usize>() {
Ok(n) if n > 0 => self.replay_last_macro(n),
_ => self.status = format!("Not a repeat count: {}", value.trim()),
}
}
InputPurpose::ArchiveExtract { member } => {
self.close_input_prompt();
let dest = PathBuf::from(value.trim());
let Some((path, kind)) = self
.editor
.archive
.as_ref()
.and_then(|v| Some((self.editor.path.clone()?, v.kind)))
else {
return;
};
match crate::archive::extract_member(&path, kind, &member, &dest) {
Ok(p) => self.status = format!("Extracted to {}", p.display()),
Err(e) => self.status = format!("Extract failed: {e}"),
}
}
InputPurpose::NewWorktreeLane => {
self.close_input_prompt();
self.create_worktree_lane(&value);
}
InputPurpose::FleetCommand => {
// Closed FIRST, like every sibling arm. Leaving it open hides
// the status line the run writes, so the user cannot see the
// answer they just asked for.
self.close_input_prompt();
self.run_fleet_command(&value);
}
InputPurpose::HexFind => {
self.close_input_prompt();
match crate::hex::HexView::parse_find_query(&value) {
Some(needle) => {
let from = match self.editor.hex.as_mut() {
Some(view) => {
view.last_find = Some(needle);
// The submit searches from the cursor
// INCLUSIVE so a match under it is
// found; F3 then steps past it.
view.cursor
}
None => return,
};
self.hex_find_run(from);
}
None => self.status = String::from("Hex find: empty query"),
}
}
InputPurpose::SaveWorkspaceAs => {
self.close_input_prompt();
let dest = PathBuf::from(value.trim());
let folders: Vec<PathBuf> = self.roots.iter().map(Path::to_path_buf).collect();
match crate::workspace::write_workspace_file(&dest, &folders) {
Ok(()) => {
self.status = format!(
"Saved workspace ({} folder{}): {}",
folders.len(),
if folders.len() == 1 { "" } else { "s" },
dest.display()
);
}
Err(e) => self.status = format!("Save workspace: {e}"),
}
}
InputPurpose::CloneUrl => {
self.close_input_prompt();
let parent = self
.tree
.root
.parent()
.map(|p| p.to_path_buf())
.unwrap_or_else(|| self.tree.root.clone());
match crate::git::clone_into(&parent, &value) {
Ok(dest) => {
self.log_git("clone", &Ok(format!("into {}", dest.display())));
self.status = format!("Cloned into {}", self.status_path(&dest));
self.change_workspace_root(dest);
}
Err(err) => {
self.log_git("clone", &Err(err.clone()));
self.source_control.commit_feedback = Some(format!("clone failed: {err}"));
self.source_control.commit_feedback_is_error = true;
self.status = format!("Clone failed: {err}");
}
}
}
InputPurpose::RenameBranch => {
self.close_input_prompt();
let r = crate::git::rename_branch(&self.scm_root(), &value);
self.run_scm_op("branch -m", r, "Renamed branch");
}
InputPurpose::CreateBranchFrom { base } => {
self.close_input_prompt();
let r = crate::git::create_branch_from(&self.scm_root(), &value, &base);
self.run_scm_op("switch -c (from)", r, "Created branch");
}
InputPurpose::AddRemoteName => {
// First step: capture the name, then re-prompt for the URL.
self.close_input_prompt();
self.open_input_prompt(InputPrompt::new(
InputPurpose::AddRemoteUrl { name: value },
"Add Remote",
"Remote URL",
));
}
InputPurpose::AddRemoteUrl { name } => {
self.close_input_prompt();
let r = crate::git::add_remote(&self.scm_root(), &name, &value);
self.run_scm_op("remote add", r, "Added remote");
}
InputPurpose::CreateTag => {
self.close_input_prompt();
let r = crate::git::create_tag(&self.scm_root(), &value);
self.run_scm_op("tag", r, "Created tag");
}
InputPurpose::ViewerConsent { key, path } => {
// The user allowed the viewer's extension; record it and
// resume the open that asked. The viewer is looked up first:
// one removed while the prompt was up gets a status line and
// no consent, since what was allowed no longer exists.
self.close_input_prompt();
let Some(viewer) =
crate::mcp::registry::viewer_by_id_in_dir(&self.config_dir, &key)
else {
self.status = format!("{key} is no longer available");
return;
};
// The session grant first, so the open passes the gate; the
// prefs write after, so a failure it reports is the status
// the user is left with rather than one the open overwrote.
self.consented_extensions.insert(viewer.ext_id.clone());
self.open_in_viewer(&viewer, &path);
self.persist_extension_consent(&viewer.ext_id);
}
InputPurpose::McpConsent { command_id } => {
// The user confirmed; record consent for this command's
// extension and resume the command (which now passes the gate
// and proceeds to its argument prompt or runs).
self.close_input_prompt();
// The session grant first, so the run passes the gate, and
// the prefs write before the run here: a sidecar command's
// run ends on its own argument prompt with no status of its
// own, so a failure reported after it would sit under that
// prompt and be cleared with it.
let ext_id =
crate::mcp::registry::resolve_command_in_dir(&self.config_dir, &command_id)
.map(|r| r.ext_id);
if let Some(ext_id) = &ext_id {
self.consented_extensions.insert(ext_id.clone());
self.persist_extension_consent(ext_id);
}
self.run_extension_command(&command_id);
}
InputPurpose::McpArg { command_id } => {
self.close_input_prompt();
if let Some(resolved) =
crate::mcp::registry::resolve_command_in_dir(&self.config_dir, &command_id)
{
self.spawn_mcp_command(resolved, Some(value));
}
}
InputPurpose::ExtensionUninstall { id } => {
self.close_input_prompt();
self.perform_extension_uninstall(&id);
}
InputPurpose::TreeDelete { paths } => {
self.close_input_prompt();
self.perform_delete_paths(paths);
}
InputPurpose::ReloadConflict { paths } => {
self.close_input_prompt();
let reverted = self.editor.revert_paths_to_disk(&paths);
self.sync_open_file_poll_mtime();
// A failed reload (file deleted since the popup opened) keeps
// its unsaved edits — say so instead of silently doing nothing.
let failed = paths.len().saturating_sub(reverted.len());
self.status = match (reverted.len(), failed) {
(0, _) => String::from("Reload from disk failed; unsaved edits kept"),
(1, 0) => format!("Reloaded {} from disk", reverted[0].display()),
(n, 0) => format!("Reloaded {n} files from disk"),
(n, f) => format!("Reloaded {n} files; {f} failed and kept their edits"),
};
}
InputPurpose::AskNavigator {
file,
range,
selection,
} => {
// The prompt closes only on a SENT ask: a failure (navigator
// gone or gone busy while the user typed) keeps the box open
// with the draft intact for a retry, like a failed comment
// reply keeps its draft.
let Some(host) = &self.pair_host else {
self.status = String::from("Navigator is not active");
return;
};
let content = self.editor.lines.join("\n");
let name = host.name().to_string();
let result = host.send_ask_turn(&file, range, &selection, &value, &content);
match result {
Ok(()) => {
self.close_input_prompt();
self.status = format!("Asked {name} about {file}:{}", range.0 + 1);
// Anchor the turn's prose commentary where it was asked.
self.pair_turn_origin = Some((file, range.0));
}
Err(e) => self.status = format!("Ask Navigator failed: {e}"),
}
}
}
}
/// "Session: Participants" (Cmd+K A): who is attached to this
/// multiplayer session, from the host's presence sidecar
/// (docs/MULTIPLAYER.md). Enter on a row opens the action picker.
fn open_participants_picker(&mut self) {
if self.session_channel.is_none() {
self.status = String::from("Not a persistent session (start one with `croft attach`)");
return;
}
let rows: Vec<crate::widgets::list_picker::ListRow> = self
.session_participants
.iter()
.map(participant_row)
.collect();
let picker = crate::widgets::list_picker::ListPicker::new(
crate::widgets::list_picker::ListPurpose::SessionParticipant,
"Session Participants",
rows,
);
self.open_list_picker(picker, "No participants yet");
}
/// Second-level picker for one participant: grant or revoke write
/// control, or disconnect them. Safe to expose to every attacher: a
/// read-only guest's keystrokes are dropped at the session host, so any
/// key that reaches this UI came from a control-holding client.
fn open_participant_actions(&mut self, id: u64) {
let Some(p) = self.session_participants.iter().find(|p| p.id == id) else {
return;
};
use crate::widgets::list_picker::{ListPicker, ListPurpose, ListRow};
let control_row = if p.control {
ListRow {
id: format!("revoke:{id}"),
label: String::from("Revoke write control"),
}
} else {
ListRow {
id: format!("grant:{id}"),
label: String::from("Grant write control"),
}
};
let rows = vec![
control_row,
ListRow {
id: format!("kick:{id}"),
label: String::from("Disconnect"),
},
];
let picker = ListPicker::new(ListPurpose::SessionParticipantAction, p.name.clone(), rows);
self.open_list_picker(picker, "No actions");
}
/// Send a participant action to the session host and report it. The
/// roster update comes back through the presence poll.
fn run_participant_action(&mut self, verb: ParticipantVerb, id: u64) {
let name = self
.session_participants
.iter()
.find(|p| p.id == id)
.map(|p| p.name.clone())
.unwrap_or_else(|| format!("participant {id}"));
let Some(channel) = self.session_channel.as_mut() else {
return;
};
let ok = match verb {
ParticipantVerb::Grant => channel.set_control(id, true),
ParticipantVerb::Revoke => channel.set_control(id, false),
ParticipantVerb::Kick => channel.kick(id),
};
self.status = if ok {
match verb {
ParticipantVerb::Grant => format!("Granted write control to {name}"),
ParticipantVerb::Revoke => format!("Revoked write control from {name}"),
ParticipantVerb::Kick => format!("Disconnected {name}"),
}
} else {
String::from("Session host unreachable")
};
}
/// Poll the session host's presence sidecar (multiplayer roster): a stat
/// every 500ms, reparse only when the mtime moves. Surfaces joins and
/// leaves in the status line and keeps an open participants picker live.
fn poll_session_presence(&mut self) -> bool {
const INTERVAL: std::time::Duration = std::time::Duration::from_millis(500);
if self.session_channel.is_none() {
return false;
}
if self.last_session_presence_poll.elapsed() < INTERVAL {
return false;
}
// A host swap (#238) tears this privileged channel down while the
// session lives on under the successor host. The socket and token in
// the environment are still valid - the successor inherited both -
// so revival is just authenticating again, throttled by this poll's
// own interval.
if self.session_channel.as_ref().is_some_and(|c| c.is_dead())
&& let Some(fresh) = crate::session_host::InnerChannel::from_env()
{
self.session_channel = Some(fresh);
}
let Some(channel) = self.session_channel.as_ref() else {
return false;
};
self.last_session_presence_poll = std::time::Instant::now();
// #238: the serve wrapper normally re-execs itself into an updated
// binary, carrying the session along - the marker appears only when
// that handoff could not happen (exec failed, no handoff fds), so
// the host is stuck on the old image and the one recovery is a
// fresh host, which a detach + reattach of the last participant
// produces. Checked before the presence-mtime early-return: a
// roster that never changes must not hide the hint.
if !self.session_host_stale_seen && channel.stale_marker.exists() {
self.session_host_stale_seen = true;
self.status = String::from(
"Session host runs a pre-update binary; detach and reattach (all participants) to pick up the update",
);
}
let path = channel.presence.clone();
let mtime = std::fs::metadata(&path).and_then(|m| m.modified()).ok();
if mtime == self.session_presence_mtime {
return false;
}
self.session_presence_mtime = mtime;
let roster = crate::session_host::read_presence(&path).unwrap_or_default();
if roster == self.session_participants {
return false;
}
let before = self.session_participants.len();
let after = roster.len();
self.session_participants = roster;
// before == 0 is the initial self-only read; not worth announcing.
if after > before && before > 0 {
self.status = format!(
"A participant attached read-only ({after} attached). Manage via Session: Participants (Cmd+K A)"
);
} else if after < before {
self.status = format!("A participant detached ({after} attached)");
}
// Keep an open participants picker live without wiping the user's
// typed filter, highlight, or scroll (any client resizing churns the
// roster within the poll window; a naive rebuild would reset it).
if let Some(p) = self.list_picker.as_ref()
&& p.purpose == crate::widgets::list_picker::ListPurpose::SessionParticipant
{
let (query, cursor, selected, scroll) =
(p.query.clone(), p.cursor, p.selected, p.scroll);
self.open_participants_picker();
if let Some(p) = self.list_picker.as_mut() {
let last = p.rows.len().saturating_sub(1);
p.query = query;
p.cursor = cursor;
p.selected = selected.min(last);
p.scroll = scroll.min(last);
}
}
true
}
/// Drain typing attribution from the session host: when the typing
/// participant changes, hand the shared cursor over (stash the previous
/// typist's caret, restore the new one's).
fn poll_session_typing(&mut self) -> bool {
let Some(channel) = self.session_channel.as_mut() else {
return false;
};
let typists = channel.drain_typing();
if typists.is_empty() {
return false;
}
let mut changed = false;
for id in typists {
if self.session_typist != Some(id) {
self.apply_typist_change(id);
changed = true;
}
}
changed
}
/// Participant `id` is typing now: park the previous typist's caret and
/// move the shared cursor back to where `id` last was (same file only;
/// a caret parked in another file just renders there as a ghost once
/// that file is active again).
fn apply_typist_change(&mut self, id: u64) {
let path = self.editor.path.clone();
if let (Some(prev), Some(path)) = (self.session_typist, path.as_ref()) {
self.session_carets.insert(
prev,
SessionCaret {
path: path.clone(),
row: self.editor.cursor_row,
col: self.editor.cursor_col,
},
);
}
self.session_typist = Some(id);
if let (Some(parked), Some(path)) = (self.session_carets.get(&id), path.as_ref())
&& parked.path == *path
&& !self.editor.lines.is_empty()
{
let row = parked.row.min(self.editor.lines.len() - 1);
let col = parked.col.min(self.editor.lines[row].chars().count());
self.editor.cursor_row = row;
self.editor.cursor_col = col;
}
}
/// The resident navigator's activation check (docs/MULTIPLAYER.md):
/// stat the workspace's pair record on a 1s cadence, seat or unseat the
/// pilot on `enabled` transitions, and — on a plain launch with no
/// collab session — self-appoint the OWNER seat first, because only an
/// owner answers the pilot's snapshot requests. Solo guests never host:
/// the owner's croft does.
fn maybe_seat_navigator(&mut self) -> bool {
let due = self
.last_pair_check
.is_none_or(|t| t.elapsed() >= std::time::Duration::from_secs(1));
if !due {
return false;
}
self.last_pair_check = Some(std::time::Instant::now());
// A rewritten record re-arms seating: after a failed seat the user
// re-runs `croft pair`, and the CLI promises "a running croft seats
// it within a second" — but an enabled→enabled rewrite has no other
// observable transition. The record's BYTES are the signal (every
// write stamps them, and mtime misses a same-grain rewrite on a
// coarse-timestamp filesystem).
let raw = std::fs::read(&self.pair_record_path).ok();
if self.last_pair_record_raw != raw {
if self.last_pair_record_raw.is_some() {
self.navigator_down = false;
}
self.last_pair_record_raw = raw.clone();
}
let record: Option<crate::session::PairRecord> = raw
.as_deref()
.and_then(|bytes| serde_json::from_slice(bytes).ok());
let want = record.as_ref().is_some_and(|r| r.enabled);
if !want {
// Deactivation clears the death latch, so `croft pair --off`
// then `croft pair` (or a palette off/on) re-activates.
self.navigator_down = false;
self.pair_lock_denied = None;
// A fix stream cannot outlive the seat: with the navigator
// deactivated no TurnDone can arrive, and a marker left here
// spun the row (and woke the renderer) forever (#374 review).
self.clear_problem_fix();
if let Some(host) = self.pair_host.take() {
// Drop tears the seat down; its parked caret goes with it.
let sites = host.caret_sites();
self.collab_carets.retain(|s, _| !sites.contains(s));
self.navigator_notes.clear();
self.pair_commentary_buf.clear();
self.pair_turn_origin = None;
// The turn counters die with the seat: leaking them made
// the NEXT seat's first TurnDone report a dead seat's notes.
self.pair_notes_this_turn = 0;
self.pair_last_noted_file = None;
self.pair_noted_files.clear();
self.editor.comment_focus = None;
self.status = String::from("Navigator unseated");
return true;
}
return false;
}
if self.pair_host.is_some() {
return false;
}
// The pilot died or failed to seat: do not respawn it every second.
// The user re-activates (off/on) to try again; a fresh croft retries.
if self.navigator_down {
return false;
}
if self
.collab_config
.as_ref()
.is_some_and(|(_, role)| *role == crate::collab::CollabRole::Guest)
{
return false;
}
let record = record.expect("want implies a record");
let mut self_appointed_now = false;
if self.collab_config.is_none() {
// Only one croft may self-appoint owner per workspace: two owners
// would both claim site id 1 and corrupt the shared buffer. Claim
// the single-host lock first; if another croft holds it, do not
// host (keep checking — take over when that croft exits).
if self.pair_host_lock.is_none() {
match crate::session::try_acquire_pair_host_lock(&self.pair_host_lock_path) {
Ok(lock) => {
self.pair_host_lock = Some(lock);
self.pair_lock_denied = None;
}
Err(e) => {
// Announced ONCE per reason: the takeover poll keeps
// running every second, and re-announcing clobbered
// the window's status line forever at a 1 Hz repaint.
let denial = match &e {
crate::session::PairHostLockError::Busy => PairLockDenial::Busy,
crate::session::PairHostLockError::Io(_) => PairLockDenial::Io,
};
if self.pair_lock_denied == Some(denial) {
return false;
}
self.pair_lock_denied = Some(denial);
// Busy and unopenable read the same from here (no
// host this tick, poll again) but not to the user:
// one has a window to close, the other has a path
// to fix and no window anywhere (#337).
self.status = match e {
crate::session::PairHostLockError::Busy => format!(
"Navigator '{}' is hosted by another croft window in this workspace",
record.name
),
crate::session::PairHostLockError::Io(e) => format!(
"Navigator '{}': cannot open host lock {}: {e}",
record.name,
self.pair_host_lock_path.display()
),
};
return true;
}
}
}
if let Err(e) = crate::collab::ensure_relay(&self.pair_socket) {
self.status = format!("Navigator: relay failed: {e}");
// The spawn failure's sibling: this window holds the lock
// but cannot host without a relay. Release it so another
// window can try; this one retries next second and may
// re-acquire.
self.pair_host_lock = None;
return true;
}
self.collab_config = Some((self.pair_socket.clone(), crate::collab::CollabRole::Owner));
self.last_collab_connect = None; // connect this tick, not in 2s
self_appointed_now = true;
}
let cfg = crate::pair::PairConfig {
socket: self.pair_socket.clone(),
workspace: self.tree.root.clone(),
name: record.name.clone(),
model: record.model.clone(),
// Resident seating never replays a task: a persisted task would
// re-execute on every launch, and an @file task would freeze the
// UI thread on seat (the owner that must serve the file is this
// very thread). Instructions come from Cmd+K Q. The --repl driver
// still takes a one-shot task via PairConfig directly.
task: None,
provider: crate::pair::Provider::from_record(
record.provider.as_deref(),
record.base_url.as_deref(),
),
};
#[cfg(test)]
let spawned = match &self.pair_spawn_override {
Some(spawn) => spawn(&cfg),
None => crate::pair_host::PairHost::spawn(cfg),
};
#[cfg(not(test))]
let spawned = crate::pair_host::PairHost::spawn(cfg);
match spawned {
Ok(host) => {
self.status = format!(
"Navigator '{}' seated (Cmd+K Q asks, Cmd+K Y yields)",
host.title()
);
self.pair_host = Some(host);
}
Err(e) => {
self.status = format!("Navigator failed to seat: {e}");
self.navigator_down = true; // no 1s retry storm
if self_appointed_now {
// A window that cannot host must not block one that can:
// undo the self-appointment made moments ago (nothing
// has connected yet within this same call) and release
// the lock so another croft may claim the seat. A host
// whose PILOT died later keeps both — it is still the
// live collab owner and re-seats on re-activation.
self.collab_config = None;
self.pair_host_lock = None;
}
}
}
true
}
/// Drain the navigator's per-tick events: commentary to the Navigator
/// OUTPUT channel, note/turn/death news to the status line, and the
/// active file's note snapshot for the gutter marks and popup.
fn poll_pair(&mut self) -> bool {
let Some(host) = self.pair_host.as_mut() else {
return false;
};
let name = host.name().to_string();
let events = host.poll();
let mut changed = !events.is_empty();
let mut died = false;
for event in events {
match event {
crate::pair_host::PairEvent::Commentary(text) => {
// The navigator's voice is its comment boxes: prose
// accumulates and lands as one box when the turn ends.
if !text.trim().is_empty() {
if !self.pair_commentary_buf.is_empty() {
self.pair_commentary_buf.push('\n');
}
self.pair_commentary_buf.push_str(text.trim_end());
}
}
crate::pair_host::PairEvent::NoteAdded { file, row, body } => {
let snippet: String = body.chars().take(60).collect();
self.status = format!("{name} commented on {file}:{}: {snippet}", row + 1);
self.pair_notes_this_turn += 1;
self.pair_noted_files.insert(file.clone());
self.pair_last_noted_file = Some(file);
}
crate::pair_host::PairEvent::TurnDone { cancelled, failed } => {
let mut notes = std::mem::take(&mut self.pair_notes_this_turn);
let mut files = std::mem::take(&mut self.pair_noted_files);
let file = self.pair_last_noted_file.take();
let prose = std::mem::take(&mut self.pair_commentary_buf);
let origin = self.pair_turn_origin.take();
// Whatever the outcome, the fix turn is over: the row's
// spinner stops, and the LSP's next publish decides
// whether the row itself goes (#374).
self.clear_problem_fix();
if !cancelled && !prose.trim().is_empty() {
// Anchor the turn's prose at its invocation point (or
// where it last commented). A file that is not live
// any more falls back to the OUTPUT channel rather
// than losing the navigator's words.
let anchor = origin.or_else(|| {
file.clone().map(|f| {
// The caret row only means something in the
// file it is in: pairing the last-noted
// file with the ACTIVE tab's cursor row
// anchored the box at an unrelated line.
// Any other file clamps to its end.
let same = self
.editor
.path
.as_ref()
.and_then(|p| collab_file_key(&self.tree.root, p))
.is_some_and(|active| active == f);
let row = if same {
self.editor.cursor_row
} else {
usize::MAX
};
(f, row)
})
});
let landed = anchor.as_ref().and_then(|(f, row)| {
self.pair_host
.as_ref()
.and_then(|h| h.add_note_now(f, *row, prose.trim()))
});
match (landed, anchor) {
(Some(_), Some((f, _))) => {
notes += 1;
files.insert(f);
}
_ => {
for line in prose.lines().filter(|l| !l.trim().is_empty()) {
crate::output::push(
"Navigator",
crate::output::OutputLevel::Info,
line,
);
}
}
}
}
self.status = if cancelled {
format!("{name}: turn cancelled")
} else if let Some(err) = failed {
let err: String = err.chars().take(80).collect();
format!("{name}: turn failed: {err}")
} else if notes > 0 {
format!(
"{name} finished: {} · F4 to review",
turn_note_summary(notes, &files)
)
} else {
format!("{name} finished its turn")
};
}
crate::pair_host::PairEvent::Died(reason) => {
self.status = format!("Navigator: {reason}");
died = true;
}
}
}
if died {
let sites = self
.pair_host
.take()
.map(|h| h.caret_sites())
.unwrap_or_default();
self.collab_carets.retain(|s, _| !sites.contains(s));
self.navigator_notes.clear();
self.pair_commentary_buf.clear();
self.pair_turn_origin = None;
self.clear_problem_fix();
// The turn counters die with the seat (see the unseat twin).
self.pair_notes_this_turn = 0;
self.pair_last_noted_file = None;
self.pair_noted_files.clear();
self.editor.comment_focus = None;
self.navigator_down = true; // no auto-respawn; re-activate to retry
return true;
}
// Refresh the active file's snapshot every tick: rows move under
// concurrent edits without any new event arriving.
if let Some(file) = self
.editor
.path
.as_ref()
.and_then(|p| collab_file_key(&self.tree.root, p))
&& let Some(host) = &self.pair_host
{
let snap = host.notes_snapshot(&file);
if self.navigator_notes.get(&file) != Some(&snap) {
self.navigator_notes.insert(file, snap);
changed = true;
}
}
changed
}
/// Keys while a comment box's reply field has focus: type into the
/// draft, Enter sends the reply turn, Esc leaves the box (its draft
/// survives until the box goes), F4 hops to the next box, Shift+F4
/// ignores this one.
fn handle_comment_focus_key(&mut self, key: KeyEvent) {
if matches!(key.code, KeyCode::F(4)) {
if key.modifiers.contains(KeyModifiers::SHIFT) {
self.ignore_focused_comment();
} else {
self.cycle_comment_box();
}
return;
}
match key.code {
KeyCode::Esc => {
self.editor.comment_focus = None;
return;
}
KeyCode::Enter => {
self.submit_comment_reply();
return;
}
_ => {}
}
let Some(focus) = self.editor.comment_focus.as_mut() else {
return;
};
match key.code {
KeyCode::Backspace if focus.cursor > 0 => {
let idx = focus
.reply
.char_indices()
.nth(focus.cursor - 1)
.map(|(i, _)| i)
.unwrap_or(0);
focus.reply.remove(idx);
focus.cursor -= 1;
}
KeyCode::Left => focus.cursor = focus.cursor.saturating_sub(1),
KeyCode::Right => {
focus.cursor = (focus.cursor + 1).min(focus.reply.chars().count());
}
KeyCode::Char(c)
if !key.modifiers.intersects(
KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SUPER,
) =>
{
let idx = focus
.reply
.char_indices()
.nth(focus.cursor)
.map(|(i, _)| i)
.unwrap_or(focus.reply.len());
focus.reply.insert(idx, c);
focus.cursor += 1;
}
_ => {}
}
}
/// Enter in the focused box: append the reply to the box (the running
/// conversation stays visible) and send it to the navigator as a
/// comment-only turn carrying the note's context.
fn submit_comment_reply(&mut self) {
let Some(focus) = self.editor.comment_focus.clone() else {
return;
};
let reply = focus.reply.trim().to_string();
if reply.is_empty() {
return;
}
let Some(host) = &self.pair_host else {
self.status =
String::from("Navigator is not active (run croft pair in this workspace)");
return;
};
if host.is_busy() {
self.status = format!("{} is mid-turn; wait for it to finish", host.name());
return;
}
let Some(file) = self
.editor
.path
.as_ref()
.and_then(|p| collab_file_key(&self.tree.root, p))
else {
self.status = String::from("Reply: no active workspace file");
return;
};
let Some((_, row, note_body)) = self
.navigator_notes
.get(&file)
.and_then(|notes| notes.iter().find(|(id, ..)| *id == focus.id))
.cloned()
else {
self.status = String::from("That comment is gone");
self.editor.comment_focus = None;
return;
};
let content = self.editor.lines.join("\n");
match host.send_reply_turn(&file, row, ¬e_body, &reply, &content) {
Ok(()) => {
// Only after the send: a failed send keeps the draft for a
// retry, and appending first would duplicate the reply in
// the box on every attempt.
host.append_to_note(focus.id, &format!("you: {reply}"));
self.pair_turn_origin = Some((file, row));
self.status = format!("Replied to {}", host.name());
self.editor.comment_focus = None;
}
Err(e) => self.status = format!("Reply failed: {e}"),
}
}
/// Follow the open file to its new path so its review boxes survive a
/// rename or an explorer cut/paste (#366).
///
/// Both guards — the render merge and the F4 walk — compare the stored
/// path against `editor.path`. A rename repoints the tab and would
/// otherwise leave the field naming a path nothing matches, so the boxes
/// vanish from the buffer the user is still editing and the field holds
/// unreachable garbage.
fn rename_review_boxes_path(&mut self, old: &Path, new: &Path) {
if let Some((p, _)) = &mut self.review_boxes
&& p == old
{
*p = new.to_path_buf();
}
}
/// Dismiss one comment box: drop the note from the pilot's state and
/// from the local snapshot (the next poll would resurrect it otherwise
/// only if the pilot still had it).
fn ignore_comment_box(&mut self, id: u64) {
if let Some(host) = &self.pair_host {
host.remove_note(id);
}
for notes in self.navigator_notes.values_mut() {
notes.retain(|(nid, ..)| *nid != id);
}
// Review boxes share this footer and this hit-test, so without
// retaining here the button would report "Comment ignored" and the
// box would return on the very next frame (#366).
//
// Matching on the id alone is safe because the two sources cannot
// collide in practice: a navigator note's id counts up from 1 (see
// `pair.rs`'s `take_note_id`, over `next_note_id`), while a review
// thread's is GitHub's own comment id, currently around 3.9e9. If
// notes ever gain a wider allocator, this needs a tag rather than a
// bare id.
if let Some((_, threads)) = &mut self.review_boxes {
threads.retain(|t| t.id != id);
}
if self
.editor
.comment_focus
.as_ref()
.is_some_and(|f| f.id == id)
{
self.editor.comment_focus = None;
}
self.status = String::from("Comment ignored");
}
/// Shift+F4 / palette: ignore the focused box, or the next one from the
/// caret when none is focused.
fn ignore_focused_comment(&mut self) {
let id = self
.editor
.comment_focus
.as_ref()
.map(|f| f.id)
.or_else(|| self.next_comment_from_caret().map(|(id, _)| id));
match id {
Some(id) => self.ignore_comment_box(id),
None => self.status = String::from("No navigator comments in this file"),
}
}
/// The active file's next comment from the caret (by row, wrapping):
/// (id, row).
fn next_comment_from_caret(&self) -> Option<(u64, usize)> {
// Built from the same two SOURCES the render merges, in the same
// order, rather than from `editor.comment_boxes` itself: that field
// is a render output, so reading it would make F4 depend on a frame
// having been drawn first, and the walk would find nothing before
// the first render. Review threads are included so F4 reaches them
// too (#366) — reading only the navigator's notes left review boxes
// on screen but unreachable by keyboard, reported as "No navigator
// comments in this file" while the user was looking at several.
let mut notes: Vec<(u64, usize, String)> = self
.editor
.path
.as_ref()
.and_then(|p| collab_file_key(&self.tree.root, p))
.and_then(|file| self.navigator_notes.get(&file))
.cloned()
.unwrap_or_default();
if let Some((path, threads)) = &self.review_boxes
&& self.editor.path.as_deref() == Some(path.as_path())
{
let lines = self.editor.lines.len();
notes.extend(
threads
.iter()
.map(|t| (t.id, t.box_line(lines), t.body.clone())),
);
}
if notes.is_empty() {
return None;
}
let here = self
.editor
.comment_focus
.as_ref()
.and_then(|f| notes.iter().position(|(id, ..)| *id == f.id))
.map(|i| (notes[i].1, i))
.unwrap_or((self.editor.cursor_row, usize::MAX));
let idx = next_note_by_row(¬es, here);
Some((notes[idx].0, notes[idx].1))
}
/// Open the ask box: an instruction input for the resident navigator,
/// scoped to a 0-based inclusive line `range` of the active file, with
/// `selection` carrying selected text when the scope came from one.
/// Cmd+K Q, the gutter menu, and the body menu all land here.
fn open_ask_navigator(&mut self, range: (usize, usize), selection: String) {
let Some(host) = &self.pair_host else {
self.status =
String::from("Navigator is not active (run croft pair in this workspace)");
return;
};
if host.is_busy() {
self.status = format!("{} is mid-turn; wait for it to finish", host.name());
return;
}
let Some(file) = self
.editor
.path
.as_ref()
.and_then(|p| collab_file_key(&self.tree.root, p))
else {
self.status = String::from("Ask Navigator: no active workspace file");
return;
};
let scope = if range.0 == range.1 {
format!("line {}", range.0 + 1)
} else {
format!("lines {}-{}", range.0 + 1, range.1 + 1)
};
self.open_input_prompt(crate::widgets::input_prompt::InputPrompt::new(
crate::widgets::input_prompt::InputPurpose::AskNavigator {
file: file.clone(),
range,
selection,
},
format!("Ask {} · {file} · {scope}", host.name()),
"What should it look at or do?",
));
}
/// Cmd+K Y: hand the navigator the floor on the active file. The turn
/// is comment-only (host-enforced): its say lands as anchored notes and
/// commentary, and it must ask before editing.
fn yield_to_navigator(&mut self) {
let Some(host) = &self.pair_host else {
self.status =
String::from("Navigator is not active (run croft pair in this workspace)");
return;
};
if host.is_busy() {
self.status = format!("{} is mid-turn; wait for it to finish", host.name());
return;
}
let Some(file) = self
.editor
.path
.as_ref()
.and_then(|p| collab_file_key(&self.tree.root, p))
else {
self.status = String::from("Yield: no active workspace file");
return;
};
let content = self.editor.lines.join("\n");
match host.send_yield_turn(&file, &content) {
Ok(()) => {
self.status = format!("Yielded {file} to {} (comment-only turn)", host.name());
// Anchor the turn's prose commentary at the caret.
self.pair_turn_origin = Some((file, self.editor.cursor_row));
}
Err(e) => self.status = format!("Yield failed: {e}"),
}
}
/// Proactive navigator look (docs/MULTIPLAYER.md): when the driver
/// completes a NEW construct in the active file (tree-sitter judged —
/// half-typed code never parses as one) and pauses typing, the seated
/// navigator takes the same comment-only turn Cmd+K Y hands it, anchored
/// at the new construct. Only files the navigator has already looked at
/// re-engage it (this is RE-engagement, not ambush), and a buffer state
/// is scanned at most once. Runs once per frame tick; true = turn sent.
fn tick_proactive_navigator(&mut self) -> bool {
if !self.proactive_navigator_enabled {
return false;
}
let Some(host) = &self.pair_host else {
return false;
};
if host.is_busy() || self.editor.comment_focus.is_some() {
return false;
}
// The user is mid-typing in a prompt (the ask box included):
// stealing the seat now would make their Enter land on a busy host
// and fail. Suppress WITHOUT consuming the scan latch below, so the
// look fires once the prompt closes.
if self.input_prompt.is_some() {
return false;
}
let Some(edited) = self.editor.last_edit_at else {
return false;
};
if edited.elapsed() < PROACTIVE_PAUSE {
return false;
}
let Some(path) = self.editor.path.clone() else {
return false;
};
let seq = self.editor.edit_seq;
if self.proactive_scanned.get(&path) == Some(&seq) {
return false;
}
self.proactive_scanned.insert(path.clone(), seq);
let Some(file) = collab_file_key(&self.tree.root, &path) else {
return false;
};
let Some(kind) = path
.extension()
.and_then(|e| e.to_str())
.and_then(crate::highlight::lang_for_extension)
else {
return false;
};
let Some(old) = host.last_seen(&file) else {
return false; // it never looked at this file; no self-invite
};
let content = self.editor.lines.join("\n");
let Some(row) = crate::pair::proactive::new_construct_row(kind, &old, &content) else {
return false;
};
match host.send_yield_turn(&file, &content) {
Ok(()) => {
self.status = format!("{} is taking a look at {file}:{}", host.name(), row + 1);
self.pair_turn_origin = Some((file, row));
true
}
Err(_) => false,
}
}
/// Palette toggle for the proactive looks, persisted like the inline
/// blame preference.
fn toggle_proactive_navigator(&mut self) {
self.proactive_navigator_enabled = !self.proactive_navigator_enabled;
self.status = if self.proactive_navigator_enabled {
String::from("Navigator proactive comments: on")
} else {
String::from("Navigator proactive comments: off")
};
if !cfg!(test) {
let _ = crate::prefs::save_proactive_navigator(self.proactive_navigator_enabled);
}
}
/// Palette toggle: flip the workspace's pair record and let the next
/// activation check seat or unseat the pilot (within a second).
fn toggle_navigator(&mut self) {
let current = crate::session::read_pair_record(&self.pair_record_path);
let enabled = !current.as_ref().is_some_and(|r| r.enabled);
let record = crate::session::PairRecord {
model: current.as_ref().and_then(|r| r.model.clone()),
name: current
.as_ref()
.map(|r| r.name.clone())
.unwrap_or_else(|| String::from("claude")),
enabled,
task: None,
// The seat's backend survives an off/on round trip: erasing it
// silently reseated a local-only navigator on the cloud claude
// CLI - with a model name claude does not even have.
provider: current.as_ref().and_then(|r| r.provider.clone()),
base_url: current.as_ref().and_then(|r| r.base_url.clone()),
};
if let Some(dir) = self.pair_record_path.parent() {
let _ = std::fs::create_dir_all(dir);
}
match crate::session::write_pair_record(&self.pair_record_path, &record) {
Ok(()) => {
self.last_pair_check = None; // act on this tick, not in 1s
self.status = if enabled {
format!("Navigator '{}' activated; seating", record.name)
} else {
String::from("Navigator deactivated; unseating")
};
}
Err(e) => self.status = format!("Navigator toggle failed: {e}"),
}
}
/// Palette: drop every navigator comment — the pilot's anchors, the
/// per-file snapshots, and the boxes they feed.
fn clear_navigator_notes(&mut self) {
if let Some(host) = &self.pair_host {
host.clear_notes();
}
self.navigator_notes.clear();
self.editor.comment_boxes.clear();
self.editor.comment_focus = None;
self.status = String::from("Navigator comments cleared");
}
/// F4: focus the active file's next comment box (by row, wrapping),
/// jumping the caret to its anchor line so the box scrolls into view.
fn cycle_comment_box(&mut self) {
let Some((id, row)) = self.next_comment_from_caret() else {
self.status = String::from("No navigator comments in this file");
return;
};
let row = row.min(self.editor.lines.len().saturating_sub(1));
let path = self.editor.path.clone().expect("comments imply a file");
match self.open_at(&path, row, 0) {
Ok(()) => {
self.editor.comment_focus = Some(crate::widgets::editor::CommentFocus {
id,
reply: String::new(),
cursor: 0,
});
}
Err(e) => self.status = format!("Comment jump failed: {e}"),
}
}
/// Phase D per-tick collab pump (docs/MULTIPLAYER.md): connect lazily,
/// have guests bootstrap newly opened workspace files, extract local
/// edits into ops BEFORE applying inbound ones (the echo-storm
/// invariant), then resolve inbound events against the open buffers.
fn poll_collab(&mut self) -> bool {
use crate::collab::{CollabChannel, CollabEvent, CollabRole, CollabSession};
if self.collab.is_none() {
let Some((socket, role)) = self.collab_config.clone() else {
return false;
};
// While the link is down there is no doc to converge panes of a
// shared file through, yet input still reaches the active pane:
// mirror it onto its siblings so panes cannot diverge
// independently — the reconnect bootstrap keeps and replays
// exactly ONE divergent text per file, and a second divergent
// pane would be silently replaced by the attach pass.
let mirrored = self.mirror_offline_siblings();
let due = self
.last_collab_connect
.is_none_or(|t| t.elapsed() >= std::time::Duration::from_secs(2));
if !due {
return mirrored;
}
self.last_collab_connect = Some(std::time::Instant::now());
match CollabChannel::connect(&socket, role) {
Some(ch) => self.collab = Some(CollabSession::new(ch, collab_display_name())),
None => return mirrored,
}
}
let mut session = self.collab.take().expect("connected above");
let root = self.tree.root.clone();
let mut changed = false;
// Guests share every text file they open under the workspace; files
// not open on a peer are ignored until opened, then bootstrapped.
if session.role == CollabRole::Guest {
let mut files: Vec<String> = Vec::new();
let mut collect = |editors: &[crate::widgets::editor::Editor]| {
for ed in editors {
if ed.has_non_text_view() {
continue;
}
if let Some(file) = ed.path.as_ref().and_then(|p| collab_file_key(&root, p)) {
files.push(file);
}
}
};
collect(&self.editor.editors);
for group in self.editor_layout.inactive_groups() {
collect(&group.editors);
}
for file in files {
if !session.is_live(&file) && !session.is_bootstrapping(&file) {
session.request_file(&file);
changed = true;
}
}
}
// Invariant 1a: extract-before-apply. Applying remote ops first
// would re-diff them below as local edits and rebroadcast (echo).
// Only ATTACHED buffers extract (collab_doc_gen != 0): a buffer
// created after its file went live — a split duplicate, a reopen —
// was loaded from the disk copy, which is stale by construction
// (guests never write shared files). Diffing it against the doc
// would broadcast a delete-everything/reinsert-the-old-file op set
// and revert every peer; the attach pass below seeds it instead.
let mut extract = |editors: &mut [crate::widgets::editor::Editor]| {
for ed in editors.iter_mut() {
if ed.has_non_text_view() {
continue;
}
let Some(file) = ed.path.as_ref().and_then(|p| collab_file_key(&root, p)) else {
continue;
};
if ed.collab_doc_gen == 0
|| ed.edit_seq == ed.collab_synced_seq
|| !session.is_live(&file)
{
continue;
}
session.local_change(&file, &ed.lines.join("\n"));
ed.collab_synced_seq = ed.edit_seq;
ed.collab_doc_gen = session.doc_gen(&file).unwrap_or(0);
}
};
extract(&mut self.editor.editors);
for group in self.editor_layout.inactive_groups_mut() {
extract(&mut group.editors);
}
// Invariant 1b: drain and resolve. The owner-side lookup opens the
// requested file as a background tab when needed, so guest edits
// land in a real buffer that saves, auto-saves, and reloads through
// the one code path.
let events = session.poll(|file| self.owner_buffer_text(&root, file));
for event in events {
changed = true;
match event {
CollabEvent::RemoteEdit { file, spans } => {
let doc_gen = session.doc_gen(&file).unwrap_or(0);
self.apply_collab_spans(&root, &file, &spans, doc_gen);
}
CollabEvent::Bootstrapped { file, text } => {
let doc_gen = session.doc_gen(&file).unwrap_or(0);
let owner_text = text.clone();
let base = self.collab_offline_base.remove(&file);
if let Some(kept) = self.finish_collab_bootstrap(&root, &file, text, doc_gen) {
// A buffer diverged while the link was down: replay
// the divergence as local edits so the offline work
// reaches every peer; the attach pass below re-seeds
// the kept panes from the doc once it holds the
// replayed text. With a harvested base, only this
// side's offline delta replays (three-way against
// the owner's snapshot), so owner edits made during
// the outage survive.
let replay = match base {
Some(base) => {
crate::collab::merge_offline_texts(&base, &kept, &owner_text)
}
None => kept,
};
session.local_change(&file, &replay);
}
}
CollabEvent::BootstrapTimedOut { file } => {
self.status = format!("{file}: no session owner answered; editing locally");
}
CollabEvent::Caret {
file,
site,
row,
col,
name,
} => {
// Truncate at ingest so a peer's name can never paint a
// whole row; refresh the fade clock only on real moves
// (a re-broadcast of a parked caret keeps its old tag
// age, or the tag would never fade).
let name: String = name.chars().take(24).collect();
let moved = self.collab_carets.get(&site).is_none_or(|c| {
c.file != file || c.row != row || c.col != col || c.name != name
});
if moved {
self.collab_carets.insert(
site,
CollabCaret {
file,
row,
col,
name,
last_moved: std::time::Instant::now(),
},
);
}
}
CollabEvent::StreamState {
file,
site,
name,
active,
} => {
// Truncate like caret names: a badge can never paint a
// whole status row.
let name: String = name.chars().take(24).collect();
self.collab_stream = active.then_some(CollabStreamInfo { file, name, site });
}
// The cancel request is for the streaming pilot, not for
// viewers; the badge clears via StreamState(inactive).
CollabEvent::StreamCancel => {}
}
}
// Attach-and-mirror: a buffer of a live file that has never synced
// (gen 0: a fresh split duplicate or reopen holding stale disk
// text) is seeded from the replicated text, and a clean buffer
// whose generation fell behind (a sibling pane extracted a local
// edit) mirrors the doc. Every pane of a live file converges every
// tick — "the first found stays synced" was unstable, because
// focusing another group reorders which pane is found first, and a
// behind pane accepting a keystroke would diff its older text
// against the doc and silently delete the other pane's work.
let mut attach = |editors: &mut [crate::widgets::editor::Editor]| {
for ed in editors.iter_mut() {
// Diff/image/sheet tabs can carry a shared file's path, but
// their `lines` are not documents: never seed or mark them.
if ed.has_non_text_view() {
continue;
}
let Some(file) = ed.path.as_ref().and_then(|p| collab_file_key(&root, p)) else {
continue;
};
let Some(doc_gen) = session.doc_gen(&file) else {
continue;
};
if ed.collab_doc_gen == doc_gen
|| (ed.collab_doc_gen != 0 && ed.edit_seq != ed.collab_synced_seq)
{
continue;
}
let text = session
.doc_text(&file)
.expect("doc_gen implies a live doc")
.to_string();
// The owner's buffer at snapshot creation already IS the
// doc text: attach without a cursor-jolting replace.
if ed.lines.join("\n") != text {
ed.replace_all_lines(text.split('\n').map(str::to_string).collect());
changed = true;
}
ed.collab_synced_seq = ed.edit_seq;
ed.collab_doc_gen = doc_gen;
}
};
attach(&mut self.editor.editors);
for group in self.editor_layout.inactive_groups_mut() {
attach(&mut group.editors);
}
// Broadcast this participant's caret when it moved in a live file.
if let Some(file) = self
.editor
.path
.as_ref()
.and_then(|p| collab_file_key(&root, p))
&& session.is_live(&file)
{
let caret = (file, self.editor.cursor_row, self.editor.cursor_col);
if self.collab_caret_sent.as_ref() != Some(&caret) {
session.send_caret(&caret.0, caret.1, caret.2);
self.collab_caret_sent = Some(caret);
}
}
if session.disconnected() {
self.drop_lost_collab_session(session);
return true;
}
self.collab = Some(session);
changed | self.collab_labels_dirty()
}
/// The relay hung up (EOF or a failed write): keeping the dead session
/// made `is_live` lie forever while every op vanished. Drop it; the
/// connect path re-attaches (2s backoff) and guest files re-bootstrap
/// through the normal request path.
fn drop_lost_collab_session(&mut self, session: crate::collab::CollabSession) {
// Harvest each live doc's replicated text first: it is the merge
// base for offline edits at the next bootstrap. Without it, the
// whole diverged buffer replays and reads the owner's concurrent
// (unseen) edits as deletions.
for (file, text) in session.live_texts() {
self.collab_offline_base.insert(file, text);
}
self.status = String::from("Shared session link lost; reconnecting");
}
/// One redraw when the set of visible caret name tags changes with no
/// accompanying wire traffic — i.e. the last tag crossing its 2s fade
/// window (appearances already redraw via the Caret event itself).
fn collab_labels_dirty(&mut self) -> bool {
let now = std::time::Instant::now();
let any = self
.collab_carets
.values()
.any(|c| now.duration_since(c.last_moved) < CARET_LABEL_FADE);
let flipped = any != self.collab_labels_visible;
self.collab_labels_visible = any;
flipped
}
/// Cancel the AI stream (gutter stop button, Cmd+K X, palette): ask the
/// streaming pilot over the relay to stop and revert. The badge clears
/// when the pilot broadcasts StreamState(inactive), not optimistically —
/// the revert is the pilot's to confirm.
pub fn collab_cancel_stream(&mut self) {
let Some(stream) = &self.collab_stream else {
self.status = "No AI stream is active".into();
return;
};
let Some(session) = &mut self.collab else {
self.status = "No AI stream is active".into();
return;
};
session.send_stream_cancel();
self.status = format!("Asked {} to stop streaming", stream.name);
}
/// The buffer row wearing the gutter stop button: the pilot's ghost
/// caret row when the streamed file is active here (the button rides
/// the stream), else the top visible row so the button is always in
/// view; None when no stream targets the active file.
fn stream_stop_row(&self) -> Option<usize> {
let stream = self.collab_stream.as_ref()?;
let active = self
.editor
.path
.as_ref()
.and_then(|p| collab_file_key(&self.tree.root, p))?;
if active != stream.file {
return None;
}
Some(
self.collab_carets
.get(&stream.site)
.filter(|c| c.file == stream.file)
.map(|c| c.row)
.unwrap_or(self.editor.scroll),
)
}
/// While the collab link is down, mirror the active pane onto its
/// sibling panes of the same file (nothing else converges them without
/// a live doc). Input only reaches the active pane, so running this
/// every tick keeps all panes equal and the reconnect bootstrap sees
/// exactly one divergent text per file. Only a previously-attached pane
/// (generation != 0) mirrors out: a fresh reopen's disk text is stale
/// by construction and would revert siblings still holding session
/// text.
fn mirror_offline_siblings(&mut self) -> bool {
if self.editor.collab_doc_gen == 0 || self.editor.has_non_text_view() {
return false;
}
let Some(path) = self.editor.path.clone() else {
return false;
};
if collab_file_key(&self.tree.root, &path).is_none() {
return false;
}
let lines = self.editor.lines.clone();
let mut changed = false;
let mut mirror = |ed: &mut crate::widgets::editor::Editor| {
if ed.has_non_text_view() {
return;
}
if ed.path.as_deref() != Some(path.as_path()) || ed.lines == lines {
return;
}
ed.replace_all_lines(lines.clone());
changed = true;
};
let active = self.editor.active_index();
for (i, ed) in self.editor.editors.iter_mut().enumerate() {
if i != active {
mirror(ed);
}
}
for group in self.editor_layout.inactive_groups_mut() {
for ed in group.editors.iter_mut() {
mirror(ed);
}
}
changed
}
/// The owner's current text for a file a guest asked to share: the open
/// buffer if any, else open it as a background tab (keeping the owner's
/// focus where it was) and read that. None declines the request
/// (missing, unreadable, or not a text buffer).
fn owner_buffer_text(&mut self, root: &Path, file: &str) -> Option<String> {
let path = crate::collab::contained_path(root, file)?;
// First TEXT tab with the path: a diff tab of the same file found
// first must not make the owner decline a share its real buffer
// could serve.
let is_text = |ed: &&crate::widgets::editor::Editor| {
ed.path.as_deref() == Some(path.as_path())
&& ed.diff.is_none()
&& ed.image.is_none()
&& ed.sheet.is_none()
};
if let Some(ed) = self.editor.editors.iter().find(is_text) {
return Some(ed.lines.join("\n"));
}
for group in self.editor_layout.inactive_groups() {
if let Some(ed) = group.editors.iter().find(is_text) {
return Some(ed.lines.join("\n"));
}
}
if !path.is_file() {
return None;
}
let keep = self.editor.active_index();
self.editor.open_in_new_tab(&path).ok()?;
let opened = self.editor.active_index();
self.editor.select(keep);
let ed = &self.editor.editors[opened];
(ed.diff.is_none() && ed.image.is_none() && ed.sheet.is_none()).then(|| ed.lines.join("\n"))
}
/// Replay resolved remote spans onto every open buffer for `file`,
/// converting each byte span to the editor's char coordinates. Spans are
/// sequential (each relative to the text with earlier ones applied), so
/// they go through `apply_span_edits` one at a time. Every ATTACHED pane
/// gets them (attached panes hold identical text, so the byte offsets
/// are valid in each); a never-attached pane still holds stale disk
/// text where the offsets would splice garbage — the attach pass seeds
/// it from the doc instead.
fn apply_collab_spans(
&mut self,
root: &Path,
file: &str,
spans: &[crate::collab::ResolvedSpan],
doc_gen: u64,
) {
let Some(path) = crate::collab::contained_path(root, file) else {
return;
};
// Every matching TEXT tab, not the first tab found by path: a
// diff/image/sheet tab carries the path too (close-by-path), and a
// first-found lookup let one shadow the real text tab out of its
// updates while the spans spliced into a buffer that is not a
// document.
let apply = |ed: &mut crate::widgets::editor::Editor| {
if ed.has_non_text_view() {
return;
}
if ed.collab_doc_gen == 0 {
return;
}
for s in spans {
let (sr, sc) = crate::collab::position(&ed.lines, s.at);
let (er, ec) = crate::collab::position(&ed.lines, s.at + s.deleted);
ed.apply_span_edits(&[crate::widgets::editor::TextSpanEdit {
start: (sr, sc),
end: (er, ec),
new_text: s.inserted.clone(),
}]);
}
// Echo suppression: apply_span_edits bumped edit_seq, which would
// re-arm the tick diff and rebroadcast what was just applied.
ed.collab_synced_seq = ed.edit_seq;
ed.collab_doc_gen = doc_gen;
};
// A symbol tab is a view over a byte range, so a remote edit moves it
// too (#369). Outside the closure because the tab belongs to the app
// rather than to one editor.
// Only when the tab is anchored to THIS file. The range is a byte
// offset into one buffer, so an edit to any other file would shift,
// resize or close it against offsets that mean nothing there — a
// collaborator typing in `other.rs` would move a tab pointed at
// `main.rs`, or announce that its symbol is gone.
if self
.symbol_tab
.as_ref()
.is_some_and(|(_, p, _)| p.as_path() == path)
{
for span in spans {
self.follow_symbol_tab_edit(span.at, span.deleted, span.inserted.len());
}
}
for ed in self.editor.editors.iter_mut() {
if ed.path.as_deref() == Some(path.as_path()) {
apply(ed);
}
}
for group in self.editor_layout.inactive_groups_mut() {
for ed in group.editors.iter_mut() {
if ed.path.as_deref() == Some(path.as_path()) {
apply(ed);
}
}
}
}
/// A guest's bootstrap snapshot landed: swap every open buffer for the
/// file to the owner's canonical text (usually identical to what was
/// read from disk) and mark them synced, which also lifts the input
/// gate. A buffer that was already attached to an earlier session
/// incarnation and diverges from the snapshot holds work made while the
/// link was down — work that exists nowhere else, so replacing it would
/// silently delete it. Such a buffer keeps its text and is returned for
/// the caller to re-inject as local edits (panes converged every tick
/// before the link died, so any divergent pane carries the same text).
fn finish_collab_bootstrap(
&mut self,
root: &Path,
file: &str,
text: String,
doc_gen: u64,
) -> Option<String> {
let path = crate::collab::contained_path(root, file)?;
let lines: Vec<String> = text.split('\n').map(str::to_string).collect();
let mut kept = None;
let mut finish = |ed: &mut crate::widgets::editor::Editor| {
if ed.has_non_text_view() {
return;
}
if ed.collab_doc_gen != 0 && ed.lines != lines {
// Offline divergence: keep the buffer; gen 0 lets the
// attach pass re-mark it once the doc holds the merged
// text (the caller's local_change makes them equal).
if kept.is_none() {
kept = Some(ed.lines.join("\n"));
}
ed.collab_doc_gen = 0;
return;
}
if ed.lines != lines {
ed.replace_all_lines(lines.clone());
}
ed.collab_synced_seq = ed.edit_seq;
ed.collab_doc_gen = doc_gen;
};
// Every matching TEXT tab (see apply_collab_spans): first-found let
// a diff tab of the file swallow the snapshot while the text tab
// went unmarked.
for ed in self.editor.editors.iter_mut() {
if ed.path.as_deref() == Some(path.as_path()) {
finish(ed);
}
}
for group in self.editor_layout.inactive_groups_mut() {
for ed in group.editors.iter_mut() {
if ed.path.as_deref() == Some(path.as_path()) {
finish(ed);
}
}
}
self.status = format!("{file} is now live-shared");
kept
}
/// True when this croft is a solo-viewport guest: the session owner is
/// the one writer of shared files to disk, so every save/reload/replace
/// path for workspace files is gated here. Config-based (not
/// connection-based) so the gates hold while the relay is still coming
/// up.
fn is_collab_guest(&self) -> bool {
matches!(
self.collab_config,
Some((_, crate::collab::CollabRole::Guest))
)
}
/// Act on the row chosen in the list picker.
fn confirm_list_picker(&mut self) {
use crate::widgets::list_picker::ListPurpose;
let Some(picker) = self.list_picker.as_ref() else {
return;
};
let Some(row) = picker.selected_row().cloned() else {
return;
};
let purpose = picker.purpose;
self.close_list_picker();
let index = row.id.parse::<usize>().unwrap_or(0);
match purpose {
ListPurpose::StashApply => {
let r = crate::git::stash_apply(&self.scm_root(), index);
self.run_scm_op("stash apply", r, "Applied stash");
}
ListPurpose::StashPop => {
let r = crate::git::stash_pop_at(&self.scm_root(), index);
self.run_scm_op("stash pop", r, "Popped stash");
}
ListPurpose::StashDrop => {
let r = crate::git::stash_drop(&self.scm_root(), index);
self.run_scm_op("stash drop", r, "Dropped stash");
}
ListPurpose::RemoveRemote => {
let r = crate::git::remove_remote(&self.scm_root(), &row.id);
self.run_scm_op("remote remove", r, "Removed remote");
}
ListPurpose::DeleteTag => {
let r = crate::git::delete_tag(&self.scm_root(), &row.id);
self.run_scm_op("tag -d", r, "Deleted tag");
}
ListPurpose::PushToRemote => {
let r = crate::git::push_to_remote(&self.scm_root(), &row.id);
self.run_scm_op("push", r, "Pushed");
}
ListPurpose::MergeConflict => {
let res = match row.id.as_str() {
"current" => crate::merge::Resolution::Current,
"both" => crate::merge::Resolution::Both,
_ => crate::merge::Resolution::Incoming,
};
self.resolve_merge_at_cursor(res);
}
ListPurpose::CodeAction => {
// The navigator row's id is not numeric, and the shared
// `index` above parses non-numbers to 0 — routing through
// it would silently apply the server's FIRST action
// instead. Branch on the id itself (#374 review).
if row.id == "navigator" {
if let Some((path, item)) = self.navigator_fix_candidate() {
// The server's titles ride along as hints.
let hints = self
.pending_code_actions
.iter()
.map(|a| a.title.clone())
.collect();
self.fix_problem_with_navigator(path, item, hints);
}
} else if let Some(item) = self.pending_code_actions.get(index).cloned() {
self.apply_code_action(item);
}
self.pending_code_actions.clear();
}
ListPurpose::ColorPresentation => {
// The edits were computed against a specific buffer state;
// an external reload while the picker was open orphans
// them (#277 review) — refuse rather than splice at
// stale offsets.
let context_ok = self.pending_color_context.take().is_some_and(|(p, seq)| {
self.editor.path.as_deref() == Some(p.as_path()) && self.editor.edit_seq == seq
});
if context_ok {
if let Some((label, edits)) =
self.pending_color_presentations.get(index).cloned()
{
let applied = self.editor.apply_span_edits(&edits);
self.status = if applied > 0 {
format!("Color rewritten as {label}")
} else {
String::from("The presentation's edit no longer applies")
};
}
} else {
self.status =
String::from("The buffer changed — re-run Change Color Presentation");
}
self.pending_color_presentations.clear();
}
ListPurpose::RunTask => {
if let Some(task) = self.run_tasks.get(index).cloned() {
self.run_project_task(task);
}
}
ListPurpose::DebugConfig => {
if let Some(idx) = row.id.strip_prefix("compound:") {
// Index the row straight through rather than round-tripping
// via the name. `discover_compounds` dedupes by name, so a
// lookup would find the same element today — but it asks a
// weaker question than the one the row already answers, and
// it made the not-found arm unreachable-but-present.
let found = idx
.parse::<usize>()
.ok()
.and_then(|i| self.debug_compounds.get(i));
if let Some(compound) = found {
// Resolve first: a compound naming a configuration no
// launch.json declares is a config error worth
// reporting now, separately from the unbuilt feature.
// The un-deduped list: `debug_configs` is the picker's
// display list and drops a lower-precedence duplicate by
// name, which is the very entry a `.vscode` compound
// naming that name has to bind.
let all = crate::dap::configs::discover_configs_all(
&self.active_workspace_root(),
);
// #310 defers compounds that need SEVERAL sessions at
// once. A compound naming ONE configuration needs one,
// which croft has run since #250 — so the arity has to
// be READ here rather than assumed. Reporting the
// multi-session limit for a one-member compound cites
// a limitation that does not apply and tells the user
// something false about their own launch.json.
match crate::dap::configs::resolve_compound(compound, &all) {
Err(e) => self.debug_error(e),
// A one-member compound carrying keys croft does
// not honour is REFUSED rather than launched.
// Since #318 completed, only VALUES croft cannot
// READ remain: a `presentation` that is not an
// object, or a `hidden`/`group`/`order` that is
// not a bool/string/number. Every key that says
// something croft can act on is honoured -
// `preLaunchTask` by the branch below, `hidden`,
// `group` and `order` by the picker's sort.
// Launching while ignoring what the compound asked
// for is the "silently debug something other than
// what was asked for" outcome every guard here
// exists to prevent.
Ok(members)
if members.len() == 1
&& !compound.unsupported_keys.is_empty() =>
{
// #318, NOT #310: this compound needs ONE
// session, which croft runs. What it cannot do
// is honour the key. Citing the multi-session
// limit here would be the same false claim the
// launching branch below exists to stop making.
//
// The remedy names both ways out: fix the
// value, or run the member directly. Running
// it directly DOES skip the compound's own
// preLaunchTask, which the message leaves
// unsaid on purpose - a test pins that the
// status never mentions preLaunchTask, since
// naming it here would read as advice to
// accept the skip.
// Up to three keys can be listed now, so
// "a and b and c" would read as one run-on;
// the last pair keeps the "and".
let keys = match compound.unsupported_keys.split_last() {
Some((last, [])) => (*last).to_string(),
Some((last, rest)) => {
format!("{} and {last}", rest.join(", "))
}
None => String::new(),
};
let plural = if compound.unsupported_keys.len() > 1 {
"those keys"
} else {
"that key"
};
self.debug_error(format!(
"compound \"{}\" sets {}, which croft cannot read — fix {} to launch \"{}\" through the compound, or run \"{}\" directly",
compound.name,
keys,
plural,
members[0].name,
members[0].name
));
}
Ok(members) if members.len() == 1 => {
let cfg = members[0].clone();
self.selected_debug_config = Some(cfg.name.clone());
self.run_debug.selected_config = Some(cfg.name.clone());
match compound.pre_launch_task.clone() {
// #318: the compound's own task runs
// first, and the member starts only if it
// exits 0 - the same contract a config's
// own task already gets. Chained rather
// than merged: the member may declare a
// task too, and VS Code runs both.
Some(task) => self.launch_after_compound_task(&task, cfg),
None => self.launch_debug_config(&cfg),
}
}
Ok(_) => self.debug_error(format!(
"compound \"{}\" needs several debug sessions at once, which croft does not support yet (#310)",
compound.name
)),
}
}
} else if row.id == "active" {
self.selected_debug_config = None;
self.run_debug.selected_config = None;
self.start_selected_debug();
} else if let Some(cfg) = row
.id
.parse::<usize>()
.ok()
.and_then(|i| self.debug_configs.get(i))
.cloned()
{
self.selected_debug_config = Some(cfg.name.clone());
self.run_debug.selected_config = Some(cfg.name.clone());
self.launch_debug_config(&cfg);
}
}
ListPurpose::SessionParticipant => {
if let Ok(id) = row.id.parse::<u64>() {
self.open_participant_actions(id);
}
}
ListPurpose::SessionParticipantAction => {
if let Some((verb, id)) = parse_participant_action(&row.id) {
self.run_participant_action(verb, id);
}
}
ListPurpose::Settings => {
match row.id.as_str() {
"toggle:format_on_save" => self.toggle_format_on_save(),
"toggle:auto_close_pairs" => self.toggle_auto_close_pairs(),
"toggle:auto_save" => self.toggle_auto_save(),
"toggle:auto_save_on_focus_change" => self.toggle_auto_save_on_focus_change(),
"toggle:inline_blame" => self.toggle_inline_blame(),
"toggle:indent_guides" => self.toggle_indent_guides(),
"toggle:bracket_colors" => self.toggle_bracket_colors(),
"toggle:render_whitespace" => self.toggle_render_whitespace(),
"toggle:inline_values" => self.toggle_inline_values(),
"toggle:inlay_hints" => self.toggle_inlay_hints(),
"toggle:copy_on_select" => self.toggle_copy_on_select(),
"toggle:log_highlight" => self.toggle_log_highlight(),
"toggle:secret_redaction" => self.toggle_secret_redaction(),
"toggle:format_on_type" => self.toggle_format_on_type(),
"cmd:color_theme" => {
self.open_theme_picker();
return;
}
"cmd:open_settings_json" => {
self.open_config_file_in_editor(
crate::prefs::config_path(),
ConfigFileSeed::Settings,
);
return;
}
"cmd:open_user_settings_local_json" => {
self.open_config_file_in_editor(
crate::config_layers::user_local_config_path(),
ConfigFileSeed::SettingsLayer,
);
return;
}
"cmd:open_workspace_settings_json" => {
self.open_workspace_settings(false);
return;
}
"cmd:open_workspace_settings_local_json" => {
self.open_workspace_settings(true);
return;
}
"cmd:open_keybindings_json" => {
self.open_config_file_in_editor(
crate::keymap::keybindings_path(),
ConfigFileSeed::Keybindings,
);
return;
}
"cmd:configure_snippets" => {
self.open_config_file_in_editor(
crate::snippets::snippets_path(),
ConfigFileSeed::Snippets,
);
return;
}
_ => return,
}
// A toggle stays in the hub: reopen so the new value shows and
// the user can flip more without reinvoking the palette.
self.open_settings_view();
}
}
}
/// Preferences: Open Settings — a searchable hub over the toggleable
/// settings plus shortcuts to the raw JSON files and the theme picker. Each
/// toggle row shows its current value; confirming a toggle flips it live and
/// reopens the hub so the change is visible and more can be flipped.
pub fn open_settings_view(&mut self) {
use crate::widgets::list_picker::{ListPicker, ListPurpose, ListRow};
let on_off = |b: bool| if b { "on" } else { "off" };
// Per-value provenance (#251): where a non-user layer set the backing
// key, say so — the usual "I toggled it and nothing changed" is a
// workspace layer winning the merge.
let prov = |key: &str| {
use crate::config_layers::LayerKind;
match crate::config_layers::layer_of(&self.settings_provenance, key) {
LayerKind::Default | LayerKind::User => String::new(),
other => format!(" · {}", other.label()),
}
};
let rows = vec![
ListRow {
id: String::from("toggle:auto_close_pairs"),
label: format!(
"Auto Closing Pairs: {}{}",
on_off(self.auto_close_pairs),
prov("disable_auto_close_pairs")
),
},
ListRow {
id: String::from("toggle:format_on_save"),
label: format!(
"Format on Save: {}{}",
on_off(self.format_on_save),
prov("format_on_save")
),
},
ListRow {
id: String::from("toggle:auto_save"),
label: format!("Auto Save: {}{}", on_off(self.auto_save), prov("auto_save")),
},
ListRow {
id: String::from("toggle:auto_save_on_focus_change"),
label: format!(
"Auto Save on Focus Change: {}{}",
on_off(self.auto_save_on_focus_change),
prov("auto_save_on_focus_change")
),
},
ListRow {
id: String::from("toggle:inline_blame"),
label: format!(
"Git: Inline Blame: {}{}",
on_off(self.inline_blame_enabled),
prov("disable_inline_blame")
),
},
ListRow {
id: String::from("toggle:indent_guides"),
label: format!(
"Editor: Indent Guides: {}{}",
on_off(self.indent_guides_enabled),
prov("disable_indent_guides")
),
},
ListRow {
id: String::from("toggle:bracket_colors"),
label: format!(
"Editor: Bracket Pair Colorization: {}{}",
on_off(self.bracket_colors_enabled),
prov("disable_bracket_colors")
),
},
ListRow {
id: String::from("toggle:render_whitespace"),
label: format!(
"Editor: Render Whitespace: {}{}",
self.whitespace_mode.label(),
prov("render_whitespace")
),
},
ListRow {
id: String::from("toggle:inline_values"),
label: format!(
"Debugger: Inline Values: {}{}",
on_off(self.inline_values_enabled),
prov("disable_inline_values")
),
},
ListRow {
id: String::from("toggle:inlay_hints"),
label: format!(
"Editor: Inlay Hints: {}{}",
on_off(self.inlay_hints_enabled),
prov("disable_inlay_hints")
),
},
ListRow {
id: String::from("toggle:format_on_type"),
label: format!(
"Editor: Format on Type: {}{}",
on_off(self.format_on_type),
prov("format_on_type")
),
},
ListRow {
id: String::from("toggle:copy_on_select"),
label: format!(
"Terminal: Copy on Selection: {}{}",
on_off(self.copy_on_select),
prov("copy_on_select")
),
},
ListRow {
id: String::from("toggle:log_highlight"),
label: format!(
"Log: Highlighting (tailspin): {}{}",
on_off(self.log_highlight),
prov("disable_log_highlight")
),
},
ListRow {
id: String::from("toggle:secret_redaction"),
label: format!(
"Terminal: Redact Secrets (keys, tokens): {}{}",
on_off(self.secret_redaction),
prov("disable_secret_redaction")
),
},
ListRow {
id: String::from("cmd:color_theme"),
label: format!("Color Theme: {}{}", self.theme.label(), prov("theme")),
},
ListRow {
id: String::from("cmd:open_settings_json"),
label: String::from("Open User Settings (JSON)"),
},
ListRow {
id: String::from("cmd:open_user_settings_local_json"),
label: String::from("Open User Settings — Local (JSON, this machine only)"),
},
ListRow {
id: String::from("cmd:open_workspace_settings_json"),
label: String::from("Open Workspace Settings (JSON)"),
},
ListRow {
id: String::from("cmd:open_workspace_settings_local_json"),
label: String::from("Open Workspace Settings — Local (JSON, gitignored)"),
},
ListRow {
id: String::from("cmd:open_keybindings_json"),
label: String::from("Open Keyboard Shortcuts (JSON)"),
},
ListRow {
id: String::from("cmd:configure_snippets"),
label: String::from("Configure User Snippets"),
},
];
self.open_list_picker(
ListPicker::new(ListPurpose::Settings, "Settings", rows),
"No settings",
);
}
/// Preferences: Open Workspace Settings (#251) — the committed
/// `.croft/config.json`, or with `local` the gitignored
/// `.croft/config.local.json`. Creating either ensures
/// `.croft/.gitignore` covers the local file first, so a personal
/// override can never land in a commit by accident.
pub fn open_workspace_settings(&mut self, local: bool) {
let root = self.roots.primary().to_path_buf();
if let Err(e) = crate::config_layers::ensure_workspace_local_ignored(&root) {
self.status = format!("Could not prepare .croft/: {e}");
return;
}
let path = if local {
crate::config_layers::workspace_local_config_path(&root)
} else {
crate::config_layers::workspace_config_path(&root)
};
self.open_config_file_in_editor(path, ConfigFileSeed::SettingsLayer);
}
/// Tasks: Run Task — discover the workspace's tasks and open the
/// picker over them.
pub fn open_run_task_picker(&mut self) {
self.run_tasks = crate::tasks::discover_tasks(&self.active_workspace_root());
let rows: Vec<crate::widgets::list_picker::ListRow> = self
.run_tasks
.iter()
.enumerate()
.map(|(i, t)| crate::widgets::list_picker::ListRow {
id: i.to_string(),
label: format!("{} — {}", t.label, t.source),
})
.collect();
self.open_list_picker(
crate::widgets::list_picker::ListPicker::new(
crate::widgets::list_picker::ListPurpose::RunTask,
"Run Task",
rows,
),
"No tasks found (Makefile, justfile, package.json, Cargo.toml, pyproject.toml, .vscode/tasks.json)",
);
}
/// Run `task` in its own named terminal pane. Rerunning a task whose
/// pane sits idle at a prompt writes the command into that pane
/// instead of stacking a new one; a busy pane gets a fresh sibling.
/// Run a task in its named pane. Returns the pane's uid so a caller can
/// correlate the task's FinishedCommand (the preLaunchTask gate, #250);
/// `None` when no pane could be started (already reported in `status`).
pub fn run_project_task(&mut self, task: crate::tasks::Task) -> Option<u64> {
let pane_name = format!("Task: {}", task.label);
// The task's problemMatcher (#252), translated up front so both the
// reuse and fresh-pane paths assign the same thing (or clear a
// previous task's leftover).
let matcher = task
.problem_matcher
.as_ref()
.and_then(crate::problem_matchers::from_tasks_json)
.map(std::sync::Arc::new);
// Ctrl-E + Ctrl-U first: the idle shell's line editor may hold a
// half-typed command that would otherwise concatenate and run
// (same rule `format_cd_command` pins for the cd seed).
let command = format!("\x05\x15{}\r", task.command);
self.last_task = Some(task.clone());
// Reuse only a pane whose shell is standing exactly where this
// task will run: after a re-root the old pane's label still
// matches, and running the new project's build there builds the
// old one. Shares `pane_is_idle_at` with the runnable-fence path
// (#430) — this guard existed twice and only one copy was fixed,
// which is precisely how the two defects survived a green suite.
let active = self.active_workspace_root();
let root = active.canonicalize().unwrap_or(active);
if let Some(idx) = self
.terminals
.iter()
.position(|t| pane_is_idle_at(t, &pane_name, &root))
{
// Reused panes may be folded (#313): the release notes name the
// build pane as the thing you would fold, and a task written into
// a pane that is never rendered runs invisibly under a status line
// saying it started.
self.reveal_terminal_pane(idx);
self.terminals[idx].write_input(command.as_bytes());
self.show_terminal = true;
self.focus_pane(Pane::Terminal);
self.status = format!("Running {}", task.label);
let uid = self.terminals[idx].uid();
self.assign_task_matcher(uid, matcher);
return Some(uid);
}
match crate::widgets::terminal::PtyTerminal::new(&self.active_workspace_root()) {
Ok(mut term) => {
term.set_manual_name(Some(pane_name));
term.write_input(command.as_bytes());
let uid = term.uid();
self.insert_terminal(term);
self.assign_task_matcher(uid, matcher);
self.status = format!("Running {}", task.label);
Some(uid)
}
Err(e) => {
self.status = format!("Could not start task pane: {e}");
None
}
}
}
/// Record (or clear) the problemMatcher owning a task pane (#252): the
/// map drives the batch scan at the FinishedCommand boundary, the
/// pane's watch slot drives the mid-run engine when the matcher is a
/// background one. Rerunning a matcher-less task in a pane clears the
/// previous task's leftover, and either way the pane starts the new
/// run without a stale watch-published flag.
fn assign_task_matcher(
&mut self,
pane: u64,
matcher: Option<std::sync::Arc<crate::problem_matchers::CompiledMatcher>>,
) {
self.watch_published_panes.remove(&pane);
match &matcher {
Some(m) => {
self.task_matcher_by_pane.insert(pane, m.clone());
}
None => {
self.task_matcher_by_pane.remove(&pane);
}
}
if let Some(t) = self.terminals.iter().find(|t| t.uid() == pane) {
t.set_pane_watch(matcher.filter(|m| m.background.is_some()));
}
}
/// Tasks: Run Build Task (`Cmd+Shift+B`) — run the conventional build
/// for whatever the workspace is; fall back to the picker when no
/// manifest declares one.
pub fn run_build_task(&mut self) {
let tasks = crate::tasks::discover_tasks(&self.active_workspace_root());
match crate::tasks::default_build_task(&tasks).cloned() {
Some(task) => {
self.run_project_task(task);
}
None => {
self.open_run_task_picker();
self.status = "No build task detected; pick one".to_string();
}
}
}
/// Tasks: Rerun Last Task.
pub fn rerun_last_task(&mut self) {
match self.last_task.clone() {
Some(task) => {
self.run_project_task(task);
}
None => self.status = "No task has run yet".to_string(),
}
}
/// Resolve the branch-picker selection per its open purpose.
fn apply_branch_picker_selection(&mut self) {
let Some(picker) = self.branch_picker.as_ref() else {
return;
};
match self.branch_purpose {
BranchPurpose::Checkout => {
if let Some(action) = picker.selected_action() {
self.apply_branch_action(action);
} else {
self.close_branch_picker();
}
}
BranchPurpose::CreateFrom => {
let Some(base) = picker.selected_existing_branch() else {
return;
};
self.close_branch_picker();
self.open_input_prompt(crate::widgets::input_prompt::InputPrompt::new(
crate::widgets::input_prompt::InputPurpose::CreateBranchFrom { base },
"Create Branch from",
"New branch name",
));
}
BranchPurpose::Delete => {
let Some(name) = picker.selected_existing_branch() else {
return;
};
self.close_branch_picker();
let r = crate::git::delete_branch(&self.scm_root(), &name);
self.run_scm_op("branch -d", r, "Deleted branch");
}
BranchPurpose::Merge => {
let Some(name) = picker.selected_existing_branch() else {
return;
};
self.close_branch_picker();
let r = crate::git::merge_branch(&self.scm_root(), &name);
self.run_scm_op("merge", r, "Merged");
}
BranchPurpose::Rebase => {
let Some(name) = picker.selected_existing_branch() else {
return;
};
self.close_branch_picker();
let r = crate::git::rebase_branch(&self.scm_root(), &name);
self.run_scm_op("rebase", r, "Rebased");
}
}
}
/// Open the staged-changes diff (`git diff --staged`) in a read-only
/// editor tab. Mirrors VS Code's "View Staged Changes" — users hit
/// the dropdown, click View Staged Changes, and the editor tab pops up
/// with every `+`/`-` line of the staged hunks highlighted.
pub fn view_staged_diff_source_control(&mut self) {
let raw = match crate::git::diff_staged(&self.scm_root()) {
Ok(r) => r,
Err(err) => {
self.source_control.commit_feedback = Some(format!("diff failed: {err}"));
self.source_control.commit_feedback_is_error = true;
self.status = format!("View Staged Changes failed: {err}");
return;
}
};
let label = std::path::PathBuf::from("git diff --staged");
if let Err(err) = self.editor.open_git_diff_side_by_side(&label, &raw) {
self.source_control.commit_feedback = Some(format!("open failed: {err}"));
self.source_control.commit_feedback_is_error = true;
self.status = format!("Could not open staged diff: {err}");
return;
}
self.tag_open_diff(crate::widgets::diff::DiffSource::GitCommand {
root: self.scm_root(),
kind: crate::widgets::diff::GitDiffKind::Staged,
});
self.source_control.commit_feedback = None;
self.status = String::from("Showing git diff --staged");
self.focus_pane(Pane::Editor);
}
/// Open `git diff <default-branch>` in a read-only editor tab. The
/// default branch is resolved via `git::default_branch` (origin/HEAD
/// first, then common local names). If resolution fails the error
/// surfaces in the commit-feedback line so the user can fix the
/// upstream-HEAD config instead of getting a silent no-op.
pub fn view_default_branch_diff_source_control(&mut self) {
let branch = match crate::git::default_branch(&self.scm_root()) {
Ok(b) => b,
Err(err) => {
self.source_control.commit_feedback = Some(err.clone());
self.source_control.commit_feedback_is_error = true;
self.status = format!("Default branch: {err}");
return;
}
};
let raw = match crate::git::diff_against_branch(&self.scm_root(), &branch) {
Ok(r) => r,
Err(err) => {
self.source_control.commit_feedback = Some(format!("diff failed: {err}"));
self.source_control.commit_feedback_is_error = true;
self.status = format!("View Changes vs {branch} failed: {err}");
return;
}
};
let label = std::path::PathBuf::from(format!("git diff {branch}"));
if let Err(err) = self.editor.open_git_diff_side_by_side(&label, &raw) {
self.source_control.commit_feedback = Some(format!("open failed: {err}"));
self.source_control.commit_feedback_is_error = true;
self.status = format!("Could not open diff vs {branch}: {err}");
return;
}
self.tag_open_diff(crate::widgets::diff::DiffSource::GitCommand {
root: self.scm_root(),
kind: crate::widgets::diff::GitDiffKind::AgainstBranch(branch.clone()),
});
self.default_branch_label = Some(branch.clone());
self.source_control.commit_feedback = None;
self.status = format!("Showing git diff {branch}");
self.focus_pane(Pane::Editor);
}
/// Open `git diff HEAD~1` (working tree versus the commit before HEAD)
/// in a read-only editor tab. Mirrors "View Changes vs <default>" but
/// anchored on the previous commit, so the user can review everything
/// that changed since the last commit. A single-commit repo has no
/// `HEAD~1`; that error surfaces in the commit-feedback line rather
/// than as a silent no-op.
pub fn view_previous_commit_diff_source_control(&mut self) {
let raw = match crate::git::diff_previous_commit(&self.scm_root()) {
Ok(r) => r,
Err(err) => {
self.source_control.commit_feedback = Some(format!("diff failed: {err}"));
self.source_control.commit_feedback_is_error = true;
self.status = format!("View Changes vs previous failed: {err}");
return;
}
};
let label = std::path::PathBuf::from("git diff HEAD~1");
if let Err(err) = self.editor.open_git_diff_side_by_side(&label, &raw) {
self.source_control.commit_feedback = Some(format!("open failed: {err}"));
self.source_control.commit_feedback_is_error = true;
self.status = format!("Could not open diff vs previous: {err}");
return;
}
self.tag_open_diff(crate::widgets::diff::DiffSource::GitCommand {
root: self.scm_root(),
kind: crate::widgets::diff::GitDiffKind::PreviousCommit,
});
self.source_control.commit_feedback = None;
self.status = String::from("Showing git diff HEAD~1");
self.focus_pane(Pane::Editor);
}
pub fn commit_and_push_source_control(&mut self) {
let message = self.source_control.message.trim().to_string();
if message.is_empty() {
self.source_control.commit_feedback = Some(String::from("Empty commit message"));
self.source_control.commit_feedback_is_error = true;
return;
}
let commit_summary = match crate::git::commit_all_tracked(&self.scm_root(), &message) {
Ok(s) => s,
Err(err) => {
self.source_control.commit_feedback = Some(err.clone());
self.source_control.commit_feedback_is_error = true;
self.status = format!("Commit failed: {err}");
return;
}
};
self.source_control.clear_message();
self.status = format!("Committed: {commit_summary}");
match crate::git::push_current_branch(&self.scm_root()) {
Ok(push_summary) => {
let combined = if push_summary.is_empty() {
commit_summary
} else {
format!("{commit_summary} | pushed: {push_summary}")
};
self.source_control.commit_feedback = Some(combined.clone());
self.source_control.commit_feedback_is_error = false;
self.status = format!("Committed & pushed: {combined}");
}
Err(err) => {
self.source_control.commit_feedback =
Some(format!("commit ok; push failed: {err}"));
self.source_control.commit_feedback_is_error = true;
self.status = format!("Commit ok; push failed: {err}");
}
}
self.active_git_bypass_debounce();
self.refresh_git_status_debounced();
self.refresh_source_control();
}
pub fn stage_source_control_entry(&mut self, entry_idx: usize) {
let Some(entry) = self.source_control.entries.get(entry_idx).cloned() else {
return;
};
match crate::git::stage_path(&self.scm_root(), &entry.path) {
Ok(()) => {
self.status = format!("Staged {}", entry.path);
self.active_git_bypass_debounce();
self.refresh_git_status_debounced();
self.refresh_source_control();
}
Err(err) => {
self.status = format!("Stage failed: {err}");
self.source_control.commit_feedback = Some(err);
self.source_control.commit_feedback_is_error = true;
}
}
}
/// The workspace-relative path + single-hunk patch for the hunk under
/// the diff caret. Sets a status message and returns `None` when the
/// active tab isn't a working-tree diff or no hunk is at the cursor.
fn diff_hunk_patch_at_caret(&mut self) -> Option<(String, String)> {
let root = self.tree.root.clone();
let built = match self.editor.diff.as_ref() {
None => Err("Hunk actions work inside a Source Control diff"),
Some(diff) if !diff.left_is_git_head => {
Err("Hunk actions need a working-tree diff from Source Control")
}
Some(diff) => match diff.right_path.strip_prefix(&root) {
Err(_) => Err("File is outside the workspace"),
Ok(rel) => {
let rel = rel.to_string_lossy().to_string();
match diff.hunk_range_at(diff.action_row()) {
None => Err("No change hunk at the cursor"),
Some(range) => {
let patch = diff.hunk_patch(&rel, range);
Ok((rel, patch))
}
}
}
},
};
match built {
Ok(pair) => Some(pair),
Err(msg) => {
self.status = msg.to_string();
None
}
}
}
/// The workspace-relative path + patch for the SELECTED lines of the
/// open working-tree diff (VS Code's "Stage Selected Ranges"), or
/// `None` when there is no selection spanning a changed row, so the
/// caller falls back to the whole-hunk action.
fn diff_selected_lines_patch(&self) -> Option<(String, String)> {
let root = self.tree.root.clone();
let diff = self.editor.diff.as_ref()?;
if !diff.left_is_git_head {
return None;
}
let sel = diff.selection?;
if !sel.has_area() {
return None;
}
let rel = diff.right_path.strip_prefix(&root).ok()?;
let rel = rel.to_string_lossy().to_string();
let (start, end) = sel.normalized();
let patch = diff.selected_lines_patch(&rel, (start.0, end.0))?;
Some((rel, patch))
}
/// Cycle the open diff's ignore-whitespace mode (off → leading → all).
/// Per-view only: the `diff_ignore_whitespace` pref supplies the starting
/// mode for each new diff and is not rewritten here, so an experiment in
/// one view never changes what the next file opens with.
pub fn diff_cycle_whitespace_mode(&mut self) {
let Some(diff) = self.editor.diff.as_mut() else {
self.status = String::from("Ignore whitespace applies to a diff view");
return;
};
let mode = diff.ws_mode.next();
diff.set_whitespace_mode(mode);
self.status = format!("Diff: ignore whitespace {}", mode.label());
}
/// Turn the group-by-seat lens on or off for the diff in view (#349),
/// so a change can be read as "the agent's part" and "my part".
///
/// Offered only on the Source Control HEAD-vs-working view, the one diff
/// whose right side IS the working tree: there the row's `right` index
/// is a real file line and the seat map is keyed on the same index. A
/// diff parsed out of raw `git diff` text numbers its rows by position
/// in that text, so the same join would paint confident wrong seats.
pub fn diff_toggle_group_by_seat(&mut self) {
let history_root = self.history_root.clone();
let Some(diff) = self.editor.diff.as_mut() else {
self.status = String::from("Group by seat applies to a diff view");
return;
};
if !diff.left_is_git_head {
self.status =
String::from("Group by seat applies to a Source Control diff of the working tree");
return;
}
diff.group_by_seat = !diff.group_by_seat;
if !diff.group_by_seat {
self.status = String::from("Diff: group by seat off");
return;
}
// Read the map fresh each time the lens comes on: the working file
// may have been saved since the view was built, and a map from
// before that describes text this diff no longer shows.
diff.seats = crate::provenance::Provenance::new();
let path = diff.right_path.clone();
let right_lines = diff.right_lines.clone();
let seats = Self::seats_for_working_file(&history_root, &path, &right_lines);
let Some(diff) = self.editor.diff.as_mut() else {
return;
};
if let Some(seats) = seats {
diff.seats = seats;
}
self.status = format!("Diff: group by seat \u{2022} {}", diff.seat_summary());
}
/// Reload the group-by-seat map of a rebuilt view against its new rows
/// (#349). `carry_view_from` keeps the lens ON but deliberately drops
/// its map, which named line indices the rebuilt rows have renumbered;
/// this puts back a map that describes the rows now on screen, or none.
/// A no-op for a view whose lens is off.
fn reload_seats_for(history_root: &Path, diff: &mut crate::widgets::diff::DiffData) {
// The same gate the toggle applies, restated rather than assumed:
// the map is keyed on working-file line indices, so it may only be
// joined onto a view whose right side IS the working tree.
if !diff.group_by_seat || !diff.left_is_git_head {
return;
}
let right_lines = diff.right_lines.clone();
diff.seats = Self::seats_for_working_file(history_root, &diff.right_path, &right_lines)
.unwrap_or_default();
}
/// The persisted provenance map for a working-tree file, for the rows a
/// diff view is actually showing (#349). Both halves of the rule
/// `sync_provenance_for` applies: the newest snapshot must still hold the
/// bytes on disk, AND those bytes must be the lines this view shows.
///
/// The second half is not redundant. A diff's `right_lines` were read
/// when the view was built, and a same-length rewrite inside one
/// filesystem timestamp tick moves the file without moving the
/// `(mtime, len)` stamp that triggers a rebuild - so the view can be
/// showing older lines than the snapshot describes. Joining a newer map
/// onto them would credit lines it never saw, which is the one outcome
/// the module forbids. Either half failing reads as no map at all.
fn seats_for_working_file(
history_root: &Path,
path: &Path,
right_lines: &[String],
) -> Option<crate::provenance::Provenance> {
let newest = crate::history::entries_in(history_root, path)
.into_iter()
.next()?;
let mut seats = crate::history::seats_for(history_root, path, newest.millis)?;
let (on_disk, snapshot) = (std::fs::read(path).ok()?, std::fs::read(&newest.file).ok()?);
if on_disk != snapshot {
return None;
}
// Split the way the DIFF OPENER splits (`str::lines`), NOT the way
// `Editor::open` does: a lone `\r` is one line to the opener and two
// to the editor's splitter, and the comparison has to be against the
// lines this view was actually built from. The bare UTF-8 decode
// matches the opener too, which reads the right side with
// `read_to_string` and so never builds a view for a file this
// cannot decode.
let text = String::from_utf8(snapshot).ok()?;
if !text.lines().eq(right_lines.iter().map(String::as_str)) {
return None;
}
// Defensive: the comparison above already forces equal lengths, so
// this drops nothing today. It keeps the map bounded by the rows if
// that gate is ever loosened.
seats.truncate(right_lines.len());
Some(seats)
}
/// Stage only the hunk under the diff caret (`git apply --cached`).
pub fn stage_hunk_at_caret(&mut self) {
// A selection spanning changed rows narrows the action to those
// lines (VS Code's "Stage Selected Ranges"); without one the whole
// hunk under the caret is staged, as before.
if let Some((rel, patch)) = self.diff_selected_lines_patch() {
match crate::git::apply_patch(&self.scm_root(), &patch, true, false) {
Ok(_) => {
self.status = format!("Staged selected lines in {rel}");
self.refresh_after_hunk_op();
}
Err(err) => self.status = format!("Stage selected lines failed: {err}"),
}
return;
}
let Some((rel, patch)) = self.diff_hunk_patch_at_caret() else {
return;
};
match crate::git::apply_patch(&self.scm_root(), &patch, true, false) {
Ok(_) => {
self.status = format!("Staged hunk in {rel}");
self.refresh_after_hunk_op();
}
Err(err) => self.status = format!("Stage hunk failed: {err}"),
}
}
/// Remove only the hunk under the diff caret from the index
/// (`git apply --cached -R`). Errors surface verbatim, e.g. when the
/// hunk was never staged.
pub fn unstage_hunk_at_caret(&mut self) {
// Same selection-first rule as staging: the reverse patch removes
// exactly the selected lines from the index.
if let Some((rel, patch)) = self.diff_selected_lines_patch() {
match crate::git::apply_patch(&self.scm_root(), &patch, true, true) {
Ok(_) => {
self.status = format!("Unstaged selected lines in {rel}");
self.refresh_after_hunk_op();
}
Err(err) => self.status = format!("Unstage selected lines failed: {err}"),
}
return;
}
let Some((rel, patch)) = self.diff_hunk_patch_at_caret() else {
return;
};
match crate::git::apply_patch(&self.scm_root(), &patch, true, true) {
Ok(_) => {
self.status = format!("Unstaged hunk in {rel}");
self.refresh_after_hunk_op();
}
Err(err) => self.status = format!("Unstage hunk failed: {err}"),
}
}
/// Arm the revert-hunk confirm popup for the hunk under the caret.
pub fn request_revert_hunk_at_caret(&mut self) {
if let Some((rel_path, patch)) = self.diff_hunk_patch_at_caret() {
self.pending_revert_hunk = Some(PendingRevertHunk { rel_path, patch });
}
}
pub fn confirm_pending_revert_hunk(&mut self) {
let Some(pr) = self.pending_revert_hunk.take() else {
return;
};
match crate::git::apply_patch(&self.scm_root(), &pr.patch, false, true) {
Ok(_) => {
self.status = format!("Reverted hunk in {}", pr.rel_path);
self.refresh_after_hunk_op();
// The revert rewrote the working file; force the HEAD-side rebuild
// of the open view so it refreshes even if the rewrite landed
// within the stamp's granularity. Forced by the root the VIEW is
// tagged with, not `scm_root()` re-read now: the tag may predate the
// worker's first status reply and hold the workspace root.
let force_root = self
.editor
.diff
.as_ref()
.and_then(|d| match &d.source {
crate::widgets::diff::DiffSource::HeadVsWorking { root, .. } => {
Some(root.clone())
}
_ => None,
})
.unwrap_or_else(|| self.scm_root());
self.refresh_open_diff_views(
true,
std::slice::from_ref(&force_root),
&std::collections::BTreeSet::new(),
);
}
Err(err) => self.status = format!("Revert hunk failed: {err}"),
}
}
pub fn cancel_pending_revert_hunk(&mut self) {
self.pending_revert_hunk = None;
}
fn refresh_after_hunk_op(&mut self) {
self.active_git_bypass_debounce();
self.refresh_git_status_debounced();
self.refresh_source_control();
}
/// Record on the diff view the opener just made active how it is to be
/// rebuilt when a side moves (#471), and take its first disk stamps.
fn tag_open_diff(&mut self, source: crate::widgets::diff::DiffSource) {
if let Some(diff) = self.editor.diff.as_mut() {
diff.source = source;
diff.stamp_sides();
}
}
/// Rebuild every open diff view, in every split group, whose sides may
/// have moved (#471), keeping each reader's viewport. Returns true when
/// any view's content actually changed, so the caller owes a redraw.
///
/// Two triggers, two costs. A filesystem event or poll (`git_too` false)
/// re-reads only file-backed sides, and only those whose stat stamp
/// moved, so an idle tick is a stat per open diff and nothing more. A
/// git-status drain (`git_too` true; the worker debounces it) also
/// re-runs the `git diff` behind a staged / branch / previous-commit
/// view, whose input is the index or a ref rather than a file, and
/// re-reads the HEAD blob behind a Source Control view for the roots in
/// `heads_moved` -- the drain already knows whose HEAD oid changed, and
/// a `git show` per open diff per status refresh would otherwise run
/// during every write burst for a HEAD that had not moved.
/// A view whose content came back identical is left untouched: no reset
/// of selection or find, no redraw.
pub fn refresh_open_diff_views(
&mut self,
git_too: bool,
heads_moved: &[PathBuf],
changed_files: &std::collections::BTreeSet<PathBuf>,
) -> bool {
// Bound before the borrow of `self.editor` below, for the seat map a
// carried group-by-seat lens needs against its rebuilt rows (#349).
let self_history_root = self.history_root.clone();
// The watcher's own list of written paths bypasses the stamp gate: a
// same-length rewrite that lands within the filesystem's mtime
// granularity (or restores the mtime) shows the same `(mtime, len)`
// as before, and the event is the only evidence it happened.
// Canonicalised once, so a path the watcher reports through a
// symlinked root (macOS's /tmp -> /private/tmp) still matches the
// path the view was opened with.
let touched: Vec<PathBuf> = changed_files
.iter()
.map(|p| std::fs::canonicalize(p).unwrap_or_else(|_| p.clone()))
.collect();
let mut changed = false;
// The active group's active tab, by address: a rebuild there is the
// one that owes the find bar a recompute. A diff refreshing in a
// background tab or split must not touch the view the reader is on.
let active_ptr: *const crate::widgets::editor::Editor = &*self.editor;
let mut active_changed = false;
for group in
std::iter::once(&mut self.editor).chain(self.editor_layout.inactive_groups_mut())
{
for ed in &mut group.editors {
let Some(old) = ed.diff.as_ref() else {
continue;
};
let Some(mut fresh) = rebuild_diff_view(old, git_too, heads_moved, &touched) else {
continue;
};
if fresh.same_content_as(old) {
// Same rows: keep the reader's selection and find
// state, but take the new stamps so the next tick does
// not re-read the file again for a no-op write.
if let Some(cur) = ed.diff.as_mut() {
cur.left_stamp = fresh.left_stamp;
cur.right_stamp = fresh.right_stamp;
}
continue;
}
fresh.carry_view_from(old);
// The carried lens needs a map for the REBUILT rows:
// `carry_view_from` deliberately drops the old one, which
// named lines these rows have renumbered (#349).
Self::reload_seats_for(&self_history_root, &mut fresh);
ed.diff = Some(fresh);
changed = true;
if std::ptr::eq(&*ed, active_ptr) {
active_changed = true;
}
}
}
// A rebuilt ACTIVE diff with a find bar open gets its match set and
// active match recomputed against the new rows, the same way a
// typed query would; `carry_view_from` deliberately dropped the old
// active match because it named rows that may be gone.
if active_changed
&& self.editor.diff.is_some()
&& self
.editor_find
.as_ref()
.is_some_and(|s| !s.query.is_empty())
{
let pos = self.diff_find_current_pos();
self.diff_find_apply(pos);
}
changed
}
pub fn request_discard_source_control_entry(&mut self, entry_idx: usize) {
use crate::git::ChangeKind;
let Some(entry) = self.source_control.entries.get(entry_idx).cloned() else {
return;
};
let untracked = matches!(entry.kind, ChangeKind::Untracked);
self.pending_discard = Some(PendingDiscard {
rel_path: entry.path,
untracked,
});
}
pub fn confirm_pending_discard(&mut self) {
let Some(pd) = self.pending_discard.take() else {
return;
};
match crate::git::discard_path(&self.scm_root(), &pd.rel_path, pd.untracked) {
Ok(()) => {
self.status = format!("Discarded {}", pd.rel_path);
self.active_git_bypass_debounce();
self.refresh_git_status_debounced();
self.refresh_source_control();
}
Err(err) => {
self.status = format!("Discard failed: {err}");
self.source_control.commit_feedback = Some(err);
self.source_control.commit_feedback_is_error = true;
}
}
}
pub fn cancel_pending_discard(&mut self) {
self.pending_discard = None;
}
/// Decide whether to show the unsupported-terminal nudge. Call AFTER
/// `init_graphics` has resolved `inline_protocol` (including the sixel
/// promotion), so a sixel host is correctly treated as supported. No-op
/// when the user has already silenced the nudge in their prefs.
fn arm_terminal_warning(&mut self) {
if crate::prefs::Prefs::load_or_default().suppress_terminal_warning {
return;
}
self.pending_terminal_warning = crate::iterm2_inline::terminal_warrants_switch_warning(
self.inline_protocol,
crate::iterm2_inline::detect_termux(),
);
}
/// Dismiss the unsupported-terminal nudge. `dont_show_again` persists the
/// dismissal so it never reappears; otherwise it returns next launch.
fn dismiss_terminal_warning(&mut self, dont_show_again: bool) {
self.pending_terminal_warning = false;
if dont_show_again {
let _ = crate::prefs::save_suppress_terminal_warning(true);
}
}
fn commit_source_control(&mut self) {
let message = self.source_control.message.trim().to_string();
if message.is_empty() {
self.source_control.commit_feedback = Some(String::from("Empty commit message"));
self.source_control.commit_feedback_is_error = true;
return;
}
match crate::git::commit_all_tracked(&self.scm_root(), &message) {
Ok(summary) => {
self.source_control.clear_message();
self.source_control.commit_feedback = Some(summary.clone());
self.source_control.commit_feedback_is_error = false;
self.status = format!("Committed: {summary}");
self.active_git_bypass_debounce();
self.refresh_git_status_debounced();
self.refresh_source_control();
}
Err(err) => {
self.source_control.commit_feedback = Some(err.clone());
self.source_control.commit_feedback_is_error = true;
self.status = format!("Commit failed: {err}");
}
}
}
/// Housekeeping for the ssh-pane offer (#364), from the top of `render`
/// like `dress_host_accents`: an offer nobody took or dismissed clears
/// itself after [`SSH_OFFER_TTL`], and a pane that closed takes its offer
/// and its per-pane memory along. No system calls: the sampling itself
/// rides the label thread (see `refresh_terminal_labels`).
fn expire_ssh_offer(&mut self) {
let now = std::time::Instant::now();
if self
.ssh_offer
.as_ref()
.is_some_and(|o| now.duration_since(o.since) > SSH_OFFER_TTL)
{
self.dismiss_ssh_offer();
}
let live: std::collections::BTreeSet<u64> =
self.terminals.iter().map(|t| t.uid()).collect();
self.ssh_offer_seen.retain(|uid, _| live.contains(uid));
if self
.ssh_offer
.as_ref()
.is_some_and(|o| !live.contains(&o.pane))
{
self.dismiss_ssh_offer();
}
}
/// Fold the label thread's ssh samples into the offer state (#364):
/// each `(shell pid, host)` names the pane by its shell and goes through
/// `consider_ssh_offer` keyed on the pane's uid.
fn apply_ssh_samples(&mut self, samples: Vec<(i32, Option<String>)>) {
for (shell_pid, host) in samples {
let Some(uid) = self
.terminals
.iter()
.find(|t| t.shell_pid() == Some(shell_pid))
.map(|t| t.uid())
else {
continue;
};
self.consider_ssh_offer(uid, host);
}
}
/// One pane's sampled ssh host, against what it was last seen connected
/// to (#364). A session is offered when it STARTS: the same host on the
/// next sample is the same session, not a new reason to prompt. `None`
/// ends the session; an offer for that pane goes with it.
fn consider_ssh_offer(&mut self, pane: u64, host: Option<String>) {
let previous = self.ssh_offer_seen.insert(pane, host.clone()).flatten();
match host {
None => {
if self.ssh_offer.as_ref().is_some_and(|o| o.pane == pane) {
self.dismiss_ssh_offer();
}
}
Some(host) => {
if previous.as_deref() == Some(host.as_str()) {
return;
}
// The pane moved to another host: whatever it was offered
// for is no longer where it is, offerable or not.
if self.ssh_offer.as_ref().is_some_and(|o| o.pane == pane) {
self.dismiss_ssh_offer();
}
if !crate::remote::offer_allowed(
&host,
self.remote_offer_disabled,
&self.remote_offer_excluded,
&self.remote_offer_refused,
std::time::SystemTime::now(),
) {
return;
}
self.status =
format!("Connected to {host} · Open workspace here? (Cmd+K G, Esc dismisses)");
self.ssh_offer = Some(SshOffer {
pane,
host,
since: std::time::Instant::now(),
});
}
}
}
/// Take the open offer's host for launching (#364), clearing the offer.
fn accept_ssh_offer(&mut self) -> Option<String> {
let offer = self.ssh_offer.take()?;
if self.status.starts_with("Connected to ") {
self.status.clear();
}
Some(offer.host)
}
/// Remember that provisioning `host` failed (#364): the ssh-pane offer
/// stops prompting for it for `REFUSED_HOST_TTL`. Recorded for any
/// install that fails, offer-launched or not, because the fact learned
/// is about the host; and undone by the next success (below), so a box
/// that merely failed on a bad day is offered again once it works.
fn note_provisioning_failed(&mut self, host: &str) {
let key = host.to_ascii_lowercase();
let now = std::time::SystemTime::now();
self.remote_offer_refused.insert(key.clone(), now);
let _ = crate::remote::remember_refused_host(
&crate::remote::refused_hosts_path(&croft_cache_dir()),
&key,
now,
);
}
/// A provisioning of `host` succeeded (#364): any remembered refusal is
/// stale, in memory and on disk. The disk side runs unconditionally:
/// the file is shared by every croft on the machine, so another
/// instance may have recorded a refusal this one never loaded, and
/// `forget_refused_host` is a no-op when there is nothing to forget.
fn note_provisioning_succeeded(&mut self, host: &str) {
let key = host.to_ascii_lowercase();
self.remote_offer_refused.remove(&key);
let _ = crate::remote::forget_refused_host(
&crate::remote::refused_hosts_path(&croft_cache_dir()),
&key,
);
}
/// Drop the open offer and its status line, if any (#364).
fn dismiss_ssh_offer(&mut self) {
if self.ssh_offer.take().is_some() && self.status.starts_with("Connected to ") {
self.status.clear();
}
}
fn request_remote_launch(&mut self, host: String, path: Option<String>) {
self.status = format!("Connecting to {host}");
match crate::remote_connect::SshAuth::start(&host) {
Ok(auth) => {
self.connect_auth = Some(auth);
self.connect_dialog = Some(crate::widgets::connect_dialog::ConnectDialog::new(
host.clone(),
));
self.pending_remote_launch_path = path;
self.pending_remote_launch_host = Some(host);
self.overlays.welcome.request_clear();
}
Err(e) => {
self.status = format!("Could not start ssh: {e}");
}
}
}
/// Re-root the workspace onto the host the active pane is ssh'd into
/// (#364).
///
/// Reads the pane's foreground argv rather than its scrollback: what the
/// user typed may have scrolled away, been edited, or never been typed at
/// all (a shell function, a `Host` alias resolved by ssh itself), while
/// argv is what is actually running.
///
/// The foreground PROCESS GROUP LEADER is what identifies the session,
/// and it is right for the case that matters: `ssh box` typed at a
/// prompt is its own group leader. A PIPELINE is the limit — `ssh box |
/// tee log` makes the whole pipeline one group whose leader is not
/// necessarily the ssh, so the command reports "not an SSH session"
/// rather than guessing. Measured rather than assumed: on zsh the leader
/// resolves to the LAST stage. Refusing is the right failure here, since
/// the alternative is walking the process tree to find an ssh somewhere
/// under the pane and offering to re-root onto a host the user piped
/// output from rather than one they are working on.
///
/// Explicit in the first slice, deliberately: the automatic status-bar
/// offer needed a per-host opt-out, a memory of hosts that refused
/// provisioning and a decision about how often to prompt, none of which
/// belonged alongside the detection itself. Those exist now (the second
/// slice: `consider_ssh_offer` and its gates), and the offer accepts
/// through the same `request_remote_launch` this command reaches for.
fn open_workspace_on_ssh_host(&mut self) {
let Some(term) = self.terminals.get(self.active_terminal) else {
self.status = String::from("No terminal pane is open");
return;
};
let Some(fg) = term.foreground_pid() else {
self.status = String::from("This pane is not running anything");
return;
};
let Some(cmd) = crate::widgets::terminal::process_cmdline(fg) else {
self.status = String::from("Could not read what this pane is running");
return;
};
let argv: Vec<&str> = cmd.iter().map(String::as_str).collect();
let targets = crate::remote::discover_ssh_targets();
match crate::remote::ssh_reroot_decision(&argv, &targets) {
Ok(host) => {
let alias = host.alias.clone();
// No path: the remote flow opens the login directory, which
// is where the ssh session started. Carrying the pane's
// remote cwd across would need the shell's OSC 7 report from
// the far side, and croft only trusts those against a local
// cwd it can verify.
self.request_remote_launch(alias, None);
}
// The message distinguishes "not ssh" from "ssh to a box croft
// has no config entry for": the second names the host, because
// adding it to ~/.ssh/config is the action available.
Err(why) => self.status = why,
}
}
/// Open the history scrubber over the current branch (#371).
///
/// Parks at the WORKING TREE rather than at HEAD, so opening the
/// scrubber changes nothing about what the user is looking at — the
/// first step is theirs to take. That also makes the gesture free to
/// try: a user who opens it by accident is exactly where they were.
fn scrub_history(&mut self) {
// `branch_history`, NOT `commit_graph`: the latter logs
// `--branches --tags HEAD` to draw the repo-wide graph, so with any
// other branch present index 0 is whatever topological order put
// first rather than HEAD, and stepping back from the working tree
// lands on a commit the current branch may not even contain.
let commits = crate::git::branch_history(self.workspace_root(), SCRUB_COMMIT_LIMIT);
if commits.is_empty() {
self.status = String::from("No commits to scrub through");
return;
}
let n = commits.len();
self.scrubber = Some(crate::scrubber::Scrubber::new(commits));
self.status =
format!("Scrubbing {n} commits — arrows step, Home returns to your working tree");
}
/// Follow an edit with the open symbol tab's range (#369).
///
/// A symbol tab is a VIEW over a byte range rather than a copy, so an
/// edit that is not reported here leaves the tab pointing at bytes that
/// have moved — showing the wrong text under the right title, which is
/// worse than showing nothing.
///
/// **Wired only to the collab span path today**, which is the one place
/// an edit already arrives as `(at, deleted, inserted)`. Local typing,
/// backspace, paste, undo and formatting all mutate the buffer through
/// line/column APIs that do not report a byte span, so a tab opened
/// while those run would go stale — which is why the tab VIEW is not
/// built yet and this ships as the tracking layer alone. Giving the
/// editor a byte-span edit signal is the next piece of #369, and doing
/// it before there is a view to break is deliberate: the alternative is
/// a tab that is right for remote edits and silently wrong for the
/// user's own.
///
/// A symbol the edit removed or straddled CLOSES the tab with a notice,
/// rather than re-anchoring to half a function glued to whatever
/// followed it.
pub(crate) fn follow_symbol_tab_edit(&mut self, at: usize, removed: usize, inserted: usize) {
let Some((name, path, range)) = self.symbol_tab.take() else {
return;
};
match range.after_edit(at, removed, inserted) {
crate::symbol_range::RangeAfterEdit::At(moved) => {
self.symbol_tab = Some((name, path, moved));
}
crate::symbol_range::RangeAfterEdit::Gone => {
self.status = format!("Closed the {name} tab: that symbol is gone");
}
}
}
/// Open the symbol under the cursor as its own tab (#369).
///
/// The INNERMOST enclosing symbol, so opening from inside a method shows
/// the method rather than its `impl` — the enclosing block is almost
/// never what was meant.
fn open_symbol_tab(&mut self) {
let line = self.editor.cursor_row as u32;
let symbols = self.outline.symbols();
let Some(sym) = crate::symbol_range::enclosing_symbol(symbols, line) else {
self.status = if symbols.is_empty() {
String::from("No symbols for this file yet")
} else {
String::from("The cursor is not inside a symbol")
};
return;
};
let name = sym.name.clone();
let (first, last) = (sym.range_start_line as usize, sym.range_end_line as usize);
// Converted to BYTES once, here. `SymbolRange` tracks bytes because
// that is what an edit reports, and holding lines as well would be
// two representations that can disagree the moment one is updated
// and the other is not.
let start: usize = self
.editor
.lines
.iter()
.take(first)
.map(|l| l.len() + 1)
.sum();
let mut len: usize = self
.editor
.lines
.iter()
.skip(first)
.take(last + 1 - first)
.map(|l| l.len() + 1)
.sum();
// The `+ 1` is a SEPARATOR between lines, not a terminator: croft's
// offset model gives an N-line buffer no trailing newline. Charging
// one to the final line puts `end` a byte past the buffer, which
// panics anything that slices by the range — and makes an append at
// true EOF read as INSIDE the symbol rather than below it.
if last + 1 >= self.editor.lines.len() {
len = len.saturating_sub(1);
}
let range = crate::symbol_range::SymbolRange::new(start, start + len);
let Some(path) = self.editor.path.clone() else {
self.status = String::from("Save this buffer before opening a symbol from it");
return;
};
self.symbol_tab = Some((name.clone(), path, range));
self.status = format!("{name}: {} bytes", range.len());
}
/// Start or stop recording the active terminal as an asciicast (#356).
///
/// Toggling rather than two commands, because a recording is a mode with
/// exactly one visible state: a user who cannot remember whether they
/// started one reaches for the same entry either way, and gets told
/// which happened.
fn toggle_session_recording(&mut self) {
use std::io::Write as _;
if let Some((_, _, started)) = self.recording.take() {
let secs = started.elapsed().as_secs_f64();
self.status = format!("Stopped recording after {secs:.1}s");
return;
}
let Some(term) = self.terminals.get(self.active_terminal) else {
self.status = String::from("No terminal pane to record");
return;
};
// `last_inner`, not `last_area`. The PTY grid is sized from the
// pane's INNER rect — `Borders::ALL` takes a cell on each side — so
// recording the outer size declares a terminal two columns wider and
// two rows taller than the content was wrapped for. The player then
// wraps every long line at the wrong column.
let (cols, rows) = (term.last_inner.width, term.last_inner.height);
if cols == 0 || rows == 0 {
// A zero-sized header makes a cast every player refuses, and the
// error names the file rather than the moment it was started.
self.status = String::from("The terminal has no size yet — try once it has drawn");
return;
}
// A per-recording name, not a per-process one: two recordings in
// one session would otherwise write the same file, and the second
// would silently destroy the first — which the user only discovers
// when they go to share the earlier one.
let stamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
let path = self
.workspace_root()
.join(format!("croft-{}-{stamp}.cast", std::process::id()));
let rec = crate::asciicast::Recorder::new(cols, rows);
let header = rec.header(Some("croft session"));
match std::fs::File::create(&path) {
Ok(mut f) => {
if let Err(e) = writeln!(f, "{header}") {
self.status = format!("Could not write {}: {e}", path.display());
return;
}
self.recorded_size = (cols, rows);
self.recording = Some((rec, f, std::time::Instant::now()));
self.status = format!("\u{25cf} REC to {}", path.display());
}
Err(e) => self.status = format!("Could not create {}: {e}", path.display()),
}
}
/// Load this PR's review threads onto the open file as comment boxes
/// (#366).
///
/// Only threads for THIS file. A review's comments span the whole PR,
/// and hanging another file's objections off this buffer's line numbers
/// would put them against unrelated code — the same failure as placing
/// an outdated thread silently, arriving through the other axis.
fn load_review_threads(&mut self) {
let Some(path) = self.editor.path.clone() else {
self.status = String::from("Open a file from the PR first");
return;
};
// The root that OWNS the open file, not the primary. In a
// multi-root workspace the two differ, and using the primary runs
// `gh` in the wrong repository — which answers about a different
// PR entirely rather than failing.
let root = self.active_workspace_root();
// Relative to the REPOSITORY TOPLEVEL, not the workspace root. The
// API's `path` is repo-relative, and the two coincide only when the
// workspace root IS the toplevel — open croft on `repo/src` and
// every comparison fails silently, so a file with review comments
// reports having none. That is #139's rule; this is the same trap in
// a new place.
let Some(repo_root) = self.git_worker_for_root(&root).status().repo_root.clone() else {
self.status = String::from("This folder is not inside a git repository");
return;
};
let Ok(rel) = path.strip_prefix(&repo_root) else {
self.status = format!(
"{} is outside the repository, so it has no review comments",
path.display()
);
return;
};
// Forward slashes: the API always uses them, and on Windows a
// `to_string_lossy` here yields backslashes that match nothing.
let rel = rel
.components()
.map(|c| c.as_os_str().to_string_lossy())
.collect::<Vec<_>>()
.join("/");
let out = std::process::Command::new("gh")
.args(["pr", "view", "--json", "number", "--jq", ".number"])
.current_dir(&root)
.output();
let number = match out {
Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).trim().to_string(),
_ => {
self.status = String::from("No PR for this branch — check it out first");
return;
}
};
let api = std::process::Command::new("gh")
.args([
"api",
&format!("repos/{{owner}}/{{repo}}/pulls/{number}/comments"),
"--paginate",
])
.current_dir(&root)
.output();
let json = match api {
Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).to_string(),
Ok(o) => {
// gh's own message names the problem — a missing scope, a
// rate limit — far better than anything invented here.
let err = String::from_utf8_lossy(&o.stderr);
self.status = format!(
"Could not read the PR's comments: {}",
err.trim().lines().next().unwrap_or("gh failed")
);
return;
}
Err(e) => {
self.status = format!("Could not run gh: {e}");
return;
}
};
let threads: Vec<crate::review_threads::Thread> =
crate::review_threads::parse_threads(&json)
.into_iter()
.filter(|t| t.path == rel)
.collect();
if threads.is_empty() {
self.status = format!("No review comments on {rel}");
return;
}
let outdated = threads
.iter()
.filter(|t| matches!(t.anchor, crate::review_threads::Anchor::Outdated(_)))
.count();
// Stored against the file they describe; the render derives each
// box's row and title from the buffer as it is at that moment.
// `path` is the binding taken at the top of this function, so the
// threads are keyed to the file the `gh` query was actually about
// rather than to whatever `editor.path` says afterwards. Today those
// cannot differ — the event loop is single-threaded and `gh` blocks
// it, so no keystroke is handled mid-call — but keying to the
// queried file is the property that matters, and it stops being
// free the moment this moves off the main thread.
self.review_boxes = Some((path, threads.clone()));
self.status = match outdated {
0 => format!("{} review comments on {rel}", threads.len()),
n => format!(
"{} review comments on {rel} \u{b7} {n} outdated, shown where they WERE",
threads.len()
),
};
}
/// Append terminal output to the open recording, if there is one (#356).
///
/// Times are measured from the recording's start rather than from the
/// process's, because a cast's first event should be at ~0 — a player
/// given a first timestamp of 4000 seconds sits on a blank screen for
/// over an hour before anything happens.
pub(crate) fn record_terminal_output(&mut self, data: &str) {
use std::io::Write as _;
let Some((rec, file, started)) = self.recording.as_mut() else {
return;
};
let line = rec.line(&crate::asciicast::Event::Output {
at: started.elapsed().as_secs_f64(),
data: data.to_string(),
});
// A write failure STOPS the recording rather than being ignored: a
// half-written cast that keeps growing is worse than one that ends,
// and the user needs to know the file they are about to share is
// truncated.
if writeln!(file, "{line}").is_err() {
self.recording = None;
self.status = String::from("Recording stopped: could not write to the cast file");
}
}
/// Run `command` on every configured ssh host and report what differs
/// (#363).
///
/// In PARALLEL, one thread per host, because the whole point is
/// comparing a fleet: run serially, ten hosts at a two-second timeout
/// each is twenty seconds of staring, and a single unreachable host
/// would hold up every other result behind it.
fn run_fleet_command(&mut self, command: &str) {
let command = command.trim();
if command.is_empty() {
self.status = String::from("Fleet run needs a command");
return;
}
let known: Vec<String> = crate::remote::discover_ssh_targets()
.into_iter()
.map(|t| t.alias)
.collect();
if known.is_empty() {
self.status = String::from("No hosts in ~/.ssh/config to run on");
return;
}
// The fleet must be NAMED. Defaulting to every configured host means
// running arbitrary text on every remote the user ever set up — and
// a confirmation saying "run on 5 hosts?" asks them to approve a list
// they cannot see, which is not consent. `*` is how to say "all of
// them" deliberately.
let Some((picked, command)) =
crate::fleet::parse_request_with_groups(command, &known, &self.fleet_groups)
else {
self.status = format!(
"Fleet run needs 'hosts: command' — e.g. '{}: uptime', or '*: uptime' for all {}",
known[0],
known.len()
);
return;
};
let hosts: Vec<String> = picked.into_iter().cloned().collect();
if self.fleet_running {
self.status = String::from("A fleet run is already in flight");
return;
}
crate::output::push(
crate::output::CHANNEL_FLEET,
crate::output::OutputLevel::Info,
&format!("$ {command} on {}", hosts.join(", ")),
);
// Off the event loop: the run waits on the network for up to
// FLEET_TIMEOUT, and blocking the loop for that would freeze the
// editor — the user could not scroll, type, or cancel while their
// fleet answered. Results arrive through `fleet_rx` and are drained
// on a later tick, the same shape the port poll and label lookup use.
let host_count = hosts.len();
let tx = self.fleet_tx.clone();
let command = command.to_string();
self.fleet_running = true;
std::thread::spawn(move || {
let _ = tx.send(crate::fleet::run_on_hosts(&hosts, &command, FLEET_TIMEOUT));
});
self.status = format!("Fleet: running on {host_count} hosts…");
}
/// Report a finished fleet run, if one arrived (#363).
///
/// Drained on the tick like the other background results. Returns
/// whether anything landed, so the caller can redraw only when there is
/// something new.
fn drain_fleet_results(&mut self) -> bool {
// Every queued run, not just the newest. Each message is ONE run's
// results, unlike the label channel this idiom comes from where each
// message is a complete snapshot — taking `.last()` there is right
// and here would drop a whole run's output with no trace of it.
let batches: Vec<Vec<crate::fleet::HostResult>> = self.fleet_rx.try_iter().collect();
if batches.is_empty() {
return false;
}
self.fleet_running = false;
for results in batches {
let reference = crate::fleet::reference_output(&results).map(String::from);
for r in &results {
let mark = match (r.ok(), Some(r.output.as_str()) == reference.as_deref()) {
(false, _) => "FAILED",
(true, true) => "same",
(true, false) => "DIFFERS",
};
crate::output::push(
crate::output::CHANNEL_FLEET,
if r.ok() {
crate::output::OutputLevel::Info
} else {
crate::output::OutputLevel::Error
},
&format!("{} [{mark}] {}", r.host, r.output.replace('\n', " ")),
);
}
let summary = crate::fleet::summarise(&results, reference.as_deref());
crate::output::push(
crate::output::CHANNEL_FLEET,
crate::output::OutputLevel::Info,
&summary.line(),
);
self.status = format!("Fleet: {}", summary.line());
}
true
}
/// Ask for a new lane's name (#348); the palette command and `Cmd+K
/// Shift+L` both land here.
fn open_new_lane_prompt(&mut self) {
self.open_input_prompt(crate::widgets::input_prompt::InputPrompt::new(
crate::widgets::input_prompt::InputPurpose::NewWorktreeLane,
String::from("New worktree lane"),
String::from("what the agent will work on"),
));
}
/// Create a worktree lane and add it as a workspace root (#348).
///
/// The worktree is a SIBLING of the repo, never a child: a worktree
/// nested inside its own repo is a working tree git then tries to track,
/// and the Explorer would show the lane inside the root it was cut from.
fn create_worktree_lane(&mut self, name: &str) {
let repo = self.workspace_root().to_path_buf();
let Some(mut lane) = crate::git::WorktreeLane::plan(&repo, name) else {
// Refused rather than defaulted: a name with nothing usable in
// it would otherwise become the branch `agent/`.
self.status = format!("{name:?} has no letters or digits to name a lane after");
return;
};
if lane.path.exists() {
self.status = format!("{} already exists — pick another name", lane.path.display());
return;
}
match crate::git::add_worktree_lane(&repo, &mut lane) {
Ok(()) => {
self.add_workspace_folder(lane.path.clone());
self.open_lane_pane(&lane);
}
Err(why) => self.status = format!("Could not create the lane: {why}"),
}
}
/// The pane half of a new lane (#348): a named terminal in the worktree,
/// running the configured agent's launch line when there is one. The
/// status says which of the three outcomes happened — agent started,
/// plain shell because no agent is configured, or plain shell because
/// the configured agent has no launch line — since a lane that quietly
/// opens a shell where the user expected an agent reads as broken.
fn open_lane_pane(&mut self, lane: &crate::git::WorktreeLane) {
let slug = lane
.branch
.strip_prefix("agent/")
.unwrap_or(&lane.branch)
.to_string();
let agent = self
.lane_agent
.as_deref()
.map(str::trim)
.filter(|a| !a.is_empty())
.map(str::to_ascii_lowercase);
let launch = agent
.as_deref()
.and_then(|a| self.agents.launch_line(a))
.map(str::to_string);
let mut term = match PtyTerminal::new(&lane.path) {
Ok(t) => t,
Err(e) => {
self.status = format!(
"Lane {} on branch {} — could not open its pane: {e}",
lane.path.display(),
lane.branch
);
return;
}
};
term.set_manual_name(Some(format!("Lane: {slug}")));
if let Some(cmd) = &launch {
term.write_input(lane_launch_input(cmd).as_bytes());
}
let seated = launch.is_some();
// Recorded BEFORE the insert: `insert_terminal` saves the terminal
// session, and the save reads this map.
self.lane_panes.insert(
term.uid(),
crate::terminal_session::LaneRecord {
// Canonical, like the workspace roots it is compared with
// when the lane closes; taken now, while the directory
// exists to resolve.
path: lane
.path
.canonicalize()
.unwrap_or_else(|_| lane.path.clone())
.display()
.to_string(),
branch: lane.branch.clone(),
agent: if seated { agent.clone() } else { None },
base: lane.base.clone(),
},
);
self.insert_terminal(term);
let pane = match (agent, seated) {
(Some(a), true) => format!("{a} started in pane Lane: {slug}"),
(Some(a), false) => {
format!(
"plain shell in pane Lane: {slug} (agents.json has no launch line for {a:?})"
)
}
(None, _) => format!("shell in pane Lane: {slug} (set lane_agent to start an agent)"),
};
self.status = format!(
"Lane {} on branch {} — {pane}",
lane.path.display(),
lane.branch
);
}
/// The review-queue summary, one row per agent, grouped by the workspace
/// root each file lives under (#348).
///
/// Grouping is what makes the queue usable once worktree lanes exist:
/// with an agent working in a lane and you working in the main checkout,
/// a flat list of basenames cannot say which `mod.rs` it means. Each
/// group is named by its lane's BRANCH where the root is a lane, and by
/// the root's display label otherwise.
///
/// A row whose files all sit under ONE root keeps the pre-grouping flat
/// shape, `agent: n to review (a.rs, b.rs)`: with one group the label
/// names the only place the files could be and the group count merely
/// repeats `n`. So the common single-root session is untouched, and
/// grouping appears exactly when there is something to tell apart.
///
/// A grouped row carries labels and counts but no file names, because
/// the status bar is one row that elides its MIDDLE: a row long enough
/// to be cut loses the group labels, which is precisely what grouping
/// exists to show. The flat row keeps its sample, being short already.
fn agent_lane_rows(&self) -> Vec<String> {
let roots: Vec<PathBuf> = self.roots.iter().map(Path::to_path_buf).collect();
let labels = crate::workspace::root_display_labels(&roots);
// A lane's branch names it better than its directory does: the
// directory is `repo-fix-login`, the branch is what the agent is on.
let branch_of = |root: &Path| -> Option<String> {
self.lane_panes
.values()
.find(|l| Path::new(&l.path) == root)
.map(|l| l.branch.clone())
};
// Up to three names per group, with an ellipsis when there are more:
// a count next to a truncated list otherwise reads as an
// enumeration that lost two entries.
let sample = |files: &[&crate::agent_lane::LaneFile]| -> String {
let names: Vec<String> = files
.iter()
.take(3)
.map(|f| {
let name = f
.path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
if f.shared {
format!("{name} (shared)")
} else {
name
}
})
.collect();
let mut out = names.join(", ");
if files.len() > names.len() {
out.push_str(", \u{2026}");
}
out
};
self.agent_ledger
.agents()
.into_iter()
.map(|agent| {
let n = self.agent_ledger.unreviewed_count(agent);
let groups = self.agent_ledger.lane_by_root(agent, &roots);
// One group is the single-root session this feature does not
// change: the root label would name the only place the files
// could be, and the group count would repeat `n`.
if groups.len() <= 1 {
let files = groups.first().map(|(_, f)| sample(f)).unwrap_or_default();
return format!("{agent}: {n} to review ({files})");
}
// A lane's branch is derived from its slug alone, so two
// lanes cut from different repos can share one; fall back to
// the disambiguated root label when that happens, since a
// row naming two groups identically is worse than a row
// naming them by folder.
let branches: Vec<Option<String>> = groups
.iter()
.map(|(root, _)| root.and_then(&branch_of))
.collect();
let named: Vec<String> = groups
.iter()
.zip(&branches)
.map(|((root, files), branch)| {
let root_label = |r: &Path| {
roots
.iter()
.position(|candidate| candidate == r)
.and_then(|i| labels.get(i).cloned())
.unwrap_or_else(|| r.display().to_string())
};
let label = match (root, branch) {
(Some(_), Some(b))
if branches.iter().flatten().filter(|o| *o == b).count() == 1 =>
{
b.clone()
}
(Some(r), _) => root_label(r),
(None, _) => String::from("outside the workspace"),
};
// Labels and counts only. The status bar is ONE row
// and elides the MIDDLE of anything too long
// (`elide_middle`), so a row carrying samples for
// every group loses the group labels first — the
// one thing grouping adds. Which files they are is
// a question the Explorer's dots already answer.
format!("{label} {}", files.len())
})
.collect();
format!("{agent}: {n} to review \u{2014} {}", named.join("; "))
})
.collect()
}
/// Give each lane's root row in the Explorer its branch and its agent
/// (#348), from the lane panes: `agent/fix-login · ◆ claude ●` while the
/// agent is seated, the configured agent's name before it is, the branch
/// alone for a plain-shell lane. Runs from the top of `render`; the map
/// is swapped only when its contents change, so the common frame costs a
/// walk over a handful of lanes and a small map that is then dropped.
fn sync_lane_root_badges(&mut self) {
// Several panes on one lane: the pane that knows the most decides
// the badge, whichever order the map walks them in. Seated beats
// configured beats plain, decided from the state rather than by
// reading the glyph back out of the text.
let mut best: std::collections::HashMap<PathBuf, (u8, String)> =
std::collections::HashMap::new();
for (uid, lane) in &self.lane_panes {
let seated = self
.terminals
.iter()
.find(|t| t.uid() == *uid)
.and_then(|t| t.agent());
let rank = match (seated, lane.agent.as_deref()) {
(Some(_), _) => 2,
(None, Some(_)) => 1,
(None, None) => 0,
};
let key = PathBuf::from(&lane.path);
if best.get(&key).is_some_and(|(have, _)| *have >= rank) {
continue;
}
let badge = lane_root_badge(&lane.branch, seated, lane.agent.as_deref());
best.insert(key, (rank, badge));
}
let badges: std::collections::HashMap<PathBuf, String> =
best.into_iter().map(|(k, (_, b))| (k, b)).collect();
// Swapped only on a change: the map built here is dropped, not
// handed to the tree, when nothing moved.
if *self.tree.root_badges != badges {
self.tree.root_badges = std::sync::Arc::new(badges);
}
}
/// Close the panes that belong to the lane at `lane` (#348), through the
/// undoable close so a mistaken lane removal does not also lose the
/// pane's scrollback. Returns how many closed and how many stayed.
///
/// The close refuses the last pane, and a lane pane left standing would
/// sit in a directory git just removed; so when the lane's panes are ALL
/// the panes, a fresh shell in the primary root is opened first to be
/// the one that stays. Only when that shell cannot spawn does a lane
/// pane remain, stripped of its lane name, and the caller says so.
fn close_lane_panes(&mut self, lane: &Path) -> (usize, usize) {
let doomed: Vec<usize> = self
.terminals
.iter()
.enumerate()
.filter(|(_, t)| {
self.lane_panes
.get(&t.uid())
.is_some_and(|l| Path::new(&l.path) == lane)
})
.map(|(i, _)| i)
.collect();
if !doomed.is_empty() && doomed.len() == self.terminals.len() {
// Pushed, not `insert_terminal`ed: the doomed indices must stay
// where they are, and the session is saved by the closes below.
match PtyTerminal::new(self.roots.primary()) {
Ok(term) => self.terminals.push(term),
Err(e) => self.status = format!("Could not open a replacement pane: {e}"),
}
}
let (mut closed, mut kept) = (0, 0);
// Highest index first so the earlier indices stay valid.
for idx in doomed.into_iter().rev() {
let uid = self.terminals[idx].uid();
if self.close_terminal_at(idx) {
closed += 1;
} else {
// The last pane stays; it is no longer a lane's (its
// worktree is gone), so it stops wearing the lane's name.
kept += 1;
self.terminals[idx].set_manual_name(None);
self.lane_panes.remove(&uid);
}
}
(closed, kept)
}
/// Point the COMMITS graph at `base..lane` for the active lane (#348).
///
/// Uses `active_scm_root` like `close_worktree_lane` beside it, rather
/// than the primary: a lane is never index 0, and a sibling command that
/// silently switched which root it acted on is how that one destroyed a
/// lane in testing.
///
/// Leaves the panel showing the diff until something else refreshes it -
/// the tag on the reply keeps a background history fetch from replacing
/// it, and returning to history is the ordinary refresh path.
fn diff_worktree_lane(&mut self) {
let lane = self.active_scm_root.clone();
if lane == self.roots.primary() {
self.status =
String::from("The primary folder is not a lane — open a file in the lane first");
return;
}
let Some(record) = self
.lane_panes
.values()
.find(|r| std::path::Path::new(&r.path) == lane)
else {
self.status = String::from("No lane is open for this folder");
return;
};
// A lane made before the base was recorded, or cut from a detached
// HEAD, has nothing to diff against. Say which rather than showing an
// empty graph that reads as "no commits".
let Some(base) = record.base.clone() else {
self.status = format!(
"Lane {} records no base branch to diff against",
record.branch
);
return;
};
let branch = record.branch.clone();
self.graph_revspec = Some(format!("{base}..{branch}"));
self.refresh_commit_graph();
self.status = format!("COMMITS: {branch} against {base}");
}
/// Remove the active root's worktree lane, refusing when it is dirty
/// (#348).
///
/// The refusal is the point. `git worktree remove` DISCARDS uncommitted
/// work, so this is the one place in the lane flow where being wrong
/// destroys something rather than annoying someone — and the check fails
/// closed, treating a tree git cannot report on as unsafe.
fn close_worktree_lane(&mut self) {
// The ACTIVE root, not the primary. `workspace_root()` is
// `roots.primary()`, and a lane is appended by `add_workspace_folder`
// so it is never index 0 — this targeted the user's main repo every
// time. Today git's own "is a main working tree" refusal masks that,
// but the guard is git's rather than ours: launch croft INSIDE a lane
// (the workflow this feature creates) and the primary becomes a
// removable worktree, so the directory is deleted, the folder cannot
// be dropped, and the status reports success.
let lane = self.active_scm_root.clone();
if lane == self.roots.primary() {
self.status =
String::from("The primary folder is not a lane — open a file in the lane first");
return;
}
// The diff outlives the lane otherwise: `remove_workspace_folder`
// re-seeds the primary, and its COMMITS panel is then stuck on a
// range whose right side no longer resolves.
//
// Cleared BEFORE the refusals, not in the success arm: `git worktree
// remove` can still fail after `lane_removal_block` passed (a locked
// worktree, below), and that arm returns too. On a refusal the rows
// already drawn outlive the clear until the next refresh, which is
// correct - they are still this lane's commits, and the lane is
// still here.
self.graph_revspec = None;
if let Some(why) = crate::git::lane_removal_block(&lane) {
self.status = format!("Keeping the lane: {why}");
return;
}
// git FIRST, then the folder. `lane_removal_block` answers "is there
// uncommitted work", which is not the same question as "will git
// remove this" — a LOCKED worktree reports a clean status and is
// then refused, measured. Dropping the folder first would leave the
// user with the lane gone from their workspace and the directory
// still on disk, which is the worst of both.
match crate::git::remove_worktree_lane(&lane) {
Ok(()) => {
self.remove_workspace_folder(lane.clone());
// `remove_workspace_folder` refuses the primary and says so
// in the status; only claim success when the folder really
// left, or a refusal there would be overwritten by a message
// saying the whole thing worked.
let (closed, kept) = self.close_lane_panes(&lane);
if self.roots.iter().any(|r| r == lane) {
self.status = format!(
"Removed {} on disk, but it is still in this workspace",
lane.display()
);
} else if kept > 0 {
self.status = format!(
"Removed lane {} — its pane stays (no replacement pane could open) in a directory that is now gone",
lane.display()
);
} else if closed > 0 {
self.status = format!(
"Removed lane {} and closed its pane (Cmd+K Shift+T reopens it)",
lane.display()
);
} else {
self.status = format!("Removed lane {}", lane.display());
}
}
Err(why) => self.status = format!("Keeping the lane: {why}"),
}
}
/// One scrubber keystroke. Returns whether it was consumed (#371).
///
/// Returning `false` for anything else matters: the scrubber is a view,
/// not a mode that swallows the keyboard, so a key it does not use keeps
/// its normal meaning rather than being silently eaten.
fn handle_scrubber_key(&mut self, code: KeyCode) -> bool {
let Some(scrub) = self.scrubber.as_mut() else {
return false;
};
match code {
KeyCode::Left => scrub.older(),
KeyCode::Right => scrub.newer(),
KeyCode::Home => scrub.home(),
KeyCode::Esc => {
// Closing returns to the live buffer by construction: the
// scrubber never replaced it, so there is nothing to put
// back and no path where unsaved edits could be lost.
self.scrubber = None;
self.status = String::from("Left the history scrubber");
return true;
}
_ => return false,
}
// git's own short hash, not a byte slice of the full one: that
// slice is safe only while the string is ASCII hex, and the width
// git abbreviates to is per-repo rather than always seven.
self.status = match self.scrubber.as_ref().and_then(|s| s.commit()) {
Some(c) => format!("At {} — {}", c.short_hash, c.summary),
None => String::from("At your working tree"),
};
true
}
pub fn poll_connect_dialog(&mut self) -> bool {
let Some(auth) = self.connect_auth.as_mut() else {
return false;
};
let events = auth.drain_events();
if events.is_empty() {
return false;
}
let Some(dialog) = self.connect_dialog.as_mut() else {
return false;
};
let mut authenticated = false;
let mut failed: Option<String> = None;
for ev in events {
match ev {
crate::remote_connect::SshAuthEvent::Log(chunk) => {
dialog.push_log(&chunk);
}
crate::remote_connect::SshAuthEvent::Prompt { kind, line } => {
dialog.set_prompt(kind, line);
}
crate::remote_connect::SshAuthEvent::Authenticated => {
dialog.set_installing();
authenticated = true;
}
crate::remote_connect::SshAuthEvent::Failed(detail) => {
failed = Some(detail);
}
}
}
if let Some(detail) = failed {
dialog.set_failed(detail);
self.tear_down_connect_auth();
}
if authenticated
&& let (Some(auth), Some(host)) = (
self.connect_auth.take(),
self.pending_remote_launch_host.take(),
)
{
let adopted = auth.hand_off();
let path = self.pending_remote_launch_path.take();
self.install_session = Some(crate::install_session::InstallSession::start(
adopted,
host.clone(),
path,
));
self.status = format!("Preparing remote croft on {host}");
}
true
}
pub fn poll_install_session(&mut self) -> bool {
let Some(session) = self.install_session.as_mut() else {
return false;
};
let events = session.drain_events();
let mut changed = !events.is_empty();
let mut can_launch = false;
let mut done = false;
let mut failure: Option<String> = None;
for ev in events {
match ev {
crate::install_session::InstallEvent::Log(line) => {
if let Some(dialog) = self.connect_dialog.as_mut() {
dialog.push_log(&line);
}
}
crate::install_session::InstallEvent::CanLaunch => can_launch = true,
crate::install_session::InstallEvent::FallbackPrompt { reason } => {
if let Some(dialog) = self.connect_dialog.as_mut() {
dialog.set_fallback_prompt(&reason);
} else if let Some(session) = self.install_session.as_ref() {
// No dialog to ask through: decline so the installer
// errors out with the `croft setup-cross` guidance
// instead of blocking forever on an answer.
session.respond_fallback(false);
}
}
crate::install_session::InstallEvent::Done(Ok(())) => done = true,
crate::install_session::InstallEvent::Done(Err(detail)) => {
failure = Some(detail);
}
}
}
// Once we've handed the terminal to the remote croft, the install
// keeps running in a detached thread and signals completion to that
// remote process via the install-stamp it watches; nothing here.
if self.remote_launch.is_some() {
return changed;
}
// A croft is already on the remote: drop the user into it now and
// let the (re)install finish in the background. The running remote
// croft re-execs into the new binary when the stamp advances.
if can_launch {
if let Some(session) = self.install_session.as_mut()
&& let Some(adopted) = session.take_adopted()
{
let host = session.host.clone();
let path = session.path.clone();
self.note_provisioning_succeeded(&host);
self.remote_launch = Some(RemoteLaunch {
host: host.clone(),
path,
adopted: Some(adopted),
});
self.status = format!("Launching croft on {host}");
self.connect_dialog = None;
self.quit = true;
}
return true;
}
if let Some(detail) = failure {
// Remember the host as one croft could not provision (#364), so
// the ssh-pane offer stops prompting for it for a while. Kept
// beside the failure it learns from, and best-effort: a write
// that fails costs one repeated offer.
if let Some(host) = self.install_session.as_ref().map(|s| s.host.clone()) {
self.note_provisioning_failed(&host);
}
if let Some(dialog) = self.connect_dialog.as_mut() {
dialog.set_failed(detail.clone());
}
self.install_session = None;
self.status = format!("Remote install failed: {detail}");
changed = true;
} else if done {
if let Some(mut session) = self.install_session.take()
&& let Some(adopted) = session.take_adopted()
{
let host = session.host.clone();
let path = session.path.clone();
self.note_provisioning_succeeded(&host);
self.remote_launch = Some(RemoteLaunch {
host: host.clone(),
path,
adopted: Some(adopted),
});
self.status = format!("Launching croft on {host}");
self.connect_dialog = None;
self.quit = true;
}
changed = true;
}
changed
}
/// Start the background self-update watcher on a remote-launched croft.
/// No-op unless `CROFT_REMOTE_AUTOUPDATE` is set (it is, by the remote
/// launch command) and an install-stamp exists to compare against.
fn start_update_watch_if_remote(&mut self) {
if std::env::var_os("CROFT_REMOTE_AUTOUPDATE").is_none() {
return;
}
let cache_dir = croft_cache_dir();
let launch_stamp = std::fs::read_to_string(cache_dir.join("install-stamp"))
.map(|s| s.trim().to_string())
.unwrap_or_default();
self.update_watch = Some(crate::update_watch::UpdateWatch::start(
cache_dir,
launch_stamp,
));
}
/// Start the one-shot local drift probe (#242) on a locally-launched
/// croft. A remote-launched croft skips it: its binary is re-stamped by
/// the launching machine on every connect, and its baked manifest dir
/// points at a tree on another box anyway.
fn start_drift_probe_if_local(&mut self) {
if std::env::var_os("CROFT_REMOTE_AUTOUPDATE").is_some() {
return;
}
self.drift_probe = Some(crate::update_watch::DriftProbe::start(
String::from(env!("CARGO_MANIFEST_DIR")),
String::from(env!("CROFT_GIT_HASH_FULL")),
));
}
/// Start the release-availability check (#333) on a locally-launched
/// croft. A remote-launched croft is shipped by its launcher; a build
/// with `CROFT_NO_UPDATE_CHECK` set in the environment never asks.
fn start_update_check_if_local(&mut self) {
if std::env::var_os("CROFT_REMOTE_AUTOUPDATE").is_some()
|| std::env::var_os("CROFT_NO_UPDATE_CHECK").is_some()
{
return;
}
self.update_check = Some(crate::update_check::UpdateCheck::start(
croft_cache_dir(),
String::from(env!("CARGO_PKG_VERSION")),
));
}
/// Raise the popup when the check finds a newer, undismissed release.
/// The check is dropped either way - it only ever answers once.
fn poll_update_check(&mut self) -> bool {
let Some(check) = self.update_check.as_ref() else {
return false;
};
let Some(verdict) = check.take() else {
return false;
};
self.update_check = None;
let Some(version) = verdict else {
return false;
};
self.update_toast = Some(UpdateToast {
version,
ready: false,
buttons: Vec::new(),
});
true
}
/// Kick off the staged build the popup offered. The existing update
/// state machine takes it from here: spinner while cargo runs, then
/// the popup and the status bar both offer Relaunch.
fn start_staged_update(&mut self, version: String) {
self.staged_status = UpdateStatus::Idle;
self.staged_install = Some(crate::update_check::StagedInstall::start(
croft_cache_dir(),
version,
staged_install_log_path(),
));
}
/// Decline the offered version for good (until a newer one appears).
fn dismiss_update_offer(&mut self, version: &str) {
if let Err(e) = crate::update_check::dismiss(&croft_cache_dir(), version) {
self.status = format!("Could not remember the dismissed update: {e}");
}
}
/// The staged binary waiting to be swapped in, once its build landed.
fn staged_update_binary(&self) -> Option<PathBuf> {
let install = self.staged_install.as_ref()?;
(self.staged_status == UpdateStatus::Ready).then(|| install.binary().to_path_buf())
}
/// Whether any producer has an update ready to re-exec into: the
/// status-bar pill and bare F9 mean "any".
fn any_update_ready(&self) -> bool {
self.update_status == UpdateStatus::Ready || self.staged_status == UpdateStatus::Ready
}
/// Whether any producer is mid-build (drives the spinner).
fn any_update_in_progress(&self) -> bool {
self.update_status == UpdateStatus::InProgress
|| self.staged_status == UpdateStatus::InProgress
}
/// Arm the rebuild hint when the drift probe's verdict lands. The probe
/// is dropped either way — it only ever answers once.
fn poll_drift_probe(&mut self) -> bool {
let Some(probe) = self.drift_probe.as_ref() else {
return false;
};
let Some(verdict) = probe.take() else {
return false;
};
self.drift_probe = None;
let Some(current) = verdict else {
return false;
};
self.status = format!(
"This croft was built at {}, but its repo is now at {current} - press F9 to rebuild & reinstall in the background",
env!("CROFT_GIT_HASH"),
);
self.local_drift = Some(current);
true
}
/// Kick off the background reinstall the drift hint offered. The
/// existing update state machine takes it from here: spinner while
/// `cargo install` runs, then the same "F9 to relaunch" flow a remote
/// background update uses.
fn start_local_reinstall(&mut self) {
self.self_install = Some(crate::update_watch::SelfInstall::start(
String::from(env!("CARGO_MANIFEST_DIR")),
self_install_log_path(),
));
}
/// True when bare F9 is claimed by the update flow: either a landed
/// update waiting to re-exec, or an armed drift hint waiting to rebuild.
fn f9_update_armed(&self) -> bool {
self.any_update_ready()
|| (self.local_drift.is_some()
&& self.update_status == UpdateStatus::Idle
&& self.staged_status != UpdateStatus::InProgress
// `update_status` only leaves Idle when the InProgress event
// is drained - once per outer loop, BEFORE the input drain -
// so without this latch two F9s in one crossterm batch spawn
// two concurrent `cargo install`s racing cargo's locks
// (#245). The staged release build holds the same cargo
// lock, so it latches F9 the same way.
&& self.self_install.is_none()
&& self.staged_install.is_none())
}
pub fn poll_update_watch(&mut self) -> bool {
let mut changed = self.poll_drift_probe();
changed |= self.poll_update_check();
// Three producers share one event vocabulary; each event keeps its
// origin so a drift rebuild's failure is never charged to the
// staged release build (or the reverse).
let mut events: Vec<(UpdateSource, crate::update_watch::UpdateEvent)> = Vec::new();
if let Some(watch) = self.update_watch.as_ref() {
events.extend(watch.drain().into_iter().map(|e| (UpdateSource::Watch, e)));
}
if let Some(install) = self.self_install.as_ref() {
events.extend(
install
.drain()
.into_iter()
.map(|e| (UpdateSource::SelfInstall, e)),
);
}
if let Some(staged) = self.staged_install.as_ref() {
events.extend(
staged
.drain()
.into_iter()
.map(|e| (UpdateSource::Staged, e)),
);
}
for (source, ev) in events {
changed = true;
// Each producer writes ITS cell; the other cell is never
// touched, so nothing one build does can strand the other's
// landed binary (there is exactly one Ready per channel).
let staged = source == UpdateSource::Staged;
match ev {
crate::update_watch::UpdateEvent::InProgress => {
if staged {
self.staged_status = UpdateStatus::InProgress;
} else {
self.update_status = UpdateStatus::InProgress;
}
// The dedicated red, spinning status-bar span renders the
// message now, so the generic status line stays clear.
self.update_spinner_start = Some(std::time::Instant::now());
self.status.clear();
}
crate::update_watch::UpdateEvent::Failed => {
if staged {
self.staged_status = UpdateStatus::Idle;
} else {
self.update_status = UpdateStatus::Idle;
}
if !self.any_update_in_progress() {
self.update_spinner_start = None;
}
self.status = match source {
UpdateSource::Staged => {
let version = self
.staged_install
.take()
.map(|s| s.version)
.unwrap_or_default();
// The offer stays declinable: the popup comes
// back so a retry or Later is one click away -
// unless the user already said Later to this
// version in an earlier session.
let dismissed =
crate::update_check::CheckCache::load(&croft_cache_dir())
.dismissed
.as_deref()
== Some(version.as_str());
if !dismissed {
self.update_toast = Some(UpdateToast {
version: version.clone(),
ready: false,
buttons: Vec::new(),
});
}
format!(
"croft {version} could not be built - see {} (still on v{})",
staged_install_log_path().display(),
env!("CARGO_PKG_VERSION")
)
}
UpdateSource::SelfInstall => {
self.self_install = None;
format!(
"croft rebuild failed - see {} (still on the old binary)",
self_install_log_path().display()
)
}
UpdateSource::Watch => String::from(
"Background croft update failed; staying on current version",
),
};
}
crate::update_watch::UpdateEvent::Ready => {
if staged {
self.staged_status = UpdateStatus::Ready;
} else {
self.update_status = UpdateStatus::Ready;
}
if !self.any_update_in_progress() {
self.update_spinner_start = None;
}
// Do NOT yank the user mid-work: surface a persistent
// "Update ready - F9 to relaunch" prompt in the status
// bar and let them pick the moment. The re-exec only
// fires when they press F9 (handle_key) or click
// Relaunch on the popup (#333).
self.status = String::from(
"Update ready - press F9 to relaunch croft (terminals will reset)",
);
if staged && let Some(install) = self.staged_install.as_ref() {
self.update_toast = Some(UpdateToast {
version: install.version.clone(),
ready: true,
buttons: Vec::new(),
});
}
}
}
}
changed
}
/// Current spinner glyph for an in-progress update (frame 0 when idle).
fn update_spinner_glyph(&self) -> &'static str {
match self.update_spinner_start {
Some(t) => update_spinner_frame(t.elapsed().as_millis()),
None => UPDATE_SPINNER_FRAMES[0],
}
}
/// Monotonic spinner phase the main loop watches to force a redraw each
/// time the glyph should advance. Stays `0` whenever no update is running,
/// so it never wakes the renderer outside an active update.
fn update_spinner_phase(&self) -> u128 {
match self.update_spinner_start {
Some(t) => t.elapsed().as_millis() / UPDATE_SPINNER_FRAME_MS,
None => 0,
}
}
/// Spinner glyph for an in-flight extension command (frame 0 when idle).
fn mcp_spinner_glyph(&self) -> &'static str {
match self.mcp_started {
Some(t) => update_spinner_frame(t.elapsed().as_millis()),
None => UPDATE_SPINNER_FRAMES[0],
}
}
/// Monotonic phase so the loop redraws each frame while an extension command
/// runs (`0` when idle, so it never wakes the renderer otherwise).
fn mcp_spinner_phase(&self) -> u128 {
match self.mcp_started {
Some(t) => t.elapsed().as_millis() / UPDATE_SPINNER_FRAME_MS,
None => 0,
}
}
pub fn capture_session_state(&self) -> crate::session_state::SessionState {
let mut tabs = Vec::new();
let mut active_tab = 0;
for (idx, ed) in self.editor.editors.iter().enumerate() {
// Only plain text file tabs survive a re-exec; diff / sheet /
// image tabs are derived views with no path to reopen from.
if ed.has_non_text_view() {
continue;
}
let Some(path) = ed.path.clone() else {
continue;
};
if idx == self.editor.active_index() {
active_tab = tabs.len();
}
let unsaved_text = if ed.dirty {
Some(ed.lines.join("\n"))
} else {
None
};
tabs.push(crate::session_state::OpenTabState {
path,
cursor_row: ed.cursor_row,
cursor_col: ed.cursor_col,
scroll: ed.scroll,
scroll_col: ed.scroll_col,
dirty: ed.dirty,
unsaved_text,
});
}
crate::session_state::SessionState {
workspace_root: self.workspace_root().to_path_buf(),
tabs,
active_tab,
sidebar_view: sidebar_view_label(self.sidebar_view).to_string(),
sidebar_width: self.sidebar_width,
terminal_height: self.terminal_height,
focus_editor: self.focus == Pane::Editor,
}
}
fn apply_session_state(&mut self, state: &crate::session_state::SessionState) {
for tab in &state.tabs {
if self.editor.open_pinned(&tab.path).is_err() {
continue;
}
let Some(ed) = self
.editor
.editors
.iter_mut()
.find(|e| e.path.as_deref() == Some(tab.path.as_path()))
else {
continue;
};
if tab.dirty
&& let Some(text) = &tab.unsaved_text
{
ed.lines = text.split('\n').map(str::to_string).collect();
if ed.lines.is_empty() {
ed.lines.push(String::new());
}
ed.dirty = true;
// Make the restored unsaved content eligible for auto save:
// due() keys on last_edit_at, which a fresh Editor lacks.
ed.last_edit_at = Some(std::time::Instant::now());
}
let max_row = ed.lines.len().saturating_sub(1);
ed.cursor_row = tab.cursor_row.min(max_row);
let max_col = ed.lines.get(ed.cursor_row).map_or(0, |l| l.chars().count());
ed.cursor_col = tab.cursor_col.min(max_col);
ed.scroll = tab.scroll;
ed.scroll_col = tab.scroll_col;
}
if state.active_tab < self.editor.tab_count() {
self.editor.select(state.active_tab);
}
if let Some(view) = sidebar_view_from_label(&state.sidebar_view) {
self.set_sidebar_view(view);
}
self.sidebar_width = state.sidebar_width;
self.terminal_height = state.terminal_height;
self.focus = if state.focus_editor {
Pane::Editor
} else {
Pane::Tree
};
}
fn tear_down_connect_auth(&mut self) {
if let Some(mut auth) = self.connect_auth.take() {
auth.cancel();
}
self.install_session = None;
self.pending_remote_launch_host = None;
self.pending_remote_launch_path = None;
}
pub fn handle_connect_dialog_key(&mut self, key: KeyEvent) {
let Some(dialog) = self.connect_dialog.as_mut() else {
return;
};
if dialog.phase.is_terminal() {
if matches!(key.code, KeyCode::Esc | KeyCode::Enter | KeyCode::Char(' ')) {
self.connect_dialog = None;
self.tear_down_connect_auth();
}
return;
}
let has_mod = key
.modifiers
.intersects(KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SUPER);
match key.code {
KeyCode::Esc => {
self.connect_dialog = None;
self.tear_down_connect_auth();
self.status = String::from("Connect cancelled");
}
KeyCode::Enter => {
if !dialog.phase.awaits_input() {
return;
}
if matches!(
dialog.phase,
crate::widgets::connect_dialog::DialogPhase::AwaitingFallbackConfirmation
) {
let payload = dialog.input_for_submit();
self.answer_install_fallback(&payload);
return;
}
let payload = dialog.input_for_submit();
dialog.submitted = true;
dialog.status_line = format!("Verifying credentials with {}", dialog.host);
dialog.clear_input();
if let Some(auth) = self.connect_auth.as_mut() {
auth.respond_password(&payload);
}
}
KeyCode::Backspace => dialog.pop_input_char(),
KeyCode::Char('l') | KeyCode::Char('L') if has_mod || !dialog.phase.awaits_input() => {
dialog.toggle_logs();
}
KeyCode::Char(c) if !has_mod => dialog.push_input_char(c),
_ => {}
}
}
pub fn handle_connect_dialog_click(&mut self, col: u16, row: u16) -> bool {
let Some(dialog) = self.connect_dialog.as_mut() else {
return false;
};
if rect_contains(dialog.toggle_logs_btn, col, row) {
dialog.toggle_logs();
return true;
}
if rect_contains(dialog.cancel_btn, col, row) {
self.connect_dialog = None;
self.tear_down_connect_auth();
self.status = String::from("Connect cancelled");
return true;
}
if rect_contains(dialog.submit_btn, col, row) && dialog.phase.awaits_input() {
if matches!(
dialog.phase,
crate::widgets::connect_dialog::DialogPhase::AwaitingFallbackConfirmation
) {
let payload = dialog.input_for_submit();
self.answer_install_fallback(&payload);
return true;
}
let payload = dialog.input_for_submit();
dialog.submitted = true;
dialog.status_line = format!(
"Sending {} chars to {}",
payload.chars().count(),
dialog.host
);
dialog.clear_input();
if let Some(auth) = self.connect_auth.as_mut() {
auth.respond_password(&payload);
}
return true;
}
rect_contains(dialog.last_area, col, row)
}
/// Resolve the connect dialog's slow-fallback question. "y"/"yes"
/// continues with the compile-on-remote install; anything else aborts
/// the connect so the user can run `croft setup-cross` and reconnect
/// for the seconds-fast prebuilt-binary path.
fn answer_install_fallback(&mut self, payload: &str) {
let proceed = matches!(payload.trim().to_ascii_lowercase().as_str(), "y" | "yes");
if proceed {
if let Some(dialog) = self.connect_dialog.as_mut() {
dialog.set_installing();
}
if let Some(session) = self.install_session.as_ref() {
session.respond_fallback(true);
}
return;
}
if let Some(session) = self.install_session.as_ref() {
session.respond_fallback(false);
}
self.connect_dialog = None;
self.tear_down_connect_auth();
self.status = String::from(
"Connect cancelled — run `croft setup-cross`, then reconnect for a fast install",
);
}
fn open_ssh_config_in_editor(&mut self) {
let Some(path) = crate::remote::primary_ssh_config_path() else {
self.status = String::from("Cannot find $HOME/.ssh/config");
return;
};
if let Some(parent) = path.parent() {
let _ = std::fs::create_dir_all(parent);
}
if !path.exists()
&& let Err(e) = std::fs::write(&path, "")
{
self.status = format!("Could not create {}: {e}", path.display());
return;
}
match self.editor.open_pinned(&path) {
Ok(()) => {
self.focus_pane(Pane::Editor);
self.status = format!("Opened {}", self.status_path(&path));
}
Err(e) => {
self.status = format!("Open {} failed: {e}", self.status_path(&path));
}
}
}
fn open_ssh_learn_more(&mut self) {
let url = "https://man.openbsd.org/ssh_config";
if self.drop_relay_active() {
if self.trust_local_browser {
self.request_remote_url_open(url.to_string());
self.status = String::from("Opening ssh_config(5) on your local Mac");
} else {
self.pending_local_open = Some(url.to_string());
}
return;
}
match open_url(url) {
Ok(()) => self.status = String::from("Opened ssh_config(5) docs"),
Err(e) => self.status = format!("Open link failed: {e}"),
}
}
fn refresh_remote_if_config_changed(&mut self) -> bool {
if self.sidebar_view != SidebarView::Remote {
return false;
}
if !self.remote.refresh_if_config_changed() {
return false;
}
self.status = String::from("Reloaded SSH remotes");
true
}
fn open_search_hit(&mut self, hit: &crate::widgets::search::SearchHit) {
match self.editor.open_preview(&hit.path) {
Ok(()) => {
self.sync_open_file_poll_mtime();
let row = hit
.line_no
.saturating_sub(1)
.min(self.editor.lines.len().saturating_sub(1));
self.editor.cursor_row = row;
// Drop the cursor at the first match column on this line so
// long lines (HTML with base64 blobs, minified JS) auto-scroll
// horizontally and the user lands on the match instead of the
// line's leftmost cell - which on a 200k-char line means
// never seeing the match without manual scrolling.
let needle = self.search.query.trim();
let opts = self.search.opts;
let line = self.editor.lines.get(row).cloned().unwrap_or_default();
// Locate the first match on the line: its start column and
// length (in chars). The length lets us mark this occurrence
// as the *active* match so the renderer paints it the stronger
// orange while sibling matches stay yellow - mirroring the
// Cmd+F path's `active_search_match` behaviour and VS Code's
// "current match" highlight.
let first_match = if needle.is_empty() {
None
} else {
let mut col = 0usize;
let mut found = None;
for (chunk, is_match) in
crate::widgets::search::split_for_highlight(&line, needle, opts)
{
if is_match {
found = Some((col, chunk.chars().count()));
break;
}
col = col.saturating_add(chunk.chars().count());
}
found
};
let match_col = first_match.map(|(c, _)| c).unwrap_or(0);
self.editor.active_search_match = first_match.map(|(c, len)| (row, c, len));
self.editor.cursor_col = match_col;
self.editor.scroll_col = 0;
self.editor.ensure_cursor_col_visible();
self.status = format!(
"Opened {} at line {}",
self.status_path(&hit.path),
hit.line_no
);
self.focus_pane(Pane::Editor);
}
Err(e) => {
self.status = format!("Open failed: {e}");
}
}
}
fn handle_tree_key(&mut self, key: KeyEvent) {
// Delete key (or Cmd+Backspace) trashes every selected node.
if is_delete_node_key(key) {
self.delete_selection();
return;
}
if is_editor_select_all_key(key) {
self.tree.select_all_visible();
return;
}
if is_editor_copy_key(key) {
self.copy_selection_to_explorer_clipboard(ExplorerClipMode::Copy);
return;
}
if is_editor_cut_key(key) {
self.copy_selection_to_explorer_clipboard(ExplorerClipMode::Cut);
return;
}
if is_clipboard_paste_key(key) {
self.paste_explorer_clipboard();
return;
}
if is_compare_key(key) {
self.toggle_compare_on_selected_file();
return;
}
if key.code == KeyCode::Esc {
if !self.tree.marked.is_empty() {
self.tree.clear_marks();
}
return;
}
let extending = key.modifiers.contains(KeyModifiers::SHIFT);
match key.code {
KeyCode::Up => {
if extending {
self.tree.move_up_extend();
} else {
self.tree.move_up();
}
}
KeyCode::Down => {
if extending {
self.tree.move_down_extend();
} else {
self.tree.move_down();
}
}
KeyCode::PageUp => {
if extending {
self.tree.page_up_extend(10);
} else {
self.tree.page_up(10);
}
}
KeyCode::PageDown => {
if extending {
self.tree.page_down_extend(10);
} else {
self.tree.page_down(10);
}
}
KeyCode::Home => {
if extending {
self.tree.home_extend();
} else {
self.tree.home();
}
}
KeyCode::End => {
if extending {
self.tree.end_extend();
} else {
self.tree.end();
}
}
KeyCode::Enter => {
if let Some(path) = self.tree.activate() {
// Ctrl+Enter is the primary "open in new tab" gesture — it
// reaches the app on every terminal. Cmd+Enter is also
// accepted but iTerm2 binds it to Toggle Fullscreen by
// default and never forwards it to the app unless the user
// has remapped that shortcut in iTerm Preferences →
// Profiles → Keys.
let in_new_tab = key.modifiers.intersects(
KeyModifiers::CONTROL | KeyModifiers::SUPER | KeyModifiers::META,
);
let result = if in_new_tab {
self.editor.open_pinned(&path)
} else {
self.editor.open_preview(&path)
};
match result {
Ok(()) => {
self.sync_open_file_poll_mtime();
self.status = self.editor.status.clone();
// Hand the keyboard to the editor, as VS Code does
// on Enter. Without this every navigation key the
// new tab defines is dead on arrival - arrows walk
// the file list while a PDF sits frozen on page 1
// and a spreadsheet never scrolls. Right-arrow
// (below) is the gesture that previews *without*
// leaving the tree.
self.focus_pane(Pane::Editor);
}
Err(e) => {
self.status = format!("Error: {e}");
}
}
}
}
KeyCode::Right => {
let selected_is_dir = self
.tree
.nodes
.get(self.tree.selected)
.is_some_and(|node| node.is_dir);
if selected_is_dir {
self.tree.expand_selected();
} else if let Some(path) = self.tree.activate() {
let result = self.editor.open_preview(&path);
match result {
Ok(()) => {
self.sync_open_file_poll_mtime();
self.status = self.editor.status.clone();
}
Err(e) => {
self.status = format!("Error: {e}");
}
}
}
}
KeyCode::Left => {
self.tree.collapse_selected();
}
KeyCode::Char(c)
if !key.modifiers.intersects(
KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SUPER,
) =>
{
self.apply_tree_typeahead(c, std::time::Instant::now());
}
_ => {}
}
}
/// Flip native modal (vim) editing on or off. Driven by the global Cmd+E
/// shortcut, so it can fire from any pane. Turning it off also dismisses
/// any lingering `/` `?` search-match highlights, since the modal layer is
/// the only place that clears them.
fn toggle_vim_mode(&mut self) {
// The Vim modal layer is a bundled, toggleable extension: when disabled
// in the Extensions panel, Cmd+E is inert (and any active session is
// force-ended so a disable can't strand the editor in modal mode).
if !self.is_extension_enabled("vim") {
if self.vim.enabled {
self.vim.toggle();
}
self.status = String::from("Vim extension is disabled");
return;
}
self.vim.toggle();
if self.vim.enabled {
self.status = String::from("vim mode on");
} else {
self.editor
.set_search_highlight(None, crate::widgets::search::SearchOpts::default());
self.status = String::from("vim mode off");
}
}
/// True when the active editor tab holds an editable text buffer (not a
/// read-only diff / spreadsheet / image preview), so text-editing chords
/// know whether to act.
fn editor_is_text(&self) -> bool {
!self.editor.has_non_text_view() && self.editor.markdown_preview.is_none()
}
/// Markdown: Toggle Preview — flips the active tab between source and the
/// rendered view; explains itself on a non-Markdown tab.
fn toggle_markdown_preview(&mut self) {
if self.editor.toggle_markdown_preview() {
self.status = if self.editor.markdown_preview.is_some() {
String::from("Markdown Preview")
} else {
String::from("Markdown source")
};
} else {
self.status = String::from("Markdown Preview needs a Markdown file");
}
}
fn handle_editor_key(&mut self, key: KeyEvent) {
// Inline find bar (Cmd+F / Ctrl+F) eats every key while open.
if self.editor_find.is_some() {
self.handle_editor_find_key(key);
return;
}
// F7 / Shift+F7 in a buffer with merge conflicts: jump between the
// blocks, the same chord the diff view uses for its hunks (VS Code's
// "Go to Next/Previous Conflict"). Only claimed while conflicts
// exist, so F7 keeps its normal meaning everywhere else.
if matches!(key.code, KeyCode::F(7)) && !self.editor.conflicts().is_empty() {
self.jump_conflict(key.modifiers.contains(KeyModifiers::SHIFT));
return;
}
// Merge editor (#253): F7 hops the tracked Result regions (the
// Result has no markers, so the arm above never claims it) and
// Alt+Up/Down scrolls the source panes together. Every other key
// falls through to the ordinary text path — the Result is a real
// buffer.
if self.editor.merge.is_some() {
if matches!(key.code, KeyCode::F(7)) {
self.merge_jump(key.modifiers.contains(KeyModifiers::SHIFT));
return;
}
if key.modifiers.contains(KeyModifiers::ALT)
&& matches!(key.code, KeyCode::Up | KeyCode::Down)
{
let delta = if key.code == KeyCode::Up { -3 } else { 3 };
if let Some(mv) = self.editor.merge.as_mut() {
mv.scroll_panes(delta);
}
return;
}
}
if is_editor_find_key(key) {
self.open_editor_find();
return;
}
if is_editor_replace_key(key) {
self.open_editor_replace();
return;
}
// `.http`/`.rest` (#370): Cmd/Ctrl+Enter sends the request under
// the caret, REST Client's own chord. Checked BEFORE the runnable
// fence (#353), which claims the same chord: this arm is scoped to
// request files, so the two compose — a `.http` file sends, and
// every other file falls through to the fence path with its
// meaning intact.
if matches!(key.code, KeyCode::Enter)
&& key
.modifiers
.intersects(KeyModifiers::SUPER | KeyModifiers::CONTROL)
&& self
.editor
.path
.as_deref()
.is_some_and(crate::http_file::is_http_file)
{
self.send_http_request_under_caret();
return;
}
// Runnable docs (#353): Cmd+Enter runs the fence under the caret.
if is_run_fence_key(key) && self.focus == Pane::Editor && self.run_fence_at_cursor() {
return;
}
// Markdown: Toggle Preview (Cmd/Ctrl+Shift+V, the VS Code default).
if is_markdown_preview_key(key) {
self.toggle_markdown_preview();
return;
}
// While the rendered preview is up the buffer is not visible, so
// navigation scrolls the preview and every other key is swallowed
// (no invisible edits). Cmd+Shift+V above flips back to the source.
if self.editor.markdown_preview.is_some() {
// Copy Path / Copy Relative Path first: their chords are
// Cmd+Opt+C and Cmd+Opt+Shift+C, which the looser copy-key
// predicate below also matches. They are meaningful while a
// preview is up (the file has a path either way), and this
// block returns unconditionally, so they must be dispatched
// here or they never run.
if is_copy_path_key(key) {
if let Some(path) = self.editor.path.clone() {
self.copy_path_to_clipboard(path);
}
return;
}
if is_copy_relative_path_key(key) {
if let Some(path) = self.editor.path.clone() {
self.copy_relative_path_to_clipboard(path);
}
return;
}
// Copy the rendered selection (#215): the preview swallows every
// other key, so without this branch Cmd+C here never copies.
if is_editor_copy_key(key) {
self.copy_editor_selection();
return;
}
if matches!(key.code, KeyCode::Esc)
&& let Some(md) = self.editor.markdown_preview.as_mut()
&& md.has_selection()
{
md.selection = None;
md.dragging = false;
return;
}
let page = self.editor.text_rows() as i32;
match key.code {
KeyCode::Up => {
self.editor.scroll_markdown_preview(-1);
}
KeyCode::Down => {
self.editor.scroll_markdown_preview(1);
}
KeyCode::PageUp => {
self.editor.scroll_markdown_preview(-page);
}
KeyCode::PageDown | KeyCode::Char(' ') => {
self.editor.scroll_markdown_preview(page);
}
KeyCode::Home => {
self.editor.scroll_markdown_preview(i16::MIN as i32);
}
// The render pass clamps to the wrapped height, so jumping
// far past the end lands exactly on the last page.
KeyCode::End => {
self.editor.scroll_markdown_preview(i16::MAX as i32);
}
_ => {}
}
return;
}
// Completion popup intercepts navigation / accept / dismiss keys
// before normal editor handling. Any other key dismisses the popup
// and falls through so the character lands in the buffer.
if self.handle_completion_popup_key(key) {
return;
}
// A snippet tab-stop session survives only plain typing, Backspace, and
// Tab (which advances it). Any other key ends the session so Tab returns
// to its normal indent role.
if self.editor.snippet_active() && !snippet_key_continues(key) {
self.editor.cancel_snippet();
}
// Esc closes the parameter-hints popup first (VS Code parity); a second
// Esc then falls through to clear the selection / collapse cursors.
if self.signature_help_popup.is_some() && matches!(key.code, KeyCode::Esc) {
self.dismiss_signature_help();
return;
}
// F4: focus the active file's next navigator comment box;
// Shift+F4 ignores the nearest one.
if matches!(key.code, KeyCode::F(4)) {
if key.modifiers == KeyModifiers::SHIFT {
self.ignore_focused_comment();
return;
}
if key.modifiers.is_empty() {
self.cycle_comment_box();
return;
}
}
if is_completion_trigger_key(key) {
self.trigger_completion();
return;
}
// Rename Symbol (F2) and Change All Occurrences (Cmd/Ctrl+F2) are only
// meaningful on a text buffer, so they sit above the read-only diff /
// sheet / image guards below.
if is_rename_symbol_key(key) {
self.start_rename_symbol();
return;
}
if is_change_all_occurrences_key(key) {
self.start_change_all_occurrences();
return;
}
if is_select_next_occurrence_key(key) {
self.start_select_next_occurrence();
return;
}
if is_delete_line_key(key) {
self.delete_current_line();
return;
}
// VS Code "Reveal in Finder" (Cmd+Opt+R) for the active file. Works on
// any tab backed by a real path (text, diff, sheet, image), so it sits
// above the text-only guards. Local-macOS only, matching the Explorer
// chord and the tab-menu entry; withheld on remote/headless sessions.
if !self.is_remote && cfg!(target_os = "macos") && is_reveal_in_finder_key(key) {
if let Some(path) = self.editor.path.clone() {
self.reveal_in_finder(path);
}
return;
}
// VS Code "Copy Path" (Cmd+Opt+C): copy the active file's absolute path
// to the clipboard. Works on any tab with a real path, local or remote;
// a blank/untitled buffer is a no-op (the keystroke is still swallowed).
if is_copy_path_key(key) {
if let Some(path) = self.editor.path.clone() {
self.copy_path_to_clipboard(path);
}
return;
}
// VS Code "Copy Relative Path" (Cmd+Opt+Shift+C): copy the active file's
// path relative to the workspace root. Same path-or-no-op rule as Copy
// Path; the keystroke is swallowed even on a blank/untitled buffer.
if is_copy_relative_path_key(key) {
if let Some(path) = self.editor.path.clone() {
self.copy_relative_path_to_clipboard(path);
}
return;
}
// VS Code "Toggle Line Comment" (Cmd+/ / Ctrl+/), "Toggle Block
// Comment" (Shift+Alt+A), and "View: Toggle Word Wrap" (Alt+Z). All
// act on a text buffer, so they no-op on read-only diff / sheet /
// image tabs (the keystroke is still swallowed). Each is also
// reachable from the Command Palette, which guarantees parity on
// terminals that don't deliver the Alt+letter chords.
if is_toggle_line_comment_key(key) {
if self.editor_is_text() {
self.editor.toggle_line_comment();
}
return;
}
if is_toggle_block_comment_key(key) {
if self.editor_is_text() {
self.editor.toggle_block_comment();
}
return;
}
if is_toggle_wrap_key(key) {
if self.editor_is_text() {
self.editor.toggle_wrap();
}
return;
}
// VS Code "Go to Bracket" (Cmd+Shift+\): jump the cursor to the
// matching bracket. Also reachable from the Command Palette.
if is_goto_bracket_key(key) {
if self.editor_is_text() {
self.editor.jump_to_matching_bracket();
}
return;
}
// VS Code "Select to Bracket" (Cmd+Opt+\): select the region between
// the matching brackets, including the brackets.
if is_select_to_bracket_key(key) {
if self.editor_is_text() {
self.editor.select_to_matching_bracket();
}
return;
}
// VS Code "Go Back" (Ctrl+-): the keyboard twin of the
// Ctrl+Shift+click chord, so navigation history is reachable
// without depending on the host terminal's mouse delivery (#31).
if is_navigate_forward_key(key) {
self.nav_forward();
return;
}
if is_navigate_back_key(key) {
self.nav_back();
return;
}
// VS Code "Transpose Characters around the Cursor" (Ctrl+T).
if is_transpose_key(key) {
if self.editor_is_text() {
self.editor.transpose_chars();
}
return;
}
// VS Code "Convert Indentation to Spaces" (Cmd+Opt+Shift+S).
if is_indentation_to_spaces_key(key) {
if self.editor_is_text() {
self.editor.indentation_to_spaces();
self.status = String::from("Converted indentation to spaces");
}
return;
}
// VS Code "Convert Indentation to Tabs" (Cmd+Opt+Shift+T).
if is_indentation_to_tabs_key(key) {
if self.editor_is_text() {
self.editor.indentation_to_tabs();
self.status = String::from("Converted indentation to tabs");
}
return;
}
// VS Code's `files.trimFinalNewlines`, as a command (Cmd+Opt+Shift+N).
if is_trim_final_newlines_key(key) {
if self.editor_is_text() && self.editor.trim_final_newlines() {
self.status = String::from("Trimmed final newlines");
}
return;
}
// Formerly palette-only editor commands, now each on a chord so none
// ships without an accelerator (croft tenet: everything has a shortcut).
if is_join_lines_key(key) {
if self.editor_is_text() {
self.editor.join_lines();
}
return;
}
if is_transform_upper_key(key) {
if self.editor_is_text() {
self.editor
.transform_selection_case(crate::widgets::editor::CaseTransform::Upper);
}
return;
}
if is_transform_lower_key(key) {
if self.editor_is_text() {
self.editor
.transform_selection_case(crate::widgets::editor::CaseTransform::Lower);
}
return;
}
if is_sort_lines_asc_key(key) {
if self.editor_is_text() {
self.editor.sort_lines(true);
}
return;
}
if is_sort_lines_desc_key(key) {
if self.editor_is_text() {
self.editor.sort_lines(false);
}
return;
}
if is_trim_trailing_whitespace_key(key) {
if self.editor_is_text() && self.editor.trim_trailing_whitespace() {
self.status = String::from("Trimmed trailing whitespace");
}
return;
}
// VS Code "Format Document" (Cmd+Opt+Shift+F): reformat the whole buffer
// through the language server. No-op on read-only diff / sheet / image.
if is_format_document_key(key) {
if self.editor_is_text() {
self.start_format_document();
}
return;
}
// VS Code "Quick Fix" (Cmd+. / Ctrl+.): code actions at the cursor.
if is_quick_fix_key(key) {
if self.editor_is_text() {
self.start_code_action();
}
return;
}
// Go to Definition (F12) / References (Shift+F12) / Type Definition
// (Ctrl+F12) / Implementations (Cmd+F12) / Declaration (Ctrl+Shift+F12),
// the VS Code F12-family bindings, also need a real text buffer. All are
// no-ops on read-only diff / sheet / image tabs; the keystroke is still
// swallowed so it never leaks into the buffer.
if is_peek_definition_key(key) {
if self.editor.diff.is_none()
&& self.editor.sheet.is_none()
&& self.editor.image.is_none()
{
self.peek_definition_at_cursor();
}
return;
}
if is_go_to_definition_key(key) {
if self.editor.diff.is_none()
&& self.editor.sheet.is_none()
&& self.editor.image.is_none()
{
self.request_definition_at_cursor();
}
return;
}
if is_go_to_declaration_key(key) {
if self.editor.diff.is_none()
&& self.editor.sheet.is_none()
&& self.editor.image.is_none()
{
self.request_declaration_at_cursor();
}
return;
}
if is_go_to_type_definition_key(key) {
if self.editor.diff.is_none()
&& self.editor.sheet.is_none()
&& self.editor.image.is_none()
{
self.request_type_definition_at_cursor();
}
return;
}
if is_go_to_implementation_key(key) {
if self.editor.diff.is_none()
&& self.editor.sheet.is_none()
&& self.editor.image.is_none()
{
self.request_implementation_at_cursor();
}
return;
}
if is_go_to_references_key(key) {
if self.editor.diff.is_none()
&& self.editor.sheet.is_none()
&& self.editor.image.is_none()
{
self.request_references_at_cursor();
}
return;
}
// While multi-cursor mode is live, printable typing / backspace /
// delete fan out to every caret and Esc collapses back to one cursor.
// Any other key collapses the carets and falls through to normal
// single-cursor handling (e.g. an arrow moves just the primary).
if self.editor.has_multi_cursor() {
match key.code {
KeyCode::Esc => {
self.editor.collapse_carets();
self.status = String::from("Cursors collapsed");
return;
}
KeyCode::Backspace => {
self.editor.multi_backspace();
return;
}
KeyCode::Delete => {
self.editor.multi_delete_forward();
return;
}
KeyCode::Char(c)
if !key.modifiers.contains(KeyModifiers::CONTROL)
&& !key.modifiers.contains(KeyModifiers::ALT)
&& !key.modifiers.contains(KeyModifiers::SUPER) =>
{
self.editor.multi_insert_char(c);
return;
}
_ => self.editor.collapse_carets(),
}
}
// Close-tab (Cmd/Ctrl+W) applies to every tab type, so it sits above
// the read-only diff / sheet / image guards below. Those guards each
// short-circuit to a view-specific handler that has no close branch,
// so without this hoist Cmd+W is silently swallowed on a diff, sheet,
// or image tab and the tab can never be closed from the keyboard.
if is_close_tab_key(key) {
self.record_closed_tab_at(self.editor.active_index());
if self.editor.close_active() {
self.sync_open_file_poll_mtime();
self.status = String::from("Closed tab");
// Closing the focused group's last tab while split closes
// the group: collapse back to the surviving column.
self.collapse_split_if_empty();
} else {
self.status = String::from("Cannot close last tab");
}
return;
}
if self.editor.diff.is_some() {
self.handle_diff_key(key);
return;
}
if self.editor.sheet.is_some() {
self.handle_sheet_key(key);
return;
}
if self.editor.hex.is_some() {
self.handle_hex_key(key);
return;
}
if self.editor.archive.is_some() {
self.handle_archive_key(key);
return;
}
// Image preview tabs are read-only. PDF tabs page with every
// navigation key (arrows, PageUp/PageDown, Space, Home/End) and with
// the wheel; everything else is swallowed.
if self.editor.image.is_some() {
match key.code {
KeyCode::Right | KeyCode::PageDown | KeyCode::Down | KeyCode::Char(' ') => {
self.step_pdf_page(1);
}
KeyCode::Left | KeyCode::PageUp | KeyCode::Up => {
self.step_pdf_page(-1);
}
KeyCode::Home => self.jump_pdf_page(1),
KeyCode::End => self.jump_pdf_page(u32::MAX),
_ => {}
}
return;
}
// When modal editing is on it fully owns the editor pane and the
// always-on `editor_vim_chord` convenience layer is bypassed. A
// PassThrough means the key is not claimed by vim (Insert-mode typing,
// or any Cmd/Ctrl shortcut in Normal mode) and falls through to the
// editor's normal handling below.
if self.vim.enabled {
match self.vim.on_key(key) {
crate::vim::VimKeyResult::Consumed(actions) => {
for action in actions {
self.apply_vim_action(action);
}
return;
}
crate::vim::VimKeyResult::PassThrough => {}
}
} else if self.handle_editor_vim_chord(key) {
return;
}
if is_editor_line_home_key(key) {
self.editor.clear_selection();
self.editor.home_line();
return;
}
if is_editor_line_end_key(key) {
self.editor.clear_selection();
self.editor.end_line();
return;
}
if is_editor_kill_to_eol_key(key) {
let killed = self.editor.kill_to_eol();
if !killed.is_empty() {
copy_to_clipboard(&killed);
self.status = format!("Killed {} chars", killed.chars().count());
}
return;
}
if is_editor_kill_to_bol_key(key) {
let killed = self.editor.kill_to_bol();
if !killed.is_empty() {
copy_to_clipboard(&killed);
self.status = format!("Killed {} chars", killed.chars().count());
}
return;
}
if is_editor_open_line_below_key(key) {
self.editor.open_line_below();
self.status = String::from("Opened line below");
return;
}
if is_editor_open_line_above_key(key) {
self.editor.open_line_above();
self.status = String::from("Opened line above");
return;
}
// Clipboard gestures take precedence over text input. They never
// conflict with normal typing (Ctrl/Cmd + C/X/A) so the order is
// safe even when the user is in the middle of editing.
if is_editor_copy_key(key) {
self.copy_editor_selection();
return;
}
if is_editor_cut_key(key) {
self.cut_editor_selection();
return;
}
if is_editor_paste_key(key) {
let text = (self.clipboard_reader)();
self.paste_clipboard_into_editor(text.as_deref());
return;
}
if is_editor_select_all_key(key) {
self.editor.select_all();
self.status = format!(
"Selected {} chars",
self.editor.selection_text().chars().count()
);
return;
}
if is_editor_undo_key(key) {
if self.editor.undo() {
self.status = String::from("Undo");
} else {
self.status = String::from("Nothing to undo");
}
return;
}
if is_editor_redo_key(key) {
if self.editor.redo() {
self.status = String::from("Redo");
} else {
self.status = String::from("Nothing to redo");
}
return;
}
if let Some(idx) = jump_to_tab_index(key) {
if self.editor.select(idx) {
self.sync_open_file_poll_mtime();
self.status = format!("Tab {}", idx + 1);
}
return;
}
if matches!(key.code, KeyCode::Esc) && self.editor.selection.is_some() {
self.editor.clear_selection();
return;
}
// Shift+<motion> extends selection in the motion's direction.
let shift = key.modifiers.contains(KeyModifiers::SHIFT);
let is_motion = matches!(
key.code,
KeyCode::Up
| KeyCode::Down
| KeyCode::Left
| KeyCode::Right
| KeyCode::Home
| KeyCode::End
| KeyCode::PageUp
| KeyCode::PageDown
);
let alt = key.modifiers.contains(KeyModifiers::ALT);
// The command modifier: Cmd (SUPER) on macOS, Ctrl on Linux / Termux.
let cmd = key.modifiers.contains(KeyModifiers::SUPER)
|| key.modifiers.contains(KeyModifiers::CONTROL);
// VS Code "Add Cursor Above/Below" (Cmd+Opt+Up / Cmd+Opt+Down). Must
// come before the plain-Alt move-line check so the cmd+alt combo is
// routed here, not there.
if cmd && alt && matches!(key.code, KeyCode::Up | KeyCode::Down) {
match key.code {
KeyCode::Up => self.editor.add_cursor_above(),
KeyCode::Down => self.editor.add_cursor_below(),
_ => unreachable!(),
}
return;
}
if shift && alt && matches!(key.code, KeyCode::Up | KeyCode::Down) {
match key.code {
KeyCode::Up => self.editor.duplicate_lines_up(),
KeyCode::Down => self.editor.duplicate_lines_down(),
_ => unreachable!(),
}
return;
}
// Expand / Shrink Selection (#254): Shift+Alt+Right/Left, VS Code's
// smart-select chords. This deliberately claims what used to be
// word-wise selection extension — the same collision VS Code
// resolves the same way.
if shift && alt && !cmd && matches!(key.code, KeyCode::Left | KeyCode::Right) {
if key.code == KeyCode::Right {
self.expand_selection();
} else {
self.shrink_selection();
}
return;
}
// VS Code "Move Line Up/Down" (Alt+Up / Alt+Down, no Shift, no Cmd).
if alt && !shift && !cmd && matches!(key.code, KeyCode::Up | KeyCode::Down) {
match key.code {
KeyCode::Up => self.editor.move_lines_up(),
KeyCode::Down => self.editor.move_lines_down(),
_ => unreachable!(),
}
return;
}
if is_motion && shift {
if self.editor.selection.is_none() {
self.editor.start_selection_at_cursor();
}
match key.code {
KeyCode::Up => self.editor.move_up(),
KeyCode::Down => self.editor.move_down(),
KeyCode::Left if alt => self.editor.move_word_left(),
KeyCode::Right if alt => self.editor.move_word_right(),
KeyCode::Left => self.editor.move_left(),
KeyCode::Right => self.editor.move_right(),
KeyCode::Home => self.editor.home_line(),
KeyCode::End => self.editor.end_line(),
KeyCode::PageUp => self.editor.page_up_one_screen(),
KeyCode::PageDown => self.editor.page_down_one_screen(),
_ => {}
}
self.editor.extend_selection_to_cursor();
return;
}
if is_motion {
// Plain motion clears any prior selection (VS Code / Sublime
// convention: arrows without Shift collapse the selection).
self.editor.clear_selection();
}
match key.code {
KeyCode::Up => self.editor.move_up(),
KeyCode::Down => self.editor.move_down(),
KeyCode::Left if alt => self.editor.move_word_left(),
KeyCode::Right if alt => self.editor.move_word_right(),
KeyCode::Left => self.editor.move_left(),
KeyCode::Right => self.editor.move_right(),
KeyCode::PageUp => self.editor.page_up_one_screen(),
KeyCode::PageDown => self.editor.page_down_one_screen(),
KeyCode::Home => self.editor.home_line(),
KeyCode::End => self.editor.end_line(),
KeyCode::Backspace => self.editor.backspace(),
KeyCode::Delete => self.editor.delete_forward(),
KeyCode::Enter => self.editor.insert_newline(),
// Tab advances a live snippet, else expands a snippet whose prefix
// was just typed, else indents (whole block for a multi-line
// selection, otherwise to the next tab stop).
KeyCode::Tab => self.handle_editor_tab(),
// Shift+Tab arrives as BackTab. Outdent the current line, or every
// line a selection touches, mirroring VS Code's Shift+Tab.
KeyCode::BackTab => self.editor.dedent_lines(),
KeyCode::Char(c)
if !key.modifiers.contains(KeyModifiers::CONTROL)
&& !key.modifiers.contains(KeyModifiers::ALT)
&& !key.modifiers.contains(KeyModifiers::SUPER) =>
{
self.editor.insert_char(c);
// `.` is the canonical LSP trigger character for member
// access in Python / TS / Rust. Fire a completion request
// immediately so the popup pops without a Ctrl+Space.
// The popup's fallthrough already dismissed any prior
// popup when this char arrived, so the new request just
// populates a fresh popup when the response lands.
if c == '.' {
self.trigger_completion();
}
// Parameter hints: `(` / `,` open or advance a call. Closing
// (typing `)`, moving away, deleting) is handled by the tick's
// re-query, which also covers nested calls.
if is_signature_help_trigger(c) {
self.trigger_signature_help();
}
}
_ => {}
}
}
/// Vim-style chord layer for the editor: `cmd+gg` jumps to top, `cmd+G`
/// jumps to bottom, `cmd+yy` yanks a line. Counts go between the chord
/// start and the completion key (`cmd+g 12 g` jumps to line 12). There is
/// no `cmd+dd`: `cmd+d` is Add Selection to Next Match, and Delete Line
/// moved to `cmd+shift+k`.
/// Returns true when the key was consumed; false means the caller
/// should continue with normal editor handling.
fn handle_editor_vim_chord(&mut self, key: KeyEvent) -> bool {
if is_vim_goto_bottom(key) {
let count = self.editor_vim_chord.count;
self.editor_vim_chord.reset();
if count > 0 {
self.editor.goto_line(count);
self.status = format!("Line {count}");
} else {
self.editor.goto_bottom();
self.status = String::from("Bottom of file");
}
return true;
}
let count_pending = self.editor_vim_chord.count > 0;
let op_pending = self.editor_vim_chord.op != VimOp::None;
if (op_pending || count_pending)
&& let Some(d) = chord_digit_value(key)
{
self.editor_vim_chord.count = self
.editor_vim_chord
.count
.saturating_mul(10)
.saturating_add(d);
let op = match self.editor_vim_chord.op {
VimOp::G => 'g',
VimOp::Y => 'y',
VimOp::None => ' ',
};
self.status = chord_status_text(op, self.editor_vim_chord.count);
return true;
}
if !op_pending {
if is_vim_chord_g(key) {
self.editor_vim_chord.op = VimOp::G;
self.status = chord_status_text('g', self.editor_vim_chord.count);
return true;
}
if is_vim_chord_y(key) {
self.editor_vim_chord.op = VimOp::Y;
self.status = chord_status_text('y', self.editor_vim_chord.count);
return true;
}
if !count_pending {
if let Some(d) = cmd_only_digit_value(key) {
self.editor_vim_chord.count = d;
self.status = chord_status_text(' ', self.editor_vim_chord.count);
return true;
}
return false;
}
self.editor_vim_chord.reset();
self.status = String::from("Chord cancelled");
return false;
}
let completes = match self.editor_vim_chord.op {
VimOp::G => is_plain_letter(key, 'g') || is_vim_chord_g(key),
VimOp::Y => is_plain_letter(key, 'y') || is_vim_chord_y(key),
VimOp::None => false,
};
if completes {
let count = self.editor_vim_chord.count;
match self.editor_vim_chord.op {
VimOp::G => {
if count > 0 {
self.editor.goto_line(count);
self.status = format!("Line {count}");
} else {
self.editor.goto_top();
self.status = String::from("Top of file");
}
}
VimOp::Y => {
let n = count.max(1);
let yanked = self.editor.yank_lines(n);
if !yanked.is_empty() {
copy_to_clipboard(&yanked);
}
self.status = format!("Yanked {n} {}", if n == 1 { "line" } else { "lines" });
}
VimOp::None => {}
}
self.editor_vim_chord.reset();
return true;
}
self.editor_vim_chord.reset();
self.status = String::from("Chord cancelled");
false
}
/// Apply one resolved vim intent to the editor. The vim state machine has
/// already advanced its own mode; this only mutates the buffer/cursor.
fn apply_vim_action(&mut self, action: crate::vim::VimAction) {
use crate::vim::{Target, VimAction};
match action {
VimAction::Move(motion, count) => {
self.vim_apply_motion(motion, count);
self.vim_sync_visual_selection();
}
VimAction::Operate { op, target, count } => match target {
Target::Lines => self.vim_operate_lines(op, self.editor.cursor_row, count),
Target::Object(obj) => self.vim_operate_textobject(op, obj),
Target::Motion(m) => self.vim_operate_motion(op, m, count),
},
VimAction::DeleteChar(count) => self.vim_delete_chars(count),
VimAction::Insert(at) => self.vim_enter_insert(at),
VimAction::Paste(at, count) => self.vim_paste(at, count),
VimAction::Undo => {
self.status = if self.editor.undo() {
String::from("Undo")
} else {
String::from("Nothing to undo")
};
}
VimAction::Redo => {
self.status = if self.editor.redo() {
String::from("Redo")
} else {
String::from("Nothing to redo")
};
}
VimAction::EnterVisual { line } => {
self.editor.break_undo_coalescing();
self.vim_visual_line = line;
self.vim
.set_visual_anchor(self.editor.cursor_row, self.editor.cursor_col);
self.editor.start_selection_at_cursor();
self.status = String::from(if line {
"-- VISUAL LINE --"
} else {
"-- VISUAL --"
});
}
VimAction::ExitVisual => {
self.editor.clear_selection();
self.vim_visual_line = false;
self.status.clear();
}
VimAction::VisualOperate(op) => self.vim_visual_operate(op),
VimAction::ExitInsert => {
self.editor.break_undo_coalescing();
if self.editor.cursor_col > 0 {
self.editor.cursor_col -= 1;
}
self.status.clear();
}
VimAction::RunEx(cmd) => self.vim_run_ex(&cmd),
VimAction::Search(dir, term) => self.vim_search(dir, &term),
VimAction::ClearPending => {
self.editor.clear_selection();
self.vim_visual_line = false;
}
// `q{a-z}` starts, a bare `q` stops. The vim machine reports the
// gesture; the recording itself lives on App so a macro recorded
// in vim mode replays from the palette and vice versa (#255).
// Recording control is inert during replay. `macro_replaying`
// gates capture, not dispatch, so without this a replayed `q`
// would reach here and leave the user silently recording after
// the replay returned — the class of command the issue's
// exclusion list exists for.
VimAction::MacroRecord(_) | VimAction::MacroReplay(..) if self.macro_replaying => {}
VimAction::MacroRecord(register) => match register {
// A register letter STARTS; a bare `q` stops. The app owns
// the recording state, so vim never has to track it.
Some(r) if self.macro_recording.is_none() => self.start_macro_recording(Some(r)),
_ => self.stop_macro_recording(),
},
VimAction::MacroReplay(register, count) => match register {
Some(r) => self.replay_macro_register(r, count),
None => self.replay_last_macro(count),
},
}
}
fn vim_line_len(&self, row: usize) -> usize {
self.editor
.lines
.get(row)
.map(|l| l.chars().count())
.unwrap_or(0)
}
fn vim_first_non_blank(&self, row: usize) -> usize {
self.editor
.lines
.get(row)
.map(|l| l.chars().take_while(|c| c.is_whitespace()).count())
.unwrap_or(0)
}
fn vim_apply_motion(&mut self, motion: crate::vim::Motion, count: usize) {
use crate::vim::Motion;
let n = count.max(1);
match motion {
Motion::Left => {
self.editor.cursor_col = self.editor.cursor_col.saturating_sub(n);
}
Motion::Right => {
let len = self.vim_line_len(self.editor.cursor_row);
self.editor.cursor_col = (self.editor.cursor_col + n).min(len);
}
Motion::Up => {
for _ in 0..n {
self.editor.move_up();
}
}
Motion::Down => {
for _ in 0..n {
self.editor.move_down();
}
}
Motion::WordForward => {
for _ in 0..n {
self.vim_word_forward();
}
}
Motion::WordBackward => {
for _ in 0..n {
self.vim_word_backward();
}
}
Motion::WordEnd => {
for _ in 0..n {
self.vim_word_end();
}
}
Motion::LineStart => self.editor.cursor_col = 0,
Motion::FirstNonBlank => {
self.editor.cursor_col = self.vim_first_non_blank(self.editor.cursor_row);
}
Motion::LineEnd => {
self.editor.cursor_col = self.vim_line_len(self.editor.cursor_row);
}
Motion::FileStart => self.editor.goto_top(),
Motion::FileEnd => self.editor.goto_bottom(),
Motion::GotoLine(line) => self.editor.goto_line(line),
Motion::Find(kind, ch) => {
self.vim_last_find = Some((kind, ch));
self.vim_find_char(kind, ch, n);
}
Motion::RepeatFind => {
if let Some((kind, ch)) = self.vim_last_find {
self.vim_find_char(kind, ch, n);
}
}
Motion::RepeatFindRev => {
if let Some((kind, ch)) = self.vim_last_find {
self.vim_find_char(reverse_find(kind), ch, n);
}
}
}
self.editor.ensure_cursor_col_visible();
}
fn vim_find_char(&mut self, kind: crate::vim::FindKind, ch: char, count: usize) {
use crate::vim::FindKind;
let row = self.editor.cursor_row;
let Some(line) = self.editor.lines.get(row) else {
return;
};
let chars: Vec<char> = line.chars().collect();
let mut col = self.editor.cursor_col;
for _ in 0..count.max(1) {
match kind {
FindKind::CharForward => match (col + 1..chars.len()).find(|&i| chars[i] == ch) {
Some(idx) => col = idx,
None => return,
},
FindKind::TillForward => match (col + 1..chars.len()).find(|&i| chars[i] == ch) {
Some(idx) if idx > 0 => col = idx - 1,
_ => return,
},
FindKind::CharBackward => match (0..col).rev().find(|&i| chars[i] == ch) {
Some(idx) => col = idx,
None => return,
},
FindKind::TillBackward => match (0..col).rev().find(|&i| chars[i] == ch) {
Some(idx) => col = idx + 1,
None => return,
},
}
}
self.editor.cursor_col = col;
}
/// Character class for vim word motions: 0 = blank (or past line end),
/// 1 = keyword (alphanumeric/underscore), 2 = punctuation. A `w`/`b`/`e`
/// word is a maximal run of one non-blank class.
fn vim_class_at(&self, row: usize, col: usize) -> u8 {
match self.editor.lines.get(row).and_then(|l| l.chars().nth(col)) {
None => 0,
Some(c) if c.is_whitespace() => 0,
Some(c) if c.is_alphanumeric() || c == '_' => 1,
Some(_) => 2,
}
}
fn vim_next_pos(&self, row: usize, col: usize) -> Option<(usize, usize)> {
if col < self.vim_line_len(row) {
Some((row, col + 1))
} else if row + 1 < self.editor.lines.len() {
Some((row + 1, 0))
} else {
None
}
}
fn vim_prev_pos(&self, row: usize, col: usize) -> Option<(usize, usize)> {
if col > 0 {
Some((row, col - 1))
} else if row > 0 {
Some((row - 1, self.vim_line_len(row - 1)))
} else {
None
}
}
fn vim_word_forward(&mut self) {
let mut row = self.editor.cursor_row;
let mut col = self.editor.cursor_col;
let start = self.vim_class_at(row, col);
if start != 0 {
while self.vim_class_at(row, col) == start {
match self.vim_next_pos(row, col) {
Some((r, c)) => {
row = r;
col = c;
}
None => {
self.editor.cursor_row = row;
self.editor.cursor_col = col;
return;
}
}
}
}
while self.vim_class_at(row, col) == 0 {
match self.vim_next_pos(row, col) {
Some((r, c)) => {
row = r;
col = c;
}
None => break,
}
}
self.editor.cursor_row = row;
self.editor.cursor_col = col;
}
fn vim_word_backward(&mut self) {
let mut row = self.editor.cursor_row;
let mut col = self.editor.cursor_col;
let Some((r, c)) = self.vim_prev_pos(row, col) else {
return;
};
row = r;
col = c;
while self.vim_class_at(row, col) == 0 {
match self.vim_prev_pos(row, col) {
Some((r, c)) => {
row = r;
col = c;
}
None => {
self.editor.cursor_row = row;
self.editor.cursor_col = col;
return;
}
}
}
let class = self.vim_class_at(row, col);
while let Some((pr, pc)) = self.vim_prev_pos(row, col) {
if self.vim_class_at(pr, pc) != class {
break;
}
row = pr;
col = pc;
}
self.editor.cursor_row = row;
self.editor.cursor_col = col;
}
fn vim_word_end(&mut self) {
let mut row = self.editor.cursor_row;
let mut col = self.editor.cursor_col;
let Some((r, c)) = self.vim_next_pos(row, col) else {
return;
};
row = r;
col = c;
while self.vim_class_at(row, col) == 0 {
match self.vim_next_pos(row, col) {
Some((r, c)) => {
row = r;
col = c;
}
None => {
self.editor.cursor_row = row;
self.editor.cursor_col = col;
return;
}
}
}
let class = self.vim_class_at(row, col);
while let Some((nr, nc)) = self.vim_next_pos(row, col) {
if self.vim_class_at(nr, nc) != class {
break;
}
row = nr;
col = nc;
}
self.editor.cursor_row = row;
self.editor.cursor_col = col;
}
fn vim_operate_lines(&mut self, op: crate::vim::Op, start_row: usize, count: usize) {
use crate::vim::Op;
self.editor.cursor_row = start_row.min(self.editor.lines.len().saturating_sub(1));
let n = count.max(1);
match op {
Op::Delete => {
let text = self.editor.delete_lines(n);
copy_to_clipboard(&text);
self.status = format!("Deleted {n} line(s)");
}
Op::Yank => {
let text = self.editor.yank_lines(n);
copy_to_clipboard(&text);
self.status = format!("Yanked {n} line(s)");
}
Op::Change => {
let text = self.editor.delete_lines(n);
copy_to_clipboard(&text);
self.editor.open_line_above();
self.vim.enter_insert_mode();
self.status = String::from("-- INSERT --");
}
}
}
fn vim_operate_motion(&mut self, op: crate::vim::Op, motion: crate::vim::Motion, count: usize) {
if vim_motion_is_linewise(motion) {
let (first, last) = self.vim_line_range_for_motion(motion, count);
self.vim_operate_lines(op, first, last + 1 - first);
return;
}
let start = (self.editor.cursor_row, self.editor.cursor_col);
self.vim_apply_motion(motion, count);
let end = (self.editor.cursor_row, self.editor.cursor_col);
let (lo, hi) = if start <= end {
(start, end)
} else {
(end, start)
};
// Forward-inclusive motions (f/t/e) cover the char they land on.
let head = if start <= end && vim_motion_is_forward_inclusive(motion) {
let len = self.vim_line_len(hi.0);
(hi.0, (hi.1 + 1).min(len))
} else {
hi
};
self.editor.selection = Some(crate::widgets::editor::EditorSelection { anchor: lo, head });
self.vim_apply_operator_to_selection(op, lo);
}
fn vim_operate_textobject(&mut self, op: crate::vim::Op, obj: crate::vim::TextObject) {
use crate::vim::TextObject;
let row = self.editor.cursor_row;
let Some((start, mut end)) = self.editor.word_at(row, self.editor.cursor_col) else {
return;
};
if obj == TextObject::AWord
&& let Some(line) = self.editor.lines.get(row)
{
let chars: Vec<char> = line.chars().collect();
while end < chars.len() && chars[end].is_whitespace() {
end += 1;
}
}
self.editor.selection = Some(crate::widgets::editor::EditorSelection {
anchor: (row, start),
head: (row, end),
});
self.vim_apply_operator_to_selection(op, (row, start));
}
/// Delete / yank / change whatever the editor selection currently spans,
/// leaving the cursor at `start` and entering Insert mode for a change.
fn vim_apply_operator_to_selection(&mut self, op: crate::vim::Op, start: (usize, usize)) {
use crate::vim::Op;
let text = self.editor.selection_text();
copy_to_clipboard(&text);
match op {
Op::Yank => {
self.editor.clear_selection();
self.editor.cursor_row = start.0;
self.editor.cursor_col = start.1;
}
Op::Delete => {
self.editor.delete_selection();
}
Op::Change => {
self.editor.delete_selection();
self.vim.enter_insert_mode();
self.status = String::from("-- INSERT --");
}
}
}
fn vim_line_range_for_motion(
&self,
motion: crate::vim::Motion,
count: usize,
) -> (usize, usize) {
use crate::vim::Motion;
let row = self.editor.cursor_row;
let last = self.editor.lines.len().saturating_sub(1);
let n = count.max(1);
match motion {
Motion::Down => (row, (row + n).min(last)),
Motion::Up => (row.saturating_sub(n), row),
Motion::FileStart => (0, row),
Motion::FileEnd => (row, last),
Motion::GotoLine(line) => {
let target = line.saturating_sub(1).min(last);
if target >= row {
(row, target)
} else {
(target, row)
}
}
_ => (row, row),
}
}
fn vim_delete_chars(&mut self, count: usize) {
let row = self.editor.cursor_row;
let Some(line) = self.editor.lines.get(row) else {
return;
};
let chars: Vec<char> = line.chars().collect();
let col = self.editor.cursor_col;
let end = (col + count.max(1)).min(chars.len());
if col < end {
let deleted: String = chars[col..end].iter().collect();
copy_to_clipboard(&deleted);
for _ in col..end {
self.editor.delete_forward();
}
}
}
fn vim_enter_insert(&mut self, at: crate::vim::InsertAt) {
use crate::vim::InsertAt;
let row = self.editor.cursor_row;
match at {
InsertAt::Cursor => {}
InsertAt::After => {
let len = self.vim_line_len(row);
if self.editor.cursor_col < len {
self.editor.cursor_col += 1;
}
}
InsertAt::LineStart => self.editor.cursor_col = self.vim_first_non_blank(row),
InsertAt::LineEnd => self.editor.cursor_col = self.vim_line_len(row),
InsertAt::Below => self.editor.open_line_below(),
InsertAt::Above => self.editor.open_line_above(),
}
self.editor.break_undo_coalescing();
self.status = String::from("-- INSERT --");
}
fn vim_paste(&mut self, at: crate::vim::PasteAt, count: usize) {
use crate::vim::PasteAt;
let Some(text) = (self.clipboard_reader)() else {
return;
};
if text.is_empty() {
return;
}
let n = count.max(1);
if let Some(body) = text.strip_suffix('\n') {
// Linewise paste: the yank ended on a newline, so it lands on
// fresh lines rather than inside the current one.
let block = std::iter::repeat_n(body, n).collect::<Vec<_>>().join("\n");
match at {
PasteAt::After => {
self.editor.cursor_col = self.vim_line_len(self.editor.cursor_row);
self.editor.insert_str(&format!("\n{block}"));
}
PasteAt::Before => {
self.editor.cursor_col = 0;
self.editor.insert_str(&format!("{block}\n"));
}
}
} else {
let block = text.repeat(n);
if at == PasteAt::After {
let len = self.vim_line_len(self.editor.cursor_row);
if self.editor.cursor_col < len {
self.editor.cursor_col += 1;
}
}
self.editor.insert_str(&block);
}
self.status = String::from("Pasted");
}
fn vim_visual_operate(&mut self, op: crate::vim::Op) {
use crate::vim::Op;
let Some(sel) = self.editor.selection else {
return;
};
if self.vim_visual_line {
let ((sr, _), (er, _)) = sel.normalised();
self.vim_operate_lines(op, sr, er + 1 - sr);
self.vim_visual_line = false;
return;
}
// Charwise visual is inclusive of the cell under the cursor, so extend
// the high end one char before operating.
let ((sr, sc), (er, ec)) = sel.normalised();
let len = self.vim_line_len(er);
self.editor.selection = Some(crate::widgets::editor::EditorSelection {
anchor: (sr, sc),
head: (er, (ec + 1).min(len)),
});
self.vim_apply_operator_to_selection(op, (sr, sc));
self.vim_visual_line = false;
if !matches!(op, Op::Change) {
self.status.clear();
}
}
fn vim_run_ex(&mut self, cmd: &str) {
let cmd = cmd.trim();
if let Ok(line) = cmd.parse::<usize>() {
self.editor.goto_line(line);
return;
}
match cmd {
"w" | "write" => self.save(),
"q" | "q!" | "quit" => {
self.record_closed_tab_at(self.editor.active_index());
if self.editor.close_active() {
self.sync_open_file_poll_mtime();
self.status = String::from("Closed tab");
} else {
self.quit = true;
}
}
"wq" | "x" | "wq!" => {
self.save();
self.record_closed_tab_at(self.editor.active_index());
if !self.editor.close_active() {
self.quit = true;
}
}
"qa" | "qa!" | "quitall" => self.quit = true,
other => self.status = format!("Unknown command: {other}"),
}
}
fn vim_search(&mut self, dir: crate::vim::SearchDir, term: &str) {
self.editor.set_search_highlight(
Some(term.to_string()),
crate::widgets::search::SearchOpts::default(),
);
match self.vim_find_match(dir, term) {
Some((row, col)) => {
self.editor.cursor_row = row;
self.editor.cursor_col = col;
self.editor.ensure_cursor_col_visible();
// Record the hit the cursor jumped to so the renderer paints it
// in the distinct active colour (orange) while the remaining
// matches keep the regular yellow. Literal search, so the match
// is exactly `term` long in characters.
self.editor.active_search_match = Some((row, col, term.chars().count()));
self.status = match dir {
crate::vim::SearchDir::Forward => format!("/{term}"),
crate::vim::SearchDir::Backward => format!("?{term}"),
};
}
None => {
self.editor.active_search_match = None;
self.status = format!("Pattern not found: {term}");
}
}
}
fn vim_find_match(&self, dir: crate::vim::SearchDir, term: &str) -> Option<(usize, usize)> {
use crate::vim::SearchDir;
let lines = &self.editor.lines;
if term.is_empty() || lines.is_empty() {
return None;
}
let (cr, cc) = (self.editor.cursor_row, self.editor.cursor_col);
let total = lines.len();
match dir {
SearchDir::Forward => {
for off in 0..=total {
let row = (cr + off) % total;
let from = if off == 0 { cc + 1 } else { 0 };
if let Some(col) = find_char_index(&lines[row], term, from) {
return Some((row, col));
}
}
None
}
SearchDir::Backward => {
for off in 0..=total {
let row = (cr + total - off) % total;
let limit = if off == 0 { cc } else { usize::MAX };
if let Some(col) = rfind_char_index(&lines[row], term, limit) {
return Some((row, col));
}
}
None
}
}
}
fn vim_sync_visual_selection(&mut self) {
if !matches!(
self.vim.mode(),
crate::vim::VimMode::Visual | crate::vim::VimMode::VisualLine
) {
return;
}
if let Some(anchor) = self.vim.visual_anchor() {
self.editor.selection = Some(crate::widgets::editor::EditorSelection {
anchor,
head: (self.editor.cursor_row, self.editor.cursor_col),
});
}
}
/// Keyboard handling for the PROBLEMS view while it owns the panel pane:
/// arrow / page keys scroll the list, Escape hands focus back to the editor.
/// Keys while the PROBLEMS tab owns the panel pane. Plain typing goes
/// to the free-text filter (VS Code's Problems filter box), so Esc
/// clears the filter first and only hands the pane back once it is
/// already empty, mirroring the Remote panel's filter behaviour.
fn handle_problems_key(&mut self, key: KeyEvent) {
match key.code {
KeyCode::Up => self.problems.scroll_up(1),
KeyCode::Down => self.problems.scroll_down(1),
KeyCode::PageUp => self.problems.scroll_up(10),
KeyCode::PageDown => self.problems.scroll_down(10),
KeyCode::Backspace if !self.problems.text_filter.is_empty() => {
self.problems.pop_filter_char();
}
KeyCode::Char(c)
if !key.modifiers.intersects(
KeyModifiers::CONTROL | KeyModifiers::SUPER | KeyModifiers::ALT,
) =>
{
self.problems.push_filter_char(c);
}
KeyCode::Esc if !self.problems.clear_text_filter() => {
self.focus_pane(Pane::Editor);
}
_ => {}
}
}
fn handle_output_key(&mut self, key: KeyEvent) {
match key.code {
KeyCode::Up => self.output.scroll_up(1),
KeyCode::Down => self.output.scroll_down(1),
KeyCode::PageUp => self.output.scroll_up(10),
KeyCode::PageDown => self.output.scroll_down(10),
KeyCode::Esc => self.focus_pane(Pane::Editor),
_ => {}
}
}
/// Keys while the PORTS tab owns the panel pane. `⏎` opens (forwarding first
/// on a remote port), `f` forwards without opening, `c` copies the address,
/// `x` stops watching (and tears the tunnel down).
fn handle_ports_key(&mut self, key: KeyEvent) {
match key.code {
KeyCode::Up => self.ports.move_selection(-1),
KeyCode::Down => self.ports.move_selection(1),
KeyCode::Esc => self.focus_pane(Pane::Editor),
KeyCode::Enter => self.ports_open_selected(),
KeyCode::Char('f') => self.ports_forward_selected(),
KeyCode::Char('c') => self.ports_copy_selected(),
KeyCode::Char('x') => self.ports_stop_selected(),
_ => {}
}
}
fn handle_captures_key(&mut self, key: KeyEvent) {
match key.code {
KeyCode::Up => self.captures.move_selection(-1),
KeyCode::Down => self.captures.move_selection(1),
KeyCode::Esc => self.focus_pane(Pane::Editor),
KeyCode::Enter => self.captures_open_selected(),
KeyCode::Char('n') => self.ask_navigator_about_capture(),
KeyCode::Char('x') => self.captures.remove_selected(),
KeyCode::Char('c') => {
self.captures.clear();
self.status = String::from("Cleared captured output");
}
_ => {}
}
}
/// Cmd+K D: snapshot the active pane's scrollback + screen. A pane that
/// showed colour is written, colours as SGR, to a private file under the
/// scrollback dir and opened as a pinned rendered-log tab (#257); a pane
/// with no colour goes into the scratch editor tab it always had. Read
/// from one grid pass (`grid_lines_ansi`, the plain twin of which is the
/// text the find bar searches); the blank live-screen tail is trimmed so
/// the buffer ends at the last real row.
fn open_scrollback_in_editor(&mut self) {
// Plain and coloured rows come from ONE grid read, so a redact rule
// is applied to the row it matches and never to a neighbour that
// shifted in while a second read was taken.
let rows_both = self.terminal().grid_lines_ansi();
let last = rows_both
.iter()
.rposition(|(plain, _)| !plain.trim().is_empty())
.map_or(0, |i| i + 1);
let pane = self.terminal().label();
let pane = if pane.is_empty() { "terminal" } else { pane };
let label = format!("{pane} scrollback");
// Every redact rule applies here, copy-mode or not: this buffer
// leaves the pane as bytes (#360). Masking works on the plain text;
// a row the rules touch keeps its masked plain form and gives up its
// colour, since a mask spliced between escapes could break them.
let mut plain_rows: Vec<String> = Vec::with_capacity(last);
let mut rows: Vec<String> = Vec::with_capacity(last);
let mut fallback_reason: Option<String> = None;
for (plain, ansi) in &rows_both[..last] {
let masked = crate::triggers::mask_text(plain, &self.triggers, false);
rows.push(if masked == *plain {
ansi.clone()
} else {
masked.clone()
});
plain_rows.push(masked);
}
// A pane that showed colour lands in the rendered log view (#257),
// which indexes from disk, so the rows go to a real file under the
// scrollback dir, one per pane, overwritten on each dump. The gate
// uses the open path's own sniff, so the file can never open as an
// editable buffer of raw escapes. A pane with no colour keeps the
// scratch buffer it always had.
if scrollback_opens_as_log(&rows) {
// Keyed on the pane's stable uid as well as its label: two
// unnamed shells both read `terminal`, and two labels can
// sanitise to one name, and neither may overwrite the other's
// dump or close its tab.
// The uid is a per-process counter that restarts at 1, so two
// croft processes would share a name without the pid, as the
// session handoff file learned before this one.
let file = self.scrollback_dir.join(format!(
"{}-{}-{}-scrollback.log",
pane.chars()
.map(|c| if c.is_alphanumeric() || c == '-' || c == '_' {
c
} else {
'_'
})
.collect::<String>(),
std::process::id(),
self.terminal().uid()
));
// A tab from an earlier dump holds a byte index over the OLD
// file; it is closed so the open below rebuilds the view over the
// new bytes rather than reading them through the stale index.
self.close_tabs_with_path_everywhere(&file);
// Terminal output is written owner-only whatever the umask: the
// redaction rules are finite, and another local account has no
// business reading a shell's history.
let written = write_private(&self.scrollback_dir, &file, &(rows.join("\n") + "\n"));
// Dumps left by croft processes that have exited are reaped on
// the way past: nothing will ever overwrite them. Here rather
// than at startup because this is the one place the dir grows,
// so its size is bounded at the moment it would grow; the cost
// is one `read_dir` and one `kill(0)` per stale file, paid by a
// command that just wrote a scrollback to disk.
if written.is_ok() {
reap_dead_scrollback_dumps(&self.scrollback_dir);
}
// Pinned, as the scratch buffer was: a later file peek must not
// replace the dump, and two panes' dumps must not share a slot.
let opened = written
.map_err(anyhow::Error::from)
.and_then(|()| self.editor.open_pinned(&file));
match opened {
Ok(()) if self.editor.log.is_some() => {
self.focus_pane(Pane::Editor);
self.sync_open_file_poll_mtime();
self.status = format!("Opened {last} scrollback lines as a rendered log");
return;
}
Ok(()) => {
// The open path decided this was not a log after all:
// never leave the user an editable file of raw escapes,
// nor the file itself, which nothing will read now.
self.close_tabs_with_path_everywhere(&file);
let _ = std::fs::remove_file(&file);
fallback_reason = Some(String::from(
"Rendered scrollback unavailable; opened as text",
));
}
Err(e) => {
// Fall through to the plain scratch buffer rather than
// lose the dump: a full disk still leaves the text. A
// partial file, if one was written, serves nobody.
let _ = std::fs::remove_file(&file);
fallback_reason = Some(format!(
"Rendered scrollback unavailable ({e}); opened as text"
));
}
}
}
let text = plain_rows.join("\n");
match self.editor.open_text_buffer(Path::new(&label), &text) {
Ok(()) => {
self.focus_pane(Pane::Editor);
self.sync_open_file_poll_mtime();
// The reason travels in a local, not in `status`: a message
// left by an earlier action must not be mistaken for one
// this dump produced.
self.status = fallback_reason
.unwrap_or_else(|| format!("Opened {last} scrollback lines in the editor"));
}
Err(e) => self.status = format!("Open scrollback failed: {e}"),
}
}
/// Close every tab holding `path`, in the focused group and in every
/// other one: a tab in an unfocused group would otherwise keep reading a
/// rewritten file through its old index, and nothing heals it. Every
/// match goes, not the first: `push_editor` can open one path twice. A
/// group emptied by this is pruned as every other close path prunes it;
/// the focused group is left blank for the caller to refill.
fn close_tabs_with_path_everywhere(&mut self, path: &Path) {
// `close_tab` on a group's last tab leaves a blank editor with no
// path, so the search finds nothing more and the loop ends.
while let Some(idx) = self.editor.find_tab_with_path(path) {
self.editor.close_tab(idx);
}
// The prune names the groups THIS close emptied, by position: a
// group the user left blank on purpose (a split with one side
// cleared) is not this command's to fold away, and a blankness
// sweep would take it along with the emptied one.
let pre_blank: Vec<bool> = self
.editor_layout
.inactive_groups()
.iter()
.map(|g| g.is_blank_initial())
.collect();
let mut doomed = Vec::new();
for (i, group) in self
.editor_layout
.inactive_groups_mut()
.into_iter()
.enumerate()
{
let mut closed_here = false;
while let Some(idx) = group.find_tab_with_path(path) {
group.close_tab(idx);
closed_here = true;
}
if closed_here && group.is_blank_initial() && !pre_blank[i] {
doomed.push(i);
}
}
if !doomed.is_empty() {
self.editor_layout.prune_inactive_at(&doomed);
}
}
/// `.http`/`.rest` (#370): send the request under the caret. The env
/// file's values are substituted before the send; a hole with no value
/// refuses to send rather than leaking `{{name}}` to a server. The send
/// runs on a worker thread and [`Self::drain_http_responses`] opens the
/// response tab when it lands.
pub(crate) fn send_http_request_under_caret(&mut self) {
let Some((req, resolved, path)) = self.http_request_under_caret() else {
return;
};
if self.http_run.is_some() {
self.status = String::from("An HTTP request is already in flight");
return;
}
// History records the RAW line: what the user wrote, secrets still
// folded inside their {{names}}.
let raw_line = format!("{} {}", req.method, req.url);
let (tx, rx) = std::sync::mpsc::channel();
let file = path.clone();
let line = raw_line.clone();
let spawned = std::thread::Builder::new()
.name(String::from("croft-http"))
.spawn(move || {
let result = crate::http_file::send(&resolved, crate::http_file::REQUEST_TIMEOUT);
let _ = tx.send(HttpRunOutcome {
file,
raw_line: line,
result,
});
});
if spawned.is_err() {
self.status = String::from("HTTP: could not start the request worker");
return;
}
self.http_run = Some(rx);
self.status = format!("Sending {raw_line}");
}
/// `.http` (#370): put the request under the caret on the clipboard as
/// a curl command, variables substituted — the clipboard is the user's
/// own hand, unlike history and the response tab.
pub(crate) fn copy_http_request_as_curl(&mut self) {
let Some((_, resolved, _)) = self.http_request_under_caret() else {
return;
};
copy_to_clipboard(&crate::http_file::to_curl(&resolved));
self.status = String::from("curl command copied");
}
/// The parsed and variable-resolved request under the caret, or a
/// status naming why there is none (wrong file, no block, or a
/// `{{name}}` with no value in `.http.env.json` / the environment).
fn http_request_under_caret(
&mut self,
) -> Option<(
crate::http_file::HttpRequest,
crate::http_file::ResolvedRequest,
PathBuf,
)> {
let Some(path) = self.editor.path.clone() else {
self.status = String::from("No file open");
return None;
};
if !crate::http_file::is_http_file(&path) {
self.status = String::from("Not a .http/.rest file");
return None;
}
let text = self.editor.lines.join("\n");
let requests = crate::http_file::parse_requests(&text);
let Some(req) = crate::http_file::request_at(&requests, self.editor.cursor_row).cloned()
else {
self.status = String::from("No request under the caret");
return None;
};
let dir = path.parent().unwrap_or(Path::new(".")).to_path_buf();
let vars = crate::http_file::load_env(&dir);
let (resolved, missing) = crate::http_file::resolve(&req, &vars);
if !missing.is_empty() {
let holes: Vec<String> = missing.iter().map(|m| format!("{{{{{m}}}}}")).collect();
self.status = format!(
"HTTP: no value for {} (add it to {} beside the file, or $env)",
holes.join(", "),
crate::http_file::ENV_FILE
);
return None;
}
Some((req, resolved, path))
}
/// Fold in a finished `.http` request (#370): record it in the durable
/// command history (raw line, status as the exit, elapsed as the
/// duration), materialise the response under the cache, and open it —
/// a text document with status/headers as comments, or the image
/// itself. Returns whether a repaint is due.
pub fn drain_http_responses(&mut self) -> bool {
let Some(rx) = self.http_run.as_ref() else {
return false;
};
let outcome = match rx.try_recv() {
Ok(o) => o,
Err(std::sync::mpsc::TryRecvError::Empty) => return false,
Err(std::sync::mpsc::TryRecvError::Disconnected) => {
self.http_run = None;
self.status = String::from("HTTP: the request worker died");
return true;
}
};
self.http_run = None;
let cwd = outcome
.file
.parent()
.map(|d| d.to_string_lossy().into_owned())
.unwrap_or_default();
let ts = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
match outcome.result {
Err(e) => {
self.command_history
.append(crate::command_history::HistoryEntry {
cmd: format!("http {}", outcome.raw_line),
cwd,
host: String::new(),
exit: None,
dur_ms: 0,
ts,
});
self.status = format!("HTTP: {} failed: {e}", outcome.raw_line);
}
Ok(resp) => {
self.command_history
.append(crate::command_history::HistoryEntry {
cmd: format!("http {}", outcome.raw_line),
cwd,
host: String::new(),
exit: Some(i32::from(resp.status)),
dur_ms: resp.elapsed_ms,
ts,
});
let dir = croft_cache_dir().join("http");
if let Err(e) = std::fs::create_dir_all(&dir) {
self.status = format!("HTTP: cannot write the response: {e}");
return true;
}
let slug: String = outcome
.raw_line
.chars()
.map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
.collect::<String>()
.trim_matches('-')
.chars()
.take(48)
.collect();
let stamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis())
.unwrap_or(0);
let (file, bytes): (PathBuf, Vec<u8>) =
match crate::http_file::response_kind(&resp.content_type()) {
crate::http_file::ResponseKind::Image(ext) => {
(dir.join(format!("{slug}-{stamp}.{ext}")), resp.body.clone())
}
crate::http_file::ResponseKind::Text(_) => {
let (ext, doc) =
crate::http_file::response_doc(&outcome.raw_line, &resp);
(dir.join(format!("{slug}-{stamp}.{ext}")), doc.into_bytes())
}
};
if let Err(e) = std::fs::write(&file, &bytes) {
self.status = format!("HTTP: cannot write the response: {e}");
return true;
}
match self.editor.open_pinned(&file) {
Ok(()) => {
self.focus_pane(Pane::Editor);
self.status = format!(
"{} \u{2192} {} {} \u{00b7} {} ms",
outcome.raw_line, resp.status, resp.status_text, resp.elapsed_ms
);
}
Err(e) => self.status = format!("HTTP: response open failed: {e}"),
}
}
}
true
}
/// Ctrl+Shift+H: open the durable command-history search over the
/// active pane's context (atuin's enhanced Ctrl+R, embedded).
fn open_command_history(&mut self) {
let mut pop = crate::widgets::history_popup::HistoryPopup::new();
pop.cwd = self
.terminal()
.shell_cwd()
.map(|p| p.display().to_string())
.unwrap_or_default();
pop.host = self.terminal().shell_host().unwrap_or_default();
pop.set_results(
self.command_history
.search("", pop.scope, &pop.cwd, &pop.host),
);
self.command_history_popup = Some(pop);
}
/// Re-run the store search after any query / scope change.
fn refresh_command_history_results(&mut self) {
let Some(pop) = self.command_history_popup.as_ref() else {
return;
};
let (query, scope, cwd, host) = (
pop.query.clone(),
pop.scope,
pop.cwd.clone(),
pop.host.clone(),
);
let results = self.command_history.search(&query, scope, &cwd, &host);
if let Some(pop) = self.command_history_popup.as_mut() {
pop.set_results(results);
}
}
fn handle_command_history_key(&mut self, key: KeyEvent) {
// Ctrl+R (and the opening chord itself) cycles the scope filter:
// all → this directory → failed only.
if matches!(key.code, KeyCode::Char('r' | 'R'))
&& key.modifiers.contains(KeyModifiers::CONTROL)
{
if let Some(pop) = self.command_history_popup.as_mut() {
pop.scope = pop.scope.next();
}
self.refresh_command_history_results();
return;
}
match key.code {
KeyCode::Esc => {
self.command_history_popup = None;
}
KeyCode::Enter => {
let cmd = self
.command_history_popup
.as_ref()
.and_then(|p| p.selected_entry())
.map(|e| e.cmd.clone());
self.command_history_popup = None;
if let Some(cmd) = cmd {
self.focus_pane(Pane::Terminal);
self.terminal_mut().paste_input(cmd.as_bytes());
self.status = String::from("Command typed at the prompt (Enter runs it)");
}
}
KeyCode::Up => {
if let Some(pop) = self.command_history_popup.as_mut() {
pop.select_prev();
}
}
KeyCode::Down => {
if let Some(pop) = self.command_history_popup.as_mut() {
pop.select_next();
}
}
KeyCode::Left => {
if let Some(pop) = self.command_history_popup.as_mut() {
pop.move_cursor_left();
}
}
KeyCode::Right => {
if let Some(pop) = self.command_history_popup.as_mut() {
pop.move_cursor_right();
}
}
KeyCode::Backspace => {
if let Some(pop) = self.command_history_popup.as_mut() {
pop.pop_char();
}
self.refresh_command_history_results();
}
KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => {
if let Some(pop) = self.command_history_popup.as_mut() {
pop.push_char(c);
}
self.refresh_command_history_results();
}
_ => {}
}
}
/// Jump the selected capture's pane back to the captured line: switch to
/// the TERMINAL tab, focus the pane (found by shell pid; a closed pane
/// falls back to the active one), locate the newest grid row matching
/// the captured text, scroll it into view and select it. A very long
/// captured line wraps across grid rows, so the match is prefix-based
/// on the first wrapped row.
pub fn captures_open_selected(&mut self) {
let Some(entry) = self.captures.selected_entry().cloned() else {
return;
};
let idx = entry
.shell_pid
.and_then(|pid| {
self.terminals
.iter()
.position(|t| t.shell_pid() == Some(pid))
})
.unwrap_or(self.active_terminal);
self.reveal_terminal_pane(idx);
self.set_bottom_panel_tab(BottomPanelTab::Terminal);
self.focus_pane(Pane::Terminal);
let needle: String = entry.line.trim_end().chars().take(60).collect();
let Some(line) = self.terminals[idx].find_captured_line(&needle) else {
self.status = String::from("Captured line is no longer in the scrollback");
return;
};
let (_, _, cols, _) = self.terminals[idx].grid_bounds();
let t = &mut self.terminals[idx];
t.set_selection(Some(crate::widgets::terminal::Selection {
anchor: (line, 0),
head: (line, cols.saturating_sub(1)),
block: false,
}));
t.scroll_to_line(line);
self.status = format!("Capture: {}", entry.message);
}
fn handle_terminal_key(&mut self, key: KeyEvent) {
// Quick-select owns every keystroke while its labels are up.
if self.terminal_quick_select.is_some() {
self.handle_terminal_quick_select_key(key);
return;
}
// Copy mode owns every keystroke while it is on.
if self.terminal_copy_mode.is_some() {
self.handle_terminal_copy_mode_key(key);
return;
}
// The find bar owns every keystroke while it is open.
if self.terminal_find.is_some() {
self.handle_terminal_find_key(key);
return;
}
// Ctrl+Shift+Space (WezTerm's quick-select): label every URL / path /
// hash / IP on screen; typing a label copies it, UPPERCASE pastes.
if is_quick_select_key(key) {
self.open_terminal_quick_select();
return;
}
// Ctrl+Shift+Y (WezTerm's copy mode, Y for yank): keyboard-select
// from the grid and scrollback with vi motions.
if is_copy_mode_key(key) {
self.open_terminal_copy_mode();
return;
}
// Ctrl+Shift+H (H for history; atuin's enhanced Ctrl+R lives on the
// shell side): search the durable cross-session command history.
// Plain Ctrl+R still reaches the shell's own reverse search.
if is_command_history_key(key) {
self.open_command_history();
return;
}
// Open find-in-terminal (scrollback search). Cmd+F everywhere;
// Ctrl+F only off macOS, matching VS Code's terminal find defaults:
// on macOS Ctrl+F is a control byte the child owns (vim page-forward,
// emacs forward-char) and iTerm2/VS Code pass it through, while on
// Linux/Windows Ctrl+F opening find IS the VS Code default.
if is_terminal_find_key(key) {
self.open_terminal_find();
return;
}
// Ctrl+Shift+T: open another terminal next to the active one.
if is_terminal_split_key(key) {
match self.split_terminal() {
Ok(()) => {
self.terminal_status(format!(
"Split terminal: {} active",
self.terminals.len()
));
}
Err(e) => {
self.status = format!("Split terminal failed: {e}");
}
}
return;
}
// Cmd+W (or legacy Ctrl+Shift+W): close the active terminal (no-op when
// only one is left).
if is_terminal_close_key(key) {
if self.close_active_terminal() {
self.terminal_status(format!(
"Closed terminal: {} remaining",
self.terminals.len()
));
} else {
self.status = String::from("Cannot close the last terminal; press Ctrl+J to hide");
}
return;
}
// Cmd+]: next terminal. Cmd+[: previous terminal.
if is_terminal_cycle_key(key) {
self.cycle_terminal();
return;
}
if is_terminal_cycle_back_key(key) {
self.cycle_terminal_back();
return;
}
// Cmd+Opt+Up / Cmd+Opt+Down (Linux: Ctrl+Alt): jump to the previous /
// next prompt via the OSC 133 marks shell integration records —
// VS Code's command navigation. (VS Code's own Cmd+Up/Down chord is
// impossible here: bare Cmd+arrows are reserved by the user, see
// src/iterm2.rs. The chord is already forwarded globally for the
// editor's Add Cursor Above/Below and is unused in the terminal.)
if key
.modifiers
.intersects(KeyModifiers::SUPER | KeyModifiers::CONTROL)
&& key.modifiers.contains(KeyModifiers::ALT)
&& matches!(key.code, KeyCode::Up | KeyCode::Down)
{
self.terminal_prompt_jump(matches!(key.code, KeyCode::Down));
return;
}
// Shift+PageUp / Shift+PageDown: page through the scrollback;
// Shift+Home / Shift+End jump to the oldest line / the live bottom
// (xterm's keyboard-scrollback convention, leaving the plain keys
// for the running program). In the alternate screen there is no
// scrollback, so the chord falls through to the program instead.
if key.modifiers.contains(KeyModifiers::SHIFT)
&& matches!(
key.code,
KeyCode::PageUp | KeyCode::PageDown | KeyCode::Home | KeyCode::End
)
{
let page = self.terminal().last_inner.height.max(2) as usize - 1;
let scrolled = match key.code {
KeyCode::PageUp => self.terminal_mut().scroll_up(page),
KeyCode::PageDown => self.terminal_mut().scroll_down(page),
KeyCode::Home => self.terminal_mut().scroll_to_top(),
_ => self.terminal_mut().reset_scrollback(),
};
if scrolled {
return;
}
}
// Ctrl+Shift+C / Cmd+C: copy current selection.
if is_terminal_copy_key(key) {
self.copy_terminal_selection();
return;
}
// Cmd+V / Ctrl+V / Ctrl+Shift+V: paste local clipboard into the
// embedded shell. Without this, raw Ctrl+V bytes (\x16) just go
// through to the shell unchanged, and Cmd+V — when not eaten by
// the host terminal's menu shortcut — would do nothing useful.
if is_clipboard_paste_key(key) {
self.paste_clipboard_into_terminal();
return;
}
// Any other keystroke clears the selection so the user's input is
// sent without the previous highlight lingering on screen.
if self.terminal().selection().is_some() {
self.terminal_mut().clear_selection();
}
self.write_terminal_key(key);
}
/// Shell-bound keystroke from the focused terminal: normally just the
/// active pane, mirrored to every non-excluded pane while broadcast is
/// on. Encoded per pane because DECCKM is per-PTY state: every pane gets
/// the form its own child asked for (a zsh pane wants SS3 arrows while a
/// bash pane wants CSI), not the focused pane's.
fn write_terminal_key(&mut self, key: KeyEvent) {
if self.broadcast_input {
let active = self.active_terminal;
for (i, t) in self.terminals.iter_mut().enumerate() {
if i == active || !t.broadcast_excluded {
let bytes = key_to_bytes(key, t.app_cursor_keys());
if !bytes.is_empty() {
t.write_input(&bytes);
}
}
}
} else {
let bytes = key_to_bytes(key, self.terminal().app_cursor_keys());
if !bytes.is_empty() {
self.terminal_mut().write_input(&bytes);
}
}
}
/// Copy the terminal pane's current selection to the user's clipboard.
/// Selection stays visible so the user can verify what was copied.
///
/// A copy that finds NOTHING now says so (#538). Inside a program that has
/// ASKED for mouse tracking — Claude Code and most full-screen TUIs, but
/// not a program that never requested it — a plain drag is the child's
/// gesture and croft deliberately holds no selection of its own (#474), so
/// the old silent return left the user pressing copy with nothing
/// happening and no way to learn that Shift+drag selects there. The hint
/// is keyed on `mouse_reporting`, so a pane whose child is not tracking is
/// told to drag, which is what works there.
fn copy_terminal_selection(&mut self) {
if !self.terminal().selection().is_some_and(|s| s.has_area()) {
self.status = String::from(if self.terminal().mouse_reporting() {
"Nothing selected: Shift+drag selects inside a program that tracks the mouse"
} else {
"Nothing selected: drag to select first"
});
return;
}
let text = self.terminal_text_for_copy(self.terminal().selection_text());
if text.is_empty() {
// A real selection, but over blank cells: saying "nothing
// selected" here would describe the wrong thing to fix.
self.status = String::from("Selection has no text to copy");
return;
}
self.deliver_copied_text(&text);
}
/// Put copied text where the user can actually paste it.
///
/// "The clipboard" is not always this machine's. On a relay session croft
/// runs on a remote box while the user types at another machine, and it is
/// THAT clipboard a paste comes from — so the text goes home over the drop
/// relay, the same road `request_remote_clipboard` uses to fetch it for a
/// paste, travelled in the other direction (#538). Writing the remote
/// box's clipboard instead put the text somewhere nothing could reach, and
/// an SSH session usually has no clipboard tool to write to at all.
///
/// Everywhere else it is this machine's clipboard, with the OSC 52
/// fallback `copy_to_clipboard` already keeps for a host terminal that
/// honours it. That fallback is reported HONESTLY: whether the sequence is
/// acted on is the host terminal's choice, not something croft can see, so
/// claiming a copy landed would be a claim croft cannot make.
fn deliver_copied_text(&mut self, text: &str) {
let n = text.chars().count();
if self.is_relay_session && self.push_clipboard_via_relay(text) {
self.status = format!("Copied {n} chars to the local clipboard");
return;
}
if copy_to_clipboard(text) {
self.status = format!("Copied {n} chars to clipboard");
} else {
self.status = format!("Copied {n} chars via OSC 52 (the host terminal decides)");
}
}
/// Push copied text to the LOCAL machine's clipboard over the drop relay.
/// Returns whether the request was queued.
///
/// The payload goes in a file in the relay INBOX rather than into the
/// request line: a request is one TAB-SEPARATED LINE, while copied text
/// carries newlines and tabs of its own and can be megabytes of
/// scrollback. The line names only the request id — the pump derives
/// `<inbox>/<id>.txt` from the inbox it already owns, so no path from
/// this side is ever handed to a remote shell.
///
/// An oversized copy is REFUSED here rather than truncated there. The pump
/// caps what it will read into the local machine's memory and drops
/// anything past it, and a selection that pastes back half-formed is worse
/// than falling through to the ordinary clipboard route and saying so.
fn push_clipboard_via_relay(&mut self, text: &str) -> bool {
if text.len() > crate::remote::MAX_COPY_PAYLOAD_BYTES {
return false;
}
let (Some(log_path), Some(inbox)) = (self.relay_log_path(), self.relay_inbox_path()) else {
return false;
};
self.ensure_relay_dir();
let request_id = Self::relay_request_id("copy");
if std::fs::write(inbox.join(format!("{request_id}.txt")), text).is_err() {
return false;
}
append_to_relay_log(&log_path, &format!("copy\t{request_id}\n")).is_ok()
}
/// Paste the host clipboard into the terminal: the chord (Cmd+V /
/// Ctrl+V / Ctrl+Shift+V) and the pane menu's "Paste" both land here, so
/// bracketed paste, broadcast fan-out and the remote-clipboard fallback
/// behave identically whichever one the user reached for.
///
/// The messages name the ACTION rather than the chord: the menu route has
/// no Cmd+V in it, and a status line quoting a key the user never pressed
/// reads as a bug report about the wrong thing.
fn paste_clipboard_into_terminal(&mut self) {
match crate::clipboard::read_string() {
Some(text) if !text.is_empty() => {
self.paste_terminal_input(text.as_bytes());
}
Some(_) => {
self.status = String::from("Paste: clipboard is empty");
}
None if self.drop_relay_active() => {
self.request_remote_clipboard();
}
None => {
self.status =
String::from("Paste: clipboard read failed (no pbpaste / NSPasteboard)");
}
}
}
/// Start a mouse selection over a rendered ANSI log (#257).
///
/// Mirrors `begin_preview_selection`: a log tab's `lines` is a one-line
/// stub, so the editor's own selection coordinates cannot describe it and
/// the view carries its own, in absolute (line, char column).
fn begin_log_selection(&mut self, col: u16, row: u16) -> bool {
let scroll = self.editor.scroll;
let Some(log) = self.editor.log.as_mut() else {
return false;
};
if !rect_contains(log.last_body, col, row) {
if log.has_selection() {
log.selection = None;
log.dragging = false;
}
return false;
}
let cell = log_cell_at(log, scroll, col, row);
log.selection = Some((cell, cell));
log.dragging = true;
self.focus_pane(Pane::Editor);
true
}
/// Ctrl+click a `path:line` printed in a RENDERED log (#257).
///
/// Scanned against the escape-free text, not the raw bytes: the
/// reference's column in the file is not its column on screen once SGR
/// sequences are stripped, and a path can sit inside an escape entirely.
/// `log_cell_at` already maps a screen cell to that text's column.
///
/// Dispatched ahead of `begin_log_selection`, which runs before the
/// editor's own Ctrl handling and would otherwise swallow the gesture
/// into a selection drag. Relative paths resolve against the workspace
/// root - a log has no shell cwd to consult, unlike a terminal pane.
fn log_file_click(&mut self, col: u16, row: u16) -> bool {
let scroll = self.editor.scroll;
let Some(log) = self.editor.log.as_ref() else {
return false;
};
if !rect_contains(log.last_body, col, row) {
return false;
}
let (line, column) = log_cell_at(log, scroll, col, row);
let Some(text) = log.visible_text(line).map(str::to_string) else {
return false;
};
let Some(fr) = crate::file_ref::file_ref_at(&text, column) else {
return false;
};
let raw = std::path::PathBuf::from(&fr.path);
let abs = if let Some(rest) = fr.path.strip_prefix("~/") {
match std::env::var_os("HOME") {
Some(h) => std::path::PathBuf::from(h).join(rest),
None => return false,
}
} else if raw.is_absolute() {
raw
} else {
self.tree.root.join(raw)
};
// Only when it resolves to a real file, which is also what filters
// lookalikes like `host.com:443`.
if !abs.is_file() {
return false;
}
self.open_resolved_file_ref(&abs, fr.line, fr.column)
}
/// Extend a live log drag and finish it on release.
fn update_log_selection(&mut self, m: MouseEvent) -> bool {
let scroll = self.editor.scroll;
let copy_on_select = self.copy_on_select;
let Some(log) = self.editor.log.as_mut() else {
return false;
};
if !log.dragging {
return false;
}
match m.kind {
MouseEventKind::Drag(MouseButton::Left) => {
let body = log.last_body;
// Clamp to the body: dragging past an edge extends to it
// rather than dropping the gesture.
let col = m
.column
.clamp(body.x, body.x + body.width.saturating_sub(1));
let row = m.row.clamp(body.y, body.y + body.height.saturating_sub(1));
let head = log_cell_at(log, scroll, col, row);
if let Some((anchor, _)) = log.selection {
log.selection = Some((anchor, head));
}
true
}
MouseEventKind::Up(MouseButton::Left) => {
log.dragging = false;
if copy_on_select {
self.copy_log_selection();
}
true
}
_ => false,
}
}
/// Put the log selection on the clipboard, saying so when the copy was
/// clamped rather than leaving the user with silently less than they
/// selected.
fn copy_log_selection(&mut self) -> bool {
let Some(log) = self.editor.log.as_ref() else {
return false;
};
if !log.has_selection() {
return false;
}
let (text, clamped) = log.selection_text();
if text.is_empty() {
return false;
}
let bytes = text.len();
copy_to_clipboard(&text);
// Say what was actually copied. `clamped` is true for the byte CAP
// and for a sweep that ran out of budget on escape-heavy text, and in
// the second case the copy can be far short of the cap: naming the
// cap then tells the user they got four megabytes when they got a
// fraction of one.
self.status = if clamped {
format!("Copied {bytes} bytes; the selection was larger than one copy allows")
} else {
format!("Copied {bytes} bytes")
};
true
}
/// Start a drag-selection in the rendered Markdown/document preview
/// when `(col, row)` lands inside it. Returns true when the press was
/// consumed, so the normal editor click path is skipped: the source
/// buffer is not visible, and a caret there would serve nobody.
fn begin_preview_selection(&mut self, col: u16, row: u16) -> bool {
if let Some(idx) = self.preview_runnable_at(col, row) {
self.run_markdown_block(idx);
return true;
}
let Some(md) = self.editor.markdown_preview.as_mut() else {
return false;
};
if !rect_contains(md.last_area, col, row) {
// A press elsewhere drops the selection, like the editor's.
if md.has_selection() {
md.selection = None;
md.dragging = false;
}
return false;
}
let cell = (row - md.last_area.y, col - md.last_area.x);
md.selection = Some((cell, cell));
md.dragging = true;
self.focus_pane(Pane::Editor);
true
}
/// The runnable fence whose play glyph sits under screen `(col, row)`
/// (#353): the glyph cell itself, the first column of the block's first
/// visual row - one column, so a drag-selection starting beside it is
/// still a selection.
fn preview_runnable_at(&self, col: u16, row: u16) -> Option<usize> {
let md = self.editor.markdown_preview.as_ref()?;
if !rect_contains(md.last_area, col, row) || col != md.last_area.x {
return None;
}
let visual = (row - md.last_area.y) as usize + md.scroll as usize;
md.run_rows.iter().position(|r| *r == visual)
}
/// The confirm popup for runnable fence `idx` of the current document.
/// EVERY block confirms (#353): a README from a cloned repo is untrusted
/// input, and a substring matcher cannot tell a benign block from a
/// disguised one; the matcher only decides whether the popup is red.
fn pending_run_block_for(
&self,
idx: usize,
block: &crate::markdown::MdRunnable,
) -> PendingRunBlock {
let doc = self.editor.path.clone();
// The pane is named by the document's path under the workspace, so
// two READMEs in one tree do not share `README.md:1`.
let root = self.active_workspace_root();
let file = doc
.as_ref()
.map(|p| {
p.strip_prefix(&root)
.map(|rel| rel.display().to_string())
.unwrap_or_else(|_| {
p.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| String::from("doc"))
})
})
.unwrap_or_else(|| String::from("doc"));
let cwd = if block.cwd_root {
self.active_workspace_root()
} else {
doc.as_ref()
.and_then(|p| p.parent())
.map(Path::to_path_buf)
.unwrap_or_else(|| self.active_workspace_root())
};
PendingRunBlock {
pane_name: format!("{file}:{}", idx + 1),
cwd,
command: fence_command(block.interpreter, &block.code),
code: block.code.clone(),
destructive: block.destructive,
doc: doc.clone(),
block_line: block.lines.0,
persist: block.persist,
capture_timeout: block.capture_timeout.map(std::time::Duration::from_secs),
}
}
/// A click on runnable fence `idx` of the open preview: park it behind
/// the confirm popup.
fn run_markdown_block(&mut self, idx: usize) {
let Some(md) = self.editor.markdown_preview.as_ref() else {
return;
};
let Some(block) = md.runnables.get(idx).cloned() else {
return;
};
self.pending_run_block = Some(self.pending_run_block_for(idx, &block));
}
/// Cmd+Enter in a Markdown SOURCE buffer (#353): the fence under the
/// caret, found by the parser's own source ranges (the same walk the
/// preview uses, so the block number - and its pane - agree).
fn run_fence_at_cursor(&mut self) -> bool {
let is_markdown = self
.editor
.path
.as_deref()
.and_then(|p| p.extension().and_then(|e| e.to_str()))
.is_some_and(|e| matches!(e.to_ascii_lowercase().as_str(), "md" | "markdown"));
if self.editor.markdown_preview.is_some() || !is_markdown {
return false;
}
let text = self.editor.lines.join("\n");
let (_, _, runnables) = crate::markdown::render_markdown_full(
&text,
self.theme,
&mut crate::highlight::LangRegistry::new(),
None,
crate::markdown::BlockOutputs::new(),
);
let row = self.editor.cursor_row;
let Some((idx, block)) = runnables
.iter()
.enumerate()
.find(|(_, r)| row >= r.lines.0 && row < r.lines.1)
else {
self.status = String::from(
"Cmd+Enter: put the caret inside a runnable shell fence (sh/bash/zsh/fish; not {run=false})",
);
return true;
};
self.pending_run_block = Some(self.pending_run_block_for(idx, block));
true
}
/// Type a fence into its pane (#353): the pane named after the document
/// and block, reused when it sits idle at a prompt in the block's
/// directory, else a fresh one there. The block is typed, not spawned,
/// so the user sees it and shell history records it.
fn run_block_in_pane(&mut self, block: PendingRunBlock) {
// Ctrl-E + Ctrl-U first, as tasks do: an idle shell's line editor
// may hold a half-typed command.
let bytes = format!("\x05\x15{}", block.command);
// Same guard as `run_project_task`, and the SAME predicate rather
// than a second copy: `README.md:1` is a likely name across two
// repos opened in sequence, and a pane whose shell still sits in
// the other repo must not receive this one's block (#430).
let root = block
.cwd
.canonicalize()
.unwrap_or_else(|_| block.cwd.clone());
// `pane_is_idle_at` is main's shared predicate (#430): one
// definition for tasks and for runnable blocks, so a correction to
// the cwd rule cannot land on one and miss the other.
if let Some(idx) = self
.terminals
.iter()
.position(|t| pane_is_idle_at(t, &block.pane_name, &root))
{
self.arm_block_capture(&block, idx);
self.reveal_terminal_pane(idx);
self.terminals[idx].write_input(bytes.as_bytes());
self.show_terminal = true;
self.focus_pane(Pane::Terminal);
self.status = format!("Running {}", block.pane_name);
return;
}
match crate::widgets::terminal::PtyTerminal::new(&block.cwd) {
Ok(mut term) => {
term.set_manual_name(Some(block.pane_name.clone()));
term.write_input(bytes.as_bytes());
self.insert_terminal(term);
// A fresh pane has no decorations yet, so the capture arms
// at zero and the block's own command is the first to
// finish. Armed AFTER the insert, since that is what puts
// the pane in `self.terminals` for the settle to find.
if let Some(idx) = self
.terminals
.iter()
.position(|t| t.label() == block.pane_name)
{
self.arm_block_capture(&block, idx);
}
self.status = format!("Running {}", block.pane_name);
}
Err(e) => {
self.status = format!("Could not start a pane for {}: {e}", block.pane_name);
}
}
}
fn confirm_pending_run_block(&mut self) {
if let Some(block) = self.pending_run_block.take() {
self.run_block_in_pane(block);
}
}
fn cancel_pending_run_block(&mut self) {
self.pending_run_block = None;
self.status = String::from("Block not run");
}
/// Start waiting for `block`'s output on pane `idx` (#354).
///
/// The pane's CURRENT decoration count is recorded, so the capture is
/// the first command to finish after this moment rather than whatever
/// the pane happened to run before. Re-running a block replaces its
/// pending capture: the newest run is the one the preview describes.
fn arm_block_capture(&mut self, block: &PendingRunBlock, idx: usize) {
// The newest id the pane has already finished. Ids are monotonic,
// so "greater than this" is exactly "after the block was typed",
// and it stays true however many marks are collected in between.
let after = self.terminals[idx]
.command_decorations()
.iter()
.map(|d| d.id)
.max();
self.pending_captures
.retain(|c| c.pane_name != block.pane_name || c.block_line != block.block_line);
self.pending_captures.push(PendingCapture {
pane_name: block.pane_name.clone(),
doc: block.doc.clone(),
block_line: block.block_line,
after,
started: std::time::Instant::now(),
timeout: block.capture_timeout,
persist: block.persist,
});
}
/// Write a capture into the document as an output fence (#354).
///
/// The fence goes immediately after the block's closer, marked with an
/// HTML comment so a later run can find and REPLACE it rather than
/// stacking a new one each time. Exactly one output fence per block, and
/// no other fence is touched: the search starts at the block's closer
/// and stops at the first line that is not part of the marked pair.
///
/// This writes to the user's file from a preview action, so it is
/// deliberately narrow. It refuses rather than guesses when the document
/// on disk no longer looks like the one the block came from, since the
/// block's line numbers are only meaningful against the text that
/// produced them.
fn persist_block_output(
&mut self,
path: &Path,
block_line: usize,
out: &crate::markdown::BlockOutput,
) {
let Ok(text) = std::fs::read_to_string(path) else {
self.status = format!("Could not read {} to persist the output", path.display());
return;
};
let Some(updated) = crate::markdown::replace_output_fence(&text, block_line, &out.text)
else {
self.status =
String::from("The document changed since the block ran; output not saved");
return;
};
if std::fs::write(path, &updated).is_err() {
self.status = format!("Could not write the captured output to {}", path.display());
}
}
/// Settle any capture whose command has finished, or whose
/// `{timeout=N}` has elapsed. Returns true when something changed, so
/// the caller knows to repaint.
///
/// Deliberately its own pass rather than a branch inside
/// `drain_terminal_bells`: that function is about notifying, this one
/// is about recording, and they answer to different pane states.
fn settle_block_captures(&mut self) -> bool {
if self.pending_captures.is_empty() {
return false;
}
let mut settled: Vec<(
String,
usize,
crate::markdown::BlockOutput,
Option<PathBuf>,
bool,
)> = Vec::new();
self.pending_captures.retain_mut(|c| {
let Some(term) = self.terminals.iter().find(|t| t.label() == c.pane_name) else {
// The pane is gone, so nothing will ever finish on it.
return false;
};
let decorations = term.command_decorations();
// The first command to finish AFTER the block was typed, by id
// rather than by position (#440). Ids are monotonic and never
// renumbered, so this survives any amount of mark collection:
// an evicted command is simply absent rather than silently
// replaced by its neighbour, which is what the old positional
// index could not distinguish.
// The EARLIEST command to finish after the block was typed.
// Earliest rather than latest because a block that finishes
// while a later one is still running must not be described by
// the later one - but see `PendingCapture::after`: earliest is
// also what makes a foreign command completing in the
// arm-to-keystroke gap win, which is this rule's residual and
// not `after`'s.
let mine = decorations
.iter()
.filter(|d| c.after.is_none_or(|a| d.id > a))
.min_by_key(|d| d.id);
if let Some(d) = mine {
settled.push((
c.pane_name.clone(),
c.block_line,
crate::markdown::BlockOutput {
text: term.command_output_text(d),
exit: d.exit,
timed_out: false,
},
c.doc.clone(),
// Unconditional now. The gate existed because a
// positional index could name a stranger; an id cannot.
c.persist,
));
return false;
}
// The TIMEOUT stops the capture, never the process: the block
// keeps running in its pane and the box says the wait gave up.
if c.timeout.is_some_and(|t| c.started.elapsed() >= t) {
settled.push((
c.pane_name.clone(),
c.block_line,
crate::markdown::BlockOutput {
text: String::new(),
exit: None,
timed_out: true,
},
c.doc.clone(),
c.persist,
));
return false;
}
true
});
if settled.is_empty() {
return false;
}
for (pane, line, out, doc, persist) in settled {
if persist
&& !out.timed_out
&& let Some(path) = doc.as_ref()
{
self.persist_block_output(path, line, &out);
}
self.block_outputs.insert((pane, line), out);
}
self.publish_block_outputs();
true
}
/// Hand the editor the captures for the document it is showing (#354).
///
/// The editor has no view of which pane ran what, so the app narrows
/// `block_outputs` to the current document's pane prefix and copies the
/// result in. Called after a capture settles and when the preview is
/// rebuilt, so a box appears without the user touching anything.
fn publish_block_outputs(&mut self) {
// The common case by far: nothing has been run, so there is nothing
// to narrow and nothing to compare. Checked before the map is built
// rather than after, since this runs every tick.
if self.block_outputs.is_empty() && self.editor.md_outputs.is_empty() {
return;
}
let prefix = self.block_pane_prefix();
let narrowed: crate::markdown::BlockOutputs = self
.block_outputs
.iter()
.filter(|((pane, _), _)| pane.starts_with(&prefix))
.map(|((_, line), out)| (*line, out.clone()))
.collect();
// Idempotent, so the tick can call it unconditionally and a
// DOCUMENT SWITCH is picked up without every switch path having to
// remember to. Keying only by source line meant `B.md`'s line-12
// fence rendered `A.md`'s capture until something else rebuilt the
// preview; narrowing by pane prefix fixes that only if it actually
// re-runs, which is what this comparison buys.
if narrowed == self.editor.md_outputs {
return;
}
self.editor.md_outputs = narrowed;
if self.editor.markdown_preview.is_some() {
self.editor.rebuild_markdown_preview();
}
}
/// The pane-name prefix for the document the editor is showing: the
/// same `<file>:` the run path builds its pane names from, so a capture
/// from another document cannot appear under this one's fences.
fn block_pane_prefix(&self) -> String {
let root = self.active_workspace_root();
let file = self
.editor
.path
.as_ref()
.map(|p| {
p.strip_prefix(&root)
.map(|rel| rel.display().to_string())
.unwrap_or_else(|_| {
p.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| String::from("doc"))
})
})
.unwrap_or_else(|| String::from("doc"));
format!("{file}:")
}
/// Extend a live preview drag and finish it on release. Returns true
/// when the event was consumed.
fn update_preview_selection(&mut self, m: MouseEvent) -> bool {
let Some(md) = self.editor.markdown_preview.as_mut() else {
return false;
};
if !md.dragging {
return false;
}
match m.kind {
MouseEventKind::Drag(MouseButton::Left) => {
// Clamp to the view: dragging past an edge extends to it
// rather than dropping the gesture.
let area = md.last_area;
let row = m.row.clamp(area.y, area.y + area.height.saturating_sub(1)) - area.y;
let col = m
.column
.clamp(area.x, area.x + area.width.saturating_sub(1))
- area.x;
if let Some((anchor, _)) = md.selection {
md.selection = Some((anchor, (row, col)));
}
true
}
MouseEventKind::Up(MouseButton::Left) => {
md.dragging = false;
// Mirror the editor's copy-on-select setting so a finished
// drag lands on the clipboard when the user asked for that.
if self.copy_on_select {
let text = self
.editor
.markdown_preview
.as_ref()
.map(|md| md.selection_text())
.unwrap_or_default();
if !text.is_empty() {
copy_to_clipboard(&text);
}
}
true
}
_ => false,
}
}
fn copy_editor_selection(&mut self) {
// The rendered preview hides the source buffer, so its selection
// is the only one the user can see (#215).
if let Some(md) = self.editor.markdown_preview.as_ref() {
let text = md.selection_text();
if !text.is_empty() {
copy_to_clipboard(&text);
self.status = format!("Copied {} chars to clipboard", text.chars().count());
}
return;
}
// A rendered log likewise hides its own text behind a stub buffer,
// and the return is unconditional: falling through when there is no
// selection would run the editor's copy over that stub and put its
// placeholder content on the clipboard, which is worse than copying
// nothing.
if self.editor.log.is_some() {
self.copy_log_selection();
return;
}
if let Some(diff) = self.editor.diff.as_ref() {
if let Some(text) = diff.selection_text()
&& !text.is_empty()
{
copy_to_clipboard(&text);
self.status = format!("Copied {} chars to clipboard", text.chars().count());
}
return;
}
let Some(sel) = self.editor.selection else {
return;
};
if !sel.has_area() {
return;
}
let text = self.editor.selection_text();
if text.is_empty() {
return;
}
copy_to_clipboard(&text);
self.status = format!("Copied {} chars to clipboard", text.chars().count());
}
fn cut_editor_selection(&mut self) {
let Some(sel) = self.editor.selection else {
return;
};
if !sel.has_area() {
return;
}
let text = self.editor.selection_text();
if text.is_empty() {
self.editor.clear_selection();
return;
}
copy_to_clipboard(&text);
let n = text.chars().count();
self.editor.delete_selection();
self.status = format!("Cut {n} chars to clipboard");
}
fn paste_clipboard_into_search(&mut self, text: Option<&str>) {
let Some(s) = text else {
self.status = String::from("Cmd+V: clipboard read failed");
return;
};
if s.is_empty() {
self.status = String::from("Cmd+V: clipboard is empty");
return;
}
self.search.insert_str(s);
// Replace text doesn't change which files match, so only re-run the
// scan when the paste landed in a search-affecting field.
if self.search.field != crate::widgets::search::SearchField::Replace {
self.submit_search_query();
}
self.status = format!(
"Cmd+V: pasted into {} field",
search_field_name(self.search.field)
);
}
fn paste_clipboard_into_editor(&mut self, text: Option<&str>) {
let Some(s) = text else {
self.status = String::from("Cmd+V: clipboard read failed");
return;
};
if s.is_empty() {
self.status = String::from("Cmd+V: clipboard is empty");
return;
}
self.editor.insert_str(s);
self.status = format!("Pasted {} chars", s.chars().count());
}
fn handle_paste(&mut self, s: &str) {
// Modal overlays own paste entirely while open — paste lands in
// the modal's input field, never in the editor / tree / terminal
// behind it. Without this, hitting Cmd+V right after Cmd+P pastes
// into whatever pane was last focused instead of into the finder
// query, which makes the "open + paste a filename" path that the
// VS Code Quick Open is meant to support unusable.
if let Some(prompt) = self.input_prompt.as_mut() {
for c in s.chars() {
if !c.is_control() {
prompt.push_char(c);
}
}
return;
}
if let Some(palette) = self.command_palette.as_mut() {
for c in s.chars() {
if !c.is_control() {
palette.push_char(c);
}
}
return;
}
if let Some(picker) = self.go_to_symbol.as_mut() {
for c in s.chars() {
if !c.is_control() {
picker.push_char(c);
}
}
return;
}
if let Some(picker) = self.workspace_symbols.as_mut() {
for c in s.chars() {
if !c.is_control() {
picker.push_char(c);
}
}
self.workspace_symbols_requery();
return;
}
if let Some(finder) = self.file_finder.as_mut() {
for c in s.chars() {
if !c.is_control() {
finder.push_char(c);
}
}
return;
}
// The in-file find bar is a pane-scoped widget, not a modal: it only
// owns the paste while the editor itself is focused. Without the focus
// guard, an open find bar would swallow a paste meant for the terminal
// (or tree) the user has since clicked into — the keystroke path is
// already focus-gated via `match self.focus`, so paste must match it.
if self.focus == Pane::Editor && self.editor_find.is_some() {
let mut new_q = self
.editor_find
.as_ref()
.map(|st| st.query.clone())
.unwrap_or_default();
for c in s.chars() {
if !c.is_control() {
new_q.push(c);
}
}
self.editor_find_set_query(new_q);
return;
}
// Finder drag-and-drop into croft arrives via the host terminal as
// a bracketed paste containing absolute filesystem path(s). The
// drop in iTerm2 does NOT shift mouse focus, so we cannot require
// `self.focus == Pane::Tree` for the gesture: the user can have
// last clicked into the editor or the embedded terminal and still
// expect the drop on the sidebar to import.
//
// * Remote view: any path-shaped paste is an scp upload. There
// is no other reasonable thing the user could want, since the
// visible UI is a host list.
// * Explorer view: a path-shaped paste is an import only when
// focus is on the tree, otherwise we keep the current
// behaviour (typing a path string into the focused editor or
// terminal command line) because that is a legitimate use.
// iTerm2's inline-image drag artefact ALWAYS short-circuits the
// paste pipeline: a stray click-and-microdrag on an OSC-1337 cell
// (activity-bar icon, welcome wordmark, no-repo / run-debug / SSH
// hero) makes iTerm2 write the decoded PNG to $TMPDIR/iTerm2.<rand>.png
// and re-inject the path as a bracketed paste. parse_dropped_paths
// already filters those paths out of the import list, but without
// an early-return here the fallthrough would still paste the raw
// path string into the editor body (the user reported this as
// "Pasted 67 chars" appearing in a freshly-opened CLAUDE.local.md
// tab while they were trying to resize the sidebar near the
// Explorer icon). Detect the artefact at the payload level and
// silently drop the entire paste — no text, no import, no status.
if parsed_drop_tokens(s)
.iter()
.any(|p| p.is_absolute() && is_iterm2_inline_image_drop(p))
{
return;
}
let dropped = parse_dropped_paths(s);
if !dropped.is_empty() {
match self.sidebar_view {
SidebarView::Remote if self.focus == Pane::Tree => {
self.import_paths_into_remote(&dropped);
return;
}
SidebarView::Explorer if self.focus == Pane::Tree => {
self.import_paths_into_explorer(&dropped);
return;
}
_ => {}
}
}
// Remote-launched croft case: the path the user dragged from
// their local Finder doesn't exist on this remote box, so the
// strict parser above returned nothing. If the drop-relay env
// is plumbed (set by the local-croft parent over the SSH
// session) and the paste shape is path-like, request a reverse
// pull through the relay.
//
// Two triggers gate the relay pull. Tree focus is the explicit one,
// matching the strict branch above. The second, `is_pure_path_payload`,
// recovers a genuine Finder drag: a drop arrives as a bracketed paste
// and does NOT move keyboard focus to the tree, so a focus-only gate
// silently dropped every drag where the user had last clicked the
// terminal or editor. A real drop is nothing but absolute-path tokens,
// whereas the text pastes the focus guard protects — a shell command or
// code snippet that merely contains a `/...` token — always carry a
// non-path token, so they still fall through to a normal paste rather
// than being hijacked into a relay pull with no local file to fetch
// (the regression seen on remote sessions opened from Termux).
if self.drop_relay_active()
&& self.sidebar_view == SidebarView::Explorer
&& (self.focus == Pane::Tree || is_pure_path_payload(s))
{
let foreign = parse_foreign_dropped_paths(s);
if !foreign.is_empty() {
self.request_remote_pulls(&foreign);
return;
}
}
if self.sidebar_view == SidebarView::Search && self.focus == Pane::Tree {
self.search.insert_str_into_query(s);
self.submit_search_query();
self.status = format!("Pasted {} chars", s.chars().count());
return;
}
// Source Control commit message box: bracketed paste must
// populate it the same way Cmd+V via the key path does
// (`handle_source_control_key` -> `source_control.insert_str`).
// Without this branch, in the production setup where iTerm2
// emits Cmd+V as a bracketed paste rather than a key event,
// the payload silently vanishes when the user has the SC
// sidebar focused.
if self.sidebar_view == SidebarView::SourceControl
&& self.focus != Pane::Editor
&& self.focus != Pane::Terminal
{
self.source_control.insert_str(s);
self.status = format!("Pasted {} chars", s.chars().count());
return;
}
match self.focus {
Pane::Editor => {
self.editor.insert_str(s);
self.status = format!("Pasted {} chars", s.chars().count());
}
Pane::Terminal => {
if self.terminal_find.is_some() {
let mut q = self
.terminal_find
.as_ref()
.map(|st| st.query.clone())
.unwrap_or_default();
for c in s.chars() {
if !c.is_control() {
q.push(c);
}
}
self.terminal_find_set_query(q);
} else {
self.paste_terminal_input(s.as_bytes());
}
}
Pane::Tree => {}
}
}
/// Move every dropped path into the directory the explorer is
/// currently pointing at. Files outside the workspace are *moved* in
/// (matching the user's Finder-drop expectation), not copied — they
/// disappear from the source location and re-appear in the explorer.
fn import_paths_into_explorer(&mut self, paths: &[PathBuf]) {
let dest_dir = self.paste_target_dir();
let total = paths.len();
let mut placed: Vec<PathBuf> = Vec::new();
let mut errors: Vec<String> = Vec::new();
let mut affected: BTreeSet<PathBuf> = BTreeSet::new();
affected.insert(dest_dir.clone());
for src in paths {
if let Some(parent) = src.parent() {
affected.insert(parent.to_path_buf());
}
match crate::widgets::file_tree::move_into(&dest_dir, src) {
Ok(p) => placed.push(p),
Err(e) => errors.push(format!("{}: {e}", src.display())),
}
}
for dir in &affected {
if let Some(idx) = self.tree.index_of_dir(dir) {
self.tree.refresh_children(idx);
}
}
self.tree.marked.clear();
for p in &placed {
self.tree.marked.insert(p.clone());
}
if let Some(first) = placed.first()
&& let Some(idx) = self.tree.nodes.iter().position(|n| &n.path == first)
{
self.tree.selected = idx;
self.tree.anchor = idx;
}
self.status = if !errors.is_empty() {
format!(
"Imported {}/{}; failed: {}",
placed.len(),
total,
errors.join("; ")
)
} else if total == 1 {
format!(
"Imported {} into {}",
paths[0].display(),
dest_dir.display()
)
} else {
format!(
"Imported {total} items into {}",
self.status_path(&dest_dir)
)
};
}
/// Queue every dropped path for an interactive SCP upload to the
/// currently selected SSH target. The actual scp invocation happens
/// in `main_loop` after suspending the alt-screen, so scp inherits
/// the host shell's stdin / stdout / stderr — that means password
/// prompts, FIDO touch requests, and host-key confirmations all work
/// the way the user expects, and the user sees scp's progress and
/// errors directly. After all uploads finish (success or failure),
/// croft prompts for Enter and resumes the TUI.
fn import_paths_into_remote(&mut self, paths: &[PathBuf]) {
let Some(target) = self.remote.selected_target().cloned() else {
self.status = String::from("Drop ignored: no Remote Explorer host selected");
return;
};
if paths.is_empty() {
return;
}
for src in paths {
self.pending_scp_uploads.push(ScpUpload {
alias: target.alias.clone(),
src: src.clone(),
});
}
self.status = format!(
"Queued {} item(s) for scp copy to {} (you'll see scp's prompts next)",
paths.len(),
target.alias,
);
}
pub fn take_pending_scp_uploads(&mut self) -> Vec<ScpUpload> {
std::mem::take(&mut self.pending_scp_uploads)
}
/// Service edge auto-scroll while a terminal drag-selection is held
/// past the top/bottom edge. Called every main-loop wakeup; advances
/// the viewport by one row at ~30 ms intervals (a readable ~33 rows/s)
/// and re-pins the selection head to the new edge. Returns true when a
/// scroll happened so the caller knows it owes a redraw.
pub fn tick_terminal_autoscroll(&mut self) -> bool {
let Some(state) = self.terminal_select_autoscroll else {
return false;
};
if state.last.elapsed() < std::time::Duration::from_millis(30) {
return false;
}
// A forwarded click-only drag (#474) may be on a pane other than the
// active one: Cmd+] moves the active pane mid-drag, and no further
// Drag event arrives while the pointer rests past the edge to
// re-check. This tick scrolls the ACTIVE pane, so it stands down
// rather than walk the wrong pane's scrollback -- HELD, not dropped:
// the parked pointer sends nothing to re-arm, so cycling back to the
// origin pane must resume the scroll on its own (and the untouched
// `last` stamp makes that first tick fire at once).
if let Some(fp) = self.terminal_pointer_forwarded {
let Some(idx) = self.forwarded_pane_index(fp) else {
// The origin pane is gone (closed by its button while the
// pointer was parked): nothing can ever resume this, so
// drop the gesture rather than hold it to the release.
self.terminal_pointer_forwarded = None;
self.terminal_select_autoscroll = None;
return false;
};
if idx != self.active_terminal {
return false;
}
}
self.terminal_mut().autoscroll_select(state.dir, state.col);
self.terminal_select_autoscroll = Some(TerminalSelectAutoScroll {
last: std::time::Instant::now(),
..state
});
true
}
/// True when this croft is a remote-launched session whose local parent is
/// running a drop pump. Gated on `CROFT_RELAY_KEY`, set only by a `croft
/// remote` launch command. The key is the deterministic `hash(launch arg)`
/// shared with the local pump; because it's deterministic, dtach freezing it
/// at first launch is harmless — every reconnect recomputes the same value,
/// so the running croft and a fresh pump always agree on one relay dir. A
/// session predating this var (an old long-lived dtach session) simply has
/// no key and reports the relay unavailable rather than timing out.
fn drop_relay_active(&self) -> bool {
self.relay_dir().is_some()
}
/// `$HOME/.cache/croft/relay-<CROFT_RELAY_KEY>/` on this remote box. The key
/// is `hash(launch arg)` — the same id the dtach socket uses — computed by
/// the local launcher and the local pump and carried here in env. Keying on
/// the launch identity (not `workspace_root`) keeps the rendezvous stable
/// across an in-session workspace change and the F9 self-re-exec, both of
/// which move `workspace_root` away from where the pump's `pwd` lands.
/// `None` when no `CROFT_RELAY_KEY` is set (not a relay-capable session).
fn relay_dir(&self) -> Option<PathBuf> {
let id = std::env::var("CROFT_RELAY_KEY")
.ok()
.filter(|s| !s.is_empty())?;
Some(croft_cache_dir().join(format!("relay-{id}")))
}
fn relay_log_path(&self) -> Option<PathBuf> {
self.relay_dir().map(|d| d.join("requests.log"))
}
fn relay_inbox_path(&self) -> Option<PathBuf> {
self.relay_dir().map(|d| d.join("inbox"))
}
/// Ensure the relay dir + inbox exist before writing a request. On the first
/// drop after a dtach reattach (or on a fresh box) the local pump's
/// `tail -F` may have started against a path this croft hadn't created yet;
/// `tail -F` retries, so a lazy mkdir here is enough. Idempotent and cheap.
fn ensure_relay_dir(&self) {
if let Some(inbox) = self.relay_inbox_path() {
let _ = std::fs::create_dir_all(inbox);
}
}
fn request_remote_pulls(&mut self, paths: &[PathBuf]) {
let dest_dir = self.paste_target_dir();
let Some(log_path) = self.relay_log_path() else {
self.status = String::from("Drop relay not available on this remote session");
return;
};
self.ensure_relay_dir();
let mut lines = String::new();
let mut staged: Vec<PendingRemotePull> = Vec::new();
let now = std::time::Instant::now();
for src in paths {
let request_id = Self::relay_request_id("pull");
let basename = src
.file_name()
.map(|s| s.to_string_lossy().into_owned())
.unwrap_or_else(|| String::from("dropped"));
lines.push_str("pull\t");
lines.push_str(&request_id);
lines.push('\t');
lines.push_str(&src.to_string_lossy());
lines.push('\n');
staged.push(PendingRemotePull {
request_id,
src_display: src.to_string_lossy().into_owned(),
basename,
dest_dir: dest_dir.clone(),
started_at: now,
kind: RemotePullKind::File,
});
}
match append_to_relay_log(&log_path, &lines) {
Ok(()) => {
self.status = format!(
"Fetching {} item(s) from your local Mac via croft relay",
staged.len(),
);
self.pending_remote_pulls.extend(staged);
}
Err(e) => {
self.status = format!("Drop relay write failed: {e}");
}
}
}
/// Ask the local-croft drop pump to fetch the user's macOS clipboard
/// and stage it on this remote box. The drained pull resolves to a
/// `paste_input` call on the embedded terminal — see `drain_remote_pulls`.
fn request_remote_clipboard(&mut self) {
let Some(log_path) = self.relay_log_path() else {
self.status = String::from("Cmd+V: drop relay vanished");
return;
};
self.ensure_relay_dir();
let request_id = Self::relay_request_id("clip");
let mut line = String::from("clipboard\t");
line.push_str(&request_id);
line.push('\n');
match append_to_relay_log(&log_path, &line) {
Ok(()) => {
self.pending_remote_pulls.push(PendingRemotePull {
request_id,
src_display: String::from("clipboard"),
basename: String::from("clipboard.txt"),
dest_dir: PathBuf::new(),
started_at: std::time::Instant::now(),
kind: RemotePullKind::Clipboard,
});
self.status = String::from("Cmd+V: fetching local Mac clipboard via croft relay");
}
Err(e) => {
self.status = format!("Cmd+V: relay write failed: {e}");
}
}
}
/// Bind this croft's `croft view` socket and publish it to panes.
///
/// Keyed by pid so two crofts on one box never contend, and published
/// through [`crate::view_ipc::SOCK_PATH`], which `apply_pane_env` reads
/// at spawn time so no spawn site has to remember it. Not the process
/// env: `set_var` is unsound with threads running, and the body below
/// says so at length. Under `cfg(test)` the bind is skipped, since a test
/// that stood up an App would otherwise leave a live socket in the real
/// cache dir and set the one-shot global for every OTHER test in the same
/// process.
fn bind_view_socket() -> Option<std::os::unix::net::UnixListener> {
if cfg!(test) {
return None;
}
let dir = croft_cache_dir();
// Latched, not swallowed. "A full or read-only `$HOME`" is one of the
// causes VIEW_BIND_ERROR's own doc names, and it fails HERE, one line
// above the `map_err` that would have reported it. Returning `None`
// quietly left `status` on "Ready" and told the user to run from a
// pane inside croft, which is what they were already doing.
if let Err(e) = std::fs::create_dir_all(&dir) {
*VIEW_BIND_ERROR.lock().unwrap() = Some(format!("{e}"));
return None;
}
// ABSOLUTE, always. `croft_cache_dir` falls back to `.` when `HOME`
// is unset, and the client resolves what it is handed against the
// PANE's cwd - so a relative socket path published here reports "the
// croft that opened this pane is gone" from any pane that has `cd`'d,
// while the croft is running. The module's own invariant is that the
// server only ever sees absolute paths; this is where that starts.
let path = crate::view_ipc::socket_path(&dir, std::process::id());
let path = std::path::absolute(&path).unwrap_or(path);
sweep_dead_view_sockets(&dir);
// A bind failure is reported, not swallowed. The reachable causes are
// real - `AddrInUse` from the liveness check, a full or read-only
// `$HOME`, or the 104-byte `AF_UNIX` path budget with a long home
// directory on macOS - and the client's message for an unset socket
// tells the user to run from a pane inside croft, which is exactly
// what they were doing. Saying so once at startup is the difference
// between a feature that is off and a feature that lies about why.
let listener = prepare_view_listener(&path)
.map_err(|e| {
// Latched rather than dropped. The reachable causes are real -
// `AddrInUse` from the liveness check, a full or read-only
// `$HOME`, the 104-byte `AF_UNIX` path budget with a long home
// on macOS - and the client's message for an unset socket
// tells the user to run from a pane inside croft, which is
// what they were already doing. `App::new` puts this on the
// status line, so a feature that is off says why once instead
// of misdirecting every time it is used.
*VIEW_BIND_ERROR.lock().unwrap() = Some(format!("{e}"));
})
.ok()?;
// Published through a `OnceLock` read at SPAWN time rather than
// `std::env::set_var` (#362). Two things were wrong with the env:
//
// portable-pty snapshots `std::env::vars_os()` inside
// `CommandBuilder::new` and then clears the child's environment before
// applying only that snapshot, so a variable set after a pane was
// constructed never reached its shell. This call happens while
// `App::new` runs, which is AFTER the first pane exists, so `croft
// view` was broken in the startup pane and working everywhere else.
//
// And `set_var` is unsafe in edition 2024 because a concurrent
// `getenv` in another thread is a data race. By this point croft has
// the highlight prewarm, the DAP reaper, a PTY reader, the git worker,
// the MCP index refresh and the FS watcher all running, which is
// exactly the condition `src/gui_path.rs` and `src/session.rs` both
// document when they place their own `set_var` calls at startup.
let _ = crate::view_ipc::SOCK_PATH.set(path);
Some(listener)
}
/// Accept whatever `croft view` clients have queued and open their files.
///
/// Returns whether anything changed, so the frame loop redraws. Every
/// connection is answered before the next is accepted, which is right
/// here: a request is one path and the work is opening a tab, so a
/// thread per client would buy nothing and cost the editor's `&mut self`.
pub fn drain_view_requests(&mut self) -> bool {
// The drain is bounded by TIME rather than by a connection count.
// A per-frame cap of N clients still bounds the frame at N times the
// per-read timeout; a deadline bounds it at the deadline however many
// clients stall. Whatever is left is accepted on the next frame,
// which costs a stalled client latency and costs the user nothing.
//
// The per-stream timeout below is taken from what REMAINS of this
// deadline, which is the half that actually bounds a stalled client.
// `SO_RCVTIMEO` applies per `recv`, and `read_line` loops until it
// sees a newline, so a flat 50ms is reset on every byte that arrives:
// a client dribbling one byte every 40ms and never a newline holds
// the frame loop for as long as it likes. Bounding the BYTES does not
// fix that either - 50 bytes trickled over a second is under any cap
// and still costs the second. Only a deadline the client cannot push
// forward does.
// A croft whose bind failed has no listener and never gets one, so it
// must not pay two clock reads and a loop entry every frame forever.
// The per-iteration binding below stays: it cannot be hoisted, since
// holding that borrow across `answer_view_client`'s `&mut self` does
// not compile.
if self.view_listener.is_none() {
return false;
}
let deadline = std::time::Instant::now() + std::time::Duration::from_millis(20);
let mut changed = false;
loop {
// Do not accept what we cannot serve. `read_line_by_deadline`
// checks its budget BEFORE the first read, so a well-behaved
// client accepted at deadline-minus-epsilon is refused without a
// single read attempt, and the client does not retry. Deferring it
// to the next frame costs that client one frame and costs the user
// nothing, which is the same trade the deadline itself makes.
if deadline.saturating_duration_since(std::time::Instant::now())
< std::time::Duration::from_millis(3)
{
return changed;
}
let Some(listener) = self.view_listener.as_ref() else {
return changed;
};
match listener.accept() {
Ok((stream, _)) => {
// The reply is returned so a TEST can assert on it; the
// drain only needs to know whether a file was opened.
let (_, opened) = self.answer_view_client(stream, deadline);
changed |= opened;
}
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => return changed,
Err(_) => return changed,
}
}
}
/// Open one requested path, answering with what the user should see.
///
/// The path arrives absolute (the client resolved it against the pane's
/// own cwd, which croft only approximates), so the checks here are about
/// whether the file can be shown, not about where it is.
fn apply_view_request(&mut self, path: &Path) -> crate::view_ipc::ViewReply {
use crate::view_ipc::ViewReply;
// The invariant `view_ipc`'s header states, actually enforced. The
// client resolves against ITS cwd before sending, so a relative path
// here came from something that is not `croft view`; resolving it
// against croft's own cwd would silently open a different file than
// the sender named. Same-uid, so this is not a trust boundary, but
// an invariant no code checks is a comment rather than an invariant.
if !path.is_absolute() {
return ViewReply::Err {
message: format!(
"the request must carry an absolute path, got {}",
path.display()
),
};
}
// A REGULAR file, not merely something that exists and is not a
// directory. `File::open` on a FIFO blocks until a writer appears, so
// `mkfifo /tmp/f && croft view /tmp/f` from any pane froze the whole
// editor permanently; `/dev/zero` took the same route and read until
// the machine ran out of memory. Neither is reachable through the
// Explorer without a deliberate human gesture, and this is reachable
// by any process in any pane.
//
// The 20ms drain deadline does not cover it: that bounds the READ of
// the request, and this is the step after. Bounding one stage of a
// pipeline says nothing about the next.
//
// `metadata` follows symlinks, so a symlink to a real file still
// opens (and a symlink to a FIFO is refused on the target's kind);
// one stat answers all three questions the old `exists` + `is_dir`
// pair asked in two.
//
// This bounds the file's KIND, not the time. `metadata` is itself a
// blocking syscall on a client-supplied path, so `croft view` naming
// something on a hung NFS mount still parks the frame loop here,
// before the type check runs. A real bound needs the stat off this
// thread.
//
// The OPEN below is the larger half of the same problem, and it is
// not bounded either: `open_pinned` reaches `Editor::open`, which for
// a PDF shells out to `pdftoppm` with no timeout (#493), and walks
// archives and documents on this thread for their own formats. A
// build script running `croft view out.pdf` on a large document parks
// the editor for the render. Filed rather than fixed here: moving the
// open off the frame loop changes how every viewer reports failure,
// which is a bigger change than the channel that exposed it.
//
// There is also a TOCTOU window between this and the open,
// which is same-uid and so inside the trust boundary the module
// already argues from - noted so a later reader does not mistake the
// check for airtight.
let meta = match std::fs::metadata(path) {
Ok(m) => m,
Err(e) => {
// Not necessarily absence: EACCES and ELOOP land here too,
// and the old text claimed "no such file" over an errno that
// said otherwise.
return ViewReply::Err {
message: format!("cannot read {}: {e}", path.display()),
};
}
};
if meta.is_dir() {
return ViewReply::Err {
message: format!("{} is a directory", path.display()),
};
}
if !meta.is_file() {
return ViewReply::Err {
message: format!("{} is not a regular file", path.display()),
};
}
// Staged pipe input is stamped with THIS croft's pid before it opens,
// so the staging sweep can spare a file a live croft is showing
// instead of deleting it on age alone. `croft view -` input cannot be
// produced again by re-running anything, and the tab re-opens the
// path (a SQLite page turn does it on every page), so a sweep that
// wins that race breaks a working tab and loses the only copy.
// Returns None for an ordinary file, which is then opened as named.
let claimed = crate::view_ipc::claim_staged(path, std::process::id());
let path = claimed.as_deref().unwrap_or(path);
match self.editor.open_pinned(path) {
Ok(()) => {
// Same route as an Explorer click, focus included: the user
// asked for this from a prompt and expects to be looking at
// it, not to find it filed behind the pane they typed in.
self.focus_pane(Pane::Editor);
self.sync_open_file_poll_mtime();
self.status = format!("Opened {}", path.display());
ViewReply::Ok
}
Err(e) => ViewReply::Err {
message: format!("could not open {}: {e}", path.display()),
},
}
}
/// Check the relay inbox for completed pulls and surface them in the
/// explorer. Returns true if any pending pull resolved (success,
/// failure, or timeout) so the main loop knows to redraw.
pub fn drain_remote_pulls(&mut self) -> bool {
if self.pending_remote_pulls.is_empty() {
return false;
}
let Some(inbox) = self.relay_inbox_path() else {
self.pending_remote_pulls.clear();
self.status = String::from("Drop relay vanished mid-pull");
return true;
};
let mut still_pending: Vec<PendingRemotePull> = Vec::new();
let mut placed: Vec<PathBuf> = Vec::new();
let mut opened_urls: Vec<String> = Vec::new();
let mut forwarded: Vec<(u16, u16)> = Vec::new();
let mut errors: Vec<String> = Vec::new();
let mut affected: BTreeSet<PathBuf> = BTreeSet::new();
let pulls = std::mem::take(&mut self.pending_remote_pulls);
let mut clipboard_payload: Option<Vec<u8>> = None;
for pull in pulls {
let request_dir = inbox.join(&pull.request_id);
let ok = request_dir.join(".ok");
let err = request_dir.join(".err");
if ok.exists() {
match pull.kind {
RemotePullKind::File => {
let staged_src = request_dir.join(&pull.basename);
affected.insert(pull.dest_dir.clone());
match crate::widgets::file_tree::move_into(&pull.dest_dir, &staged_src) {
Ok(p) => placed.push(p),
Err(e) => errors.push(format!("{}: {e}", pull.src_display)),
}
}
RemotePullKind::Clipboard => {
let staged = request_dir.join("clipboard.txt");
match std::fs::read(&staged) {
Ok(bytes) => clipboard_payload = Some(bytes),
Err(e) => errors.push(format!("clipboard relay: {e}")),
}
}
RemotePullKind::Open => {
opened_urls.push(pull.src_display.clone());
}
RemotePullKind::Forward { remote_port } => {
let local_port = std::fs::read_to_string(&ok)
.ok()
.and_then(|s| s.trim().parse::<u16>().ok())
.unwrap_or(remote_port);
forwarded.push((remote_port, local_port));
}
}
let _ = std::fs::remove_dir_all(&request_dir);
} else if err.exists() {
let msg =
std::fs::read_to_string(&err).unwrap_or_else(|_| String::from("relay error"));
errors.push(format!("{}: {}", pull.src_display, msg.trim()));
let _ = std::fs::remove_dir_all(&request_dir);
} else if pull.started_at.elapsed() > REMOTE_PULL_TIMEOUT {
errors.push(format!("{}: timed out after 120s", pull.src_display));
let _ = std::fs::remove_dir_all(&request_dir);
} else {
still_pending.push(pull);
}
}
if let Some(bytes) = clipboard_payload
&& !bytes.is_empty()
{
self.paste_terminal_input(&bytes);
}
let resolved_any = !placed.is_empty()
|| !opened_urls.is_empty()
|| !forwarded.is_empty()
|| !errors.is_empty();
for (remote_port, local_port) in &forwarded {
self.ports.mark_forwarded(*remote_port, *local_port);
}
self.pending_remote_pulls = still_pending;
for dir in &affected {
if let Some(idx) = self.tree.index_of_dir(dir) {
self.tree.refresh_children(idx);
}
}
if !placed.is_empty() {
self.tree.marked.clear();
for p in &placed {
self.tree.marked.insert(p.clone());
}
if let Some(first) = placed.first()
&& let Some(idx) = self.tree.nodes.iter().position(|n| &n.path == first)
{
self.tree.selected = idx;
self.tree.anchor = idx;
}
}
if resolved_any {
self.status = if errors.is_empty() {
if !forwarded.is_empty() && placed.is_empty() && opened_urls.is_empty() {
let (remote, local) = forwarded[0];
if local == remote {
format!("Forwarded port {remote} to your machine")
} else {
format!("Forwarded remote port {remote} to local {local}")
}
} else if !opened_urls.is_empty() && placed.is_empty() {
if opened_urls.len() == 1 {
format!("Opened {} in your local browser", opened_urls[0])
} else {
format!("Opened {} URL(s) in your local browser", opened_urls.len())
}
} else if placed.len() == 1 {
format!("Pulled {} from your Mac", placed[0].display())
} else {
format!("Pulled {} item(s) from your Mac", placed.len())
}
} else if placed.is_empty() && opened_urls.is_empty() {
format!("Drop relay failed: {}", errors.join("; "))
} else {
format!(
"Pulled {} / opened {}; failures: {}",
placed.len(),
opened_urls.len(),
errors.join("; "),
)
};
}
resolved_any
}
pub fn report_scp_results(
&mut self,
moved: usize,
total: usize,
errors: usize,
affected_dirs: &[PathBuf],
) {
for dir in affected_dirs {
if let Some(idx) = self.tree.index_of_dir(dir) {
self.tree.refresh_children(idx);
}
}
self.status = if errors == 0 {
format!("Uploaded {moved}/{total} via scp")
} else {
format!("Uploaded {moved}/{total} via scp; {errors} error(s)")
};
}
/// Origin to stamp on a newly detected port: a remote session's ports are
/// forwardable (and carry the host label), a local session's are already
/// reachable.
fn port_origin(&self) -> crate::widgets::ports::PortOrigin {
use crate::widgets::ports::PortOrigin;
if self.is_remote {
PortOrigin::Remote(remote_host_label())
} else {
PortOrigin::Local
}
}
/// Drain freshly scraped ports from every terminal and, on a low cadence,
/// poll the socket table. Output-scrape hits are browser-facing
/// announcements, so a new one raises the toast; socket-poll hits populate
/// the PORTS tab silently. Returns whether anything changed (for redraw).
/// Surface BEL rings and OSC 9 notifications from any pane in the status
/// bar (VS Code shows a bell on the terminal tab; croft's status line is
/// its equivalent). Returns true when either arrived so the loop redraws.
fn drain_terminal_bells(&mut self) -> bool {
self.reap_closed_terminals();
// Long-command completion notice, the Ghostty/Warp behaviour: only
// when the pane isn't the focused one (the user watching a pane sees
// the command end themselves).
const LONG_COMMAND_NOTIFY: std::time::Duration = std::time::Duration::from_secs(10);
let mut rang: Option<String> = None;
let mut notes: Vec<String> = Vec::new();
let mut finished: Option<String> = None;
let mut trigger_note: Option<String> = None;
let mut captured: Vec<crate::widgets::captures::CapturedLine> = Vec::new();
// Finished-command outputs to run through the build matchers after
// the immutable pane sweep (#119): (pane uid, cwd, command, output).
let mut build_scans: Vec<(u64, Option<PathBuf>, String, String)> = Vec::new();
// Watch-matcher batches published mid-run (#252): (pane uid, cwd,
// the cycle's diagnostics — empty clears the pane's entries).
let mut watch_installs: Vec<(u64, Option<PathBuf>, Vec<crate::build_matchers::BuildDiag>)> =
Vec::new();
// A preLaunchTask completing settles the parked debug launch (#250);
// recorded here and acted on after the sweep (launching mutates self).
let mut settled_launch: Option<Option<i32>> = None;
for t in &self.terminals {
// Keep every pane on the current trigger set, wherever it was
// created (a ptr-eq no-op when already current).
t.set_triggers(self.triggers.clone());
t.set_watch_set(self.watch_set.clone());
for (cwd, batch) in t.drain_watch_batches() {
watch_installs.push((t.uid(), cwd, batch));
}
for h in t.drain_trigger_hits() {
match h.action {
crate::triggers::TriggerAction::Capture => {
captured.push(crate::widgets::captures::CapturedLine {
pane: t.label().to_string(),
shell_pid: t.shell_pid(),
message: h.message,
line: h.line,
});
}
crate::triggers::TriggerAction::Bell => {
trigger_note =
Some(format!("Trigger bell in {}: {}", t.label(), h.message));
}
_ => {
trigger_note = Some(format!("Trigger in {}: {}", t.label(), h.message));
}
}
}
if t.take_bell() {
rang = Some(t.label().to_string());
}
for msg in t.drain_notifications() {
let cwd = t.local_shell_cwd();
self.notifier.emit(
crate::notifications::Event::Osc9 {
pane: t.label().to_string(),
message: msg.clone(),
},
self.root_for_path(cwd.as_deref()),
&remote_host_label(),
);
notes.push(msg);
}
// Always drain so completions never pile up unseen.
for f in t.drain_finished_commands() {
if !f.output.is_empty() {
build_scans.push((t.uid(), f.cwd.clone(), f.cmd.clone(), f.output.clone()));
}
// Durable command history: every finished command with a
// known text is recorded (cwd, exit, duration, timestamp)
// for the Ctrl+Shift+R cross-session search.
if !f.cmd.trim().is_empty() {
let ts = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
self.command_history
.append(crate::command_history::HistoryEntry {
// The durable history is on disk and cross-
// session: a typed `export KEY=…` is masked
// like any other persisted text (#360).
cmd: crate::triggers::mask_text(f.cmd.trim(), &self.triggers, false),
cwd: f
.cwd
.as_deref()
.map(|p| p.display().to_string())
.unwrap_or_default(),
host: f.host.clone().unwrap_or_default(),
exit: f.exit,
dur_ms: f.dur.as_millis() as u64,
ts,
});
}
if let Some(p) = self.pending_debug_launch.as_ref()
&& finished_settles_pending(t.uid(), &f.cmd, p.pane, &p.command)
{
settled_launch = Some(f.exit);
}
if t.focused {
continue;
}
// The sinks decide by their own threshold (#358); the
// status-bar notice keeps the fixed one below.
self.notifier.emit(
crate::notifications::Event::CommandFinished {
pane: t.label().to_string(),
cmd: crate::triggers::mask_text(f.cmd.trim(), &self.triggers, false),
exit: f.exit,
dur: f.dur,
cwd: f.cwd.clone(),
host: f.host.clone(),
},
self.root_for_path(f.cwd.as_deref()),
&remote_host_label(),
);
if f.dur < LONG_COMMAND_NOTIFY {
continue;
}
let code = f.exit.map_or_else(|| String::from("?"), |c| c.to_string());
finished = Some(format!(
"Command in {} finished: exit {code} in {}",
t.label(),
crate::widgets::terminal::human_duration(f.dur)
));
}
}
if let Some(exit) = settled_launch
&& let Some(pending) = self.pending_debug_launch.take()
{
self.resume_pending_launch(exit, pending.step);
}
// Liveness fallback for a still-parked launch: the FinishedCommand
// match depends on OSC 133 marks, and a pane without integration (or
// one the user closed) would otherwise park the launch forever.
let mut pending_aborted = false;
if settled_launch.is_none()
&& let Some(p) = self.pending_debug_launch.as_ref()
{
let pane = self.terminals.iter().find(|t| t.uid() == p.pane);
if let Some(reason) = pending_abort_reason(
pane.is_some(),
pane.is_some_and(|t| t.foreground_is_shell()),
p.started.elapsed(),
) {
self.pending_debug_launch = None;
self.debug_error(format!(
"preLaunchTask abandoned: {reason} — debug launch aborted"
));
pending_aborted = true;
}
}
let mut build_changed = false;
// Watch publishes first: a batch replaces the pane's entries
// wholesale, and marks the pane so the watcher's own eventual
// FinishedCommand rescan cannot resurrect stale cycles.
for (pane, cwd, diags) in watch_installs {
self.watch_published_panes.insert(pane);
build_changed |= self.install_build_diags(pane, cwd.as_deref(), diags);
}
for (pane, cwd, cmd, output) in build_scans {
build_changed |= self.apply_build_scan(pane, cwd.as_deref(), &cmd, &output);
}
// Captures collect silently (iTerm2's model: the panel is the
// surface, not the status bar), but still trigger a redraw.
let had_captures =
!captured.is_empty() || build_changed || settled_launch.is_some() || pending_aborted;
for c in captured {
self.captures.push(c);
}
if let Some(msg) = trigger_note {
self.status = msg;
return true;
}
if had_captures {
return true;
}
if let Some(msg) = notes.pop() {
self.status = format!("Terminal notification: {msg}");
return true;
}
if let Some(msg) = finished {
self.status = msg;
return true;
}
let Some(label) = rang else {
return false;
};
self.status = format!("Bell in terminal: {label}");
true
}
/// Cmd+Opt+Up / Cmd+Opt+Down in the terminal: scroll the previous / next
/// OSC 133 prompt mark to the top of the pane.
fn terminal_prompt_jump(&mut self, forward: bool) {
let prompts = self.terminal().prompt_lines();
let top = self.terminal().viewport_top_line();
let Some(target) = crate::widgets::terminal::pick_prompt_jump(&prompts, top, forward)
else {
self.status = String::from(if prompts.is_empty() {
"No command marks yet (shell integration needs a zsh prompt)"
} else if forward {
"No next command"
} else {
"No previous command"
});
return;
};
self.terminal_mut().scroll_line_to_top(target);
}
/// The most recent finished command in the active pane, for the
/// `⌘K ⇧C`/`⇧S`/`⇧R` keyboard forms of the decoration-menu actions.
fn last_command_decoration(&self) -> Option<crate::widgets::terminal::CommandDecoration> {
self.terminal().command_decorations().last().copied()
}
/// The command decoration dot under the pointer, when the panel shows
/// the terminal. Used both to open the decoration menu and to exempt
/// dot cells from the resize-seam grab zones they can overlap.
fn decoration_dot_at(
&self,
col: u16,
row: u16,
) -> Option<(usize, crate::widgets::terminal::CommandDecoration)> {
if !self.show_terminal || self.bottom_panel_tab != BottomPanelTab::Terminal {
return None;
}
let idx = self.terminal_at_pos(col, row)?;
self.terminals[idx]
.decoration_at_screen(col, row)
.map(|d| (idx, d))
}
fn copy_command_output(&mut self, idx: usize, d: crate::widgets::terminal::CommandDecoration) {
let Some(t) = self.terminals.get(idx) else {
return;
};
// Same clipboard rule as a selection copy (#360): rules marked
// copy=masked keep their mask.
let text = self.terminal_text_for_copy(t.command_output_text(&d));
if text.is_empty() {
self.status = String::from("Command produced no output");
return;
}
let lines = text.lines().count();
copy_to_clipboard(&text);
self.status = if lines == 1 {
String::from("Copied command output (1 line)")
} else {
format!("Copied command output ({lines} lines)")
};
}
fn select_command_output(
&mut self,
idx: usize,
d: crate::widgets::terminal::CommandDecoration,
) {
let Some(t) = self.terminals.get_mut(idx) else {
return;
};
t.select_command_output(&d);
self.status = String::from(if t.selection().is_some_and(|s| s.has_area()) {
"Command output selected"
} else {
"Command produced no output"
});
}
fn rerun_command(&mut self, idx: usize, d: crate::widgets::terminal::CommandDecoration) {
let Some(t) = self.terminals.get(idx) else {
return;
};
let cmd = t.command_input_text(&d);
if cmd.is_empty() {
self.status = String::from("No command text recorded at that prompt");
return;
}
self.terminals[idx].write_input(format!("{cmd}\r").as_bytes());
self.status = format!("Re-running: {cmd}");
}
/// The context menu a click on a command decoration dot opens: a header
/// with the outcome, then the VS Code decoration actions.
fn open_command_decoration_menu(
&mut self,
origin: (u16, u16),
d: crate::widgets::terminal::CommandDecoration,
) {
let idx = self.active_terminal;
let code = d.exit.map_or_else(|| String::from("?"), |c| c.to_string());
let header = match d.duration {
Some(dur) => format!(
"exit {code} in {}",
crate::widgets::terminal::human_duration(dur)
),
None => format!("exit {code}"),
};
self.context_menu = Some(ContextMenu {
origin,
items: vec![
MenuEntry::header(header),
MenuEntry::Item {
label: String::from("Copy Output"),
action: MenuAction::CopyCommandOutput(idx, d),
},
MenuEntry::Item {
label: String::from("Select Output"),
action: MenuAction::SelectCommandOutput(idx, d),
},
MenuEntry::Item {
label: String::from("Re-run Command"),
action: MenuAction::RerunCommand(idx, d),
},
],
selected: 1,
open_submenu: None,
submenu_selected: 0,
target_dir: self.tree.root.clone(),
});
}
fn drain_ports_and_poll(&mut self) -> bool {
let mut changed = false;
if self
.port_toast
.as_ref()
.is_some_and(|t| t.shown_at.elapsed() > PORT_TOAST_TTL)
{
self.port_toast = None;
changed = true;
}
let origin = self.port_origin();
let scraped: Vec<crate::port_detect::PortHit> = self
.terminals
.iter()
.flat_map(|t| t.drain_ports())
.collect();
for hit in scraped {
let port = hit.port;
let process = hit.process.clone();
if self
.ports
.upsert(port, hit.url, hit.process, origin.clone())
{
changed = true;
}
// Toast on the scrape confirmation, not on first insert: the silent
// socket poll may have added the port first (common on a remote
// session), which must not swallow the toast.
if self.ports.note_scrape_toast(port) {
self.show_port_toast(port, process);
changed = true;
}
}
// Latest background-poll snapshot (a complete listener set): add new
// ports, then reconcile so ports that stopped listening go not-live and
// eventually drop. Only the newest queued snapshot matters.
if let Some(poll) = self.port_poll_rx.try_iter().last() {
for hit in poll.hits {
if self
.ports
.upsert(hit.port, hit.url, hit.process, origin.clone())
{
changed = true;
}
}
// Reconcile only against the unscoped listener set. `None` means
// neither `lsof` nor `ss` ran, which is no evidence at all — far
// better to leave every row alone than to retire live ports and
// cancel their tunnels on a failed probe.
if let Some(live) = poll.listening {
let outcome = self.ports.reconcile_live(&live);
if outcome.changed {
changed = true;
}
// A dropped forward's tunnel is no longer needed — cancel it.
for (local, remote) in outcome.torn_down {
self.request_remote_unforward(local, remote);
}
}
}
// On cadence, kick off a fresh poll off-thread — `lsof`/`ps` block for
// tens of ms and must never run on the event loop. One in flight max.
if self.last_port_poll.elapsed() >= PORT_POLL_INTERVAL
&& !self
.port_poll_inflight
.load(std::sync::atomic::Ordering::Relaxed)
{
self.last_port_poll = std::time::Instant::now();
let pids: Vec<i32> = self
.terminals
.iter()
.filter_map(|t| t.pid().map(|p| p as i32))
.collect();
if !pids.is_empty() {
let tx = self.port_poll_tx.clone();
let inflight = self.port_poll_inflight.clone();
inflight.store(true, std::sync::atomic::Ordering::Relaxed);
std::thread::spawn(move || {
// Two questions, two scans. The subtree scan says what to
// SURFACE (a system daemon is not the user's dev server);
// the unscoped one says what is still UP, which the subtree
// cannot answer for a port nobody in it owns.
let mut hits: Vec<crate::port_detect::PortHit> = Vec::new();
for pid in pids {
for hit in crate::port_detect::poll_listeners(pid) {
if !hits.iter().any(|h| h.port == hit.port) {
hits.push(hit);
}
}
}
let listening = crate::port_detect::poll_all_listening();
let _ = tx.send(PortPoll { hits, listening });
inflight.store(false, std::sync::atomic::Ordering::Relaxed);
});
}
}
changed
}
/// A click on one of the update popup's buttons (#333). Update stages
/// the build and leaves the popup up as a progress line; Later and
/// Relaunch both take it down. A click elsewhere returns false.
fn handle_update_toast_click(&mut self, x: u16, y: u16) -> bool {
let Some(toast) = self.update_toast.as_ref() else {
return false;
};
let Some(action) = toast
.buttons
.iter()
.find(|(r, _)| rect_contains(*r, x, y))
.map(|(_, a)| *a)
else {
return false;
};
let version = toast.version.clone();
match action {
UpdateToastAction::Update => {
if self.staged_install.is_none() && self.self_install.is_none() {
self.start_staged_update(version);
}
}
UpdateToastAction::Later => {
self.update_toast = None;
self.dismiss_update_offer(&version);
}
UpdateToastAction::Relaunch => {
self.update_toast = None;
// The popup describes the staged release: only ITS
// readiness may fire it, never a drift rebuild's.
if self.staged_update_binary().is_some() {
self.pending_reexec = true;
self.quit = true;
}
}
}
true
}
fn show_port_toast(&mut self, port: u16, process: Option<String>) {
self.port_toast = Some(PortToast {
port,
process,
origin_remote: self.is_remote,
shown_at: std::time::Instant::now(),
buttons: Vec::new(),
});
}
/// Seat, re-judge, or unseat the agent in EVERY pane (#344), from the
/// `(shell_pid, process_name)` samples the pill uses, and queue the
/// transitions. Driven over panes rather than over samples: a pane whose
/// foreground did not resolve this round (the agent exited and took the
/// shell with it, a pid `sysinfo` missed) has no sample, and that must
/// unseat it rather than leave the badge on forever. `quiet_after` is
/// the working/quiet threshold ([`crate::agents::QUIET_AFTER`]; tests
/// pass zero). Returns whether any pane's lane changed.
pub(crate) fn apply_agent_samples(
&mut self,
samples: &[(i32, String)],
quiet_after: std::time::Duration,
) -> bool {
let by_pid: std::collections::HashMap<i32, &str> = samples
.iter()
.map(|(pid, name)| (*pid, name.as_str()))
.collect();
let mut changed = false;
for t in &mut self.terminals {
let next = t
.shell_pid()
.and_then(|pid| by_pid.get(&pid))
.and_then(|name| self.agents.classify(name))
.map(|kind| crate::agents::AgentLane {
name: kind.name.clone(),
status: crate::agents::judge(kind, t.quiet_for(), &t.tail_rows(6), quiet_after),
});
let prev = t.agent().cloned();
if prev == next {
continue;
}
let pane = t.label().to_string();
self.agent_events.extend(crate::agents::transition(
&pane,
prev.as_ref(),
next.as_ref(),
));
t.set_agent(next);
changed = true;
}
changed
}
/// Consume the agent transitions the last sample queued: a waiting agent
/// is announced in the status bar (the chip and the pill already show
/// it). Returns whether anything was said.
fn drain_agent_events(&mut self) -> bool {
let mut said = false;
while let Some(ev) = self.agent_events.pop_front() {
// A gone agent with nothing left to review takes its lane with
// it; one with a queue keeps it, since the files it changed
// still need looking at (#345). The event is per PANE while the
// lane is per NAME, so a second pane still running the same
// agent — or an agent swap in one pane, which fires Gone then
// Seated — must not take the shared lane down with it.
if let crate::agents::AgentEvent::Gone { agent, .. } = &ev
&& self.agent_ledger.unreviewed_count(agent) == 0
&& !self
.terminals
.iter()
.any(|t| t.agent().is_some_and(|a| a.name == *agent))
{
let agent = agent.clone();
// No decoration sync needed here, and deliberately so: the
// guard above only lets this run when the lane has NOTHING
// unreviewed, so it removes no row the Explorer is drawing
// a dot for (#345).
self.agent_ledger.forget(&agent);
}
if let crate::agents::AgentEvent::Waiting { pane, agent } = ev {
self.status = format!("{agent} in {pane} is waiting for your input");
said = true;
}
}
said
}
/// `(agents seated, of which waiting)` across every pane, for the chip.
fn agent_counts(&self) -> (usize, usize) {
let seated = self
.terminals
.iter()
.filter(|t| t.agent().is_some())
.count();
let waiting = self
.terminals
.iter()
.filter(|t| {
t.agent()
.is_some_and(|a| a.status == crate::agents::AgentStatus::Waiting)
})
.count();
(seated, waiting)
}
/// The agents whose panes are producing output right now (#345). A
/// merely SEATED agent does not count: a quiet agent's pane is no
/// reason to blame it for the user's own save.
fn working_agents(&self) -> Vec<String> {
let mut names: Vec<String> = self
.terminals
.iter()
.filter_map(|t| t.agent())
.filter(|lane| lane.status == crate::agents::AgentStatus::Working)
.map(|lane| lane.name.clone())
.collect();
names.sort();
names.dedup();
names
}
/// Record each changed file against every working agent, hashing its
/// current content. A file that cannot be read right now is skipped
/// rather than recorded at a stale hash.
///
/// A DELETION is processed whether or not an agent is working: a file
/// can be removed after its agent goes idle, and the row would
/// otherwise sit in the queue forever pointing at a file that is not
/// there (its lane staying visible with it). Only attribution — adding
/// or updating a row — needs a working agent to attribute to.
fn attribute_writes_to_working_agents(
&mut self,
changed: &std::collections::BTreeSet<PathBuf>,
) -> bool {
let working = self.working_agents();
let mut any = false;
// Resolved once: the roots cannot change inside this loop, and on a
// symlinked root the direct check never hits, so leaving it inside
// would pay `files x roots` canonicalisations on every drain.
let root_canons = self.root_canons();
for path in changed {
// Only workspace files: an agent editing its own config under
// $HOME is not part of this workspace's review queue. ANY root
// counts, not just the primary — a secondary folder's files are
// as much this session's work as the first folder's (#345).
// Compare in the same spelling on both sides. The watcher reports
// the realpath, while a root is stored as the user gave it — so on
// macOS a workspace under /var arrives as /private/var and matches
// no root. Every agent write was silently dropped and the queue
// stayed empty with nothing failing. Any root reached through a
// symlink has the same shape, which is ordinary on Linux too.
//
// The path is recorded in the form the ROOT uses, so the ledger's
// keys match what the Explorer's rows are keyed on and a later
// "mark reviewed" finds the row instead of adding a second.
let Some(under_root) = self.path_under_roots(&root_canons, path) else {
continue;
};
let path = &under_root;
match crate::agent_lane::read_baseline(path) {
// Attribution needs someone to attribute to; a quiet
// agent's pane is no reason to blame it for the user's
// own save.
crate::agent_lane::Baseline::Hash(hash) if !working.is_empty() => {
any |= self.agent_ledger.record_write(path, hash, &working);
}
crate::agent_lane::Baseline::Hash(_) => {}
// The agent deleted it: the row goes, rather than sitting in
// the queue forever pointing at a file that is not there.
crate::agent_lane::Baseline::Gone => {
any |= self.agent_ledger.forget_path(path);
}
// Unreadable this instant; the next write re-reports it.
crate::agent_lane::Baseline::Unreadable => {}
}
}
any
}
/// `path` expressed under whichever workspace root owns it, or `None`
/// when no root does.
///
/// Tries the path as given first — the common case, costing nothing —
/// then compares canonicalised, which is what a file watcher's realpath
/// needs to match a root the user spelled with a symlink in it. The
/// returned path is rooted the way the ROOT is spelled, so everything
/// keyed on it agrees with the Explorer's rows.
///
/// A DELETED path still resolves. `canonicalize` stats the final
/// component and fails with `ENOENT` on a path that is gone — which is
/// exactly what a deletion event carries, so resolving the whole path
/// would make the ledger's `forget_path` arm unreachable and strand rows
/// on files that no longer exist. The walk therefore resolves the
/// deepest ancestor that DOES exist and re-attaches the tail: a deleted
/// file's parent directory is almost always still there, and when it is
/// not the walk keeps climbing.
///
/// Longest prefix wins, mirroring `WorkspaceRoots::owning_root`: with
/// nested roots the deeper one owns the path, and picking the first
/// match instead would make the ledger's key depend on the order the
/// user added folders.
/// The roots are resolved by the CALLER so a loop over many changed
/// paths can hoist the canonicalisation, which depends only on the root
/// set and cannot change between iterations. Not a cache — there is
/// nothing to invalidate, because the value does not outlive the loop
/// that computes it.
fn path_under_roots(&self, root_canons: &[(PathBuf, PathBuf)], path: &Path) -> Option<PathBuf> {
// The direct check FIRST, and that ordering is load-bearing rather
// than merely quick. If an intermediate directory is itself a
// symlink pointing outside the workspace, resolving the whole path
// would land the result outside the root; hitting on the spelled
// path here means the walk below never sees that case.
if self.roots.owning_root(path).is_some() {
return Some(path.to_path_buf());
}
let canon = canonicalize_existing_ancestor(path)?;
root_canons
.iter()
.cloned()
.filter_map(|(spelled, canon_root)| {
let rel = canon.strip_prefix(&canon_root).ok()?;
Some((canon_root.components().count(), spelled.join(rel)))
})
.max_by_key(|(depth, _)| *depth)
.map(|(_, joined)| joined)
}
/// Each root as `(spelling, canonical)`.
///
/// Recomputed per call rather than cached on `App`: the set is one or
/// two entries in practice, and this runs only when a path failed the
/// direct check — i.e. on a symlinked root, where it is the price of the
/// feature working at all. A cache here would need invalidating from
/// every root mutation, which is more ways to be wrong than it saves.
fn root_canons(&self) -> Vec<(PathBuf, PathBuf)> {
self.roots
.iter()
.map(|r| {
(
r.to_path_buf(),
std::fs::canonicalize(r).unwrap_or_else(|_| r.to_path_buf()),
)
})
.collect()
}
/// Called from every place the ledger's CONTENT changes, rather than on
/// a schedule: a decoration that lags the thing it describes is worse
/// than none, because "no dot" is exactly what a reviewed file looks
/// like, so a stale one says the user reviewed something they did not.
///
/// Every site that mutates the ledger's content calls this, and here is
/// why that is all of them. `record_write`
/// and `forget_path` both run under the fs-watch drain, behind
/// `attribute_writes_to_working_agents`'s return; `mark_reviewed` under
/// `mark_agent_file_reviewed`; `mark_lane_reviewed` under
/// `mark_agent_lane_reviewed`; `forget_path` again from
/// `remove_workspace_folder`. Of the ledger's other `&mut self`
/// methods, `note_dropped_events` and `settle_if_empty` move only the
/// incomplete flag and cannot change the set, and `forget` is reachable
/// only behind a guard that requires the lane to be empty already.
fn sync_agent_lane_decorations(&mut self) {
let paths = self.agent_ledger.unreviewed_paths();
// Skip the Arc swap when both sides are empty, which is the common
// shape early in a session and after a review clears the queue.
if paths.is_empty() && self.tree.agent_touched.is_empty() {
return;
}
self.tree.agent_touched = std::sync::Arc::new(paths);
}
/// Snapshot `bytes` as `path`'s review baseline and return the millis
/// that names it (#345).
///
/// The store is only ever written by croft's OWN saves; the agent-write
/// path that creates lane rows records nothing. So adopting whatever
/// snapshot happened to be newest anchored the review to an unrelated
/// earlier save and then labelled the diff "(reviewed)" — the exact
/// "baseline other than the one claimed" the diff refuses elsewhere.
/// Recording here is what makes the anchor name the reviewed content.
///
/// `record_in` dedupes identical content and, inside the merge window,
/// REPLACES the newest entry instead of appending — so the snapshot that
/// ends up holding these bytes need not be at `millis`. Read the store
/// back rather than assuming, and return `None` when nothing holds them:
/// history is best-effort, and a row with no anchor is still reviewed,
/// it just cannot show a diff.
fn record_review_baseline(history_root: &Path, path: &Path, bytes: &[u8]) -> Option<u64> {
let millis = now_millis();
let _ = crate::history::record_in(history_root, path, bytes, millis);
crate::history::entries_in(history_root, path)
.into_iter()
.find(|s| std::fs::read(&s.file).is_ok_and(|held| held == bytes))
.map(|s| s.millis)
}
/// Diff one agent-lane row against the snapshot that was its baseline
/// when the user last marked it reviewed (#345), rather than against
/// HEAD.
///
/// Refuses rather than falling back to a different baseline. A row with
/// no recorded snapshot (never reviewed, or reviewed before the store
/// had one) and a row whose snapshot has since been PRUNED — the store
/// keeps 50 per file against a 1s autosave, so this is a live case, not
/// only a legacy one — both say so. A diff against a baseline other than
/// the one claimed is worse than no diff, because the user cannot see
/// which one they got.
pub(crate) fn diff_agent_lane_row(&mut self, agent: &str, path: &Path) {
// "Restore Snapshot" writes to the path recorded here, and only
// `open_timeline_diff` cleared it. Browsing a.txt's timeline and then
// opening this diff on b.txt left restore armed at a.txt, so the
// command would overwrite a file the user was not even looking at.
// Disarm on every exit below, including the refusals: a refused diff
// leaves the PREVIOUS diff on screen, and arming restore to that is
// exactly the stale pairing this guards.
self.history_restore = None;
let Some(row) = self
.agent_ledger
.lane(agent)
.into_iter()
.find(|f| f.path == path)
else {
self.status = format!("{} is not in {agent}'s lane", path.display());
return;
};
let Some(millis) = row.reviewed_millis else {
self.status = if row.reviewed_hash.is_some() {
format!(
"{} was reviewed before a snapshot existed - nothing to diff against",
path.display()
)
} else {
format!("{} has not been reviewed yet", path.display())
};
return;
};
let Some(snap_file) = crate::history::snapshot_file_in(&self.history_root, path, millis)
else {
self.status = format!(
"The snapshot {} was reviewed against is no longer available",
path.display()
);
return;
};
let Ok(content) = std::fs::read(&snap_file) else {
self.status = format!("Could not read the reviewed snapshot of {}", path.display());
return;
};
// Snapshots hold raw bytes; decode like the local-history diff above
// so a UTF-16 file diffs as text rather than mojibake.
let enc = encoding_rs::Encoding::for_bom(&content)
.map(|(e, _)| e)
.unwrap_or(encoding_rs::UTF_8);
let text = enc.decode(&content).0.into_owned();
let rel = match path.strip_prefix(&self.tree.root) {
Ok(r) => r.to_string_lossy().into_owned(),
Err(_) => path.display().to_string(),
};
let label = std::path::PathBuf::from(format!("{rel} (reviewed)"));
if let Err(e) = self
.editor
.open_head_diff_with_text(label, &text, path, false)
{
self.status = format!("Could not open the reviewed diff: {e}");
return;
}
self.tag_open_diff(crate::widgets::diff::DiffSource::FixedLeft { left_text: text });
// Armed to the snapshot now on screen, matching `open_timeline_diff`:
// "Restore Snapshot" puts back the version the user reviewed.
self.history_restore = Some((path.to_path_buf(), millis, content));
self.focus_pane(Pane::Editor);
self.status = format!("{rel}: changes since you last reviewed it");
}
/// Mark one file reviewed in one agent's lane (#345): the content on
/// DISK now becomes the baseline, so the row returns only on a later
/// write.
pub(crate) fn mark_agent_file_reviewed(&mut self, agent: &str, path: &Path) -> bool {
let changed = self.mark_agent_file_reviewed_inner(agent, path);
if changed {
self.sync_agent_lane_decorations();
}
changed
}
fn mark_agent_file_reviewed_inner(&mut self, agent: &str, path: &Path) -> bool {
// A file too big to hash is too big to snapshot: `read_baseline`
// stamps those from metadata rather than slurping 4 MiB+, and
// copying one into the history store on every review would be worse.
// It reviews with NO anchor - honest, and the diff then says it has
// nothing to compare against.
if std::fs::metadata(path).is_ok_and(|m| m.len() > crate::agent_lane::MAX_HASH_BYTES) {
return match crate::agent_lane::read_baseline(path) {
crate::agent_lane::Baseline::Hash(hash) => {
self.agent_ledger.mark_reviewed(agent, path, hash, None)
}
crate::agent_lane::Baseline::Gone => self.agent_ledger.forget_path(path),
crate::agent_lane::Baseline::Unreadable => {
self.status = format!("Could not read {} to mark it reviewed", path.display());
false
}
};
}
// One read, used for BOTH the hash and the snapshot: reading twice
// lets a write land in between, and the baseline would then be a hash
// of content the anchor does not hold.
match std::fs::read(path) {
Ok(bytes) => {
let hash = crate::agent_lane::content_hash(&bytes);
let snap = Self::record_review_baseline(&self.history_root, path, &bytes);
self.agent_ledger.mark_reviewed(agent, path, hash, snap)
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
self.agent_ledger.forget_path(path)
}
// Unreadable right now is NOT reviewed: say so instead of
// clearing content the user has not seen.
Err(_) => {
self.status = format!("Could not read {} to mark it reviewed", path.display());
false
}
}
}
/// Mark an agent's whole lane reviewed (#345).
pub(crate) fn mark_agent_lane_reviewed(&mut self, agent: &str) -> usize {
let root = self.history_root.clone();
// Same contract as the single-file path: the anchor must hold the
// bytes that were hashed, so read once and snapshot THOSE. Reading
// separately in the two closures would let a write land between them.
let (reviewed, dropped) = self.agent_ledger.mark_lane_reviewed(agent, |path| {
// Too big to hash is too big to snapshot: stamp it and
// review with no anchor, as the single-file path does.
if std::fs::metadata(path).is_ok_and(|m| m.len() > crate::agent_lane::MAX_HASH_BYTES) {
return (crate::agent_lane::read_baseline(path), None);
}
match std::fs::read(path) {
Ok(bytes) => (
crate::agent_lane::Baseline::Hash(crate::agent_lane::content_hash(&bytes)),
Self::record_review_baseline(&root, path, &bytes),
),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
(crate::agent_lane::Baseline::Gone, None)
}
Err(_) => (crate::agent_lane::Baseline::Unreadable, None),
}
});
// A file that vanished was not REVIEWED; saying so would tell the
// user they looked at something that is not there.
let gone = match dropped {
0 => String::new(),
1 => String::from(", 1 gone"),
n => format!(", {n} gone"),
};
self.status = match reviewed {
0 if dropped == 0 => format!("{agent}: nothing waiting for review"),
0 => format!("{agent}: nothing to review{gone}"),
1 => format!("{agent}: 1 file marked reviewed{gone}"),
n => format!("{agent}: {n} files marked reviewed{gone}"),
};
if reviewed + dropped > 0 {
self.sync_agent_lane_decorations();
}
reviewed + dropped
}
/// Focus the first waiting agent's pane, else the first seated one. Goes
/// through `set_bottom_panel_tab` like `captures_open_selected`, so a
/// click from the editor with the panel collapsed reveals the pane
/// rather than focusing something the user cannot see.
fn focus_agent_pane(&mut self) {
let pick = self
.terminals
.iter()
.position(|t| {
t.agent()
.is_some_and(|a| a.status == crate::agents::AgentStatus::Waiting)
})
.or_else(|| self.terminals.iter().position(|t| t.agent().is_some()));
match pick {
Some(idx) => {
self.reveal_terminal_pane(idx);
self.set_bottom_panel_tab(BottomPanelTab::Terminal);
}
// The chip is showing a review queue whose agents have all gone:
// a click that silently did nothing was the worst of the three
// options (#345 review).
None => self.run_command(crate::widgets::command_palette::Command::ShowAgentLane),
}
}
/// The workspace root a path belongs to, for a notification's title and
/// deep link (#358): in a multi-root session an event from a pane in a
/// secondary root must name that root, not the primary. The primary is
/// the fallback for a path outside every root, or no path at all.
fn root_for_path(&self, path: Option<&Path>) -> &Path {
path.and_then(|p| self.roots.iter().find(|r| p.starts_with(r)))
.unwrap_or_else(|| self.roots.primary())
}
/// Refresh each pane's auto-label from its live foreground process. The
/// `tcgetpgrp` reads are cheap and stay on the loop; the `sysinfo` name
/// lookups (the slow part) run on a one-shot background thread, keyed by
/// shell pid so results land on the right pane even if panes moved. Returns
/// whether any label changed (for redraw).
fn refresh_terminal_labels(&mut self) -> bool {
let mut changed = false;
// Apply whatever the last background lookup resolved.
if let Some(samples) = self.ssh_rx.try_iter().last() {
self.apply_ssh_samples(samples);
}
if let Some(labels) = self.label_rx.try_iter().last() {
for (shell_pid, name) in &labels {
if let Some(t) = self
.terminals
.iter_mut()
.find(|t| t.shell_pid() == Some(*shell_pid))
&& t.label() != name
{
t.set_auto_label(name.clone());
changed = true;
}
}
changed |= self.apply_agent_samples(&labels, crate::agents::QUIET_AFTER);
}
if self.last_label_refresh.elapsed() >= TERMINAL_LABEL_INTERVAL
&& !self
.label_inflight
.load(std::sync::atomic::Ordering::Relaxed)
{
self.last_label_refresh = std::time::Instant::now();
// (shell_pid, foreground_pid) gathered cheaply on the loop.
let targets: Vec<(i32, i32)> = self
.terminals
.iter()
.filter_map(|t| match (t.shell_pid(), t.foreground_pid()) {
(Some(sp), Some(fg)) => Some((sp, fg)),
_ => None,
})
.collect();
if targets.is_empty() {
// No pane has a foreground process to sample: any seated
// agent is gone, and only an empty sample says so.
changed |= self.apply_agent_samples(&[], crate::agents::QUIET_AFTER);
}
if !targets.is_empty() {
let tx = self.label_tx.clone();
let ssh_tx = self.ssh_tx.clone();
let sample_ssh = !self.remote_offer_disabled;
let inflight = self.label_inflight.clone();
inflight.store(true, std::sync::atomic::Ordering::Relaxed);
std::thread::spawn(move || {
let named: Vec<(i32, i32, String)> = targets
.into_iter()
.filter_map(|(sp, fg)| {
crate::widgets::terminal::process_name(fg).map(|n| (sp, fg, n))
})
.collect();
// The ssh-pane offer (#364) rides this thread: only a
// pane whose foreground IS ssh pays the argv read (a
// whole-process-table enumeration), and the config
// parse runs once per pass and only when one does. The
// verdicts themselves are `remote::ssh_pane_samples`,
// kept pure so the gate is testable without a pane.
if sample_ssh {
let _ = ssh_tx.send(crate::remote::ssh_pane_samples(
&named,
crate::remote::discover_ssh_targets,
crate::widgets::terminal::process_cmdline,
));
}
let resolved: Vec<(i32, String)> =
named.into_iter().map(|(sp, _, n)| (sp, n)).collect();
let _ = tx.send(resolved);
inflight.store(false, std::sync::atomic::Ordering::Relaxed);
});
}
}
changed
}
/// `⏎` on a port: open it. A local (or already-forwarded) port opens
/// straight away; a remote port that isn't forwarded yet is forwarded first,
/// then opened.
fn ports_open_selected(&mut self) {
let Some(entry) = self.ports.selected() else {
return;
};
match plan_port_open(entry, self.drop_relay_active()) {
PortOpenAction::Forward(port) => self.request_remote_forward(port, true),
PortOpenAction::OpenViaRelay(url) => {
self.request_remote_url_open(url.clone());
self.status = format!("Opening {url} in your local browser");
}
PortOpenAction::OpenDirect(url) => match open_url(&url) {
Ok(()) => self.status = format!("Opened {url}"),
Err(e) => self.status = format!("Open failed: {e}"),
},
PortOpenAction::Nothing => {}
}
}
fn ports_forward_selected(&mut self) {
use crate::widgets::ports::PortOrigin;
let Some(entry) = self.ports.selected() else {
return;
};
if !matches!(entry.origin, PortOrigin::Remote(_)) || entry.forwarded {
self.status = String::from("Port is already reachable locally");
return;
}
let port = entry.port;
self.request_remote_forward(port, false);
}
fn ports_copy_selected(&mut self) {
let Some(entry) = self.ports.selected() else {
return;
};
let addr = entry
.open_url()
.unwrap_or_else(|| format!("localhost:{}", entry.port));
if copy_to_clipboard(&addr) {
self.status = format!("Copied {addr}");
} else {
self.status = String::from("Copy failed");
}
}
fn ports_stop_selected(&mut self) {
use crate::widgets::ports::PortOrigin;
let Some(entry) = self.ports.selected() else {
return;
};
let port = entry.port;
let forwarded = matches!(
(&entry.origin, entry.forwarded, entry.local_port),
(PortOrigin::Remote(_), true, Some(_))
);
// Two different gestures share `x`. Stopping a forward leaves the
// server running and the row in place, so the port must stay
// detectable; dismissing the row is the one that suppresses it.
if forwarded {
if let Some((local, remote)) = self.ports.stop_forwarding(port) {
self.request_remote_unforward(local, remote);
}
self.status = format!("Stopped forwarding port {port} (the server keeps running)");
} else {
self.ports.remove(port);
self.status = format!("Dismissed port {port} from the list (the server keeps running)");
}
}
/// Cmd/Ctrl+click in the active terminal: if a printed http(s) URL sits
/// under the cursor, act on it (forward a remote dev-server port and open,
/// or open the link) and return true so the click doesn't start a
/// selection. Returns false when there's no URL there.
/// Whether the built-in Ctrl/Cmd+click would open something at this cell.
///
/// Pure: the lookups [`Self::terminal_url_click`] and
/// [`Self::terminal_file_click`] perform, with the opening left out. The
/// swallow branch needs to know whether declining a prefix click COSTS the
/// user anything, and it cannot find out by calling the acting versions.
///
/// BOTH arms of the built-in's `||` are covered deliberately: checking
/// only the URL half would let a Ctrl+click on a file reference be
/// swallowed and its jump-to-file lost, which is the same defect one
/// branch over.
///
/// Deliberately conservative on the file half. `terminal_file_click`
/// resolves relative paths against the shell's cwd and touches the
/// filesystem; reproducing that here would duplicate logic that then
/// drifts. A file REFERENCE under the cursor is enough to defer to the
/// built-in — at worst the prefix click is not swallowed, which costs a
/// stray built-in action rather than a lost one.
///
/// Takes the CLICKED pane's index rather than reading `self.terminal()`.
/// The built-in activates the clicked pane before it looks for a link, so
/// a predicate reading the ACTIVE pane answers about different content
/// whenever the two differ — which is any split layout where the click
/// lands outside the focused pane.
fn terminal_would_open_something_at(&self, idx: usize, col: u16, row: u16) -> bool {
let Some(t) = self.terminals.get(idx) else {
return false;
};
if t.hyperlink_at_screen(col, row).is_some() {
return true;
}
t.line_text_at(col, row).is_some_and(|(text, c)| {
crate::port_detect::url_at(&text, c).is_some()
|| crate::file_ref::file_ref_at(&text, c).is_some()
})
}
/// Cmd/Ctrl+click in the active terminal: if a printed http(s) URL sits
/// under the cursor, act on it (forward a remote dev-server port and open,
/// or open the link) and return true so the click doesn't start a
/// selection. Returns false when there's no URL there.
fn terminal_url_click(&mut self, col: u16, row: u16) -> bool {
// A real OSC 8 hyperlink stored in the cell wins over text sniffing —
// the visible text of a linked cell often isn't the URI at all.
if let Some(uri) = self.terminal().hyperlink_at_screen(col, row) {
self.open_detected_url(&uri);
return true;
}
let Some((text, c)) = self.terminal().line_text_at(col, row) else {
return false;
};
let Some(url) = crate::port_detect::url_at(&text, c) else {
return false;
};
self.open_detected_url(&url);
true
}
/// Seed the Search sidebar from the last `grep`/`rg` command run in the
/// focused terminal, then run it. The Search panel already has multi-file
/// replace-all, so this turns a terminal search into an editable,
/// replace-across-every-match buffer (the `:cdo` loop) with one command.
fn search_from_last_terminal_command(&mut self) {
let input = {
let term = self.terminal();
let decs = term.command_decorations();
match decs.last() {
Some(d) => term.command_input_text(d),
None => {
self.status = String::from("No terminal command yet to search from");
return;
}
}
};
if !self.seed_search_from_command(input.trim()) {
self.status =
String::from("Last terminal command wasn't a grep/rg search — nothing to seed");
}
}
/// Populate and run the Search panel from a parsed terminal search
/// command line. Returns false when `input` isn't a recognisable search.
fn seed_search_from_command(&mut self, input: &str) -> bool {
let Some(sc) = crate::quickfix::parse_search_command(input) else {
return false;
};
self.search.seed(
sc.pattern.clone(),
sc.include.unwrap_or_default(),
sc.exclude.unwrap_or_default(),
);
self.search.opts.case_sensitive = sc.case_sensitive;
self.search.opts.whole_word = sc.whole_word;
self.search.opts.use_regex = sc.use_regex;
self.set_sidebar_view(SidebarView::Search);
self.submit_search_query();
self.status = format!("Search seeded from terminal: {}", sc.pattern);
true
}
/// Cmd/Ctrl+click on a printed `path:line[:col]` reference (compiler
/// errors, test failures, grep hits, tracebacks) jumps the editor
/// there. Relative paths resolve against the pane shell's live cwd,
/// then the workspace root; `~` against $HOME. The click only lands
/// when the resolved file exists, which also filters lookalikes such
/// as `host.com:443`.
fn terminal_file_click(&mut self, col: u16, row: u16) -> bool {
let Some((text, c)) = self.terminal().line_text_at(col, row) else {
return false;
};
let Some(fr) = crate::file_ref::file_ref_at(&text, c) else {
return false;
};
let Some(abs) = self.resolve_pane_path(self.active_terminal, &fr.path) else {
return false;
};
self.open_resolved_file_ref(&abs, fr.line, fr.column)
}
/// A path printed in pane `idx`, made absolute: `~` against $HOME, a
/// relative path against the pane shell's live cwd, then the workspace
/// root. Shared by the file-ref click and the captures ask.
fn resolve_pane_path(&self, idx: usize, raw: &str) -> Option<std::path::PathBuf> {
let path = std::path::PathBuf::from(raw);
if let Some(rest) = raw.strip_prefix("~/") {
return std::env::var_os("HOME").map(|h| std::path::PathBuf::from(h).join(rest));
}
if path.is_absolute() {
return Some(path);
}
let cwd = self
.terminals
.get(idx)
.and_then(|t| t.pid())
.and_then(cwd_of_pid)
.filter(|p| p.is_dir())
.unwrap_or_else(|| self.workspace_root().to_path_buf());
let joined = cwd.join(&path);
Some(if joined.is_file() {
joined
} else {
self.workspace_root().join(&path)
})
}
/// CAPTURES: ask the resident Navigator about the selected captured line
/// (#372). The line, the trigger that caught it, and the pane rows around
/// it (redacted like any text that leaves a pane, #360) ride the ask. A
/// `path:line` in the line opens that file first so the reply lands as
/// a comment box at the referenced line; otherwise the ask is anchored
/// on the active file, and with no file at all it says so.
pub(crate) fn ask_navigator_about_capture(&mut self) {
let Some(entry) = self.captures.selected_entry().cloned() else {
self.status = String::from("No captured line is selected");
return;
};
let Some(host) = &self.pair_host else {
self.status =
String::from("Navigator is not active (run croft pair in this workspace)");
return;
};
if host.is_busy() {
self.status = format!("{} is mid-turn; wait for it to finish", host.name());
return;
}
let name = host.name().to_string();
let idx = entry
.shell_pid
.and_then(|pid| {
self.terminals
.iter()
.position(|t| t.shell_pid() == Some(pid))
})
.unwrap_or(self.active_terminal);
// The rows around the line, if it is still in the scrollback; the
// line alone otherwise.
let needle: String = entry.line.trim_end().chars().take(60).collect();
let context: Vec<String> = match self.terminals.get(idx) {
Some(t) => match t.find_captured_line(&needle) {
Some(line) => {
let (lines, top) = t.grid_lines();
let hit = usize::try_from(line - top).unwrap_or(0);
crate::widgets::captures::context_window(
&lines,
hit,
crate::widgets::captures::ASK_CONTEXT_ROWS,
)
}
None => vec![entry.line.clone()],
},
None => vec![entry.line.clone()],
};
// Anchor: the file the line names, else the active file.
let referenced = crate::widgets::captures::first_file_ref(&entry.line)
.and_then(|fr| self.resolve_pane_path(idx, &fr.path).map(|abs| (abs, fr)))
.filter(|(abs, _)| abs.is_file());
let opened = match referenced {
Some((abs, fr)) => self.open_resolved_file_ref(&abs, fr.line, fr.column),
None => false,
};
let Some(file) = self
.editor
.path
.as_ref()
.and_then(|p| collab_file_key(&self.tree.root, p))
else {
self.status = String::from(
"Ask Navigator: the captured line names no workspace file and none is open",
);
return;
};
let row = self.editor.cursor_row;
let range = (row, row);
// Every part of the ask is masked here, the line and the trigger
// message included: a capture is stored raw (#360).
let triggers = self.triggers.clone();
let (instruction, selection) =
crate::widgets::captures::ask_prompt(&entry, &context, |t| {
crate::triggers::mask_text(t, &triggers, false)
});
let content = self.editor.lines.join("\n");
let Some(host) = &self.pair_host else {
// Unreachable today (nothing above touches the host), but a
// silent return would leave the jump's status reading as success.
self.status = String::from("Navigator is not active");
return;
};
match host.send_ask_turn(&file, range, &selection, &instruction, &content) {
Ok(()) => {
// Always name the anchor: when the line's own file did not
// open, the ask went to the active file and the user must
// see which.
self.status = format!(
"Asked {name} about the captured line, anchored at {file}:{}{}",
row + 1,
if opened { "" } else { " (the active file)" }
);
self.pair_turn_origin = Some((file, row));
}
Err(e) => self.status = format!("Ask Navigator failed: {e}"),
}
}
/// PROBLEMS: Fix with Navigator (#374). Opens the file at the diagnostic
/// and sends the navigator an ask turn built from the diagnostic
/// (message, source, position) with the server's quick fixes as
/// `hints`, anchored on the diagnostic's line. The navigator's edit
/// streams into the buffer under its caret exactly as any ask does, so
/// every safety property of that path holds: visible, cancellable with
/// `Cmd+K X` (which reverts the streamed text), never written to disk by
/// the navigator. The row wears a spinner until the turn ends, and the
/// server's next publish clears or updates it.
///
/// With no navigator seated the action says so rather than doing
/// nothing; the menu model has no disabled state (#372's shape).
pub(crate) fn fix_problem_with_navigator(
&mut self,
path: PathBuf,
item: crate::widgets::problems::ProblemItem,
hints: Vec<String>,
) {
let Some(host) = &self.pair_host else {
self.status =
String::from("Navigator is not active (run croft pair in this workspace)");
return;
};
if host.is_busy() {
self.status = format!("{} is mid-turn; wait for it to finish", host.name());
return;
}
let name = host.name().to_string();
// Land on the diagnostic first: the turn is anchored on the active
// file, and the navigator's caret parks where the user is looking.
let opened = if item.col_utf16 {
self.open_at_utf16(&path, item.line, item.col)
} else {
self.open_at(&path, item.line as usize, item.col as usize)
};
if let Err(e) = opened {
self.status = format!("Fix with Navigator: open failed: {e}");
return;
}
let Some(file) = self
.editor
.path
.as_ref()
.and_then(|p| collab_file_key(&self.tree.root, p))
else {
self.status = String::from("Fix with Navigator: the file is outside the workspace");
return;
};
let row = (item.line as usize).min(self.editor.lines.len().saturating_sub(1));
let selection = self.editor.lines.get(row).cloned().unwrap_or_default();
let instruction = crate::widgets::problems::fix_prompt(&item, &file, &hints);
let content = self.editor.lines.join("\n");
let Some(host) = &self.pair_host else {
// Unreachable today (the open above does not touch the seat),
// but a silent return would leave the jump's status as success.
self.status = String::from("Navigator is not active");
return;
};
match host.send_ask_turn(&file, (row, row), &selection, &instruction, &content) {
Ok(()) => {
let what: String = item
.message
.lines()
.next()
.unwrap_or("")
.chars()
.take(60)
.collect();
self.status = format!(
"Asked {name} to fix {file}:{}: {what} (Cmd+K X cancels)",
row + 1
);
self.pair_turn_origin = Some((file, row));
self.problems.fixing = Some((path, item.line));
self.problems_fix_started = Some(std::time::Instant::now());
}
Err(e) => self.status = format!("Fix with Navigator failed: {e}"),
}
}
/// The diagnostic under the caret in the active file, as a PROBLEMS
/// item, for the `Cmd+.` and palette entry points of Fix with Navigator
/// (#374). The first diagnostic covering the caret row wins; its source
/// is recovered from the per-server store, since the editor's overlay
/// does not carry it.
pub(crate) fn navigator_fix_candidate(
&self,
) -> Option<(PathBuf, crate::widgets::problems::ProblemItem)> {
let path = self.editor.path.clone()?;
let row = self.editor.cursor_row as u32;
let d = self
.editor
.diagnostics_in_line_range(row, row)
.into_iter()
.next()?;
let source = self
.lsp_diagnostics
.get(&path)
.and_then(|by_server| {
by_server.iter().find_map(|(server, diags)| {
diags
.iter()
.any(|x| {
x.start_line == d.start_line
&& x.start_char == d.start_char
&& x.message == d.message
})
.then(|| server.clone())
})
})
.unwrap_or_default();
Some((
path,
crate::widgets::problems::ProblemItem {
line: d.start_line,
col: d.start_char,
col_utf16: true,
severity: d.severity,
message: d.message,
source,
},
))
}
/// Stop the PROBLEMS-row spinner: the fix turn ended, was cancelled, or
/// the seat is gone (#374).
fn clear_problem_fix(&mut self) {
self.problems.fixing = None;
self.problems_fix_started = None;
}
/// Monotonic phase while a Fix with Navigator turn streams, so the loop
/// repaints its spinner; `0` otherwise, so it never wakes the renderer
/// idle (the same contract as the update spinner).
fn problems_fix_spinner_phase(&self) -> u128 {
match self.problems_fix_started {
Some(t) => t.elapsed().as_millis() / UPDATE_SPINNER_FRAME_MS,
None => 0,
}
}
/// Jump the editor to an absolute `path:line[:col]`, recording where the
/// user was so Back returns to it, exactly like go-to-definition. False
/// when the file doesn't exist or won't open.
fn open_resolved_file_ref(
&mut self,
abs: &std::path::Path,
line: u32,
column: Option<u32>,
) -> bool {
self.open_resolved_file_ref_inner(abs, line, column, true)
}
/// [`Self::open_resolved_file_ref`], but `record_nav` false skips the jump
/// history. A side-by-side open is ONE jump for the user even though it
/// opens two files, so it records the origin itself and opens both halves
/// without recording (otherwise the first Back lands on the left half).
fn open_resolved_file_ref_inner(
&mut self,
abs: &std::path::Path,
line: u32,
column: Option<u32>,
record_nav: bool,
) -> bool {
if !abs.is_file() {
return false;
}
if record_nav && let Some(from) = self.editor.path.clone() {
self.nav.record(NavLoc {
path: from,
row: self.editor.cursor_row,
col: self.editor.cursor_col,
});
}
let line0 = (line as usize).saturating_sub(1);
let col0 = column.map(|c| c as usize).unwrap_or(1).saturating_sub(1);
match self.open_at(abs, line0, col0) {
Ok(()) => {
// `explorer.autoReveal` analogue, as quick-open does: sync
// the tree to the landed file without stealing editor focus.
self.tree.reveal_path(abs);
self.status = format!("{}:{}", self.status_path(abs), line);
true
}
Err(_) => false,
}
}
/// Open a `diff://` group link's two files side by side: left lands in
/// the leftmost editor group, right in the rightmost — splitting first
/// when the editor is a single group, reusing the existing pair when it
/// is already split (so repeated clicks swap the comparison in place
/// instead of accreting columns).
fn open_side_by_side(
&mut self,
left: &crate::file_ref::FileRef,
right: &crate::file_ref::FileRef,
) -> bool {
// Both sides absolute by construction (diff_uri refuses relative
// paths); gated on is_file like every terminal file click.
let lp = std::path::PathBuf::from(&left.path);
let rp = std::path::PathBuf::from(&right.path);
if !lp.is_file() || !rp.is_file() {
return false;
}
// One click, one Back entry: record the origin once here, then open
// both halves with recording off.
if let Some(from) = self.editor.path.clone() {
self.nav.record(NavLoc {
path: from,
row: self.editor.cursor_row,
col: self.editor.cursor_col,
});
}
self.focus_editor_group(true);
if !self.open_resolved_file_ref_inner(&lp, left.line, left.column, false) {
return false;
}
if self.editor_layout.is_split() {
self.focus_editor_group(false);
} else {
// The split duplicates the left file into the new focused group
// as a preview tab; opening the right file swaps into it.
self.split_editor_dir(editor_layout::SplitDir::Horizontal, true);
}
if !self.open_resolved_file_ref_inner(&rp, right.line, right.column, false) {
return false;
}
self.status = format!(
"Side by side: {} | {}",
self.status_path(&lp),
self.status_path(&rp)
);
true
}
/// Open a URL discovered in the terminal. On a remote session a loopback
/// dev-server URL is forwarded home and opened; any other link opens on the
/// local Mac through the drop relay (with the usual confirm gate). On a
/// local session everything opens directly.
///
/// Editor deep links (`vscode://file/…:line`, and the same shape from
/// Cursor/Windsurf/Zed, plus plain `file://`) name a file and line, and
/// Croft is an editor: they open in the editor pane right here, never
/// through the OS. Beyond those, web links only: an OSC 8 cell carries
/// whatever URI the printing program chose while showing unrelated text,
/// so any other custom-scheme URI would hand `open`/`xdg-open` an
/// arbitrary target (app launch, protocol handler) off one disguised
/// click. The refusal surfaces the real destination in the status line.
fn open_detected_url(&mut self, url: &str) {
// A diff:// group link names two files; open them side by side.
// Same trust story as single-file deep links: consumed internally,
// gated on is_file, never handed to the OS.
if let Some((left, right)) = crate::file_ref::diff_uri(url)
&& self.open_side_by_side(&left, &right)
{
return;
}
if let Some(fr) = crate::file_ref::editor_file_uri(url) {
// Absolute by construction; gated on is_file like every terminal
// file click. An unresolvable link falls through to the web-only
// rule so its refusal still shows the real URI.
let path = std::path::PathBuf::from(&fr.path);
if self.open_resolved_file_ref(&path, fr.line, fr.column) {
return;
}
}
let scheme_ok = {
let l = url.trim_start().to_ascii_lowercase();
l.starts_with("http://") || l.starts_with("https://")
};
if !scheme_ok {
self.status = format!("Refused to open non-web link: {url}");
return;
}
let loopback = crate::port_detect::loopback_url_port(url);
if self.drop_relay_active() {
if let Some(port) = loopback {
self.request_remote_forward(port, true);
} else if self.trust_local_browser {
self.request_remote_url_open(url.to_string());
self.status = format!("Opening {url} on your local Mac");
} else {
self.pending_local_open = Some(url.to_string());
}
return;
}
match open_url(url) {
Ok(()) => self.status = format!("Opened {url}"),
Err(e) => self.status = format!("Open link failed: {e}"),
}
}
/// Click on a port-detection toast button. Returns whether a button was hit
/// (and the action taken); a click elsewhere returns false so it falls
/// through to normal handling.
fn handle_port_toast_click(&mut self, x: u16, y: u16) -> bool {
let Some(toast) = self.port_toast.as_ref() else {
return false;
};
let Some(action) = toast
.buttons
.iter()
.find(|(r, _)| rect_contains(*r, x, y))
.map(|(_, a)| *a)
else {
return false;
};
let port = toast.port;
self.port_toast = None;
match action {
PortToastAction::ForwardAndOpen => self.request_remote_forward(port, true),
PortToastAction::ForwardOnly => self.request_remote_forward(port, false),
PortToastAction::Open => match open_url(&format!("http://127.0.0.1:{port}/")) {
Ok(()) => self.status = format!("Opened http://localhost:{port}/"),
Err(e) => self.status = format!("Open failed: {e}"),
},
PortToastAction::Dismiss => {}
}
true
}
/// A relay request id: the kind, this process, and a per-process counter.
/// The relay keys its remote inbox directory by this id, so two requests
/// raised in the same instant must not share one — the first reply would
/// satisfy both pending pulls and delete the directory out from under the
/// second, which then times out with its tunnel already up.
fn relay_request_id(kind: &str) -> String {
static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let n = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
format!("{kind}-{}-{n}", std::process::id())
}
/// Ask the local launcher (via the drop relay) to forward `port` home over
/// the live SSH master, optionally opening the local browser once it's up.
fn request_remote_forward(&mut self, port: u16, open: bool) {
let Some(log_path) = self.relay_log_path() else {
self.status = String::from("Forward port: drop relay vanished");
return;
};
self.ensure_relay_dir();
let request_id = Self::relay_request_id("forward");
let line = format!("forward\t{request_id}\t{port}\t{}\n", u8::from(open));
match append_to_relay_log(&log_path, &line) {
Ok(()) => {
self.pending_remote_pulls.push(PendingRemotePull {
request_id,
src_display: format!("port {port}"),
basename: String::new(),
dest_dir: PathBuf::new(),
started_at: std::time::Instant::now(),
kind: RemotePullKind::Forward { remote_port: port },
});
self.status = format!("Forwarding port {port}…");
}
Err(e) => self.status = format!("Forward port: relay write failed: {e}"),
}
}
/// Tear down a previously established forward. Fire and forget — the entry
/// is already gone from the panel, so there's no completion to await.
fn request_remote_unforward(&mut self, local: u16, remote: u16) {
let Some(log_path) = self.relay_log_path() else {
return;
};
self.ensure_relay_dir();
let request_id = Self::relay_request_id("unforward");
let line = format!("unforward\t{request_id}\t{local}\t{remote}\n");
let _ = append_to_relay_log(&log_path, &line);
}
fn request_remote_url_open(&mut self, url: String) {
let Some(log_path) = self.relay_log_path() else {
self.status = String::from("Open link: drop relay vanished");
return;
};
self.ensure_relay_dir();
let request_id = Self::relay_request_id("open");
let mut line = String::from("open\t");
line.push_str(&request_id);
line.push('\t');
line.push_str(&url);
line.push('\n');
match append_to_relay_log(&log_path, &line) {
Ok(()) => {
self.pending_remote_pulls.push(PendingRemotePull {
request_id,
src_display: url,
basename: String::new(),
dest_dir: PathBuf::new(),
started_at: std::time::Instant::now(),
kind: RemotePullKind::Open,
});
}
Err(e) => {
self.status = format!("Open link: relay write failed: {e}");
}
}
}
/// Handle a key while the local-browser confirmation modal is open.
/// `Y`/`Enter` opens this URL once. `A` opens it AND remembers
/// "always" for the rest of the session. `N`/`Esc` cancels.
fn handle_local_open_confirm_key(&mut self, key: KeyEvent) {
let Some(url) = self.pending_local_open.clone() else {
return;
};
match key.code {
KeyCode::Char('y') | KeyCode::Char('Y') | KeyCode::Enter => {
self.pending_local_open = None;
self.request_remote_url_open(url.clone());
self.status = format!("Opening {url} on your local Mac");
}
KeyCode::Char('a') | KeyCode::Char('A') => {
self.pending_local_open = None;
self.trust_local_browser = true;
self.request_remote_url_open(url.clone());
self.status = format!("Trusted local browser for this session. Opening {url}");
}
KeyCode::Char('n') | KeyCode::Char('N') | KeyCode::Esc => {
self.pending_local_open = None;
self.status = String::from("Open link cancelled");
}
_ => {}
}
}
fn open_shortcuts_modal(&mut self) {
if self.shortcuts_modal.is_none() {
self.shortcuts_modal = Some(crate::widgets::shortcuts::ShortcutsModal::default());
self.overlays.shortcuts_clear.request();
self.status = String::from("Shortcuts: Esc to close");
}
}
fn close_shortcuts_modal(&mut self) {
if self.shortcuts_modal.take().is_some() {
self.overlays.shortcuts_clear.request();
self.overlays.activity.mark_dirty();
self.overlays.welcome.mark_dirty();
self.overlays.hero.mark_dirty();
self.invalidate_editor_image_layouts();
self.status.clear();
}
}
pub fn consume_shortcuts_image_clear(&mut self) -> bool {
self.overlays.shortcuts_clear.consume()
}
pub fn consume_file_finder_image_clear(&mut self) -> bool {
self.overlays.file_finder_clear.consume()
}
/// Drain the background-build receiver into `file_finder_index`
/// without blocking. Called from `open_file_finder` and from the
/// main loop tick. Accepts REPLACEMENT results too: when the FS
/// watcher or a workspace re-root has triggered a rebuild, the
/// fresh index swaps in here and is pushed into the open finder
/// (if any) so an in-progress Cmd+P session immediately re-ranks
/// against the new file set. If a follow-up rebuild was queued
/// while this one was in flight (the `file_finder_index_dirty`
/// flag), it is re-kicked here so a long-running build on a
/// multi-GB monorepo can never miss a later FS event.
fn poll_file_finder_index(&mut self) {
let Some(rx) = self.file_finder_index_rx.as_ref() else {
return;
};
match rx.try_recv() {
Ok(entries) => {
let arc = std::sync::Arc::new(entries);
self.file_finder_index = Some(arc.clone());
self.file_finder_index_rx = None;
if let Some(finder) = self.file_finder.as_mut() {
finder.replace_entries(arc);
}
if self.file_finder_index_dirty {
self.kick_file_finder_index_rebuild();
}
}
Err(std::sync::mpsc::TryRecvError::Empty) => {}
Err(std::sync::mpsc::TryRecvError::Disconnected) => {
self.file_finder_index_rx = None;
}
}
}
/// Spawn a background walker that rebuilds the Cmd+P file index
/// against the current `workspace_root`. If a rebuild is already
/// in flight, sets the dirty flag instead; `poll_file_finder_index`
/// will re-kick on completion. Called from `change_workspace_root`
/// so Cmd+P reflects the new project, and from `drain_fs_events`
/// so creates, deletes, and git-checkout-driven swaps land in the
/// index without a croft restart.
fn kick_file_finder_index_rebuild(&mut self) {
if self.file_finder_index_rx.is_some() {
self.file_finder_index_dirty = true;
return;
}
let (tx, rx) = std::sync::mpsc::channel::<Vec<crate::widgets::file_finder::FileEntry>>();
let roots: Vec<PathBuf> = self.roots.iter().map(Path::to_path_buf).collect();
std::thread::spawn(move || {
let entries = crate::widgets::file_finder::build_multi_file_index(&roots);
let _ = tx.send(entries);
});
self.file_finder_index_rx = Some(rx);
self.file_finder_index_dirty = false;
}
fn open_file_finder(&mut self) {
if self.file_finder.is_some() {
return;
}
// Drain the background-built index if it has landed.
self.poll_file_finder_index();
// Fallback: the worker thread has not finished yet AND no
// index has ever been cached. Walk synchronously this once
// rather than open an empty finder; this only fires when
// Cmd+P is pressed within the first few hundred ms of launch.
if self.file_finder_index.is_none() {
let roots: Vec<PathBuf> = self.roots.iter().map(Path::to_path_buf).collect();
let entries = crate::widgets::file_finder::build_multi_file_index(&roots);
self.file_finder_index = Some(std::sync::Arc::new(entries));
self.file_finder_index_rx = None;
}
let entries = self
.file_finder_index
.clone()
.unwrap_or_else(|| std::sync::Arc::new(Vec::new()));
let count = entries.len();
self.file_finder = Some(crate::widgets::file_finder::FileFinder::new(entries));
self.overlays.file_finder_clear.request();
self.status = format!("Go to File: {count} files indexed — Esc to close");
}
fn close_file_finder(&mut self) {
if self.file_finder.take().is_some() {
self.overlays.file_finder_clear.request();
self.overlays.activity.mark_dirty();
self.overlays.welcome.mark_dirty();
self.overlays.hero.mark_dirty();
self.invalidate_editor_image_layouts();
self.status.clear();
}
}
fn handle_file_finder_key(&mut self, key: KeyEvent) {
// Cmd+V / Ctrl+V: paste the system clipboard into the query as if
// each character had been typed. Hosts that route Cmd+V through
// bracketed paste (iTerm2 default) deliver an `Event::Paste(s)`
// instead, which `handle_paste` forwards to the finder — but if
// the user re-bound Cmd+V to a CSI-u Cmd+V sequence or is running
// in a terminal that disables bracketed paste, the chord arrives
// here as a key event, and reading the clipboard ourselves keeps
// the "open finder, paste a filename" gesture working everywhere.
if is_clipboard_paste_key(key) {
if let Some(text) = (self.clipboard_reader)()
&& let Some(finder) = self.file_finder.as_mut()
{
for c in text.chars() {
if !c.is_control() {
finder.push_char(c);
}
}
}
return;
}
let Some(finder) = self.file_finder.as_mut() else {
return;
};
match (key.code, key.modifiers) {
(KeyCode::Esc, _) => {
self.close_file_finder();
}
(KeyCode::Enter, _) => self.open_file_finder_selection(),
(KeyCode::Up, _) => finder.select_prev(),
(KeyCode::Down, _) => finder.select_next(),
(KeyCode::PageUp, _) => {
for _ in 0..10 {
finder.select_prev();
}
}
(KeyCode::PageDown, _) => {
for _ in 0..10 {
finder.select_next();
}
}
(KeyCode::Left, _) => finder.move_cursor_left(),
(KeyCode::Right, _) => finder.move_cursor_right(),
(KeyCode::Home, _) => finder.move_cursor_home(),
(KeyCode::End, _) => finder.move_cursor_end(),
(KeyCode::Backspace, _) => finder.pop_char(),
(KeyCode::Delete, _) => finder.delete_char(),
(KeyCode::Char(c), m) if !m.intersects(KeyModifiers::CONTROL | KeyModifiers::SUPER) => {
finder.push_char(c);
}
_ => {}
}
// VS Code's shared quick input: a leading `#` turns Quick Open into
// Go to Symbol in Workspace, carrying any text after it as the query.
let hash_query = self
.file_finder
.as_ref()
.and_then(|f| f.query.strip_prefix('#'))
.map(str::to_string);
if let Some(q) = hash_query {
self.close_file_finder();
self.open_workspace_symbols(&q);
}
}
/// Open the highlighted result and dismiss the finder: Enter's action,
/// shared with a mouse click on a result row.
fn open_file_finder_selection(&mut self) {
let Some(finder) = self.file_finder.as_ref() else {
return;
};
let path = finder.selected_entry().map(|e| e.path.clone());
let hint = finder.line_hint();
if let Some(path) = path {
self.close_file_finder();
// `alpha:236-239` (#472): land on the line, centred, and select
// the range so it reads as highlighted; `alpha:236` lands with
// nothing selected, since one line is a place, not a span.
let opened = match hint {
Some(hint) => {
let row = hint.line.saturating_sub(1);
let col = hint.col.map_or(0, |c| c.saturating_sub(1));
self.open_at(&path, row, col)
}
None => self.editor.open_preview(&path),
};
match opened {
Ok(()) => {
self.sync_open_file_poll_mtime();
// A range an earlier hinted pick installed is cleared if
// it is still the selection in its tab, so neither
// `alpha:12` nor a bare `alpha` keeps showing it; a
// selection the user made or extended since is theirs
// and stays. Stale secondary carets never survive a
// pick, as they never survive a click: the next
// keystroke would edit at every one of them.
if let Some((prev, sel)) = self.quick_open_range.take()
&& let Some(idx) = self.editor.find_tab_with_path(&prev)
&& self.editor.editors[idx].selection == Some(sel)
{
self.editor.editors[idx].selection = None;
}
if hint.is_some() {
self.editor.clear_selection();
}
self.editor.collapse_carets();
if let Some(end) = hint.and_then(|h| h.end) {
let start = self.editor.cursor_row;
let last = self.editor.lines.len().saturating_sub(1);
let end_row = end.saturating_sub(1).clamp(start, last);
let end_col = self
.editor
.lines
.get(end_row)
.map_or(0, |l| l.chars().count());
let sel = crate::widgets::editor::EditorSelection {
anchor: (end_row, end_col),
head: (start, 0),
};
self.editor.selection = Some(sel);
self.quick_open_range = Some((path.to_path_buf(), sel));
// The landing line is the head, and the cursor sits at
// the head as every other selection-installing path
// leaves it: Shift+motion extends from the cursor, and
// the paint-time clamp keeps the cursor on screen, so
// a range taller than the viewport still shows the
// line the user asked for, centred by `open_at`, with
// the selection running down from it.
self.editor.cursor_row = start;
self.editor.cursor_col = 0;
}
// VS Code's `explorer.autoReveal` analogue:
// expand every parent dir of the picked file
// and park the cursor on its row so the user
// sees where in the workspace the file lives.
self.tree.reveal_path(&path);
self.focus_pane(Pane::Editor);
// The status names the lines landed on: a number past the
// file (or one that saturated in the parser) was clamped
// above, and the clamped truth is the useful signal.
let last_line = self.editor.lines.len().max(1);
self.status = match hint {
Some(hint) => match hint.end {
Some(end) => format!(
"Opened {}:{}-{}",
self.status_path(&path),
hint.line.min(last_line),
end.min(last_line)
),
None => format!(
"Opened {}:{}",
self.status_path(&path),
hint.line.min(last_line)
),
},
None => format!("Opened {}", self.status_path(&path)),
};
}
Err(e) => {
self.status = format!("Open failed: {e}");
}
}
}
}
fn handle_file_finder_mouse(&mut self, m: MouseEvent) {
let Some(finder) = self.file_finder.as_mut() else {
return;
};
let inside = rect_contains(finder.last_rect, m.column, m.row);
match m.kind {
MouseEventKind::ScrollDown => {
for _ in 0..3 {
finder.select_next();
}
}
MouseEventKind::ScrollUp => {
for _ in 0..3 {
finder.select_prev();
}
}
MouseEventKind::Down(MouseButton::Left) | MouseEventKind::Down(MouseButton::Right)
if !inside =>
{
self.close_file_finder();
}
// Click a row to open it, the way VS Code's quick-pick behaves.
MouseEventKind::Down(MouseButton::Left) => {
if let Some(idx) = finder.row_index_at(m.row) {
finder.selected = idx;
self.open_file_finder_selection();
}
}
_ => {}
}
}
fn render_file_finder(&mut self, frame: &mut ratatui::Frame) {
let theme = self.theme;
let center = self.quick_input_position == QuickInputPosition::Center;
let Some(finder) = self.file_finder.as_mut() else {
return;
};
let area = frame.area();
crate::widgets::file_finder::render_file_finder(
finder,
area,
frame.buffer_mut(),
theme,
center,
);
}
pub fn consume_command_palette_image_clear(&mut self) -> bool {
self.overlays.command_palette_clear.consume()
}
/// Open the Command Palette (Cmd/Ctrl+Shift+P). The palette is built from
/// the static command registry, so there is nothing to index — it opens
/// instantly regardless of workspace size.
fn open_command_palette(&mut self) {
if self.command_palette.is_some() {
return;
}
let mut palette = crate::widgets::command_palette::CommandPalette::new();
// Inject the commands contributed by enabled MCP sidecar extensions so
// they're discoverable alongside the built-ins (eager registration; the
// server is only spawned when one is actually invoked).
let ext_commands: Vec<crate::widgets::command_palette::ExtensionCommand> =
crate::mcp::registry::contributed_commands()
.into_iter()
.chain(crate::mcp::registry::contributed_viewer_commands_in_dir(
&self.config_dir,
))
.map(|c| crate::widgets::command_palette::ExtensionCommand {
ext_id: c.ext_id,
id: c.id,
title: c.title,
})
.collect();
palette.set_extension_commands(ext_commands);
let count = palette.results.len();
self.command_palette = Some(palette);
self.overlays.command_palette_clear.request();
self.status = format!("Command Palette: {count} commands — Esc to close");
}
fn close_command_palette(&mut self) {
if self.command_palette.take().is_some() {
self.overlays.command_palette_clear.request();
self.overlays.activity.mark_dirty();
self.overlays.welcome.mark_dirty();
self.overlays.hero.mark_dirty();
self.invalidate_editor_image_layouts();
self.status.clear();
}
}
fn handle_command_palette_key(&mut self, key: KeyEvent) {
let Some(palette) = self.command_palette.as_mut() else {
return;
};
match (key.code, key.modifiers) {
(KeyCode::Esc, _) => self.close_command_palette(),
(KeyCode::Enter, _) => self.run_command_palette_selection(),
(KeyCode::Up, _) => palette.select_prev(),
(KeyCode::Down, _) => palette.select_next(),
(KeyCode::PageUp, _) => {
for _ in 0..10 {
palette.select_prev();
}
}
(KeyCode::PageDown, _) => {
for _ in 0..10 {
palette.select_next();
}
}
(KeyCode::Left, _) => palette.move_cursor_left(),
(KeyCode::Right, _) => palette.move_cursor_right(),
(KeyCode::Home, _) => palette.move_cursor_home(),
(KeyCode::End, _) => palette.move_cursor_end(),
(KeyCode::Backspace, _) => palette.pop_char(),
(KeyCode::Delete, _) => palette.delete_char(),
(KeyCode::Char(c), m) if !m.intersects(KeyModifiers::CONTROL | KeyModifiers::SUPER) => {
palette.push_char(c);
}
_ => {}
}
}
/// Run the highlighted command and dismiss the palette: Enter's action,
/// shared with a mouse click on a result row.
fn run_command_palette_selection(&mut self) {
let Some(palette) = self.command_palette.as_ref() else {
return;
};
let item = palette.selected_item();
self.close_command_palette();
if let Some(item) = item {
self.run_palette_item(item);
}
}
fn handle_command_palette_mouse(&mut self, m: MouseEvent) {
let Some(palette) = self.command_palette.as_mut() else {
return;
};
let inside = rect_contains(palette.last_rect, m.column, m.row);
match m.kind {
MouseEventKind::ScrollDown => {
for _ in 0..3 {
palette.select_next();
}
}
MouseEventKind::ScrollUp => {
for _ in 0..3 {
palette.select_prev();
}
}
MouseEventKind::Down(MouseButton::Left) | MouseEventKind::Down(MouseButton::Right)
if !inside =>
{
self.close_command_palette();
}
// Click a row to run it, the way VS Code's quick-pick behaves.
MouseEventKind::Down(MouseButton::Left) => {
if let Some(idx) = palette.row_index_at(m.row) {
palette.selected = idx;
self.run_command_palette_selection();
}
}
_ => {}
}
}
fn render_command_palette(&mut self, frame: &mut ratatui::Frame) {
let theme = self.theme;
let center = self.quick_input_position == QuickInputPosition::Center;
let Some(palette) = self.command_palette.as_mut() else {
return;
};
let area = frame.area();
crate::widgets::command_palette::render_command_palette(
palette,
area,
frame.buffer_mut(),
theme,
center,
);
}
/// Open "Go to Symbol in Editor" (Cmd/Ctrl+Shift+O). Snapshots the active
/// file's symbols from the outline (tree-sitter is populated synchronously
/// each tick; LSP refines it). A leading `:` in the query switches to Go to
/// Line. ponytail: snapshot at open — symbols are present for any synced
/// file; if a slow LSP reply ever needs to land into an open picker, feed
/// it live from `drain_lsp_document_symbols`.
fn open_go_to_symbol(&mut self) {
if self.go_to_symbol.is_some() {
return;
}
let Some(path) = self.editor.path.clone() else {
self.status = String::from("Go to Symbol: no file open");
return;
};
let symbols = self.outline.symbols().to_vec();
let count = symbols.len();
self.go_to_symbol = Some(crate::widgets::symbol_picker::SymbolPicker::new(
path, symbols,
));
self.overlays.command_palette_clear.request();
self.status = format!("Go to Symbol: {count} symbols — Esc to close");
}
fn close_go_to_symbol(&mut self) {
if self.go_to_symbol.take().is_some() {
self.overlays.command_palette_clear.request();
self.overlays.activity.mark_dirty();
self.overlays.welcome.mark_dirty();
self.overlays.hero.mark_dirty();
self.invalidate_editor_image_layouts();
self.status.clear();
}
}
fn handle_go_to_symbol_key(&mut self, key: KeyEvent) {
let Some(picker) = self.go_to_symbol.as_mut() else {
return;
};
match (key.code, key.modifiers) {
(KeyCode::Esc, _) => self.close_go_to_symbol(),
(KeyCode::Enter, _) => {
if picker.is_line_mode() {
// Resolve the target before closing (close drops the picker).
let target = picker.line_target().map(|n| (n as u32 - 1, 0));
let path = picker.path.clone();
self.close_go_to_symbol();
if let Some((line, col)) = target {
self.go_to_definition(path, line, col);
}
} else {
self.jump_to_go_to_symbol_selection();
}
}
(KeyCode::Up, _) => picker.select_prev(),
(KeyCode::Down, _) => picker.select_next(),
(KeyCode::PageUp, _) => {
for _ in 0..10 {
picker.select_prev();
}
}
(KeyCode::PageDown, _) => {
for _ in 0..10 {
picker.select_next();
}
}
(KeyCode::Left, _) => picker.move_cursor_left(),
(KeyCode::Right, _) => picker.move_cursor_right(),
(KeyCode::Home, _) => picker.move_cursor_home(),
(KeyCode::End, _) => picker.move_cursor_end(),
(KeyCode::Backspace, _) => picker.pop_char(),
(KeyCode::Delete, _) => picker.delete_char(),
(KeyCode::Char(c), m) if !m.intersects(KeyModifiers::CONTROL | KeyModifiers::SUPER) => {
picker.push_char(c);
}
_ => {}
}
}
/// Jump to the highlighted symbol and dismiss the picker: Enter's action
/// outside line mode, shared with a mouse click on a result row (a click
/// names a concrete row, so it always means the symbol, never a `:N`
/// line query).
fn jump_to_go_to_symbol_selection(&mut self) {
let Some(picker) = self.go_to_symbol.as_ref() else {
return;
};
// Resolve the target before closing (close drops the picker).
let target = picker.selected_target();
let path = picker.path.clone();
self.close_go_to_symbol();
if let Some((line, col)) = target {
self.go_to_definition(path, line, col);
}
}
fn handle_go_to_symbol_mouse(&mut self, m: MouseEvent) {
let Some(picker) = self.go_to_symbol.as_mut() else {
return;
};
let inside = rect_contains(picker.last_rect, m.column, m.row);
match m.kind {
MouseEventKind::ScrollDown => {
for _ in 0..3 {
picker.select_next();
}
}
MouseEventKind::ScrollUp => {
for _ in 0..3 {
picker.select_prev();
}
}
MouseEventKind::Down(MouseButton::Left) | MouseEventKind::Down(MouseButton::Right)
if !inside =>
{
self.close_go_to_symbol();
}
// Click a row to jump to it, the way VS Code's quick-pick behaves.
MouseEventKind::Down(MouseButton::Left) => {
if let Some(idx) = picker.row_index_at(m.row) {
picker.selected = idx;
self.jump_to_go_to_symbol_selection();
}
}
_ => {}
}
}
fn render_go_to_symbol(&mut self, frame: &mut ratatui::Frame) {
let theme = self.theme;
let center = self.quick_input_position == QuickInputPosition::Center;
let Some(picker) = self.go_to_symbol.as_mut() else {
return;
};
let area = frame.area();
crate::widgets::symbol_picker::render_symbol_picker(
picker,
area,
frame.buffer_mut(),
theme,
center,
);
}
/// Open "Go to Symbol in Workspace" seeded with `initial` (the text
/// after Quick Open's `#`). The query goes to every running language
/// server; results stream in via [`Self::drain_lsp_workspace_symbols`].
fn open_workspace_symbols(&mut self, initial: &str) {
if self.workspace_symbols.is_some() {
return;
}
self.workspace_symbols = Some(
crate::widgets::workspace_symbols::WorkspaceSymbolPicker::new(
self.tree.root.clone(),
initial,
),
);
self.overlays.command_palette_clear.request();
self.workspace_symbols_requery();
self.status = String::from("Go to Symbol in Workspace: type to search — Esc to close");
}
fn close_workspace_symbols(&mut self) {
if self.workspace_symbols.take().is_some() {
self.ws_symbols_request_id = None;
self.ws_symbols_pending = None;
self.overlays.command_palette_clear.request();
self.overlays.activity.mark_dirty();
self.overlays.welcome.mark_dirty();
self.overlays.hero.mark_dirty();
self.invalidate_editor_image_layouts();
self.status.clear();
}
}
/// Note a query change and arm the debounce; the actual LSP request
/// fires from [`Self::workspace_symbols_dispatch_due`] once the query
/// has been still for the window. Firing per keystroke serialized a
/// round trip per character behind the per-client lock, starving every
/// other LSP feature on that server for the whole burst.
fn workspace_symbols_requery(&mut self) {
let Some(picker) = self.workspace_symbols.as_mut() else {
return;
};
let query = picker.query.trim().to_string();
if query.is_empty() {
picker.set_results(Vec::new());
// A stale notice from the previous reply reads as an error;
// an empty query should show the type-to-search hint.
picker.unsupported = false;
self.ws_symbols_request_id = None;
self.ws_symbols_pending = None;
return;
}
picker.loading = true;
// Invalidate any in-flight request: its reply answers a query the
// user has typed past and would render stale results until the
// debounced request lands.
self.ws_symbols_request_id = None;
self.ws_symbols_pending = Some(std::time::Instant::now());
}
/// Debounced dispatch for [`Self::workspace_symbols_requery`]: called
/// each tick from the drain loop, sends the newest query once it has
/// been still for the window. Only the newest reply applies via
/// `ws_symbols_request_id`.
fn workspace_symbols_dispatch_due(&mut self) {
const DEBOUNCE: std::time::Duration = std::time::Duration::from_millis(200);
let Some(armed) = self.ws_symbols_pending else {
return;
};
if armed.elapsed() < DEBOUNCE {
return;
}
self.ws_symbols_pending = None;
let Some(picker) = self.workspace_symbols.as_mut() else {
return;
};
let query = picker.query.trim().to_string();
if query.is_empty() {
return;
}
let Some(lsp) = self.lsp.as_mut() else {
if let Some(p) = self.workspace_symbols.as_mut() {
p.loading = false;
p.unsupported = true;
}
return;
};
self.ws_symbols_request_id = Some(lsp.request_workspace_symbols(query));
}
/// Install a `workspace/symbol` reply into the open picker. Only the
/// newest request's reply applies; anything else is a stale answer to a
/// query the user has already typed past. Returns true when applied.
pub fn apply_workspace_symbols(
&mut self,
request_id: u64,
symbols: Vec<crate::lsp::manager::WorkspaceSymbolItem>,
unsupported: bool,
) -> bool {
if self.ws_symbols_request_id != Some(request_id) {
return false;
}
self.ws_symbols_request_id = None;
let Some(picker) = self.workspace_symbols.as_mut() else {
return false;
};
picker.unsupported = unsupported;
picker.set_results(symbols);
true
}
pub fn drain_lsp_workspace_symbols(&mut self) -> bool {
let mut results = Vec::new();
if let Some(lsp) = self.lsp.as_ref() {
while let Some(r) = lsp.drain_workspace_symbols() {
results.push(r);
}
}
let mut changed = false;
for r in results {
changed |= self.apply_workspace_symbols(r.request_id, r.symbols, r.unsupported);
}
changed
}
fn handle_workspace_symbols_key(&mut self, key: KeyEvent) {
let Some(picker) = self.workspace_symbols.as_mut() else {
return;
};
match (key.code, key.modifiers) {
(KeyCode::Esc, _) => self.close_workspace_symbols(),
(KeyCode::Enter, _) => self.jump_to_workspace_symbol_selection(),
(KeyCode::Up, _) => picker.select_prev(),
(KeyCode::Down, _) => picker.select_next(),
(KeyCode::PageUp, _) => {
for _ in 0..10 {
picker.select_prev();
}
}
(KeyCode::PageDown, _) => {
for _ in 0..10 {
picker.select_next();
}
}
(KeyCode::Left, _) => picker.move_cursor_left(),
(KeyCode::Right, _) => picker.move_cursor_right(),
(KeyCode::Home, _) => picker.move_cursor_home(),
(KeyCode::End, _) => picker.move_cursor_end(),
(KeyCode::Backspace, _) => {
picker.pop_char();
self.workspace_symbols_requery();
}
(KeyCode::Delete, _) => {
picker.delete_char();
self.workspace_symbols_requery();
}
(KeyCode::Char(c), m) if !m.intersects(KeyModifiers::CONTROL | KeyModifiers::SUPER) => {
picker.push_char(c);
self.workspace_symbols_requery();
}
_ => {}
}
}
/// Jump to the highlighted workspace symbol and dismiss the picker:
/// Enter's action, shared with a mouse click on a result row.
fn jump_to_workspace_symbol_selection(&mut self) {
let Some(picker) = self.workspace_symbols.as_ref() else {
return;
};
let target = picker
.selected_item()
.map(|i| (i.path.clone(), i.line, i.character));
self.close_workspace_symbols();
if let Some((path, line, character)) = target {
self.go_to_definition(path, line, character);
}
}
fn handle_workspace_symbols_mouse(&mut self, m: MouseEvent) {
let Some(picker) = self.workspace_symbols.as_mut() else {
return;
};
let inside = rect_contains(picker.last_rect, m.column, m.row);
match m.kind {
MouseEventKind::ScrollDown => {
for _ in 0..3 {
picker.select_next();
}
}
MouseEventKind::ScrollUp => {
for _ in 0..3 {
picker.select_prev();
}
}
MouseEventKind::Down(MouseButton::Left) | MouseEventKind::Down(MouseButton::Right)
if !inside =>
{
self.close_workspace_symbols();
}
// Click a row to jump to it, the way VS Code's quick-pick behaves.
MouseEventKind::Down(MouseButton::Left) => {
if let Some(idx) = picker.row_index_at(m.row) {
picker.selected = idx;
self.jump_to_workspace_symbol_selection();
}
}
_ => {}
}
}
fn render_workspace_symbols(&mut self, frame: &mut ratatui::Frame) {
let theme = self.theme;
let center = self.quick_input_position == QuickInputPosition::Center;
let Some(picker) = self.workspace_symbols.as_mut() else {
return;
};
let area = frame.area();
crate::widgets::workspace_symbols::render_workspace_symbols(
picker,
area,
frame.buffer_mut(),
theme,
center,
);
}
pub fn consume_process_picker_image_clear(&mut self) -> bool {
self.overlays.process_picker_clear.consume()
}
/// Open the "Debug: Attach to Python Process" picker. Enumerates running
/// CPython 3.14+ processes (those with PEP 768 `sys.remote_exec`); shows a
/// status message and opens nothing when there are none.
fn open_attach_python_picker(&mut self) {
if self.process_picker.is_some() {
return;
}
let targets = crate::dap::discovery::attachable_python_targets();
if targets.is_empty() {
self.run_debug.feedback = Some(String::from(
"No attachable Python 3.14+ processes found (PEP 768 needs CPython 3.14+)",
));
self.run_debug.feedback_is_error = true;
self.status = String::from("Attach: no Python 3.14+ processes running");
return;
}
let count = targets.len();
self.process_picker = Some(crate::widgets::process_picker::ProcessPicker::new(targets));
self.overlays.process_picker_clear.request();
self.status = format!("Attach: {count} Python process(es) — Esc to close, Enter to attach");
}
fn close_process_picker(&mut self) {
if self.process_picker.take().is_some() {
self.overlays.process_picker_clear.request();
self.overlays.activity.mark_dirty();
self.overlays.welcome.mark_dirty();
self.overlays.hero.mark_dirty();
self.invalidate_editor_image_layouts();
self.status.clear();
}
}
fn handle_process_picker_key(&mut self, key: KeyEvent) {
let Some(picker) = self.process_picker.as_mut() else {
return;
};
match (key.code, key.modifiers) {
(KeyCode::Esc, _) => self.close_process_picker(),
(KeyCode::Enter, _) => self.attach_process_picker_selection(),
(KeyCode::Up, _) => picker.select_prev(),
(KeyCode::Down, _) => picker.select_next(),
(KeyCode::PageUp, _) => {
for _ in 0..10 {
picker.select_prev();
}
}
(KeyCode::PageDown, _) => {
for _ in 0..10 {
picker.select_next();
}
}
_ => {}
}
}
/// Attach to the highlighted process and dismiss the picker: Enter's
/// action, shared with a mouse click on a result row.
fn attach_process_picker_selection(&mut self) {
let Some(picker) = self.process_picker.as_ref() else {
return;
};
let target = picker.selected_target().cloned();
self.close_process_picker();
if let Some(target) = target {
self.attach_to_python_target(target);
}
}
fn handle_process_picker_mouse(&mut self, m: MouseEvent) {
let Some(picker) = self.process_picker.as_mut() else {
return;
};
let inside = rect_contains(picker.last_rect, m.column, m.row);
match m.kind {
MouseEventKind::ScrollDown => {
for _ in 0..3 {
picker.select_next();
}
}
MouseEventKind::ScrollUp => {
for _ in 0..3 {
picker.select_prev();
}
}
MouseEventKind::Down(MouseButton::Left) | MouseEventKind::Down(MouseButton::Right)
if !inside =>
{
self.close_process_picker();
}
// Click a row to attach to it, the way VS Code's quick-pick behaves.
MouseEventKind::Down(MouseButton::Left) => {
if let Some(idx) = picker.row_index_at(m.row) {
picker.selected = idx;
self.attach_process_picker_selection();
}
}
_ => {}
}
}
fn render_process_picker(&mut self, frame: &mut ratatui::Frame) {
let theme = self.theme;
let Some(picker) = self.process_picker.as_mut() else {
return;
};
let area = frame.area();
crate::widgets::process_picker::render_process_picker(
picker,
area,
frame.buffer_mut(),
theme,
);
}
/// Spawn `pdb -p <pid>` for the chosen target in a new PTY terminal,
/// wrapping in `sudo` when the platform requires elevation (always on
/// macOS; on Linux unless Yama `ptrace_scope` is relaxed). The PTY hosts
/// both the interactive pdb prompt and any `sudo` password prompt — the
/// edge a GUI debugger lacks.
fn attach_to_python_target(&mut self, target: crate::dap::discovery::PyTarget) {
use crate::dap::remote_attach::{Platform, plan_attach, read_yama_ptrace_scope};
let pid = target.pid;
let plan = match plan_attach(
target.version,
target.exe,
pid,
Platform::current(),
read_yama_ptrace_scope(),
) {
Ok(plan) => plan,
Err(e) => {
self.run_debug.feedback = Some(format!("Cannot attach to PID {pid}: {e:?}"));
self.run_debug.feedback_is_error = true;
return;
}
};
let (program, args) = plan.command_line();
match PtyTerminal::new_running(&program, &args, self.workspace_root()) {
Ok(term) => {
let slot = self.active_terminal + 1;
self.terminals.insert(slot, term);
self.active_terminal = slot;
if !self.show_terminal {
self.show_terminal = true;
}
self.focus_pane(Pane::Terminal);
self.run_debug.feedback = Some(format!("Attaching debugger to PID {pid}"));
self.run_debug.feedback_is_error = false;
}
Err(e) => {
self.run_debug.feedback = Some(format!("Failed to spawn terminal: {e}"));
self.run_debug.feedback_is_error = true;
}
}
}
/// Open `path` in an extension-contributed viewer (#465): a new terminal
/// pane running the tool on the file, focused. `{file}` in the declared
/// args is the file's path. A provisioned tool that is not installed yet
/// has its managed install kicked off and the user is told to run the
/// command again once it lands, the way a sidecar's first run behaves.
pub fn open_in_viewer(
&mut self,
viewer: &crate::mcp::registry::ContributedViewer,
path: &Path,
) {
// The pane spawn takes `String` args, so a name that is not valid
// UTF-8 could only be handed over mangled, and the tool would open a
// different path. Refuse with the reason rather than open the wrong
// file.
let Some(file) = path.to_str().map(str::to_owned) else {
self.status = format!(
"{}: the file's name is not valid UTF-8, so it cannot be passed to the viewer",
viewer.label
);
return;
};
// A viewer spawns a program named by a manifest, exactly what the
// sidecar consent gate exists for, and manifests can arrive from the
// signed remote index, not only the bundled catalog. The first run of
// an extension's viewer shows the exact command line and spawns
// nothing until the user allows it; allowing resumes this open.
if !self.consented_extensions.contains(&viewer.ext_id) {
use crate::widgets::input_prompt::{InputPrompt, InputPurpose};
let spawn_line = std::iter::once(viewer.command.clone())
.chain(viewer.args.iter().map(|a| a.replace("{file}", &file)))
.collect::<Vec<_>>()
.join(" ");
self.open_input_prompt(
InputPrompt::new(
InputPurpose::ViewerConsent {
key: viewer.key(),
path: path.to_path_buf(),
},
format!("Allow {} to run: {}", viewer.ext_id, spawn_line),
"Enter to allow · Esc to cancel",
)
.with_value("allow"),
);
return;
}
let install_name = viewer.install_name();
let program = match viewer.provision.as_ref() {
None => viewer.command.clone(),
Some(provision) => {
match crate::lsp::install::provisioned_command(&install_name, provision) {
Some((command, _extra_paths)) => command,
None => {
let name: &'static str = crate::lsp::install::static_name(&install_name);
let config = crate::lsp::config::ServerConfig {
name,
command: viewer.command.clone(),
args: viewer.args.clone(),
language: crate::lsp::config::Language("viewer"),
initialization_options: None,
provision: Some(provision.clone()),
};
crate::lsp::install::resolve_managed(&config, provision, true);
self.status =
format!("Installing {}; run it again once it lands", viewer.label);
return;
}
}
}
};
let args: Vec<String> = viewer
.args
.iter()
.map(|a| a.replace("{file}", &file))
.collect();
let cwd = path
.parent()
.filter(|p| p.is_dir())
.map(Path::to_path_buf)
.unwrap_or_else(|| self.workspace_root().to_path_buf());
match PtyTerminal::new_running(&program, &args, &cwd) {
Ok(term) => {
let slot = (self.active_terminal + 1).min(self.terminals.len());
self.terminals.insert(slot, term);
self.active_terminal = slot;
if !self.show_terminal {
self.show_terminal = true;
}
self.focus_pane(Pane::Terminal);
self.status = format!("{}: {}", viewer.label, self.status_path(path));
}
Err(e) => {
self.status = format!("{} failed to start: {e}", viewer.label);
}
}
}
/// A palette `viewer:<extension id>/<viewer id>` row: open the active
/// editor file in that viewer, if the file is a kind it handles.
fn run_viewer_command(&mut self, viewer_id: &str) {
let Some(viewer) = crate::mcp::registry::viewer_by_id_in_dir(&self.config_dir, viewer_id)
else {
self.status = format!("Viewer '{viewer_id}' is unavailable");
return;
};
self.open_active_file_in_viewer(&viewer);
}
/// The palette row's work once its viewer is known: the active editor
/// file must exist and be a kind the viewer handles, or the status line
/// says which it is not.
fn open_active_file_in_viewer(&mut self, viewer: &crate::mcp::registry::ContributedViewer) {
let Some(path) = self.editor.path.clone() else {
self.status = format!("{}: open a file first", viewer.label);
return;
};
let ext = path
.extension()
.map(|e| e.to_string_lossy().to_lowercase())
.unwrap_or_default();
if !viewer.extensions.contains(&ext) {
self.status = format!(
"{}: the active file is not one of .{}",
viewer.label,
viewer.extensions.join(" / .")
);
return;
}
self.open_in_viewer(viewer, &path);
}
/// Dispatch a chosen palette row: a built-in command runs inline; an
/// extension-contributed command routes through the MCP sidecar path.
fn run_palette_item(&mut self, item: crate::widgets::command_palette::PaletteItem) {
use crate::widgets::command_palette::PaletteItem;
match item {
PaletteItem::Builtin(cmd) => self.run_command(cmd),
PaletteItem::Extension(ec) => self.run_extension_command(&ec.id),
}
}
/// Invoke an MCP sidecar command by id. Gated by first-run consent (a popup
/// showing the exact spawn command); once consented, collects the declared
/// argument (if any) via an input popup, then spawns the server off-thread.
fn run_extension_command(&mut self, command_id: &str) {
use crate::widgets::input_prompt::{InputPrompt, InputPurpose};
// Viewer rows (#465) run a terminal program on the active file; no
// sidecar, so none of the MCP consent or argument flow below applies.
if let Some(viewer_id) =
command_id.strip_prefix(crate::mcp::registry::VIEWER_COMMAND_PREFIX)
{
self.run_viewer_command(viewer_id);
return;
}
let Some(resolved) =
crate::mcp::registry::resolve_command_in_dir(&self.config_dir, command_id)
else {
self.status = format!("Extension command '{command_id}' is unavailable");
return;
};
// First-run consent gate: never spawn a sidecar until the user has
// approved this extension, shown the exact command line croft will run.
// One set answers this gate and the viewer gate alike: it is loaded
// from prefs at startup and fed by every grant since, so the two
// cannot disagree, whatever became of a prefs write.
if !self.consented_extensions.contains(&resolved.ext_id) {
let spawn_line = std::iter::once(resolved.server.command.clone())
.chain(resolved.server.args.iter().cloned())
.collect::<Vec<_>>()
.join(" ");
self.open_input_prompt(
InputPrompt::new(
InputPurpose::McpConsent {
command_id: command_id.to_string(),
},
format!("Allow {} to run: {}", resolved.ext_id, spawn_line),
"Enter to allow · Esc to cancel",
)
.with_value("allow"),
);
return;
}
// Collect the declared argument, if any, then run.
if let (Some(_), Some(label)) = (resolved.arg.as_ref(), resolved.prompt.as_ref()) {
self.open_input_prompt(InputPrompt::new(
InputPurpose::McpArg {
command_id: command_id.to_string(),
},
resolved.title.clone(),
label.clone(),
));
return;
}
self.spawn_mcp_command(resolved, None);
}
/// Spawn the MCP server off the UI thread and run the command's tool; the
/// result is delivered to [`poll_mcp`](Self::poll_mcp) over a channel and
/// rendered into a markdown scratch buffer. Refuses to start a second
/// command while one is in flight.
fn spawn_mcp_command(
&mut self,
resolved: crate::mcp::registry::ResolvedCommand,
arg: Option<String>,
) {
if self.mcp_rx.is_some() {
self.status = String::from("An extension command is already running");
return;
}
let (tx, rx) = std::sync::mpsc::channel();
self.mcp_rx = Some(rx);
// On first use the server isn't provisioned yet; the worker installs it
// (block-and-wait) before running, which can take a moment. Say so, so
// the user sees install progress rather than a silent "Running".
let installing = resolved.server.provision.as_ref().is_some_and(|p| {
crate::lsp::install::provisioned_command(&resolved.server.id, p).is_none()
});
let label = if installing {
format!(
"Installing {} (first run, this can take a moment)",
resolved.title
)
} else {
format!("Running {}", resolved.title)
};
// Drive the status-bar spinner badge while the worker runs.
self.mcp_started = Some(std::time::Instant::now());
self.mcp_busy_label = Some(label.clone());
self.status = label.clone();
let cwd = self.workspace_root().to_path_buf();
let version = env!("CARGO_PKG_VERSION").to_string();
let _ = std::thread::Builder::new()
.name("mcp-cmd".into())
.spawn(move || {
let _ = tx.send(run_mcp_command_blocking(&resolved, arg, &cwd, &version));
});
}
/// On-disk path for a scratch buffer (MCP output, Git Output): anchored under
/// the workspace root with a filesystem-safe name, so Cmd+S saves it
/// predictably into the open project (and the Explorer tree shows it) instead
/// of writing a bare filename to croft's working directory.
fn scratch_buffer_path(&self, name: &str) -> PathBuf {
let safe = name.replace(['/', '\\'], "-");
self.workspace_root().join(safe)
}
/// Drain a completed MCP command: render its text into a scratch buffer on
/// success, or surface the error in the status line. Returns whether a
/// redraw is needed. Called each frame from the main loop.
pub fn poll_mcp(&mut self) -> bool {
let Some(rx) = self.mcp_rx.as_ref() else {
return false;
};
let outcome = match rx.try_recv() {
Ok(o) => o,
Err(std::sync::mpsc::TryRecvError::Empty) => return false,
Err(std::sync::mpsc::TryRecvError::Disconnected) => {
self.mcp_rx = None;
self.mcp_started = None;
self.mcp_busy_label = None;
return false;
}
};
self.mcp_rx = None;
self.mcp_started = None;
self.mcp_busy_label = None;
match outcome.body {
Ok(text) => {
let label = self.scratch_buffer_path(&format!("{}.md", outcome.title));
if self.editor.open_text_buffer(&label, &text).is_ok() {
// An MCP result arrives asynchronously; the user may be
// mid-scroll in the Explorer and did not ask for focus to
// move, let alone for the sidebar to close (#260).
self.without_auto_hide(|app| app.focus_pane(Pane::Editor));
self.status = format!(
"{}: opened in a new tab — Cmd+S saves it into the project",
outcome.title
);
}
}
Err(e) => {
self.status = format!("{}: {e}", outcome.title);
}
}
true
}
/// Capture one key into the live recording. Recording control keys are
/// excluded by the callers that own them (vim's `q`, the palette
/// commands), so a macro can never contain the gesture that ends it.
fn record_macro_key(&mut self, key: crossterm::event::KeyEvent) {
if let Some(rec) = self.macro_recording.as_mut() {
rec.recorded.push_key(key);
}
}
/// Start recording into `register` (vim `q{a-z}`) or into the unnamed
/// last-recording slot (the palette command). Starting while already
/// recording stops instead, so one gesture toggles.
fn start_macro_recording(&mut self, register: Option<char>) {
if self.macro_recording.is_some() {
self.stop_macro_recording();
return;
}
self.macro_recording = Some(crate::macros::Recording {
register,
recorded: crate::macros::Macro::default(),
});
// One source of truth: vim's `q` branches on this, and a copy the
// machine kept for itself drifted whenever the palette was used.
self.vim.set_recording(true);
self.status = match register {
Some(r) => format!("Recording macro into @{r}"),
None => String::from("Recording macro"),
};
}
/// Finish the live recording: it becomes the last macro either way, and
/// a named register is also persisted. An empty recording is discarded
/// rather than replacing a useful macro with a no-op.
fn stop_macro_recording(&mut self) {
let Some(rec) = self.macro_recording.take() else {
return;
};
self.vim.set_recording(false);
if rec.recorded.is_empty() {
self.status = String::from("Macro discarded (nothing recorded)");
return;
}
let len = rec.recorded.len();
if let Some(r) = rec.register {
let name = r.to_string();
self.macro_registers
.insert(name.clone(), rec.recorded.clone());
if let Err(e) =
crate::macros::save_register(&self.macros_path, &name, rec.recorded.clone())
{
crate::output::push("Macros", crate::output::OutputLevel::Warn, &e);
}
self.status = format!("Recorded {len} keys into @{r}");
} else {
self.status = format!("Recorded {len} keys");
}
self.macro_last = Some(rec.recorded);
}
/// Replay `mac` `count` times by feeding its keys back through
/// `handle_key`. Guarded three ways: a re-entrancy flag (a macro cannot
/// invoke itself), a total-key budget (a pathological count cannot spin
/// the UI), and an abort on the first key that errors, which leaves the
/// buffer at the abort point with earlier iterations intact.
fn replay_macro(&mut self, mac: crate::macros::Macro, count: usize) {
const MAX_REPLAY_KEYS: usize = 100_000;
if self.macro_replaying {
self.status = String::from("Macro is already replaying");
return;
}
if mac.is_empty() {
self.status = String::from("Macro is empty");
return;
}
let count = count.max(1);
// Budget the keys actually fed, not the recorded step count:
// `key_events` drops steps this build cannot replay, so `len()` is an
// upper bound rather than the real total.
let keys = mac.key_events();
if keys.is_empty() {
// Every step was one this build cannot replay (a macro from a
// newer croft). Say so rather than reporting a successful run
// of nothing.
self.status = String::from("Macro has no steps this version can replay");
return;
}
let total = keys.len().saturating_mul(count);
if total > MAX_REPLAY_KEYS {
self.status =
format!("Macro would run {total} keys (limit {MAX_REPLAY_KEYS}) — refused");
return;
}
self.macro_replaying = true;
let mut done = 0usize;
let mut aborted = None;
'outer: for iteration in 0..count {
// Break coalescing so a new iteration's opening keystrokes never
// merge into the previous iteration's typing run. This bounds
// iterations apart; it does NOT make one iteration one undo step
// — `push_undo` coalesces only InsertChar→InsertChar, so a macro
// holding a delete plus an insert still undoes in two. A real
// one-step-per-iteration guarantee needs an undo-group API the
// editor does not have (its undo is whole-buffer snapshots).
self.editor.break_undo_coalescing();
for k in &keys {
if let Err(e) = self.handle_key(*k) {
aborted = Some((iteration + 1, e.to_string()));
break 'outer;
}
}
done = iteration + 1;
}
self.macro_replaying = false;
self.status = match aborted {
Some((at, e)) => format!("Macro aborted on iteration {at}: {e}"),
None if done == 1 => String::from("Macro replayed"),
None => format!("Macro replayed {done}×"),
};
}
/// Replay the last recording (palette "Macro: Replay Last", vim `@@`).
fn replay_last_macro(&mut self, count: usize) {
match self.macro_last.clone() {
Some(m) => self.replay_macro(m, count),
None => self.status = String::from("No macro recorded yet"),
}
}
/// Replay a named register (vim `@{a-z}`).
fn replay_macro_register(&mut self, register: char, count: usize) {
match self.macro_registers.get(®ister.to_string()).cloned() {
Some(m) => {
self.macro_last = Some(m.clone());
self.replay_macro(m, count);
}
None => self.status = format!("Register @{register} is empty"),
}
}
/// Execute a Command Palette entry. Editor text commands act on the active
/// editor buffer; view / navigation commands defer to the same methods
/// their dedicated chords use, so the palette can never drift from the
/// keyboard surface.
pub(crate) fn run_command(&mut self, cmd: crate::widgets::command_palette::Command) {
use crate::widgets::command_palette::Command as Cmd;
use crate::widgets::editor::CaseTransform;
match cmd {
Cmd::MoveLineUp => self.editor.move_lines_up(),
Cmd::MoveLineDown => self.editor.move_lines_down(),
Cmd::ToggleLineComment => {
if !self.editor.toggle_line_comment() {
self.status = String::from("Toggle Line Comment: no comment for this language");
}
}
Cmd::ToggleBlockComment => {
if !self.editor.toggle_block_comment() {
self.status =
String::from("Toggle Block Comment: no block comment for this language");
}
}
Cmd::JoinLines => self.editor.join_lines(),
Cmd::DeleteLine => self.delete_current_line(),
Cmd::TransformUpper => self.editor.transform_selection_case(CaseTransform::Upper),
Cmd::TransformLower => self.editor.transform_selection_case(CaseTransform::Lower),
Cmd::TransformTitle => self.editor.transform_selection_case(CaseTransform::Title),
Cmd::SortLinesAscending => self.editor.sort_lines(true),
Cmd::SortLinesDescending => self.editor.sort_lines(false),
Cmd::TrimTrailingWhitespace => {
if self.editor.trim_trailing_whitespace() {
self.status = String::from("Trimmed trailing whitespace");
}
}
Cmd::ExpandSelection => self.expand_selection(),
Cmd::ShrinkSelection => self.shrink_selection(),
Cmd::ToggleWordWrap => {
self.editor.toggle_wrap();
self.status = if self.editor.wrap_enabled() {
String::from("Word wrap: on")
} else {
String::from("Word wrap: off")
};
}
Cmd::AddCursorAbove => self.editor.add_cursor_above(),
Cmd::AddCursorBelow => self.editor.add_cursor_below(),
Cmd::AddSelectionToNextMatch => self.start_select_next_occurrence(),
Cmd::JumpToBracket => {
if !self.editor.jump_to_matching_bracket() {
self.status = String::from("Go to Bracket: no matching bracket");
}
}
Cmd::SelectToBracket => {
if !self.editor.select_to_matching_bracket() {
self.status = String::from("Select to Bracket: no matching bracket");
}
}
Cmd::TransposeCharacters => self.editor.transpose_chars(),
Cmd::IndentationToSpaces => {
self.editor.indentation_to_spaces();
self.status = String::from("Converted indentation to spaces");
}
Cmd::IndentationToTabs => {
self.editor.indentation_to_tabs();
self.status = String::from("Converted indentation to tabs");
}
Cmd::FormatDocument => self.start_format_document(),
Cmd::FormatSelection => self.format_selection(),
Cmd::ChangeColorPresentation => self.change_color_presentation(),
Cmd::ToggleFormatOnType => self.toggle_format_on_type(),
Cmd::ToggleFormatOnSave => self.toggle_format_on_save(),
Cmd::ToggleAutoSave => self.toggle_auto_save(),
Cmd::ToggleAutoSaveOnFocusChange => self.toggle_auto_save_on_focus_change(),
Cmd::ToggleInlineBlame => self.toggle_inline_blame(),
Cmd::ToggleProvenance => self.toggle_provenance(),
Cmd::DiffToggleGroupBySeat => self.diff_toggle_group_by_seat(),
Cmd::ToggleIndentGuides => self.toggle_indent_guides(),
Cmd::ToggleBracketColors => self.toggle_bracket_colors(),
Cmd::ToggleRenderWhitespace => self.toggle_render_whitespace(),
Cmd::ToggleInlineValues => self.toggle_inline_values(),
Cmd::ToggleInlayHints => self.toggle_inlay_hints(),
Cmd::ToggleMarkdownPreview => self.toggle_markdown_preview(),
Cmd::ToggleTerminalTimestamps => self.toggle_terminal_timestamps(),
Cmd::ToggleLogHighlight => self.toggle_log_highlight(),
Cmd::CollapseTerminalPane => self.collapse_active_terminal_pane(),
Cmd::RestoreTerminalPanes => self.restore_all_terminal_panes(),
Cmd::ToggleSecretRedaction => self.toggle_secret_redaction(),
Cmd::RevealRedactedSecrets => self.reveal_redacted_secrets(),
Cmd::SearchFromTerminal => self.search_from_last_terminal_command(),
Cmd::RestoreSnapshot => self.restore_history_snapshot(),
Cmd::QuickFix => self.start_code_action(),
Cmd::ReplaceInFile => self.open_editor_replace(),
// The accept/navigate commands serve both merge flows: the
// three-way merge editor when its view is up (#253), the
// in-buffer marker flow otherwise.
Cmd::MergeAcceptCurrent => {
if self.editor.merge.is_some() {
self.merge_apply(crate::merge_editor::ConflictState::Current);
} else {
self.resolve_merge_at_cursor(crate::merge::Resolution::Current)
}
}
Cmd::MergeAcceptIncoming => {
if self.editor.merge.is_some() {
self.merge_apply(crate::merge_editor::ConflictState::Incoming);
} else {
self.resolve_merge_at_cursor(crate::merge::Resolution::Incoming)
}
}
Cmd::MergeAcceptBoth => {
if self.editor.merge.is_some() {
self.merge_apply(crate::merge_editor::ConflictState::Both);
} else {
self.resolve_merge_at_cursor(crate::merge::Resolution::Both)
}
}
Cmd::MergeAcceptBothReverse => {
if self.editor.merge.is_some() {
self.merge_apply(crate::merge_editor::ConflictState::BothReverse);
} else {
self.status = String::from("Incoming-first combination needs the merge editor");
}
}
Cmd::MergeIgnore => {
if self.editor.merge.is_some() {
self.merge_apply(crate::merge_editor::ConflictState::Base);
} else {
self.status = String::from("Ignore (keep base) needs the merge editor");
}
}
Cmd::MergeAcceptAllCurrent => {
if self.editor.merge.is_some() {
self.merge_accept_all(crate::merge_editor::ConflictState::Current);
} else {
self.resolve_all_merge(crate::merge::Resolution::Current)
}
}
Cmd::MergeAcceptAllIncoming => {
if self.editor.merge.is_some() {
self.merge_accept_all(crate::merge_editor::ConflictState::Incoming);
} else {
self.resolve_all_merge(crate::merge::Resolution::Incoming)
}
}
Cmd::MergeNextConflict => {
if self.editor.merge.is_some() {
self.merge_jump(false);
} else {
self.jump_conflict(false)
}
}
Cmd::MergePrevConflict => {
if self.editor.merge.is_some() {
self.merge_jump(true);
} else {
self.jump_conflict(true)
}
}
Cmd::MergeComplete => self.complete_merge(),
Cmd::MergeOpenEditor => match self.editor.path.clone() {
Some(p) => {
self.open_merge_editor_for(&p);
}
None => self.status = String::from("No file in the active tab"),
},
Cmd::MergeToggleBase => match self.editor.merge.as_mut() {
Some(mv) => {
mv.show_base = !mv.show_base;
self.status = if self.editor.merge.as_ref().is_some_and(|m| m.show_base) {
String::from("Base pane shown")
} else {
String::from("Base pane hidden")
};
}
None => self.status = String::from("Show Base needs the merge editor"),
},
Cmd::DebugAddWatch => self.open_add_watch_prompt(),
Cmd::PeekDefinition => self.peek_definition_at_cursor(),
// Position-carrying commands (#259). They read the click the
// dispatcher set, and do nothing from the keyboard: invoked from
// the palette there is no click to act on, and guessing the
// caret instead would make one command mean two things.
// All three arms refuse on a non-text view for the reason
// `trigger_definition_at` does: `buffer_pos_at` maps cells using
// only the text layout, so on a diff/sheet/hex/image/archive tab
// it happily returns a position into the stub text side. Acting
// on it moves the cursor somewhere meaningless and — for the
// definition arm — fires an LSP request against it. The built-in
// returns silently; a BOUND command says so instead, because the
// user asked for it explicitly and silence reads as a broken
// binding rather than a deliberate refusal.
Cmd::MouseAddCursorAtClick => match self.last_mouse_pos {
Some((col, row)) => {
if self.editor.has_non_text_view() {
self.status = String::from("No cursors in this view");
} else if self.editor.add_caret_at_screen(col, row) {
// Same as the built-in Alt+click: reset the blink
// phase, or a new caret can land mid-blink-off and
// read as "nothing happened" for up to a full period.
self.poke_cursor();
} else {
self.status = String::from("No place for a cursor there");
}
}
None => {
self.status = String::from("Mouse: Add Cursor at Click needs a mouse binding")
}
},
Cmd::MouseGoToDefinitionAtClick => match self.last_mouse_pos {
Some(_) if self.editor.has_non_text_view() => {
self.status = String::from("No definitions in this view");
}
// The outer `buffer_pos_at` exists ONLY to produce a status
// when the click resolves to no buffer position: the built-in
// fails silently there, which is right for a gesture the user
// did not aim, but a command they bound deliberately should
// say why nothing happened. `trigger_definition_at` repeats
// the lookup internally — do not "simplify" this away, or the
// bound command goes mute on a miss.
Some((col, row)) => match self.editor.buffer_pos_at(col, row) {
// Delegate rather than re-implement: `trigger_definition_at`
// follows a server-resolved document link BEFORE asking for
// a definition (#254), and a bound gesture meant to replace
// the built-in must keep that precedence. Duplicating the
// check here would let the two drift on the next change.
Some(_) => self.trigger_definition_at(col, row),
None => self.status = String::from("Nothing to define there"),
},
None => {
self.status =
String::from("Mouse: Go to Definition at Click needs a mouse binding")
}
},
Cmd::MouseOpenLinkAtClick => match self.last_mouse_pos {
Some((col, row)) => {
// `editor` is the DEFAULT `when` region, so the most
// natural binding for this command lands there. Both
// terminal helpers hit-test the TERMINAL's `last_inner`
// and return false anywhere else, so consulting only them
// made the command a permanent no-op in its own default
// region -- reporting "No link there" over a link that is.
// The refusal belongs to the EDITOR lookup only. Its
// reason — `buffer_pos_at` maps cells from the TEXT
// layout, so a diff/sheet/hex/log view still yields a
// position and we would read links from a buffer the user
// is not looking at — says nothing about the terminal
// helpers below, which read `self.terminal()` alone. The
// built-in this command replaces guards neither, so a
// guard spanning both made the bound command diverge from
// it in the opposite direction to the one being fixed.
// Bound once: the refusal and the status it explains must
// answer the SAME question, or the status describes a
// lookup that never ran.
let editor_blocked = self.editor.has_non_text_view();
let followed = !editor_blocked
&& self
.editor
.buffer_pos_at(col, row)
.and_then(|(line, c)| {
self.editor.document_link_at(line, c).map(str::to_string)
})
.inspect(|target| self.open_document_link(target))
.is_some();
if !followed
&& !self.terminal_url_click(col, row)
&& !self.terminal_file_click(col, row)
{
// Name the view only when the EDITOR lookup is the
// one that missed. A click in a terminal pane never
// consulted the editor — `editor_blocked` short-
// circuited it above — so reporting the editor's view
// there names something that was never searched.
// "a non-text view is up" and "the editor lookup is
// the one that missed" are different questions.
let in_terminal = self.terminal_at_pos(col, row).is_some();
self.status = String::from(if editor_blocked && !in_terminal {
"No links in this view"
} else {
"No link there"
});
}
}
None => {
self.status = String::from("Mouse: Open Link at Click needs a mouse binding")
}
},
Cmd::ClearBuildDiagnostics => self.clear_build_diagnostics(),
Cmd::DebugClearWatch => {
let n = self.watch_exprs.len();
self.watch_exprs.clear();
self.watch_vals.clear();
self.watch_prev.clear();
self.status = format!(
"Removed {n} watch expression{}",
if n == 1 { "" } else { "s" }
);
}
Cmd::StageHunk => self.stage_hunk_at_caret(),
Cmd::UnstageHunk => self.unstage_hunk_at_caret(),
Cmd::RevertHunk => self.request_revert_hunk_at_caret(),
Cmd::ToggleFold => {
let row = self.editor.cursor_row;
self.editor.toggle_fold(row);
}
Cmd::FoldAll => self.editor.fold_all(),
Cmd::UnfoldAll => self.editor.unfold_all(),
Cmd::FoldAllComments => self
.editor
.fold_all_of_kind(crate::lsp::manager::FoldRangeKind::Comment),
Cmd::FoldAllRegions => self
.editor
.fold_all_of_kind(crate::lsp::manager::FoldRangeKind::Region),
Cmd::UnfoldAllRegions => self
.editor
.unfold_all_of_kind(crate::lsp::manager::FoldRangeKind::Region),
Cmd::TrimFinalNewlines => {
if self.editor.trim_final_newlines() {
self.status = String::from("Trimmed final newlines");
}
}
Cmd::SaveFile => self.save(),
Cmd::Undo => {
self.status = if self.editor.undo() {
String::from("Undo")
} else {
String::from("Nothing to undo")
};
}
Cmd::Redo => {
self.status = if self.editor.redo() {
String::from("Redo")
} else {
String::from("Nothing to redo")
};
}
Cmd::CloseEditor => {
self.record_closed_tab_at(self.editor.active_index());
if self.editor.close_active() {
self.sync_open_file_poll_mtime();
self.collapse_split_if_empty();
self.status = String::from("Closed tab");
}
}
Cmd::ReopenClosedEditor => self.reopen_closed_tab(),
Cmd::SplitEditor => self.split_editor(),
Cmd::QuickOpen => self.open_file_finder(),
Cmd::GoToSymbol => self.open_go_to_symbol(),
Cmd::GoToWorkspaceSymbol => self.open_workspace_symbols(""),
Cmd::NavigateBack => self.nav_back(),
Cmd::NavigateForward => self.nav_forward(),
Cmd::GoToLastEditLocation => self.goto_last_edit_location(),
Cmd::ToggleVimMode => self.toggle_vim_mode(),
Cmd::MacroStartStopRecording if self.macro_replaying => {}
Cmd::MacroStartStopRecording => {
if self.macro_recording.is_some() {
self.stop_macro_recording();
} else {
self.start_macro_recording(None);
}
}
Cmd::MacroReplayLast if self.macro_replaying => {}
Cmd::MacroReplayLast => self.replay_last_macro(1),
// Guarded like its siblings: `macro_replay_times` is a bindable
// id, so a replayed key reaches it. A prompt opening mid-replay
// swallows the macro's remaining keys into the count field, and
// `input_prompt` is checked ABOVE the macro tap, so a later
// Enter would submit the count and re-enter replay.
Cmd::MacroReplayTimes if self.macro_replaying => {}
Cmd::MacroReplayTimes => {
use crate::widgets::input_prompt::{InputPrompt, InputPurpose};
self.open_input_prompt(InputPrompt::new(
InputPurpose::MacroReplayCount,
"Replay Macro N Times",
"count",
));
}
Cmd::ShowExplorer => self.set_sidebar_view(SidebarView::Explorer),
Cmd::ShowSearch => self.set_sidebar_view(SidebarView::Search),
Cmd::ShowSourceControl => self.set_sidebar_view(SidebarView::SourceControl),
Cmd::AddWorkspaceFolder => self.open_add_folder_picker(),
Cmd::SaveWorkspaceAs => {
use crate::widgets::input_prompt::{InputPrompt, InputPurpose};
let suggestion = {
let name = self
.workspace_root()
.file_name()
.map(|s| s.to_string_lossy().into_owned())
.unwrap_or_else(|| String::from("workspace"));
self.workspace_root()
.join(format!("{name}.code-workspace"))
.display()
.to_string()
};
self.open_input_prompt(
InputPrompt::new(
InputPurpose::SaveWorkspaceAs,
String::from("Save Workspace As"),
"Enter to save · Esc to cancel",
)
.with_value(&suggestion),
);
}
Cmd::OpenWorkspaceFromFile => match self.editor.path.clone() {
Some(p) if crate::workspace::is_workspace_file(&p) => self.open_workspace_file(&p),
_ => {
self.status = String::from("Open a .code-workspace file in the editor first");
}
},
Cmd::ReopenAsHex => match self.editor.path.clone() {
// A dirty buffer's edits exist only in memory; the hex
// view reads DISK, so switching would silently show (and
// strand) stale bytes.
Some(_) if self.editor.dirty => {
self.status = String::from("Save or revert the buffer before reopening as hex");
}
Some(p) => {
// The explicit hex choice supersedes a lingering
// Reopen-as-Text override.
self.editor.force_text = false;
if let Err(e) = self.editor.open_hex(&p) {
self.status = format!("Reopen as hex: {e}");
}
}
None => self.status = String::from("No file in the active tab"),
},
Cmd::ReopenAsText => match self.editor.path.clone() {
// Merge editor (#253): back to the in-buffer marker flow.
// The Result buffer is deliberately discarded — it was
// never saved, and the marker file on disk is the source
// of truth the old flow works on.
Some(p) if self.editor.merge.is_some() => {
self.editor.merge = None;
self.editor.dirty = false;
self.editor.force_text = true;
match self.editor.open(&p) {
Ok(()) => {
let n = self.editor.conflicts().len();
self.status = format!(
"Marker flow: {n} conflict{} — F7 jumps, Cmd+. accepts",
if n == 1 { "" } else { "s" }
);
}
Err(e) => self.status = format!("Reopen as text: {e}"),
}
}
// A rendered notebook/markdown preview counts (#180): the
// command lands in the raw source.
Some(_)
if !self.editor.has_non_text_view()
&& self.editor.markdown_preview.is_none() =>
{
self.status = String::from("The active tab is already a text view");
}
// A dirty hex tab holds unwritten byte overwrites; the
// text route would silently drop them (#173).
Some(_) if self.editor.dirty => {
self.status =
String::from("Save or revert the pending edits before reopening as text");
}
Some(p) => {
// Per-tab override (#175): skip every preview route —
// an SVG lands in its XML source, a hex tab in the
// text heuristic (whose binary verdict routes back to
// hex, reported honestly). Sticks across FS-sync
// reloads; cleared by opening a different file.
self.editor.force_text = true;
match self.editor.open(&p) {
Ok(()) if self.editor.hex.is_some() => {
self.status =
String::from("Still binary by content - staying in the hex view");
}
Ok(()) => {}
Err(e) => self.status = format!("Reopen as text: {e}"),
}
}
None => self.status = String::from("No file in the active tab"),
},
Cmd::HexFindNext => self.hex_find_next(),
Cmd::SheetInsertRowBelow
| Cmd::SheetDeleteRow
| Cmd::SheetInsertColRight
| Cmd::SheetDeleteCol => self.sheet_structure_op(cmd),
Cmd::MediaOpenExternal => match self.editor.path.clone() {
Some(p)
if self
.editor
.markdown_preview
.as_ref()
.is_some_and(|md| md.media) =>
{
// A remote session has no display to hand the file
// to (#202 review): the opener would run on the
// headless host and claim success.
if is_remote_session() {
self.status = format!(
"Running remotely: copy {} to your machine to play it",
p.display()
);
} else {
// The OS opener takes a filesystem path directly.
self.status = match open_url(&p.display().to_string()) {
Ok(()) => format!("Handed {} to the system player", p.display()),
Err(e) => format!("System player failed: {e}"),
};
}
}
_ => {
self.status = String::from("The active tab is not a media info card");
}
},
Cmd::ReopenAsPreview => match self.editor.path.clone() {
Some(_) if self.editor.dirty => {
self.status =
String::from("Save or revert the buffer before reopening the preview");
}
Some(p) => {
// Undo a Reopen-as-Text: normal routing decides the
// view again (SVG raster, image, sheet, hex).
self.editor.force_text = false;
match self.editor.open(&p) {
Ok(())
if !self.editor.has_non_text_view()
&& self.editor.markdown_preview.is_none() =>
{
self.status =
String::from("No preview for this file type; showing the text");
}
Ok(()) => {}
Err(e) => self.status = format!("Reopen as preview: {e}"),
}
}
None => self.status = String::from("No file in the active tab"),
},
Cmd::RemoveWorkspaceFolder => {
// Operates on the Explorer's selected row when it is a
// SECONDARY root section; anything else gets the hint.
let target = self
.tree
.nodes
.get(self.tree.selected)
.filter(|n| n.depth == 0 && n.path != self.tree.root)
.map(|n| n.path.clone());
match target {
Some(p) => self.remove_workspace_folder(p),
None => {
self.status =
String::from("Select a secondary root folder in the Explorer first");
}
}
}
Cmd::ShowRunDebug => self.set_sidebar_view(SidebarView::RunDebug),
Cmd::ShowRemote => self.set_sidebar_view(SidebarView::Remote),
Cmd::ShowExtensions => self.set_sidebar_view(SidebarView::Extensions),
Cmd::CompareExtensionsWithVscode => self.compare_extensions_with_vscode(),
Cmd::ShowTesting => self.open_testing_view(),
Cmd::RunTestAtCursor => self.run_test_at_cursor(),
Cmd::DebugTestAtCursor => self.debug_test_at_cursor(),
Cmd::ToggleSideBar => self.toggle_side_bar(),
Cmd::ToggleAutoHideSideBar => self.toggle_sidebar_auto_hide(),
Cmd::ToggleSecondarySideBar => self.toggle_secondary_side_bar(),
Cmd::ToggleZenMode => self.toggle_zen_mode(),
Cmd::ToggleTerminal => self.toggle_terminal(),
Cmd::ToggleMinimap => self.toggle_minimap(),
Cmd::ProblemsToggleProjectAuto => {
// auto -> on -> off -> auto. Cycling rather than a boolean
// because `auto` is a distinct answer from both, not a
// default the other two override.
let next = match Self::project_scope_mode(&self.problems_project_scope) {
"auto" => "on",
"on" => "off",
_ => "auto",
};
self.problems_project_scope = String::from(next);
let _ = crate::prefs::save_problems_project_scope(next);
// `on` and `off` are answers on their own. `auto` is the
// only mode whose effect depends on a count, and counting is
// a whole-workspace walk - which this repo runs on a
// background thread, never on a keypress. The early stop
// bounds the walk only ABOVE the cap; a root under it is
// walked to completion, which is the common case.
let effect = match next {
"on" => " (runs on its own)",
"off" => " (never runs on its own)",
// Deliberately not the answer: reporting it here would
// cost the walk. The check itself reports when it
// declines, at the point it actually declines.
_ => " (runs on its own unless the workspace is very large)",
};
self.status = format!("Whole-project check: {next}{effect}");
}
Cmd::ProblemsCheckProject => {
// An explicit ask always runs: the cap governs UNASKED runs
// (#256 criterion 5), and refusing what the user just
// requested would be answering a question nobody asked.
let root = self.workspace_root().to_path_buf();
match Self::project_check_command(&root) {
None => {
self.status = String::from(
"No whole-project checker for this workspace (expected tsconfig.json)",
);
}
Some(_) if self.project_check_running => {
self.status = String::from("A whole-project check is already running");
}
Some((program, args)) => {
// Off the main loop: tsc on a large project takes tens
// of seconds, and running it inline froze input and
// redraw for the duration - the "Checking..." status
// below never even painted. Same shape as
// `record_history_snapshot_of`: spawn, send, drain on
// the tick.
let tx = self.project_check_tx.clone();
let root_for_thread = root.clone();
let mode = self.problems_project_scope.clone();
let hint_tx = self.project_hint_tx.clone();
// NOT set here: this fires for every explicit check,
// so a run under `on`, `off`, or an under-cap `auto`
// would consume the one-shot and a later oversized
// `auto` run would stay silent forever. The flag is
// set where the hint is RECEIVED, which is the only
// point that knows one was warranted.
let hinted = self.project_check_hinted;
std::thread::spawn(move || {
// The cap's one-time hint (#256 criterion 5).
// Computed HERE, on the thread already spawned
// for the compile, because it is a whole-
// workspace walk - never on the UI thread. The
// explicit run still proceeds either way; the
// cap governs UNASKED runs, and this tells the
// user once that automatic ones will not start.
if !hinted
&& !Self::project_check_auto_enabled(
&root_for_thread,
&mode,
Self::PROJECT_CHECK_AUTO_MAX_FILES,
)
&& Self::project_scope_mode(&mode) == "auto"
{
let _ = hint_tx.send(());
}
// .output(), never .status(): the checker must not
// inherit croft's TTY, or its diagnostics spray
// over the UI.
let done = std::process::Command::new(&program)
.args(&args)
.current_dir(&root_for_thread)
.output();
let _ = tx.send((root_for_thread, done));
});
self.project_check_running = true;
self.status = String::from("Checking the whole project...");
}
}
}
Cmd::ProblemsToggleScope => {
self.problems.scope = self.problems.scope.next();
let _ = crate::prefs::save_problems_scope(self.problems.scope.to_config());
// Rebuild rather than filter in the panel: the badge counts
// the same list, so both follow the scope from one place.
self.rebuild_problems();
self.refresh_problems_badge();
self.status = format!("Problems: {}", self.problems.scope.label());
}
Cmd::DiffToggleIgnoreWhitespace => self.diff_cycle_whitespace_mode(),
Cmd::NewTerminal => match self.split_terminal() {
Ok(()) => {
self.terminal_status(format!(
"Split terminal: {} active",
self.terminals.len()
));
}
Err(e) => {
self.status = format!("Split terminal failed: {e}");
}
},
Cmd::StartDebugging => self.debug_start_or_continue(),
Cmd::SelectDebugConfig => self.open_debug_config_picker(),
Cmd::StopDebugging => self.debug_stop(),
Cmd::PauseDebugging => self.debug_pause(),
Cmd::RestartDebugging => self.debug_restart(),
Cmd::ToggleBreakpoint => self.debug_toggle_breakpoint(),
Cmd::EditLogpoint => self.debug_edit_logpoint(),
Cmd::ShowIncomingCalls => self.request_call_hierarchy_at_cursor(true),
Cmd::ShowOutgoingCalls => self.request_call_hierarchy_at_cursor(false),
Cmd::EditBreakpointCondition => self.debug_edit_condition(),
Cmd::StepOver => self.debug_step("next"),
Cmd::ToggleRaisedExceptions => self.debug_toggle_raised_exceptions(),
Cmd::AttachPythonProcess => self.open_attach_python_picker(),
Cmd::ColorTheme => self.open_theme_picker(),
Cmd::SessionParticipants => self.open_participants_picker(),
Cmd::CollabCancelStream => self.collab_cancel_stream(),
Cmd::AskNavigatorAboutCapture => self.ask_navigator_about_capture(),
Cmd::OpenWorkspaceOnSshHost => self.open_workspace_on_ssh_host(),
Cmd::ScrubHistory => self.scrub_history(),
Cmd::OpenAsSymbolTab => self.open_symbol_tab(),
Cmd::LoadReviewThreads => self.load_review_threads(),
Cmd::ToggleSessionRecording => self.toggle_session_recording(),
Cmd::FleetRun => {
self.open_input_prompt(crate::widgets::input_prompt::InputPrompt::new(
crate::widgets::input_prompt::InputPurpose::FleetCommand,
String::from("Fleet run"),
String::from("hosts: command (or *: command for every host)"),
))
}
Cmd::NewWorktreeLane => self.open_new_lane_prompt(),
Cmd::DiffWorktreeLane => self.diff_worktree_lane(),
Cmd::CloseWorktreeLane => self.close_worktree_lane(),
Cmd::MarkAgentFileReviewed => {
match self.editor.path.clone() {
None => self.status = String::from("No file open"),
Some(path) if !self.agent_ledger.is_unreviewed(&path) => {
self.status =
String::from("No agent change waiting for review on this file");
}
Some(path) => {
// Every lane holding it: a file two agents both
// touched is reviewed once, for both.
let agents: Vec<String> = self
.agent_ledger
.agents()
.into_iter()
.map(String::from)
.collect();
let mut n = 0;
for agent in &agents {
if self.mark_agent_file_reviewed(agent, &path) {
n += 1;
}
}
let name = path
.file_name()
.map(|f| f.to_string_lossy().into_owned())
.unwrap_or_default();
self.status = format!(
"{name} marked reviewed in {n} agent lane{}",
if n == 1 { "" } else { "s" }
);
}
}
}
Cmd::ShowAgentLane => {
let rows = self.agent_lane_rows();
self.status = if rows.is_empty() {
String::from("No agent has changed anything yet")
} else if self.agent_ledger.may_be_incomplete() {
format!(
"{} \u{b7} at least: the file watcher overflowed",
rows.join(" \u{b7} ")
)
} else {
rows.join(" \u{b7} ")
};
}
Cmd::DiffAgentFileSinceReview => {
match self.editor.path.clone() {
None => self.status = String::from("No file open"),
Some(path) => {
// The first lane holding it. A file two agents both
// touched has one baseline per lane, and diffing
// against an arbitrary second one would silently
// answer a different question than the row shows.
let agent = self
.agent_ledger
.agents()
.into_iter()
.map(String::from)
.find(|a| self.agent_ledger.lane(a).iter().any(|f| f.path == path));
match agent {
None => {
self.status = String::from("No agent has changed this file");
}
Some(agent) => self.diff_agent_lane_row(&agent, &path),
}
}
}
}
Cmd::MarkAgentLaneReviewed => {
let agents: Vec<String> = self
.agent_ledger
.agents()
.into_iter()
.map(String::from)
.collect();
match agents.len() {
0 => self.status = String::from("No agent has changed anything yet"),
_ => {
let mut total = 0;
for agent in &agents {
total += self.mark_agent_lane_reviewed(agent);
}
// Each lane set its own status; the summary is the
// one the user is left with.
self.status = match total {
0 => String::from("Nothing waiting for review"),
1 => String::from("1 file marked reviewed"),
n => format!("{n} files marked reviewed"),
};
}
}
}
Cmd::FixProblemWithNavigator => match self.navigator_fix_candidate() {
Some((path, item)) => self.fix_problem_with_navigator(path, item, Vec::new()),
None => self.status = String::from("No diagnostic at the caret to fix"),
},
Cmd::SendHttpRequest => self.send_http_request_under_caret(),
Cmd::CopyHttpRequestAsCurl => self.copy_http_request_as_curl(),
Cmd::AskNavigator => {
let (range, selection) = match self.editor.selection_rows() {
Some(rows) => (rows, self.editor.selection_text()),
None => {
let row = self.editor.cursor_row;
((row, row), String::new())
}
};
self.open_ask_navigator(range, selection);
}
Cmd::YieldToNavigator => self.yield_to_navigator(),
Cmd::ToggleNavigator => self.toggle_navigator(),
Cmd::ClearNavigatorNotes => self.clear_navigator_notes(),
Cmd::ToggleProactiveNavigator => self.toggle_proactive_navigator(),
Cmd::NextComment => self.cycle_comment_box(),
Cmd::IgnoreComment => self.ignore_focused_comment(),
Cmd::RunTask => self.open_run_task_picker(),
Cmd::RunBuildTask => self.run_build_task(),
Cmd::RerunLastTask => self.rerun_last_task(),
Cmd::KeyboardShortcuts => self.open_shortcuts_modal(),
Cmd::OpenSettings => self.open_settings_view(),
Cmd::OpenSettingsJson => self
.open_config_file_in_editor(crate::prefs::config_path(), ConfigFileSeed::Settings),
Cmd::OpenWorkspaceSettingsJson => self.open_workspace_settings(false),
Cmd::OpenWorkspaceSettingsLocalJson => self.open_workspace_settings(true),
Cmd::OpenKeybindingsJson => self.open_config_file_in_editor(
crate::keymap::keybindings_path(),
ConfigFileSeed::Keybindings,
),
Cmd::ConfigureSnippets => self.open_config_file_in_editor(
crate::snippets::snippets_path(),
ConfigFileSeed::Snippets,
),
Cmd::OpenAgentsJson => self
.open_config_file_in_editor(crate::agents::agents_path(), ConfigFileSeed::Agents),
Cmd::OpenTriggersJson => self.open_config_file_in_editor(
crate::triggers::triggers_path(),
ConfigFileSeed::Triggers,
),
Cmd::OpenMatchersJson => self.open_config_file_in_editor(
crate::problem_matchers::matchers_path(),
ConfigFileSeed::Matchers,
),
}
}
/// Open one of the JSON config files in the editor, creating it seeded with
/// a helpful starter when it doesn't exist yet, then reload the in-memory
/// copy so a subsequent save takes effect without a relaunch.
fn open_config_file_in_editor(&mut self, path: std::path::PathBuf, seed: ConfigFileSeed) {
if !path.exists() {
if let Some(parent) = path.parent() {
let _ = std::fs::create_dir_all(parent);
}
let contents = match seed {
ConfigFileSeed::Settings => {
let prefs = crate::prefs::Prefs::load_or_default();
serde_json::to_string_pretty(&prefs).unwrap_or_else(|_| String::from("{}\n"))
}
ConfigFileSeed::SettingsLayer => SETTINGS_LAYER_TEMPLATE.to_string(),
ConfigFileSeed::Keybindings => crate::keymap::TEMPLATE.to_string(),
ConfigFileSeed::Snippets => crate::snippets::TEMPLATE.to_string(),
ConfigFileSeed::Triggers => crate::triggers::TEMPLATE.to_string(),
ConfigFileSeed::Agents => crate::agents::TEMPLATE.to_string(),
ConfigFileSeed::Matchers => crate::problem_matchers::TEMPLATE.to_string(),
};
if let Err(e) = std::fs::write(&path, contents) {
self.status = format!("Could not create {}: {e}", path.display());
return;
}
}
if let Some(idx) = self.editor.find_tab_with_path(&path) {
self.editor.select(idx);
} else if self.editor.open(&path).is_err() {
self.status = format!("Could not open {}", path.display());
return;
}
self.focus_pane(Pane::Editor);
self.sync_open_file_poll_mtime();
self.status = match seed {
ConfigFileSeed::Settings => {
String::from("Editing settings — save to apply (theme and editor toggles live)")
}
ConfigFileSeed::SettingsLayer => {
String::from("Editing a settings layer — save to apply")
}
ConfigFileSeed::Keybindings => String::from(
"Editing keybindings.json — save, then reload keybindings from the palette",
),
ConfigFileSeed::Snippets => {
String::from("Editing snippets.json — save to apply immediately")
}
ConfigFileSeed::Triggers => {
String::from("Editing triggers.json — save to apply immediately")
}
ConfigFileSeed::Agents => {
String::from("Editing agents.json — save to apply immediately")
}
ConfigFileSeed::Matchers => {
String::from("Editing matchers.json — save to apply immediately")
}
};
}
pub fn consume_zoxide_jump_image_clear(&mut self) -> bool {
self.overlays.zoxide_jump_clear.consume()
}
/// Open the zoxide jump popup and seed it with the full frecency list
/// (`zoxide query -l`), so it shows the user's top directories before
/// they type anything — like pressing `j<Tab>` in the shell.
fn open_zoxide_jump(&mut self) {
if self.zoxide_jump.is_some() {
return;
}
let mut jump = crate::widgets::zoxide_jump::ZoxideJump::new();
jump.install_state = crate::zoxide::install_state();
jump.termux = crate::iterm2_inline::detect_termux();
jump.set_results(crate::zoxide::query(""));
// Snapshot the full frecency list so the typo-tolerant fuzzy
// fallback can rank against it without re-spawning zoxide on every
// missed keystroke.
jump.set_all_dirs(jump.results.clone());
let status = if jump.available {
format!(
"Jump: {} directories — type to filter, Esc to close",
jump.results.len()
)
} else {
// Same honest copy as the popup body (single source of truth).
format!(
"Jump: {}",
crate::widgets::zoxide_jump::unavailable_message(jump.install_state, jump.termux)
.trim_start()
)
};
self.zoxide_jump = Some(jump);
self.overlays.zoxide_jump_clear.request();
self.status = status;
}
fn close_zoxide_jump(&mut self) {
self.zoxide_add_folder = false;
if self.zoxide_jump.take().is_some() {
self.overlays.zoxide_jump_clear.request();
self.overlays.activity.mark_dirty();
self.overlays.welcome.mark_dirty();
self.overlays.hero.mark_dirty();
self.invalidate_editor_image_layouts();
self.status.clear();
}
}
/// Re-run `zoxide query` for the popup's current text and feed the
/// ranked matches back to the widget. The one subprocess per keystroke
/// is cheap (zoxide reads a small frecency DB; single-digit ms) and
/// fires only on input, never on the render hot path.
///
/// Two layers: the strict `zoxide query` is authoritative and handles
/// the common case. Only when it returns zero matches for a non-empty
/// needle does the typo-tolerant `fuzzy_rank` fallback run, ranking the
/// cached frecency DB by edit distance so a transposition like `spilt`
/// still finds `pr-split` (zoxide's own subsequence matcher cannot).
/// The fallback is purely in-memory, so it never spawns zoxide twice.
fn refresh_zoxide_results(&mut self) {
let Some(jump) = self.zoxide_jump.as_mut() else {
return;
};
let needle = jump.query.clone();
// The background install may have advanced (Running -> Done/Failed)
// since the popup opened; keep the unavailable message current.
jump.install_state = crate::zoxide::install_state();
match crate::zoxide::query(&needle) {
Some(paths) if paths.is_empty() && !needle.trim().is_empty() => {
let ranked = crate::zoxide::fuzzy_rank(&needle, &jump.all_dirs);
if ranked.is_empty() {
jump.set_results(Some(Vec::new()));
} else {
jump.set_approximate_results(ranked);
}
}
other => jump.set_results(other),
}
}
fn handle_zoxide_jump_key(&mut self, key: KeyEvent) {
let Some(jump) = self.zoxide_jump.as_mut() else {
return;
};
match (key.code, key.modifiers) {
(KeyCode::Esc, _) => {
self.close_zoxide_jump();
}
(KeyCode::Enter, _) => self.apply_zoxide_jump_selection(),
(KeyCode::Up, _) => jump.select_prev(),
(KeyCode::Down, _) => jump.select_next(),
(KeyCode::PageUp, _) => {
for _ in 0..10 {
jump.select_prev();
}
}
(KeyCode::PageDown, _) => {
for _ in 0..10 {
jump.select_next();
}
}
(KeyCode::Left, _) => jump.move_cursor_left(),
(KeyCode::Right, _) => jump.move_cursor_right(),
(KeyCode::Home, _) => jump.move_cursor_home(),
(KeyCode::End, _) => jump.move_cursor_end(),
(KeyCode::Backspace, _) => {
jump.pop_char();
self.refresh_zoxide_results();
}
(KeyCode::Delete, _) => {
jump.delete_char();
self.refresh_zoxide_results();
}
(KeyCode::Char(c), m) if !m.intersects(KeyModifiers::CONTROL | KeyModifiers::SUPER) => {
jump.push_char(c);
self.refresh_zoxide_results();
}
_ => {}
}
}
/// Jump to (or add) the highlighted directory and dismiss the popup:
/// Enter's action, shared with a mouse click on a result row.
fn apply_zoxide_jump_selection(&mut self) {
let Some(jump) = self.zoxide_jump.as_ref() else {
return;
};
let path = jump.selected_path().map(|p| p.to_path_buf());
if let Some(path) = path {
let add = self.zoxide_add_folder;
self.close_zoxide_jump();
// A zoxide row is a bare line from its database, so it can name a
// directory in a spelling nothing else in croft uses (a symlinked
// `/var/…` for `/private/var/…`). Normalise it here, where the
// untrusted path enters, so both branches agree: the folder store
// keys on `roots.primary().display()`, and two spellings of one
// directory would file and restore under different keys.
// `add_workspace_folder` canonicalises internally; the re-root
// path must not, since its callers rely on the root being exactly
// what they passed.
let path = path.canonicalize().unwrap_or(path);
if add {
self.add_workspace_folder(path);
} else {
self.change_workspace_root(path);
}
}
}
fn handle_zoxide_jump_mouse(&mut self, m: MouseEvent) {
let Some(jump) = self.zoxide_jump.as_mut() else {
return;
};
let inside = rect_contains(jump.last_rect, m.column, m.row);
match m.kind {
MouseEventKind::ScrollDown => {
for _ in 0..3 {
jump.select_next();
}
}
MouseEventKind::ScrollUp => {
for _ in 0..3 {
jump.select_prev();
}
}
MouseEventKind::Down(MouseButton::Left) | MouseEventKind::Down(MouseButton::Right)
if !inside =>
{
self.close_zoxide_jump();
}
// Click a row to jump to it, the way VS Code's quick-pick behaves.
MouseEventKind::Down(MouseButton::Left) => {
if let Some(idx) = jump.row_index_at(m.row) {
jump.selected = idx;
self.apply_zoxide_jump_selection();
}
}
_ => {}
}
}
fn render_zoxide_jump(&mut self, frame: &mut ratatui::Frame) {
let sidebar = self.last_sidebar_area;
let full = frame.area();
let theme = self.theme;
let Some(jump) = self.zoxide_jump.as_mut() else {
return;
};
// Anchor the popup over the Explorer column (it is an Explorer
// action), dropping from the sidebar's top-left. The sidebar is
// narrow, so widen the box rightward over the editor for readable
// paths, capped to the frame. When the sidebar is collapsed there
// is nothing to anchor to, so fall back to a centered box.
let rect = match sidebar {
Some(side) if side.width >= 2 && side.height >= 4 => {
let width = side
.width
.max(ZOXIDE_JUMP_MIN_WIDTH)
.min(full.width.saturating_sub(side.x));
Rect {
x: side.x,
y: side.y,
width,
height: side.height,
}
}
_ => fallback_popup_rect(full, 100),
};
crate::widgets::zoxide_jump::render_zoxide_jump(jump, rect, frame.buffer_mut(), theme);
}
fn render_command_history_popup(&mut self, frame: &mut ratatui::Frame) {
let full = frame.area();
let theme = self.theme;
let Some(pop) = self.command_history_popup.as_mut() else {
return;
};
// Centered box, the zoxide-jump fallback geometry: wide enough for
// command lines, anchored in the upper half like Quick Open.
let rect = fallback_popup_rect(full, 110);
crate::widgets::history_popup::render_history_popup(pop, rect, frame.buffer_mut(), theme);
}
pub fn consume_branch_picker_image_clear(&mut self) -> bool {
self.overlays.branch_picker_clear.consume()
}
/// Open the Checkout / Create Branch picker, seeded with the repo's
/// branches (most-recently-committed first). A one-shot `git
/// for-each-ref` runs here, off the render path — same discipline as
/// the zoxide jumper. Outside a git repo there is nothing to pick, so
/// we report that instead of opening an empty box.
fn open_branch_picker(&mut self) {
if self.branch_picker.is_some() {
return;
}
self.commit_menu_open = false;
match crate::git::list_branches(&self.scm_root()) {
Ok(branches) => {
let n = branches.len();
self.branch_picker =
Some(crate::widgets::branch_picker::BranchPicker::new(branches));
self.overlays.branch_picker_clear.request();
self.status =
format!("Branches: {n} — type to filter or name a new branch, Esc to close");
}
Err(err) => {
self.source_control.commit_feedback = Some(format!("branches: {err}"));
self.source_control.commit_feedback_is_error = true;
self.status = format!("Branch picker: {err}");
}
}
}
fn close_branch_picker(&mut self) {
if self.branch_picker.take().is_some() {
self.overlays.branch_picker_clear.request();
self.overlays.activity.mark_dirty();
self.overlays.welcome.mark_dirty();
self.overlays.hero.mark_dirty();
self.invalidate_editor_image_layouts();
self.status.clear();
}
}
/// Run the action the highlighted picker row resolves to: switch to an
/// existing branch, or create-and-switch a new one. The picker closes
/// on success; on failure it stays open with the error in the SC
/// feedback line so the user can amend the name.
fn apply_branch_action(&mut self, action: crate::widgets::branch_picker::BranchAction) {
use crate::widgets::branch_picker::BranchAction;
let (result, verb) = match &action {
BranchAction::Checkout(name) => (
crate::git::checkout_branch(&self.scm_root(), name),
"Switched to",
),
BranchAction::Create(name) => {
(crate::git::create_branch(&self.scm_root(), name), "Created")
}
};
match result {
Ok(summary) => {
self.close_branch_picker();
self.source_control.commit_feedback = Some(summary.clone());
self.source_control.commit_feedback_is_error = false;
self.status = format!("{verb}: {summary}");
self.active_git_bypass_debounce();
self.refresh_git_status_debounced();
self.refresh_source_control();
}
Err(err) => {
self.source_control.commit_feedback = Some(format!("branch: {err}"));
self.source_control.commit_feedback_is_error = true;
self.status = format!("Branch: {err}");
}
}
}
fn handle_branch_picker_key(&mut self, key: KeyEvent) {
let Some(picker) = self.branch_picker.as_mut() else {
return;
};
match (key.code, key.modifiers) {
(KeyCode::Esc, _) => self.close_branch_picker(),
(KeyCode::Enter, _) => self.apply_branch_picker_selection(),
(KeyCode::Up, _) => picker.select_prev(),
(KeyCode::Down, _) => picker.select_next(),
(KeyCode::PageUp, _) => {
for _ in 0..10 {
picker.select_prev();
}
}
(KeyCode::PageDown, _) => {
for _ in 0..10 {
picker.select_next();
}
}
(KeyCode::Left, _) => picker.move_cursor_left(),
(KeyCode::Right, _) => picker.move_cursor_right(),
(KeyCode::Home, _) => picker.move_cursor_home(),
(KeyCode::End, _) => picker.move_cursor_end(),
(KeyCode::Backspace, _) => picker.pop_char(),
(KeyCode::Delete, _) => picker.delete_char(),
(KeyCode::Char(c), m) if !m.intersects(KeyModifiers::CONTROL | KeyModifiers::SUPER) => {
picker.push_char(c);
}
_ => {}
}
}
fn handle_branch_picker_mouse(&mut self, m: MouseEvent) {
let Some(picker) = self.branch_picker.as_mut() else {
return;
};
let inside = rect_contains(picker.last_rect, m.column, m.row);
match m.kind {
MouseEventKind::ScrollDown => {
for _ in 0..3 {
picker.select_next();
}
}
MouseEventKind::ScrollUp => {
for _ in 0..3 {
picker.select_prev();
}
}
MouseEventKind::Down(MouseButton::Left) | MouseEventKind::Down(MouseButton::Right)
if !inside =>
{
self.close_branch_picker();
}
// Click a row to act on it, the way VS Code's quick-pick behaves.
MouseEventKind::Down(MouseButton::Left) => {
if let Some(idx) = picker.row_index_at(m.row) {
picker.selected = idx;
self.apply_branch_picker_selection();
}
}
_ => {}
}
}
fn render_branch_picker(&mut self, frame: &mut ratatui::Frame) {
let sidebar = self.last_sidebar_area;
let full = frame.area();
let theme = self.theme;
let Some(picker) = self.branch_picker.as_mut() else {
return;
};
// Anchor over the sidebar column like the jumper (it is a Source
// Control action), widening rightward for readable branch names;
// fall back to a centered box when the sidebar is collapsed.
let rect = match sidebar {
Some(side) if side.width >= 2 && side.height >= 4 => {
let width = side
.width
.max(ZOXIDE_JUMP_MIN_WIDTH)
.min(full.width.saturating_sub(side.x));
Rect {
x: side.x,
y: side.y,
width,
height: side.height,
}
}
_ => fallback_popup_rect(full, 100),
};
crate::widgets::branch_picker::render_branch_picker(
picker,
rect,
frame.buffer_mut(),
theme,
);
}
pub fn consume_input_prompt_image_clear(&mut self) -> bool {
self.overlays.input_prompt_clear.consume()
}
pub fn consume_list_picker_image_clear(&mut self) -> bool {
self.overlays.list_picker_clear.consume()
}
fn handle_input_prompt_key(&mut self, key: KeyEvent) {
let Some(prompt) = self.input_prompt.as_mut() else {
return;
};
match (key.code, key.modifiers) {
(KeyCode::Esc, _) => self.close_input_prompt(),
(KeyCode::Enter, _) => self.submit_input_prompt(),
(KeyCode::Left, _) => prompt.move_cursor_left(),
(KeyCode::Right, _) => prompt.move_cursor_right(),
(KeyCode::Home, _) => prompt.move_cursor_home(),
(KeyCode::End, _) => prompt.move_cursor_end(),
(KeyCode::Backspace, _) => prompt.pop_char(),
(KeyCode::Delete, _) => prompt.delete_char(),
(KeyCode::Char(c), m) if !m.intersects(KeyModifiers::CONTROL | KeyModifiers::SUPER) => {
prompt.push_char(c);
}
_ => {}
}
}
fn handle_input_prompt_mouse(&mut self, m: MouseEvent) {
let Some(prompt) = self.input_prompt.as_ref() else {
return;
};
let inside = rect_contains(prompt.last_rect, m.column, m.row);
if matches!(
m.kind,
MouseEventKind::Down(MouseButton::Left) | MouseEventKind::Down(MouseButton::Right)
) && !inside
{
self.close_input_prompt();
}
}
fn render_input_prompt(&mut self, frame: &mut ratatui::Frame) {
let full = frame.area();
let theme = self.theme;
let Some(prompt) = self.input_prompt.as_mut() else {
return;
};
crate::widgets::input_prompt::render_input_prompt(prompt, full, frame.buffer_mut(), theme);
}
fn handle_list_picker_key(&mut self, key: KeyEvent) {
let Some(picker) = self.list_picker.as_mut() else {
return;
};
match (key.code, key.modifiers) {
(KeyCode::Esc, _) => self.close_list_picker(),
(KeyCode::Enter, _) => self.confirm_list_picker(),
(KeyCode::Up, _) => picker.select_prev(),
(KeyCode::Down, _) => picker.select_next(),
(KeyCode::PageUp, _) => {
for _ in 0..10 {
picker.select_prev();
}
}
(KeyCode::PageDown, _) => {
for _ in 0..10 {
picker.select_next();
}
}
(KeyCode::Left, _) => picker.move_cursor_left(),
(KeyCode::Right, _) => picker.move_cursor_right(),
(KeyCode::Backspace, _) => picker.pop_char(),
(KeyCode::Char(c), m) if !m.intersects(KeyModifiers::CONTROL | KeyModifiers::SUPER) => {
picker.push_char(c);
}
_ => {}
}
}
fn handle_list_picker_mouse(&mut self, m: MouseEvent) {
let Some(picker) = self.list_picker.as_mut() else {
return;
};
let inside = rect_contains(picker.last_rect, m.column, m.row);
match m.kind {
MouseEventKind::ScrollDown => {
for _ in 0..3 {
picker.select_next();
}
}
MouseEventKind::ScrollUp => {
for _ in 0..3 {
picker.select_prev();
}
}
MouseEventKind::Down(MouseButton::Left) | MouseEventKind::Down(MouseButton::Right)
if !inside =>
{
self.close_list_picker();
}
// Click a row to select and run it, the way VS Code menus behave.
MouseEventKind::Down(MouseButton::Left) => {
if let Some(idx) = picker.row_index_at(m.row) {
picker.selected = idx;
self.confirm_list_picker();
}
}
_ => {}
}
}
fn render_list_picker(&mut self, frame: &mut ratatui::Frame) {
let full = frame.area();
let theme = self.theme;
let Some(picker) = self.list_picker.as_mut() else {
return;
};
crate::widgets::list_picker::render_list_picker(picker, full, frame.buffer_mut(), theme);
}
/// Render the Source Control "⋯" actions menu under the header pill.
fn render_scm_menu(&mut self, frame: &mut ratatui::Frame) {
if !self.scm_menu.open || self.sidebar_view != SidebarView::SourceControl {
self.scm_menu.close();
return;
}
let anchor = self.source_control.header_more_btn;
if anchor.width == 0 {
return;
}
let screen = frame.area();
crate::widgets::scm_menu::render(
&mut self.scm_menu,
anchor,
screen,
frame.buffer_mut(),
self.theme,
);
}
fn open_editor_find(&mut self) {
// A hex tab's find is the byte-query popup, not the text bar
// (#172): route there whether the chord or the palette got here.
if self.editor.hex.is_some() {
self.open_hex_find_prompt();
return;
}
if self.editor_find.is_some() {
return;
}
let opts = self.search.opts;
if self.editor.diff.is_some() {
let initial = self
.editor
.diff
.as_ref()
.and_then(|d| d.selection_text())
.filter(|s| !s.contains('\n'))
.unwrap_or_default();
self.editor_find = Some(crate::widgets::editor_find::EditorFind::new(
String::new(),
opts,
));
if !initial.is_empty() {
self.diff_find_set_query(initial);
}
self.status =
String::from("Find: type to search, Enter next, Shift+Enter prev, Esc close");
return;
}
let initial = if !self.editor.selection_text().is_empty()
&& !self.editor.selection_text().contains('\n')
{
self.editor.selection_text()
} else {
self.editor.word_before_cursor()
};
let mut state = crate::widgets::editor_find::EditorFind::new(initial.clone(), opts);
if !initial.is_empty() {
state.set_match_count(
crate::widgets::editor_find::count_matches(&self.editor.lines, &initial, opts),
false,
);
self.editor
.set_search_highlight(Some(initial.clone()), opts);
}
self.editor_find = Some(state);
self.status = String::from("Find: type to search, Enter next, Shift+Enter prev, Esc close");
}
/// Cmd+F in the terminal: open a find bar that searches the active pane's
/// grid + scrollback (iTerm2 / Ghostty scrollback search). Seeds from a
/// single-line selection and lands on the most recent match.
fn open_terminal_find(&mut self) {
if self.terminal_find.is_some() {
return;
}
let opts = self.search.opts;
let sel = self.terminal().selection_text();
let initial = if !sel.is_empty() && !sel.contains('\n') {
sel
} else {
String::new()
};
let (lines, _top) = self.terminal().grid_lines();
let mut state = crate::widgets::editor_find::EditorFind::new(initial.clone(), opts);
state.set_match_count(
crate::widgets::editor_find::count_matches(&lines, &initial, opts),
false,
);
self.terminal_find = Some(state);
self.terminal_find_pane = self.active_terminal;
self.terminal_find_match = None;
self.terminal_mut()
.set_search((!initial.is_empty()).then(|| initial.clone()), opts);
self.status = String::from(
"Find in terminal: type to search, Enter next, Shift+Enter prev, Esc close",
);
if !initial.is_empty() {
// Land on the bottom-most (most recent) match, like iTerm2.
self.terminal_find_jump(false);
}
}
/// Make pane `idx` the active terminal, tearing down the overlays that
/// were bound to the pane being left.
///
/// Shared by the built-in click path and the bound-gesture dispatch so
/// the two cannot drift: every terminal helper reaches the grid through
/// `self.terminal()`, which indexes `active_terminal`, so a caller that
/// skips this reads a pane the user did not click. That is not
/// hypothetical — a bound `mouse_open_link_at_click` reported "No link
/// there" over a plainly visible URL in a split, because the dispatch
/// returned above the assignment the built-in makes.
fn activate_terminal_pane(&mut self, idx: usize) {
if self.active_terminal == idx {
return;
}
// Copy mode is bound to the pane it opened on; a click on a sibling
// pane leaves it, tmux-style, rather than hijacking the new pane's
// grid.
if self
.terminal_copy_mode
.as_ref()
.is_some_and(|st| st.pane != idx)
{
self.close_terminal_copy_mode();
}
// Quick-select labels are pane-bound the same way.
if self
.terminal_quick_select
.as_ref()
.is_some_and(|st| st.pane != idx)
{
self.close_terminal_quick_select();
}
// As is the find bar and its highlight.
if self.terminal_find.is_some() && self.terminal_find_pane != idx {
self.close_terminal_find();
}
self.active_terminal = idx;
}
fn close_terminal_find(&mut self) {
if self.terminal_find.take().is_some() {
self.terminal_find_match = None;
let opts = self.search.opts;
// Clear every pane, not just the active one: the close may be
// the pane-binding invariant firing after `active_terminal`
// already moved off the pane that owns the highlight.
for t in &mut self.terminals {
t.set_search(None, opts);
t.set_current_match(None, 0);
}
}
}
/// Re-run the terminal search after the query changed: recount,
/// re-highlight every occurrence, and re-anchor on the most recent match.
fn terminal_find_set_query(&mut self, new_query: String) {
let opts = self.search.opts;
let (lines, _top) = self.terminal().grid_lines();
let count = crate::widgets::editor_find::count_matches(&lines, &new_query, opts);
if let Some(state) = self.terminal_find.as_mut() {
state.query = new_query.clone();
state.set_match_count(count, false);
state.match_index = None;
}
self.terminal_find_match = None;
self.terminal_mut()
.set_search((!new_query.is_empty()).then(|| new_query.clone()), opts);
self.terminal_mut().set_current_match(None, 0);
if !new_query.is_empty() {
self.terminal_find_jump(false);
}
}
/// Move to the next (`forward`) or previous match, wrapping. Scrolls the
/// pane so the match is visible, marks it active, and updates the "N of M"
/// index. Navigation walks from the current match, or — on the first jump —
/// from the bottom of the buffer so the newest occurrence wins.
fn terminal_find_jump(&mut self, forward: bool) {
let Some(state) = self.terminal_find.as_ref() else {
return;
};
let needle = state.query.clone();
let opts = state.opts;
if needle.is_empty() {
return;
}
let (lines, top, now) = self.terminal().grid_lines_and_clock();
if lines.is_empty() {
return;
}
let anchor = self.terminal_find_match;
let (from_row, from_col) = match anchor {
Some((clock, abs, col, _len)) => {
// Re-base the stored line by the rows scrolled since it was
// anchored, so navigation walks from the match's TEXT, not
// from the viewport row it occupied at anchor time.
let abs = abs - (now - clock) as i32;
let row = (abs - top).clamp(0, lines.len() as i32 - 1) as usize;
(row, col)
}
// No anchor: start past the last line's end so `prev` lands on the
// bottom-most match and `next` wraps to the top-most.
None => (lines.len().saturating_sub(1), usize::MAX),
};
let skip_current = anchor.is_some();
let m = if forward {
crate::widgets::editor_find::find_next_match(
&lines,
&needle,
opts,
from_row,
from_col,
skip_current,
)
} else {
crate::widgets::editor_find::find_prev_match(
&lines,
&needle,
opts,
from_row,
from_col,
skip_current,
)
};
let Some(m) = m else {
return;
};
let abs_line = top + m.row as i32;
self.terminal_find_match = Some((now, abs_line, m.col_chars, m.len_chars));
self.terminal_mut()
.set_current_match(Some((abs_line, m.col_chars, m.len_chars)), now);
self.terminal_mut().scroll_to_line(abs_line);
let idx =
crate::widgets::editor_find::match_index_at(&lines, &needle, opts, m.row, m.col_chars);
if let Some(state) = self.terminal_find.as_mut() {
state.match_index = idx;
}
}
fn handle_terminal_find_key(&mut self, key: KeyEvent) {
let shift = key.modifiers.contains(KeyModifiers::SHIFT);
match (key.code, key.modifiers) {
(KeyCode::Esc, _) => self.close_terminal_find(),
(KeyCode::Enter, _) | (KeyCode::F(3), _) => {
self.terminal_find_jump(!shift);
}
(KeyCode::Backspace, _) => {
let mut q = self
.terminal_find
.as_ref()
.map(|s| s.query.clone())
.unwrap_or_default();
q.pop();
self.terminal_find_set_query(q);
}
(KeyCode::Char('v'), m)
if m.contains(KeyModifiers::CONTROL) || m.contains(KeyModifiers::SUPER) =>
{
if let Some(text) = (self.clipboard_reader)() {
let mut q = self
.terminal_find
.as_ref()
.map(|s| s.query.clone())
.unwrap_or_default();
for c in text.chars() {
if !c.is_control() {
q.push(c);
}
}
self.terminal_find_set_query(q);
}
}
(KeyCode::Char(c), m) if !m.intersects(KeyModifiers::CONTROL | KeyModifiers::SUPER) => {
let mut q = self
.terminal_find
.as_ref()
.map(|s| s.query.clone())
.unwrap_or_default();
q.push(c);
self.terminal_find_set_query(q);
}
_ => {}
}
}
/// Ctrl+Shift+Space: enter quick-select on the active pane. Scans the
/// visible viewport for URLs / paths / hashes / IPs (see
/// [`crate::quick_select`]), assigns home-row labels with the bottom-most
/// match getting the cheapest one (WezTerm / tmux-thumbs), and overlays
/// them for the render loop.
fn open_terminal_quick_select(&mut self) {
let (lines, wraps, top, clock) = self.terminal_mut().visible_lines_and_clock();
let mut matches = crate::quick_select::find_matches_wrapped(&lines, &wraps);
// A hex run or a number inside a masked span would be a fragment of
// the secret one keystroke from the clipboard (#360): no hint there.
if self.triggers.has_redactions() && !self.redactions_revealed() {
let clear = |row: usize, start: usize, len: usize| {
lines.get(row).is_none_or(|line| {
crate::triggers::redact_spans(line, &self.triggers)
.iter()
.all(|s| start + len <= s.start || start >= s.start + s.len)
})
};
// A match that wraps the pane edge continues in `tail`; every
// segment must be clear, or the fragment past the wrap leaks.
matches.retain(|m| {
clear(m.row, m.start, m.len) && m.tail.iter().all(|&(r, s, l)| clear(r, s, l))
});
}
if matches.is_empty() {
self.status = String::from("Quick select: nothing to match on screen");
return;
}
let labels =
crate::quick_select::assign_labels(matches.len(), crate::quick_select::ALPHABET);
let dropped = matches.len().saturating_sub(labels.len());
let hints: Vec<QuickHint> = crate::quick_select::label_matches(matches, &labels)
.into_iter()
.map(|(m, label)| QuickHint {
line: top + m.row as i32,
start: m.start,
len: m.len,
text: m.text,
label,
tail: m
.tail
.iter()
.map(|&(r, s, l)| (top + r as i32, s, l))
.collect(),
})
.collect();
self.push_quick_select_hints(&hints, "", clock);
self.terminal_quick_select = Some(QuickSelectState {
pane: self.active_terminal,
clock,
hints,
typed: String::new(),
shifted: false,
});
self.status = if dropped > 0 {
format!(
"Quick select: type a label to copy, UPPERCASE pastes, Esc cancels ({dropped} top matches unlabelled)"
)
} else {
String::from("Quick select: type a label to copy, UPPERCASE pastes, Esc cancels")
};
}
/// Push the hint spans matching the typed label prefix down to the pane
/// for painting. Called on open and after every typed / erased char.
fn push_quick_select_hints(&mut self, hints: &[QuickHint], typed: &str, clock: i64) {
let spans: Vec<crate::widgets::terminal::HintSpan> = hints
.iter()
.filter(|h| h.label.starts_with(typed))
.flat_map(|h| {
// The head span carries the label glyph; a wrapped match's
// tail segments highlight their continuation rows with the
// label fully "typed" so no glyph ever paints on them.
std::iter::once(crate::widgets::terminal::HintSpan {
line: h.line,
start: h.start,
len: h.len,
label: h.label.clone(),
typed: typed.len(),
})
.chain(h.tail.iter().map(|&(line, start, len)| {
crate::widgets::terminal::HintSpan {
line,
start,
len,
label: h.label.clone(),
typed: h.label.len(),
}
}))
})
.collect();
self.terminal_mut().set_hints(Some(spans), clock);
}
fn close_terminal_quick_select(&mut self) {
if self.terminal_quick_select.take().is_some() {
// Clear every pane, not just the active one: a mouse click can
// move `active_terminal` while the labels are still up.
for t in &mut self.terminals {
t.set_hints(None, 0);
}
}
}
/// Ctrl+Shift+Y: enter copy mode on the active pane. The cursor starts
/// at the shell's cursor cell (WezTerm's convention) and the pane paints
/// it as a green modal block.
fn open_terminal_copy_mode(&mut self) {
// Cursor, bounds, and clock from ONE snapshot (see
// `begin_annotate_terminal` for why the pairing must be atomic).
let ((line, col), (top, bottom, cols, _), clock) =
self.terminal_mut().cursor_bounds_and_clock();
let line = line.clamp(top, bottom);
let col = col.min(cols.saturating_sub(1));
self.terminal_mut().set_copy_cursor(Some((line, col)));
self.terminal_copy_mode = Some(CopyModeState {
pane: self.active_terminal,
line,
col,
anchor: None,
kind: CopySelKind::Char,
clock,
});
self.status = String::from(
"Copy mode: h/j/k/l w/b/e 0/$ g/G move, v/V/^V select, y copies, Esc exits",
);
}
fn close_terminal_copy_mode(&mut self) {
if self.terminal_copy_mode.take().is_some() {
// Clear every pane, not just the active one: a mouse click can
// move `active_terminal` while the mode is up.
for t in &mut self.terminals {
t.set_copy_cursor(None);
t.clear_selection();
}
}
}
/// Push the copy-mode cursor + selection into the pane and keep the
/// cursor on screen (centering only when it left the viewport).
fn apply_terminal_copy_mode(&mut self) {
let Some(st) = self.terminal_copy_mode.as_ref() else {
return;
};
// Bound to its own pane — never paint another pane's grid (see
// `handle_terminal_copy_mode_key`).
if st.pane != self.active_terminal {
self.close_terminal_copy_mode();
return;
}
let (line, col) = (st.line, st.col);
let (_, _, cols, rows) = self.terminal().grid_bounds();
let sel = st.anchor.map(|(al, ac)| match st.kind {
CopySelKind::Char => crate::widgets::terminal::Selection {
anchor: (al, ac),
head: (line, col),
block: false,
},
CopySelKind::Line => crate::widgets::terminal::Selection {
anchor: (al.min(line), 0),
head: (al.max(line), cols.saturating_sub(1)),
block: false,
},
CopySelKind::Block => crate::widgets::terminal::Selection {
anchor: (al, ac),
head: (line, col),
block: true,
},
});
let off = self.terminal().scroll_display_offset();
let visible = (-off, rows as i32 - 1 - off);
let t = self.terminal_mut();
t.set_selection(sel);
t.set_copy_cursor(Some((line, col)));
if line < visible.0 || line > visible.1 {
t.scroll_to_line(line);
}
}
/// The char index in `text` whose grid column covers `col` (the last
/// char whose start column is <= col), for word motions over the
/// spacer-skipped row text.
fn char_idx_at_col(colmap: &[usize], col: u16) -> usize {
let col = col as usize;
match colmap.binary_search(&col) {
Ok(i) => i,
Err(0) => 0,
Err(i) => i - 1,
}
}
fn handle_terminal_copy_mode_key(&mut self, key: KeyEvent) {
let Some(mut st) = self.terminal_copy_mode.take() else {
return;
};
// The mode is bound to the pane it opened on: if a gesture moved
// `active_terminal` since (a click on a sibling pane), the stored
// coordinates and clock describe the wrong pane — close instead of
// folding another pane's clock into them.
if st.pane != self.active_terminal {
self.terminal_copy_mode = Some(st);
self.close_terminal_copy_mode();
return;
}
// Content streamed since the last key: fold the scroll-clock
// movement into the stored coordinates so this keystroke moves
// from where the pane's re-anchored highlight actually is.
let now = self.terminal_mut().scroll_clock();
let drift = (now - st.clock) as i32;
if drift != 0 {
st.line -= drift;
if let Some(a) = st.anchor.as_mut() {
a.0 -= drift;
}
st.clock = now;
}
let (top, bottom, cols, rows) = self.terminal().grid_bounds();
// Content that fell off the scrollback pins to the oldest line,
// mirroring the pane's own rebase.
st.line = st.line.clamp(top, bottom);
if let Some(a) = st.anchor.as_mut() {
a.0 = a.0.clamp(top, bottom);
}
let last_col = cols.saturating_sub(1);
let half = (rows as i32 / 2).max(1);
let page = (rows as i32 - 1).max(1);
let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
let word = crate::widgets::terminal::is_terminal_word_char;
match key.code {
KeyCode::Esc | KeyCode::Char('q') => {
self.terminal_copy_mode = Some(st);
self.close_terminal_copy_mode();
self.status = String::from("Copy mode off");
return;
}
KeyCode::Char('y') | KeyCode::Enter => {
let text = self.terminal_text_for_copy(self.terminal().selection_text());
self.terminal_copy_mode = Some(st);
self.close_terminal_copy_mode();
if text.is_empty() {
self.status =
String::from("Copy mode: nothing selected (v/V/^V starts a selection)");
} else {
copy_to_clipboard(&text);
self.status = format!("Copied {} chars to clipboard", text.chars().count());
}
return;
}
// Selection arms: v again (same kind) drops the anchor, a
// different kind reshapes the existing selection in place.
KeyCode::Char('v') if ctrl => {
if st.anchor.is_some() && st.kind == CopySelKind::Block {
st.anchor = None;
} else {
st.anchor.get_or_insert((st.line, st.col));
st.kind = CopySelKind::Block;
}
}
KeyCode::Char('v') => {
if st.anchor.is_some() && st.kind == CopySelKind::Char {
st.anchor = None;
} else {
st.anchor.get_or_insert((st.line, st.col));
st.kind = CopySelKind::Char;
}
}
KeyCode::Char('V') => {
if st.anchor.is_some() && st.kind == CopySelKind::Line {
st.anchor = None;
} else {
st.anchor.get_or_insert((st.line, st.col));
st.kind = CopySelKind::Line;
}
}
KeyCode::Char('h') | KeyCode::Left => st.col = st.col.saturating_sub(1),
KeyCode::Char('l') | KeyCode::Right => st.col = (st.col + 1).min(last_col),
KeyCode::Char('j') | KeyCode::Down => st.line = (st.line + 1).min(bottom),
KeyCode::Char('k') | KeyCode::Up => st.line = (st.line - 1).max(top),
KeyCode::Char('0') | KeyCode::Home => st.col = 0,
KeyCode::Char('$') | KeyCode::End => {
let (text, colmap) = self.terminal().row_text(st.line);
let trimmed = text.trim_end();
let chars = trimmed.chars().count();
st.col = if chars == 0 {
0
} else {
colmap.get(chars - 1).map_or(0, |&c| c as u16)
};
}
KeyCode::Char('g') => st.line = top,
KeyCode::Char('G') => st.line = bottom,
KeyCode::Char('u') if ctrl => st.line = (st.line - half).max(top),
KeyCode::Char('d') if ctrl => st.line = (st.line + half).min(bottom),
KeyCode::PageUp => st.line = (st.line - page).max(top),
KeyCode::PageDown => st.line = (st.line + page).min(bottom),
KeyCode::Char('w') => {
let (text, colmap) = self.terminal().row_text(st.line);
let chars: Vec<char> = text.chars().collect();
let mut i = Self::char_idx_at_col(&colmap, st.col);
while i < chars.len() && word(chars[i]) {
i += 1;
}
while i < chars.len() && !word(chars[i]) {
i += 1;
}
// Trailing blanks reach the row's end: wrap to the next row
// start like vim's w does at end of line.
if i >= text.trim_end().chars().count() && st.line < bottom {
st.line += 1;
st.col = 0;
} else {
st.col = colmap.get(i).map_or(last_col, |&c| c as u16);
}
}
KeyCode::Char('b') => {
let (text, colmap) = self.terminal().row_text(st.line);
let chars: Vec<char> = text.chars().collect();
let mut i = Self::char_idx_at_col(&colmap, st.col);
if i == 0 {
if st.line > top {
st.line -= 1;
let (ptext, pcolmap) = self.terminal().row_text(st.line);
let pchars = ptext.trim_end().chars().count();
st.col = if pchars == 0 {
0
} else {
pcolmap.get(pchars - 1).map_or(0, |&c| c as u16)
};
}
} else {
i -= 1;
while i > 0 && !word(chars[i]) {
i -= 1;
}
while i > 0 && word(chars[i - 1]) {
i -= 1;
}
st.col = colmap.get(i).map_or(0, |&c| c as u16);
}
}
KeyCode::Char('e') => {
let (text, colmap) = self.terminal().row_text(st.line);
let chars: Vec<char> = text.chars().collect();
let content = text.trim_end().chars().count();
let mut i = Self::char_idx_at_col(&colmap, st.col);
i += 1;
while i < chars.len() && !word(chars[i]) {
i += 1;
}
// Past the last word on this row (the scan ran into the
// trailing padding): hop to the next row's first word end,
// like vim's `e` at end of line — `w` and `b` both wrap,
// and without this `e` was a dead key at the row's last word.
if i >= content && st.line < bottom {
// Word-less rows are skipped like vim: `e` lands on the
// end of the next word wherever it lives below, and only
// falls back to the next row's column 0 when nothing
// down to the bottom has a word.
let mut landed = None;
let mut line = st.line + 1;
while line <= bottom {
let (ntext, ncolmap) = self.terminal().row_text(line);
let nchars: Vec<char> = ntext.chars().collect();
let mut j = 0;
while j < nchars.len() && !word(nchars[j]) {
j += 1;
}
if j < nchars.len() && word(nchars[j]) {
while j + 1 < nchars.len() && word(nchars[j + 1]) {
j += 1;
}
landed = Some((line, ncolmap.get(j).map_or(0, |&c| c as u16)));
break;
}
line += 1;
}
(st.line, st.col) = landed.unwrap_or((st.line + 1, 0));
} else {
while i + 1 < chars.len() && word(chars[i + 1]) {
i += 1;
}
if i < chars.len() {
st.col = colmap.get(i).map_or(last_col, |&c| c as u16);
}
}
}
_ => {}
}
st.line = st.line.clamp(top, bottom);
st.col = st.col.min(last_col);
self.terminal_copy_mode = Some(st);
self.apply_terminal_copy_mode();
}
fn handle_terminal_quick_select_key(&mut self, key: KeyEvent) {
// Bound to its origin pane: if anything moved the active pane while
// the labels were up, close instead of pushing (or pasting) the old
// pane's coordinates and text into the new one.
if self
.terminal_quick_select
.as_ref()
.is_some_and(|st| st.pane != self.active_terminal)
{
self.close_terminal_quick_select();
return;
}
match key.code {
KeyCode::Esc => {
self.close_terminal_quick_select();
self.status = String::from("Quick select cancelled");
}
KeyCode::Backspace => {
let Some(state) = self.terminal_quick_select.as_mut() else {
return;
};
state.typed.pop();
// Case history is not kept; retyping decides paste-vs-copy.
state.shifted = false;
let (hints, typed, clock) = (state.hints.clone(), state.typed.clone(), state.clock);
self.push_quick_select_hints(&hints, &typed, clock);
}
KeyCode::Char(c) if c.is_ascii_alphabetic() => {
let Some(state) = self.terminal_quick_select.as_ref() else {
return;
};
let candidate = format!("{}{}", state.typed, c.to_ascii_lowercase());
let shifted = state.shifted || c.is_ascii_uppercase();
if let Some(hit) = state.hints.iter().find(|h| h.label == candidate) {
// A hint can land inside a masked span (a hex run, a
// number); the clipboard rule applies here too (#360).
let text = self.terminal_text_for_copy(hit.text.clone());
self.close_terminal_quick_select();
copy_to_clipboard(&text);
if shifted {
self.terminal_mut().paste_input(text.as_bytes());
self.status = format!(
"Copied {} chars to clipboard and pasted into the shell",
text.chars().count()
);
} else {
self.status = format!("Copied {} chars to clipboard", text.chars().count());
}
} else if state.hints.iter().any(|h| h.label.starts_with(&candidate)) {
let Some(state) = self.terminal_quick_select.as_mut() else {
return;
};
state.typed = candidate.clone();
state.shifted = shifted;
let (hints, clock) = (state.hints.clone(), state.clock);
self.push_quick_select_hints(&hints, &candidate, clock);
}
// A char no label starts with is ignored, like WezTerm.
}
_ => {}
}
}
/// `Cmd+Opt+F` (VS Code `editor.action.startFindReplaceAction`): open
/// the find bar expanded with the replace row, or toggle the row on an
/// already-open bar. Read-only tabs (diff / sheet / image previews)
/// get the plain find bar — there is nothing to replace into.
fn open_editor_replace(&mut self) {
if !self.editor_is_text() {
self.open_editor_find();
return;
}
if self.editor_find.is_none() {
self.open_editor_find();
}
let Some(state) = self.editor_find.as_mut() else {
return;
};
state.replace_visible = !state.replace_visible;
state.focus = if state.replace_visible && !state.query.is_empty() {
crate::widgets::editor_find::FindField::Replace
} else {
crate::widgets::editor_find::FindField::Query
};
if state.replace_visible {
self.status = String::from(
"Replace: Tab switches field, Enter replaces, Cmd+Opt+Enter replaces all, Esc close",
);
}
}
fn close_editor_find(&mut self) {
if self.editor_find.take().is_some() {
self.editor.set_search_highlight(None, self.search.opts);
if let Some(diff) = self.editor.diff.as_mut() {
diff.find.needle = None;
diff.find.active = None;
}
self.status.clear();
}
}
/// Viewport geometry (visible rows, visible text columns) of the diff
/// body, derived from the last rendered inner rect the same way
/// `render_diff` lays the columns out. Used to keep a jumped-to match
/// on screen.
fn diff_find_viewport(&self) -> (usize, usize) {
let inner = self.editor.last_inner;
let viewport_rows = (inner.height as usize).saturating_sub(2);
let half = inner.width / 2;
let text_cols = match self.editor.diff.as_ref() {
Some(diff) => {
let r_gutter = (diff.right_lines.len() + 1).to_string().len() as u16 + 1;
inner
.width
.saturating_sub(half + 1)
.saturating_sub(r_gutter + 2) as usize
}
None => 0,
};
(viewport_rows, text_cols)
}
/// Recompute the diff's matches for the current query, select the
/// match at `target` (wrapping), scroll it into view, and sync the
/// find bar's count / index. Drives every diff find action.
fn diff_find_apply(&mut self, target: usize) {
let (needle, opts) = match self.editor_find.as_ref() {
Some(s) => (s.query.clone(), s.opts),
None => return,
};
let (viewport_rows, text_cols) = self.diff_find_viewport();
let Some(diff) = self.editor.diff.as_mut() else {
return;
};
diff.find.opts = opts;
if needle.is_empty() {
diff.find.needle = None;
diff.find.active = None;
if let Some(s) = self.editor_find.as_mut() {
s.set_match_count(0, false);
s.match_index = None;
}
return;
}
diff.find.needle = Some(needle.clone());
let matches = diff.find_matches(&needle, opts);
let count = matches.len();
if count == 0 {
diff.find.active = None;
if let Some(s) = self.editor_find.as_mut() {
s.set_match_count(0, false);
s.match_index = None;
}
return;
}
let pos = target % count;
let m = matches[pos];
diff.find.active = Some(m);
diff.scroll_to_match(m, viewport_rows, text_cols);
if let Some(s) = self.editor_find.as_mut() {
s.set_match_count(count, false);
s.match_index = Some(pos + 1);
}
}
fn diff_find_set_query(&mut self, new_query: String) {
if let Some(s) = self.editor_find.as_mut() {
s.query = new_query;
}
self.diff_find_apply(0);
}
fn diff_find_current_pos(&self) -> usize {
self.editor_find
.as_ref()
.and_then(|s| s.match_index)
.map(|i| i.saturating_sub(1))
.unwrap_or(0)
}
fn editor_find_set_query(&mut self, new_query: String) {
let unchanged = self
.editor_find
.as_ref()
.map(|s| s.query == new_query)
.unwrap_or(true);
if unchanged {
return;
}
if self.editor.diff.is_some() {
self.diff_find_set_query(new_query);
return;
}
if self.editor.log.is_some() {
self.log_find_set_query(new_query);
return;
}
let Some(state) = self.editor_find.as_mut() else {
return;
};
state.query = new_query;
let opts = state.opts;
state.set_match_count(
crate::widgets::editor_find::count_matches(&self.editor.lines, &state.query, opts),
false,
);
if state.query.is_empty() {
state.match_index = None;
self.editor.active_search_match = None;
self.editor.set_search_highlight(None, opts);
return;
}
self.editor
.set_search_highlight(Some(state.query.clone()), opts);
let from_row = self.editor.cursor_row;
let from_col = self.editor.cursor_col;
if let Some(m) = crate::widgets::editor_find::find_next_match(
&self.editor.lines,
&state.query,
opts,
from_row,
from_col,
false,
) {
self.jump_editor_to_match(m);
}
self.refresh_editor_find_index();
}
fn editor_find_jump_next(&mut self) {
let Some(state) = self.editor_find.as_ref() else {
return;
};
if state.query.is_empty() {
return;
}
if self.editor.diff.is_some() {
self.diff_find_apply(self.diff_find_current_pos() + 1);
return;
}
if self.editor.log.is_some() {
self.log_find_step(true);
return;
}
let opts = state.opts;
let needle = state.query.clone();
if let Some(m) = crate::widgets::editor_find::find_next_match(
&self.editor.lines,
&needle,
opts,
self.editor.cursor_row,
self.editor.cursor_col,
true,
) {
self.jump_editor_to_match(m);
self.refresh_editor_find_index();
}
}
fn editor_find_jump_prev(&mut self) {
let Some(state) = self.editor_find.as_ref() else {
return;
};
if state.query.is_empty() {
return;
}
if self.editor.diff.is_some() {
let count = state.match_count;
if count == 0 {
return;
}
self.diff_find_apply(self.diff_find_current_pos() + count - 1);
return;
}
if self.editor.log.is_some() {
self.log_find_step(false);
return;
}
let opts = state.opts;
let needle = state.query.clone();
if let Some(m) = crate::widgets::editor_find::find_prev_match(
&self.editor.lines,
&needle,
opts,
self.editor.cursor_row,
self.editor.cursor_col,
true,
) {
self.jump_editor_to_match(m);
self.refresh_editor_find_index();
}
}
/// Find over a rendered ANSI log (#257).
///
/// A log tab's `lines` is a one-line stub, because the file stays on disk
/// and only a window of it is ever parsed. Running the ordinary find path
/// over that stub answers "No results" for a file full of matches, so the
/// search goes through the view's own stripped text instead, the same fork
/// the diff view already takes.
fn log_find_set_query(&mut self, new_query: String) {
let Some(state) = self.editor_find.as_mut() else {
return;
};
state.query = new_query;
let opts = state.opts;
let needle = state.query.clone();
if needle.is_empty() {
state.set_match_count(0, false);
state.match_index = None;
self.editor.active_search_match = None;
self.editor.set_search_highlight(None, opts);
return;
}
let Some(log) = self.editor.log.as_ref() else {
return;
};
let (count, truncated) = log.count_matches(&needle, opts);
// Search from the top of the viewport, so typing finds what is on
// screen first rather than jumping to the head of the file.
let hit = log.find_next(&needle, opts, self.editor.scroll, 0, false);
if let Some(state) = self.editor_find.as_mut() {
state.set_match_count(count, truncated);
// "N of M" would have to count the matches BEFORE this one, which
// for a budgeted scan is a number we may not have; the bar falls
// back to "M matches" rather than guessing an index.
state.match_index = None;
}
self.editor.set_search_highlight(Some(needle), opts);
// A CHANGED query invalidates the old position outright, so the
// active match is cleared before the new step is applied. The early
// return for an out-of-reach STEP deliberately keeps the match the
// user was on; doing the same here left the previous query's
// highlight painted under a new query that could not reach a match
// of its own.
self.editor.active_search_match = None;
self.scroll_log_to_match(hit);
}
/// Fold in the background index of an open rendered log (#394).
///
/// Returns whether a repaint is due: the header's line count and the
/// scroll range moved. When the pass finishes, an open find bar has its
/// count re-run, since the count it shows was taken against a partial
/// index and flagged as such; a step the user makes next reaches the
/// tail on its own.
pub fn poll_log_index(&mut self) -> bool {
let Some(log) = self.editor.log.as_mut() else {
return false;
};
if !log.indexing() {
return false;
}
let changed = log.poll_index();
if log.indexing() {
return changed;
}
if let Some(state) = self.editor_find.as_ref()
&& !state.query.is_empty()
{
let (count, truncated) = log.count_matches(&state.query, state.opts);
if let Some(state) = self.editor_find.as_mut() {
state.set_match_count(count, truncated);
}
}
true
}
/// Enter / Shift+Enter over a rendered log.
fn log_find_step(&mut self, forward: bool) {
let Some(state) = self.editor_find.as_ref() else {
return;
};
let opts = state.opts;
let needle = state.query.clone();
let Some(log) = self.editor.log.as_ref() else {
return;
};
// With no active match, walk from the viewport rather than the file
// head, so the first step lands near what the user is looking at.
let (row, col) = match self.editor.active_search_match {
Some((r, c, _)) => (r, c),
None => (self.editor.scroll, 0),
};
let hit = if forward {
log.find_next(&needle, opts, row, col, true)
} else {
log.find_prev(&needle, opts, row, col)
};
self.scroll_log_to_match(hit);
}
/// Park the viewport on the step's match and mark it active. A log has
/// no caret, so the match position is carried by `active_search_match`
/// alone and the row is centred rather than merely revealed.
///
/// A step that ran out of budget is NOT the same as one that found
/// nothing: it leaves the count marked partial, so the bar keeps saying
/// how far the search actually reached instead of claiming "No results"
/// for a file it never finished reading.
fn scroll_log_to_match(&mut self, step: crate::log_view::Step) {
if step.out_of_reach() {
// Mark the count partial and STOP. Falling through to clear the
// active match left the bar reading "1+ matches" with nothing
// highlighted and no way back to the match the user was on: a
// step that could not reach further must leave them where they
// are, not throw away the position it did have.
if let Some(state) = self.editor_find.as_mut() {
let count = state.match_count;
state.set_match_count(count, true);
}
return;
}
let Some(m) = step.found() else {
self.editor.active_search_match = None;
return;
};
self.editor.active_search_match = Some((m.row, m.col_chars, m.len_chars));
// The log body starts one row below the header.
let rows = (self.editor.last_inner.height as usize).saturating_sub(1);
if rows == 0 {
self.editor.scroll = m.row;
return;
}
if m.row < self.editor.scroll || m.row >= self.editor.scroll + rows {
self.editor.scroll = m.row.saturating_sub(rows / 2);
}
}
fn jump_editor_to_match(&mut self, m: crate::widgets::editor_find::MatchPos) {
self.editor.cursor_row = m.row;
self.editor.cursor_col = m.col_chars;
self.editor.active_search_match = Some((m.row, m.col_chars, m.len_chars));
let viewport = self.editor.last_inner.height as usize;
if viewport > 0 {
if self.editor.cursor_row < self.editor.scroll {
self.editor.scroll = self.editor.cursor_row;
} else if self.editor.cursor_row >= self.editor.scroll + viewport {
self.editor.scroll = self.editor.cursor_row + 1 - viewport;
}
}
self.editor.ensure_cursor_col_visible();
}
fn refresh_editor_find_index(&mut self) {
let Some(state) = self.editor_find.as_mut() else {
return;
};
let opts = state.opts;
let needle = state.query.clone();
state.match_index = crate::widgets::editor_find::match_index_at(
&self.editor.lines,
&needle,
opts,
self.editor.cursor_row,
self.editor.cursor_col,
);
}
/// True when the replace row is shown and owns the keyboard.
fn editor_find_replace_focused(&self) -> bool {
self.editor_find
.as_ref()
.map(|s| {
s.replace_visible && s.focus == crate::widgets::editor_find::FindField::Replace
})
.unwrap_or(false)
}
/// Append / edit the focused find-bar field: the replace row edits in
/// place, the query row re-runs the search via `editor_find_set_query`.
fn editor_find_edit_focused(&mut self, edit: impl FnOnce(&mut String)) {
if self.editor_find_replace_focused() {
if let Some(s) = self.editor_find.as_mut() {
edit(&mut s.replace);
}
return;
}
let mut new_q = self
.editor_find
.as_ref()
.map(|s| s.query.clone())
.unwrap_or_default();
edit(&mut new_q);
self.editor_find_set_query(new_q);
}
fn handle_editor_find_key(&mut self, key: KeyEvent) {
if is_editor_replace_key(key) {
self.open_editor_replace();
return;
}
let shift = key.modifiers.contains(KeyModifiers::SHIFT);
let cmd_like = key
.modifiers
.intersects(KeyModifiers::CONTROL | KeyModifiers::SUPER);
match (key.code, key.modifiers) {
(KeyCode::Esc, _) => self.close_editor_find(),
// `Cmd+Opt+Enter` (Linux: `Ctrl+Alt+Enter`) = Replace All,
// VS Code's binding, from either field.
(KeyCode::Enter, m) if m.contains(KeyModifiers::ALT) && cmd_like => {
self.editor_find_replace_all();
}
(KeyCode::Enter, _) => {
if self.editor_find_replace_focused() {
self.editor_find_replace_current();
} else if shift {
self.editor_find_jump_prev();
} else {
self.editor_find_jump_next();
}
}
(KeyCode::Tab | KeyCode::BackTab, _) => {
if let Some(s) = self.editor_find.as_mut()
&& s.replace_visible
{
use crate::widgets::editor_find::FindField;
s.focus = match s.focus {
FindField::Query => FindField::Replace,
FindField::Replace => FindField::Query,
};
}
}
(KeyCode::F(3), _) => {
if shift {
self.editor_find_jump_prev();
} else {
self.editor_find_jump_next();
}
}
(KeyCode::Backspace, _) => {
self.editor_find_edit_focused(|s| {
s.pop();
});
}
(KeyCode::Char('v'), m)
if m.contains(KeyModifiers::CONTROL) || m.contains(KeyModifiers::SUPER) =>
{
if let Some(text) = (self.clipboard_reader)() {
self.editor_find_edit_focused(|s| {
for c in text.chars() {
if !c.is_control() {
s.push(c);
}
}
});
}
}
(KeyCode::Char(c), m) if !m.intersects(KeyModifiers::CONTROL | KeyModifiers::SUPER) => {
self.editor_find_edit_focused(|s| s.push(c));
}
_ => {}
}
}
/// Replace the active find match with the replace field's text
/// (expanding `$1` captures in regex mode) and advance to the next
/// match — the find bar's Replace (Enter in the replace row). With no
/// active match, Enter just finds the next one, like VS Code.
fn editor_find_replace_current(&mut self) {
if !self.editor_is_text() {
return;
}
let Some(state) = self.editor_find.as_ref() else {
return;
};
if state.query.is_empty() {
return;
}
let (needle, replacement, opts) = (state.query.clone(), state.replace.clone(), state.opts);
let Some((row, col, len)) = self.editor.active_search_match else {
self.editor_find_jump_next();
return;
};
let Some(line) = self.editor.lines.get(row) else {
return;
};
let Some(text) = crate::widgets::editor_find::expand_replacement(
line,
col,
len,
&needle,
&replacement,
opts,
) else {
// Stale match position (buffer changed underneath): resync
// instead of splicing blindly.
self.editor_find_jump_next();
return;
};
self.editor.replace_find_match(row, col, len, &text);
self.editor.active_search_match = None;
self.editor.set_search_highlight(Some(needle.clone()), opts);
if let Some(s) = self.editor_find.as_mut() {
s.set_match_count(
crate::widgets::editor_find::count_matches(&self.editor.lines, &needle, opts),
false,
);
}
if let Some(m) = crate::widgets::editor_find::find_next_match(
&self.editor.lines,
&needle,
opts,
self.editor.cursor_row,
self.editor.cursor_col,
false,
) {
self.jump_editor_to_match(m);
}
self.refresh_editor_find_index();
}
/// Replace every match in the buffer as one undo step — the find
/// bar's Replace All (`Cmd+Opt+Enter`).
fn editor_find_replace_all(&mut self) {
if !self.editor_is_text() {
return;
}
let Some(state) = self.editor_find.as_ref() else {
return;
};
if !state.replace_visible || state.query.is_empty() {
return;
}
let (needle, replacement, opts) = (state.query.clone(), state.replace.clone(), state.opts);
let Some((new_lines, n)) = crate::widgets::editor_find::replace_all_in_lines(
&self.editor.lines,
&needle,
&replacement,
opts,
) else {
return;
};
if n == 0 {
self.status = String::from("Replace All: no matches");
return;
}
self.editor.replace_all_lines(new_lines);
self.editor.active_search_match = None;
if let Some(s) = self.editor_find.as_mut() {
// Recount against the new buffer: `a` -> `aa` doubles the
// matches, and a hard zero would read "No results" over a body
// still painted full of highlights.
s.set_match_count(
crate::widgets::editor_find::count_matches(&self.editor.lines, &needle, opts),
false,
);
s.match_index = None;
}
self.editor.set_search_highlight(Some(needle), opts);
self.status = if n == 1 {
String::from("Replaced 1 occurrence")
} else {
format!("Replaced {n} occurrences")
};
}
fn render_editor_find(&mut self, frame: &mut ratatui::Frame) {
let theme = self.theme;
let Some(state) = self.editor_find.as_mut() else {
return;
};
let area = self.editor.last_full_area;
if area.width == 0 || area.height == 0 {
return;
}
crate::widgets::editor_find::render_editor_find(state, area, frame.buffer_mut(), theme);
}
/// Draw the find-in-terminal bar over the active terminal pane, reusing
/// the editor find widget (query row only). Same top-right placement.
fn render_terminal_find(&mut self, frame: &mut ratatui::Frame) {
if self.terminal_find.is_none() || !self.show_terminal {
return;
}
let theme = self.theme;
let area = self.terminal().last_area;
if area.width == 0 || area.height == 0 {
return;
}
let Some(state) = self.terminal_find.as_mut() else {
return;
};
crate::widgets::editor_find::render_editor_find(state, area, frame.buffer_mut(), theme);
}
fn handle_shortcuts_modal_key(&mut self, key: KeyEvent) {
let Some(modal) = self.shortcuts_modal.as_mut() else {
return;
};
match (key.code, key.modifiers) {
(KeyCode::Esc, _) | (KeyCode::F(1), _) => self.close_shortcuts_modal(),
(KeyCode::Char('q'), KeyModifiers::NONE) => self.close_shortcuts_modal(),
(KeyCode::Down, _) | (KeyCode::Char('j'), _) => modal.scroll_down(1),
(KeyCode::Up, _) | (KeyCode::Char('k'), _) => modal.scroll_up(1),
(KeyCode::PageDown, _) | (KeyCode::Char(' '), _) => modal.scroll_down(10),
(KeyCode::PageUp, _) => modal.scroll_up(10),
(KeyCode::Home, _) | (KeyCode::Char('g'), _) => modal.scroll_to_top(),
(KeyCode::End, _) | (KeyCode::Char('G'), _) => modal.scroll_to_bottom(),
_ => {}
}
}
fn handle_shortcuts_modal_mouse(&mut self, m: MouseEvent) {
let Some(modal) = self.shortcuts_modal.as_mut() else {
return;
};
let inside = rect_contains(modal.last_rect, m.column, m.row);
match m.kind {
MouseEventKind::ScrollDown => modal.scroll_down(3),
MouseEventKind::ScrollUp => modal.scroll_up(3),
MouseEventKind::Down(MouseButton::Left) | MouseEventKind::Down(MouseButton::Right)
if !inside =>
{
self.close_shortcuts_modal();
}
_ => {}
}
}
fn render_shortcuts_modal(&mut self, frame: &mut ratatui::Frame) {
let theme = self.theme;
let Some(modal) = self.shortcuts_modal.as_mut() else {
return;
};
let area = frame.area();
crate::widgets::shortcuts::render_shortcuts_modal(modal, area, frame.buffer_mut(), theme);
}
fn render_connect_dialog(&mut self, frame: &mut ratatui::Frame) {
let visible = self.cursor_visible_phase();
let theme = self.theme;
let Some(dialog) = self.connect_dialog.as_mut() else {
return;
};
dialog.theme = theme;
let area = frame.area();
use ratatui::widgets::Widget as _;
dialog.render(area, frame.buffer_mut());
if visible && let Some((cx, cy)) = dialog.cursor_screen_pos() {
frame.set_cursor_position((cx, cy));
}
}
/// A tap inside the on-screen keyboard band. Layer/modifier keys mutate
/// the keyboard; character/named keys synthesize a `KeyEvent` and feed
/// it through `handle_key`, so it reaches whatever currently owns the
/// keyboard focus (editor, terminal, search, or an open modal).
/// Begin a push-to-talk session on a mic press. Gated on availability:
/// only Termux with `termux-speech-to-text` can listen; a missing
/// `termux-api` package kicks off a background install and asks the user to
/// retry, and a non-Termux host just explains it is Termux-only.
/// Tap the mic: cancel a live session, or start a new one. The success path
/// is not this tap but going quiet - the system speech dialog finalizes on
/// silence and the transcript is injected then. A second tap is the escape
/// hatch (cancel) because killing the recognizer preempts its result, so it
/// can never be the way to "finish".
fn toggle_voice_input(&mut self) {
if self.voice_handle.is_some() {
self.cancel_voice_input();
} else {
self.start_voice_input();
}
}
fn start_voice_input(&mut self) {
if self.voice_handle.is_some() {
return;
}
match crate::voice::availability() {
crate::voice::Availability::Ready => {
self.voice_handle = Some(crate::voice::start(self.voice_tx.clone()));
self.voice_canceling = false;
self.status = String::from("Listening, speak then pause to insert");
}
crate::voice::Availability::NeedsApi => {
crate::voice::ensure_api_installed_in_background();
self.status = String::from(
"Installing Termux:API for voice input, tap the mic again once it finishes",
);
}
crate::voice::Availability::NeedsTermux => {
self.status = String::from("Voice input is available only on Termux");
}
}
}
/// Cancel the active session (a second mic tap): kill the recognizer and
/// discard. Recognition normally ends on its own when you stop talking;
/// this is only for abandoning a session that is stuck or unwanted. The
/// killed worker reports `Empty`, which `drain_voice` turns into a "canceled"
/// message via this flag.
fn cancel_voice_input(&mut self) {
if let Some(handle) = self.voice_handle.as_ref() {
self.voice_canceling = true;
handle.stop();
}
}
/// Per-tick: deliver a finished voice session's result. Returns whether the
/// next frame should redraw (transcript injected or a status message set).
fn drain_voice(&mut self) -> bool {
let mut changed = false;
while let Ok(msg) = self.voice_rx.try_recv() {
changed = true;
self.voice_handle = None;
match msg {
crate::voice::VoiceMsg::Transcript(text) => {
self.voice_canceling = false;
self.inject_voice_text(&text);
}
crate::voice::VoiceMsg::Empty => {
self.status = if std::mem::take(&mut self.voice_canceling) {
String::from("Voice input canceled")
} else {
String::from("No speech detected")
};
}
crate::voice::VoiceMsg::Failed(e) => {
self.voice_canceling = false;
self.status = e;
}
}
}
changed
}
/// Type a recognized transcript into whatever owns keyboard focus by
/// replaying it as synthetic key events through `handle_key` - the same
/// path an OSK key tap takes - so it reaches the editor, terminal, or an
/// open modal without pane-specific wiring.
fn inject_voice_text(&mut self, text: &str) {
for ch in text.chars() {
let code = if ch == '\n' {
KeyCode::Enter
} else {
KeyCode::Char(ch)
};
if let Err(e) = self.handle_key(KeyEvent::new(code, KeyModifiers::NONE)) {
self.status = format!("Voice input failed: {e}");
return;
}
}
self.status = String::new();
}
fn handle_osk_mouse(&mut self, m: MouseEvent) {
if !matches!(m.kind, MouseEventKind::Down(MouseButton::Left)) {
return;
}
let Some(osk) = self.osk.as_mut() else {
return;
};
let Some(key) = osk.key_at(m.column, m.row) else {
return;
};
if key == crate::widgets::osk::OskKey::Hide {
self.osk = None;
return;
}
let ev = osk.tap(key);
// Layer/modifier taps reshape the band; refresh the hit rects
// immediately so a follow-up tap that lands before the next frame
// hits the new layer, not the stale one.
let band = osk.last_area;
osk.layout(band);
// The split choice outlives the session (best-effort, like themes).
if key == crate::widgets::osk::OskKey::SplitToggle {
let _ = crate::prefs::save_osk_split(osk.split);
}
// Mic is a tap, not push-to-talk: Termux turns any finger hold into its
// own text-selection gesture (hardcoded in TerminalView, not
// suppressible from a TUI), so a hold can never reach croft as a
// sustained press. A quick tap is the only touch Termux forwards as a
// click. A tap starts recognition; the transcript lands when the user
// pauses (Android finalizes on silence), and a second tap cancels.
// Deferred until the `osk` borrow ends so the toggle can take `&mut
// self`. `tap` returned None for it, so nothing reaches handle_key.
let is_voice = key == crate::widgets::osk::OskKey::Voice;
if let Some(ev) = ev
&& let Err(e) = self.handle_key(ev)
{
self.status = format!("On-screen key failed: {e}");
}
if is_voice {
self.toggle_voice_input();
}
}
fn handle_mouse(&mut self, m: MouseEvent) {
// On-screen keyboard taps outrank every other gate - including the
// modal overlays - because the OSK is how Termux users type into
// those modals. Its band is laid out disjoint from all panes, so
// swallowing events inside it never steals a pane's click.
if self
.osk
.as_ref()
.is_some_and(|k| rect_contains(k.last_area, m.column, m.row))
{
self.handle_osk_mouse(m);
return;
}
// A click on the port-detection toast's action buttons is consumed
// before anything else; clicks elsewhere fall through to normal
// handling, so the toast never blocks the rest of the UI.
if matches!(m.kind, MouseEventKind::Down(MouseButton::Left))
&& (self.handle_port_toast_click(m.column, m.row)
|| self.handle_update_toast_click(m.column, m.row))
{
return;
}
if self.connect_dialog.is_some() {
if matches!(m.kind, MouseEventKind::Down(MouseButton::Left)) {
self.handle_connect_dialog_click(m.column, m.row);
}
return;
}
if self.shortcuts_modal.is_some() {
self.handle_shortcuts_modal_mouse(m);
return;
}
if self.file_finder.is_some() {
self.handle_file_finder_mouse(m);
return;
}
if self.process_picker.is_some() {
self.handle_process_picker_mouse(m);
return;
}
if self.command_palette.is_some() {
self.handle_command_palette_mouse(m);
return;
}
if self.workspace_symbols.is_some() {
self.handle_workspace_symbols_mouse(m);
return;
}
if self.go_to_symbol.is_some() {
self.handle_go_to_symbol_mouse(m);
return;
}
if self.zoxide_jump.is_some() {
self.handle_zoxide_jump_mouse(m);
return;
}
if self.command_history_popup.is_some() {
// Keyboard-first popup: a click anywhere dismisses it (Esc's
// mouse equivalent); the wheel moves the selection.
match m.kind {
MouseEventKind::ScrollUp => {
if let Some(pop) = self.command_history_popup.as_mut() {
pop.select_prev();
}
}
MouseEventKind::ScrollDown => {
if let Some(pop) = self.command_history_popup.as_mut() {
pop.select_next();
}
}
MouseEventKind::Down(_) => self.command_history_popup = None,
_ => {}
}
return;
}
if self.branch_picker.is_some() {
self.handle_branch_picker_mouse(m);
return;
}
if self.input_prompt.is_some() {
self.handle_input_prompt_mouse(m);
return;
}
if self.list_picker.is_some() {
self.handle_list_picker_mouse(m);
return;
}
if self.scm_menu.open && matches!(m.kind, MouseEventKind::Down(MouseButton::Left)) {
use crate::widgets::scm_menu::ClickOutcome;
match self.scm_menu.click(m.column, m.row) {
ClickOutcome::Fire(action) => self.dispatch_scm_action(action),
ClickOutcome::Toggled => {}
ClickOutcome::Missed => self.scm_menu.close(),
}
return;
}
if matches!(m.kind, MouseEventKind::Down(MouseButton::Left))
&& self
.shortcuts_hit_rect
.is_some_and(|r| rect_contains(r, m.column, m.row))
{
self.open_shortcuts_modal();
return;
}
// Clickable status-bar segments: encoding / EOL / language open a
// "change" picker; the diagnostics counts jump to the PROBLEMS panel.
if matches!(m.kind, MouseEventKind::Down(MouseButton::Left)) {
if rect_contains(self.status_language_rect, m.column, m.row) {
self.open_status_language_menu(
self.status_language_rect.x,
self.status_language_rect.y,
);
return;
}
if rect_contains(self.status_eol_rect, m.column, m.row) {
self.open_status_eol_menu(self.status_eol_rect.x, self.status_eol_rect.y);
return;
}
if rect_contains(self.status_encoding_rect, m.column, m.row) {
self.open_status_encoding_menu(
self.status_encoding_rect.x,
self.status_encoding_rect.y,
);
return;
}
if rect_contains(self.status_indent_rect, m.column, m.row) {
self.open_status_indent_menu(self.status_indent_rect.x, self.status_indent_rect.y);
return;
}
if rect_contains(self.status_diag_rect, m.column, m.row) {
self.set_bottom_panel_tab(BottomPanelTab::Problems);
return;
}
if rect_contains(self.status_agents_rect, m.column, m.row) {
self.focus_agent_pane();
return;
}
}
// Layout-control icons (Toggle Side Bar / Panel / Customize Layout) at
// the top-right of the editor tab strip / welcome screen. Checked
// before the panes so a click on an icon never falls through to the
// editor below it. Skipped while a menu is open (that block wins).
if self.context_menu.is_none() && matches!(m.kind, MouseEventKind::Down(MouseButton::Left))
{
let icons = self.layout_icon_areas;
if rect_contains(icons.toggle_side_bar, m.column, m.row) {
self.toggle_side_bar();
self.after_chrome_visibility_change();
return;
}
if rect_contains(icons.toggle_panel, m.column, m.row) {
self.toggle_terminal();
return;
}
if rect_contains(icons.customize, m.column, m.row) {
self.open_customize_layout_menu();
return;
}
}
// While a prompt is open, mouse events are ignored.
if self.prompt.is_some() {
return;
}
// While a context menu is open, route clicks to it.
if self.context_menu.is_some() {
match m.kind {
MouseEventKind::Down(MouseButton::Left) => {
// 1. A click inside the open submenu panel dispatches that child.
if let Some(child) = self.submenu_item_at(m.column, m.row) {
let dispatch = self.context_menu.as_ref().and_then(|menu| {
let parent = menu.open_submenu?;
let MenuEntry::Submenu { items, .. } = menu.items.get(parent)? else {
return None;
};
match items.get(child) {
Some(MenuEntry::Item { action, .. }) => {
Some((action.clone(), menu.target_dir.clone()))
}
_ => None,
}
});
if let Some((action, dir)) = dispatch {
self.context_menu = None;
self.dispatch_menu_action(action, dir);
}
return;
}
// 2. A click on a top-level row: dispatch an item, or open a submenu.
if let Some(idx) = self.menu_item_at(m.column, m.row) {
let action =
self.context_menu
.as_ref()
.and_then(|menu| match menu.items.get(idx) {
Some(MenuEntry::Item { action, .. }) => {
Some((action.clone(), menu.target_dir.clone()))
}
_ => None,
});
match action {
Some((action, dir)) => {
self.context_menu = None;
self.dispatch_menu_action(action, dir);
}
None => {
// A submenu parent (or a divider): open the submenu.
if let Some(menu) = self.context_menu.as_mut() {
menu.selected = idx;
menu.open_cursor_submenu();
}
}
}
return;
}
// 3. Click outside every panel: dismiss.
self.context_menu = None;
return;
}
MouseEventKind::Down(MouseButton::Right) => {
self.context_menu = None;
// fall through so the right-click below can re-open if applicable
}
_ => return,
}
}
// When the editor is split, a press anywhere in the NON-focused
// column (except its draggable seam) moves focus there first, so
// the rest of this handler - which all reads `self.editor` - then
// operates on the clicked group. The swap keeps the physical
// columns fixed.
if matches!(m.kind, MouseEventKind::Down(_))
&& self.editor_layout.is_split()
&& self.seam_at(m.column, m.row).is_none()
&& let Some(target) = self.editor_layout.inactive_dfs_index_at(m.column, m.row)
{
let current = std::mem::take(&mut self.editor);
self.editor = self.editor_layout.refocus_to_dfs(current, target);
self.focus_pane(Pane::Editor);
}
// Hit-test the side panel against the ACTIVE widget's last_area
// rather than always against `self.tree.last_area`. The tree is
// only re-rendered when the Explorer view is active; switching
// to Search / Source Control / Remote / Run-Debug freezes
// `tree.last_area` at whatever rectangle the last Explorer
// render captured, which can be smaller than the current side
// panel and silently swallow clicks on rows below that rect.
let active_sidebar_area = match self.sidebar_view {
SidebarView::Explorer => self.tree.last_area,
SidebarView::Search => self.search.last_area,
SidebarView::SourceControl => self.source_control.last_area,
SidebarView::Remote => self.remote.last_area,
SidebarView::RunDebug => self.run_debug.last_area,
SidebarView::Extensions => self.extensions.last_area,
SidebarView::Testing => self.testing.last_area,
};
// The COMMITS graph docks BELOW the change list in its own strip, so
// `source_control.last_area` alone misses it; without this union the
// graph's wheel-scroll and click handlers (all gated on `in_tree`)
// are unreachable (Codeberg #41).
let in_commit_graph = self.sidebar_view == SidebarView::SourceControl
&& rect_contains(self.commit_graph.last_area, m.column, m.row);
let in_tree = self.show_tree
&& (rect_contains(active_sidebar_area, m.column, m.row) || in_commit_graph);
// The OUTLINE section sits below the tree in the Explorer sidebar and
// scrolls independently, so wheel events over it must reach the panel
// rather than the tree above.
let in_outline = self.sidebar_view == SidebarView::Explorer
&& rect_contains(self.outline.last_area, m.column, m.row);
let in_open_editors = self.sidebar_view == SidebarView::Explorer
&& rect_contains(self.open_editors.last_area, m.column, m.row);
let in_timeline = self.sidebar_view == SidebarView::Explorer
&& rect_contains(self.timeline.last_area, m.column, m.row);
let in_deps = self.sidebar_view == SidebarView::Explorer
&& rect_contains(self.dependencies.last_area, m.column, m.row);
let in_editor_pane = rect_contains(self.editor.last_full_area, m.column, m.row);
let in_editor = rect_contains(self.editor.last_area, m.column, m.row);
let terminal_hit = self.terminal_at_pos(m.column, m.row);
let in_terminal = terminal_hit.is_some();
// User mouse bindings (#259) resolve before the built-in widget
// behaviour, mirroring how keybindings.json wins over default chords.
// Placed after the region predicates so a binding's `when` context is
// known, and above every built-in so rebinding one actually takes it
// over. A gesture croft has no binding for falls straight through.
// Classify ONCE and reuse. `gesture_for` reads the modified-click
// tracker to decide `Click` vs `DoubleClick`, so calling it a second
// time after recording would let a single click arm itself and come
// back a double — which is exactly what an earlier attempt at this did.
// The recording therefore happens after the lookup, using the gesture
// decided here, never a freshly re-derived one.
let bound_mouse = if self.keymap.has_mouse_bindings()
&& let Some(ctx) = mouse_context_for(&m, in_editor, in_terminal, in_tree, self)
&& let Some(gesture) = gesture_for(&m, self, ctx, std::time::Instant::now())
{
Some((ctx, gesture, self.keymap.command_for_mouse(gesture, ctx)))
} else {
None
};
// A modified click is recorded whether or not it matched a binding. The
// first click of a `ctrl+double_click` pair matches nothing by
// construction — it classifies as `ctrl+click`, and a user who bound
// only the double has nothing for it to hit — so recording only on a
// match left the pair's second click seeing an empty tracker, and the
// double could not fire at all.
//
// Unmodified clicks are deliberately not recorded here: their trackers
// are shared with the built-ins, which record their own clicks on the
// paths below. Doing it in both places would double-count.
//
// A click the pointer-owning child gets is not croft's to remember.
// The built-ins record INSIDE their `child_owns_pointer` check; this
// recording sat above it, so clicks croft deliberately declined to act
// on still armed the tracker, and a later modified click paired with
// one the user had aimed at the TUI in the terminal. Same predicate as
// the dispatch below, indexed by the pane that was CLICKED.
let child_owns_pointer = bound_mouse.is_some_and(|(ctx, gesture, _)| {
// Only the gestures croft actually FORWARDS: a tracking child can
// own nothing else. That is the wheel (both wheel arms below) and
// the LEFT button -- press in the Down(Left) arm, motion in Drag,
// release in Up -- since #474, when clicking a TUI's own controls
// (Claude Code's diff-panel ×) started working. `Click` and
// `DoubleClick` are both Down(Left), so both are the child's.
// Middle and right clicks are still croft's (paste, the context
// menu), so a binding on them fires over a tracking child too.
matches!(
gesture.kind,
crate::keymap::GestureKind::WheelUp
| crate::keymap::GestureKind::WheelDown
| crate::keymap::GestureKind::Click
| crate::keymap::GestureKind::DoubleClick
) && matches!(ctx, crate::keymap::MouseContext::Terminal)
&& terminal_hit.is_some_and(|idx| {
// Tracking is not enough: `terminal_at_pos` hit-tests
// `last_area`, which includes the BORDER, while delivery
// goes through `cell_at` on `last_inner`, which does not.
// Declining a binding for a cell the child will never be
// told about loses the gesture for both parties. The
// built-in wheel path already falls through on exactly
// this case — see the `report_mouse` guard on both wheel
// arms, whose comment names the border explicitly.
self.terminals[idx].mouse_reporting()
&& self.terminals[idx].cell_at(m.column, m.row).is_some()
})
&& !m.modifiers.contains(KeyModifiers::SHIFT)
});
if let Some((_, gesture, _)) = bound_mouse
&& !gesture.mods.is_empty()
&& !child_owns_pointer
{
let now = std::time::Instant::now();
match gesture.kind {
// Clear on a fired double so a third click re-arms rather than
// re-firing; record otherwise so the NEXT modified click can be
// seen as the second of a pair.
crate::keymap::GestureKind::DoubleClick => self.modified_click.clear(),
crate::keymap::GestureKind::Click => {
self.modified_click
.record(now, m.column, m.row, gesture.mods)
}
_ => {}
}
}
// The first half of a bound double-click matches no binding, so
// without this it falls through to whatever built-in owns the same
// modifier: binding `ctrl+double_click` in the editor made the pair's
// first click fire go-to-definition, and in the terminal it armed the
// plain double-click tracker so the user's NEXT ordinary click
// selected a word they never gestured for. Both are the same bug —
// croft acting on a click the user aimed at their own binding.
//
// Swallowed AFTER the modified-click recording above, which is what
// lets the second click of the pair see the first. Only the prefix of
// a bound double is swallowed: a Ctrl+click with no double bound
// reaches the built-in unchanged.
//
// `child_owns_pointer` for the same reason the matched dispatch below
// consults it — a TUI that asked for mouse tracking owns the pointer,
// so croft must not suppress a built-in on its behalf. The recording
// above already declines there, so the bound double is unreachable in
// that state anyway: swallowing would cost the built-in and buy
// nothing. Omitting it here disabled the built-in Ctrl+click over
// every full-screen TUI for anyone who bound only `ctrl+double_click`.
// Over a tracking child the click is forwarded to it (#474), so
// `child_owns_pointer` is true for a left click there and the swallow
// steps aside: the recording above already declined, the bound double
// is unreachable, and swallowing would only cost the child its press.
// Where the child does not own it, the question is narrower: would
// declining this click COST the user a built-in that was going to act?
// For Ctrl/Cmd the built-in opens a URL or a file reference, so defer
// when either is under the cursor -- that link-open runs BEFORE the
// forward in the Down(Left) arm, so it applies over a tracking child
// as well.
let builtin_would_act = matches!(bound_mouse, Some((ctx, _, _)) if
matches!(ctx, crate::keymap::MouseContext::Terminal))
&& (m.modifiers.contains(KeyModifiers::CONTROL)
|| m.modifiers.contains(KeyModifiers::SUPER))
&& terminal_hit
.is_some_and(|idx| self.terminal_would_open_something_at(idx, m.column, m.row));
if let Some((ctx, gesture, None)) = bound_mouse
&& !gesture.mods.is_empty()
&& !builtin_would_act
&& !child_owns_pointer
&& self.keymap.is_double_click_prefix(gesture, ctx)
{
// Focus still moves, as a click in a pane always does — otherwise
// the pair's second click lands in a pane the keyboard has not
// followed. This mirrors what the matched path does below.
match ctx {
crate::keymap::MouseContext::Terminal => {
if let Some(idx) = terminal_hit {
self.activate_terminal_pane(idx);
self.focus_pane(Pane::Terminal);
}
}
crate::keymap::MouseContext::Editor | crate::keymap::MouseContext::TabStrip => {
self.focus_pane(Pane::Editor)
}
crate::keymap::MouseContext::FileTree => self.focus_pane(Pane::Tree),
}
// Same teardown the matched branch runs: this is an early return
// on the same press path, and it re-focuses a pane underneath
// whatever popups were showing.
self.dismiss_click_overlays(m);
return;
}
if let Some((ctx, gesture, Some(cmd))) = bound_mouse {
// A terminal running a mouse-tracking TUI owns the pointer, same
// rule the built-ins follow: croft must not steal a click the
// child asked for. Computed once above so the recording and this
// dispatch cannot drift apart — they must agree on whether the
// click was croft's to act on.
if !child_owns_pointer {
// Every built-in pairs `is_double` with `record`/`clear` so
// the count stays right. The early return below skips the
// built-in branch that would have recorded, so the dispatch
// has to keep the tracker itself: clear on a fired double
// (or a third click re-fires it), record on a fired UNMODIFIED
// single (or a `click` binding starves the `double_click`
// binding beside it — `is_double` could never become true).
//
// Unmodified only, because the built-ins that read these
// trackers do not consult modifiers. Recording a ctrl+click
// would arm the editor's plain double-click, and the user's
// next ordinary click would select a word they never asked
// for. Bare clicks are reserved in `editor`/`terminal`, so
// the record here only ever matters for `file_tree` and
// `tab_strip`, which is exactly where it is needed.
// Modified clicks are recorded above, before the command
// lookup, so the first click of a pair is remembered even
// though it matches nothing.
let now = std::time::Instant::now();
if gesture.mods.is_empty() {
let tracker = match ctx {
crate::keymap::MouseContext::Terminal => &mut self.terminal_click,
crate::keymap::MouseContext::FileTree => &mut self.tree_click,
// The strip shares the editor's tracker, as
// `gesture_for` does: a double-click is the same
// gesture whether it lands on a tab or the text below
// it. Spelled out rather than caught by `_` so a new
// variant has to choose.
crate::keymap::MouseContext::Editor
| crate::keymap::MouseContext::TabStrip => &mut self.editor_click,
};
match gesture.kind {
crate::keymap::GestureKind::DoubleClick => tracker.clear(),
// Pass the modifiers through: #317's guard then keeps
// a MODIFIED gesture from arming the built-in tracker,
// which is what the separate ModifiedClickTracker
// exists for. Hard-coding NONE here would re-open the
// exact hole - a ctrl+click binding arming the plain
// double-click the user never made.
crate::keymap::GestureKind::Click => {
tracker.record(now, m.column, m.row, m.modifiers)
}
_ => {}
}
}
// The early return below skips the teardown every other
// press path runs, so do it here: a fired binding changes
// the state underneath these popups, and leaving them up
// paints a hover, a tab tooltip or a button hint describing
// what was there before the command ran. The dwell timer is
// cleared for the same reason — it is armed at coordinates
// whose meaning the command just changed.
self.dismiss_click_overlays(m);
// Termux: the tap still has to raise the on-screen keyboard.
// Skipping it leaves a device with no other keyboard unable
// to type into the field the tap just focused. Reachable
// despite bare clicks being reserved in editor/terminal: any
// MODIFIED click in the editor or terminal gets here, and a
// bound gesture there should raise the keyboard exactly as the
// built-in press would. `ctx` carries the region, so the
// built-in's in_editor / in_terminal / in_tree — computed
// below this block — are not needed to make the same decision.
if self.osk_auto
&& self.osk.is_none()
&& matches!(m.kind, MouseEventKind::Down(MouseButton::Left))
&& match ctx {
crate::keymap::MouseContext::Editor
| crate::keymap::MouseContext::Terminal => true,
// `mouse_context_for` only yields `FileTree` while the
// sidebar is showing the Explorer, so the Search view
// this once tested for is unreachable from here — the
// narrowing that fixed tree bindings firing over other
// sidebar views left this arm behind. The tree has no
// text input to raise a keyboard for, so `false` is
// what the reachable half always evaluated to anyway.
crate::keymap::MouseContext::FileTree
| crate::keymap::MouseContext::TabStrip => false,
}
{
let mut osk = crate::widgets::osk::Osk::new();
osk.split = crate::prefs::Prefs::load_or_default().osk_split;
self.osk = Some(osk);
}
// Every terminal command reads the grid through
// `self.terminal()`, i.e. `active_terminal`. The built-in
// click path makes the clicked pane active before it runs
// any of them; this early-returns above that, so it has to
// do the same or a bound command inspects whichever pane
// happened to be focused. Same helper, so the overlay
// teardown cannot drift between the two paths.
if matches!(ctx, crate::keymap::MouseContext::Terminal)
&& let Some(idx) = terminal_hit
{
self.activate_terminal_pane(idx);
}
// Clicking a pane focuses it — every built-in click handler
// does this, and returning above them skips it. Distinct from
// the pane activation above: that decides which terminal a
// command READS, this decides where the next KEYSTROKE goes.
// Without it a bound gesture that clicks into another pane
// acts on the clicked pane while the keyboard silently stays
// behind, so the user's next character lands in the pane they
// just clicked away from.
//
// The tab strip focuses the editor: it has no focus of its
// own, and that is what clicking a tab does anyway.
match ctx {
crate::keymap::MouseContext::Terminal => self.focus_pane(Pane::Terminal),
crate::keymap::MouseContext::FileTree => self.focus_pane(Pane::Tree),
crate::keymap::MouseContext::Editor | crate::keymap::MouseContext::TabStrip => {
self.focus_pane(Pane::Editor)
}
}
// Position-carrying commands read the click through this,
// set before dispatch and cleared after so a keyboard
// invocation of the same command never sees a stale click.
self.last_mouse_pos = Some((m.column, m.row));
self.run_command(cmd);
self.last_mouse_pos = None;
return;
}
}
let in_problems = self.bottom_panel_tab == BottomPanelTab::Problems
&& rect_contains(self.problems.last_area, m.column, m.row);
let in_output = self.bottom_panel_tab == BottomPanelTab::Output
&& rect_contains(self.output.last_area, m.column, m.row);
let in_tree_scrollbar = self.sidebar_view == SidebarView::Explorer
&& rect_contains(self.tree.last_scrollbar, m.column, m.row);
let in_remote_scrollbar = self.sidebar_view == SidebarView::Remote
&& rect_contains(self.remote.last_scrollbar, m.column, m.row);
let in_search_scrollbar = self.sidebar_view == SidebarView::Search
&& rect_contains(self.search.last_scrollbar, m.column, m.row);
let in_editor_scrollbar = rect_contains(self.editor.last_scrollbar, m.column, m.row);
let in_editor_hscrollbar = rect_contains(self.editor.last_hscrollbar, m.column, m.row);
if matches!(m.kind, MouseEventKind::Moved) {
self.pointer_cell = Some((m.column, m.row));
self.on_mouse_moved(m.column, m.row, in_editor);
return;
}
// Extend / finish a rendered-preview selection (#215) before any
// other gesture claims the drag.
if self.update_preview_selection(m) {
return;
}
// A rendered log carries its own selection for the same reason the
// preview does: the tab's `lines` is a stub (#257).
if self.update_log_selection(m) {
return;
}
// The release of a press is not a new gesture, so it keeps the popup:
// that is what lets a press-and-hold (touch) read the hover after
// lifting the finger. Every other event dismisses it.
if !matches!(m.kind, MouseEventKind::Up(_)) {
self.hover_popup = None;
self.hover_diagnostic = None;
}
// Any click dismisses the tab tooltip (selecting/closing a tab,
// or clicking elsewhere) so it can't linger over the new state.
self.tab_tooltip = None;
self.tab_hover.clear();
self.tab_hover_idx = None;
// Same for the chrome button hint: a click acts on the control, so the
// hint has served its purpose and must not survive the state change.
self.ui_tooltip = None;
self.ui_hover.clear();
self.ui_tooltip_label = None;
// A left press in the editor body arms the same dwell a resting
// pointer does: a touchscreen emits no Moved events (a finger cannot
// hover), so the tap itself is the "pointer arrived here" signal and
// the LSP hover fires HOVER_DELAY later. This matches VS Code on
// desktop too, where the hover re-shows when the pointer rests on a
// symbol after a click. Drags (selection) and scrolls cancel the
// pending dwell; the release does not, so a quick tap still fires.
match m.kind {
MouseEventKind::Down(MouseButton::Left)
if in_editor
&& !in_editor_scrollbar
&& !in_editor_hscrollbar
&& self.editor.tab_at(m.column, m.row).is_none() =>
{
// clear() before on_move(): a repeat tap on the same cell
// must restart the timer (on_move alone keys off cell change).
self.hover.clear();
self.hover
.on_move(std::time::Instant::now(), m.column, m.row);
}
MouseEventKind::Up(_) => {}
_ => self.hover.clear(),
}
// Termux: a tap in any editable area raises the on-screen keyboard,
// standing in for the native soft keyboard that active mouse
// tracking permanently suppresses. The tap still falls through to
// its normal focus / cursor handling below.
if self.osk_auto
&& self.osk.is_none()
&& matches!(m.kind, MouseEventKind::Down(MouseButton::Left))
&& (in_editor || in_terminal || (in_tree && self.sidebar_view == SidebarView::Search))
{
let mut osk = crate::widgets::osk::Osk::new();
// Restore the persisted split-layout choice (foldables).
osk.split = crate::prefs::Prefs::load_or_default().osk_split;
self.osk = Some(osk);
// The raise reflows the whole frame, so a dwell armed at the
// pre-raise coordinates would resolve the wrong buffer cell.
self.hover.clear();
}
match m.kind {
MouseEventKind::Down(MouseButton::Right) => {
// Minimap strip right-click: the VS Code-style options menu
// (Minimap toggle + Side submenu). Checked first so the strip
// wins over the editor pane it sits beside.
if rect_contains(self.minimap_img_rect, m.column, m.row) {
self.open_minimap_menu(m.column, m.row);
return;
}
// A PROBLEMS diagnostic row: Fix with Navigator (#374).
// Offered whether or not a navigator is seated, like the
// CAPTURES ask: the menu model has no disabled state, and a
// refusal that says why beats a greyed entry.
if self.bottom_panel_tab == BottomPanelTab::Problems
&& rect_contains(self.problems.last_area, m.column, m.row)
&& let Some((path, item)) = self.problems.diagnostic_at(m.row)
{
self.context_menu = Some(ContextMenu::flat(
(m.column, m.row),
vec![(
String::from("Fix with Navigator"),
MenuAction::FixProblemWithNavigator { path, item },
)],
self.tree.root.clone(),
));
return;
}
// A CAPTURES row: the ask is offered whether or not a
// navigator is seated, and says so if none is (#372).
if self.bottom_panel_tab == BottomPanelTab::Captures
&& rect_contains(self.captures.last_area, m.column, m.row)
&& let Some(idx) = self.captures.row_at(m.column, m.row)
{
self.captures.select_index(idx);
self.context_menu = Some(ContextMenu::flat(
(m.column, m.row),
vec![(
String::from("Ask Navigator About This Line"),
MenuAction::AskNavigatorAboutCapture,
)],
self.tree.root.clone(),
));
return;
}
// Editor tab strip: right-click on a tab opens the
// Close / Close Others / Close to the Right / Close All
// menu. Routed here BEFORE the explorer branch so the
// hit-test wins even when the editor pane shares its
// column with the sidebar.
if let Some(tab_idx) = self.editor.tab_at(m.column, m.row) {
self.focus_pane(Pane::Editor);
let tab_path = self.editor.tab_path(tab_idx);
let items = build_tab_context_menu_items(
tab_idx,
self.editor.tab_count(),
self.editor_layout.is_split(),
tab_path.as_deref(),
!self.is_remote && cfg!(target_os = "macos"),
self.editor.is_preview(tab_idx),
self.editor.is_pinned(tab_idx),
);
self.context_menu = Some(ContextMenu {
origin: (m.column, m.row),
items,
selected: 0,
open_submenu: None,
submenu_selected: 0,
target_dir: self.tree.root.clone(),
});
return;
}
// Terminal pane right-click: the `…`-overflow equivalent. Rename
// and Clear (the gaps vs VS Code's toolbar); split/close already
// have buttons and chords.
// A folded pane clears its `last_area`, so `terminal_at_pos`
// can never name one and the menu's "Expand Terminal" branch
// was unreachable while KEYBINDINGS.md advertised it (#313).
// Fall back to the strips so a folded pane has a second
// gesture rather than left-click alone.
let terminal_hit = terminal_hit.or_else(|| {
self.terminal_strip_rects
.iter()
.position(|r| rect_contains(*r, m.column, m.row))
});
if self.bottom_panel_tab == BottomPanelTab::Terminal
&& let Some(idx) = terminal_hit
{
self.active_terminal = idx;
self.focus_pane(Pane::Terminal);
// A folded pane cannot BE the active one: `focus_pane`
// runs `sync_focus_flags`, whose invariant walks focus to
// the nearest expanded neighbour rather than leave it on
// a pane with nothing painted. Entries carrying `idx` are
// unaffected, but the ones that read `active_terminal`
// would act on that neighbour while this menu names THIS
// pane - and the broadcast entry read its label from
// `idx` while toggling the neighbour, so it could say
// "Exclude from Broadcast" and include a different pane.
// Each of them is also a gesture on a grid the user
// cannot see while the pane is a strip.
let folded = self.terminals.get(idx).is_some_and(|t| t.collapsed);
let mut items: Vec<MenuEntry> = Vec::new();
// Copy and Paste lead the menu, as they do in VS Code's
// terminal. Both act on the ACTIVE pane, so a folded one
// offers neither: focus has already walked to an expanded
// neighbour, and pasting into a grid the user cannot see
// is worse than not offering the entry at all.
if !folded {
// Copy appears only while there is something to copy.
// The menu model has no disabled state, and an entry
// that silently copies nothing is worse than no entry.
if self.terminals[idx]
.selection()
.is_some_and(|s| s.has_area())
{
items.push(MenuEntry::Item {
label: String::from("Copy"),
action: MenuAction::TerminalCopySelection,
});
}
items.push(MenuEntry::Item {
label: String::from("Paste"),
action: MenuAction::TerminalPaste,
});
}
items.push(MenuEntry::Item {
label: String::from("Rename Terminal"),
action: MenuAction::RenameTerminal(idx),
});
items.push(MenuEntry::Item {
label: String::from("Clear"),
action: MenuAction::ClearTerminal(idx),
});
if !folded {
items.extend([
MenuEntry::Item {
label: String::from("Quick Select"),
action: MenuAction::TerminalQuickSelect,
},
MenuEntry::Item {
label: String::from("Copy Mode"),
action: MenuAction::TerminalCopyMode,
},
MenuEntry::Item {
label: String::from("Command History"),
action: MenuAction::TerminalCommandHistory,
},
MenuEntry::Item {
label: String::from("Open Scrollback in Editor"),
action: MenuAction::OpenScrollbackInEditor,
},
]);
}
// Undo close only appears while a parked pane is alive
// to restore (the grace window).
if !self.closed_terminals.is_empty() {
items.push(MenuEntry::Item {
label: String::from("Reopen Closed Terminal"),
action: MenuAction::UndoCloseTerminal,
});
}
// Maximize and broadcast both need a second pane, so a
// lone terminal doesn't offer them.
if self.terminals.len() > 1 {
items.push(MenuEntry::Item {
label: String::from(if self.terminal_pane_maximized {
"Restore Terminal Split"
} else {
"Maximize Terminal"
}),
action: MenuAction::ToggleMaximizeTerminal(idx),
});
// Collapse is meaningless while maximize owns the
// whole panel and the flags are ignored, so the entry
// is not offered there.
if !self.terminal_pane_maximized {
items.push(MenuEntry::Item {
label: String::from(if self.terminals[idx].collapsed {
"Expand Terminal"
} else {
"Collapse Terminal"
}),
action: MenuAction::ToggleCollapseTerminal(idx),
});
}
items.push(MenuEntry::Item {
label: String::from(if self.broadcast_input {
"Stop Broadcast Input"
} else {
"Broadcast Input"
}),
action: MenuAction::ToggleBroadcastInput,
});
if self.broadcast_input && !folded {
items.push(MenuEntry::Item {
label: String::from(if self.terminals[idx].broadcast_excluded {
"Include in Broadcast"
} else {
"Exclude from Broadcast"
}),
action: MenuAction::ToggleBroadcastExclusion,
});
}
}
self.context_menu = Some(ContextMenu {
origin: (m.column, m.row),
items,
selected: 0,
open_submenu: None,
submenu_selected: 0,
target_dir: self.tree.root.clone(),
});
return;
}
if in_tree && self.sidebar_view == SidebarView::Explorer {
self.focus_pane(Pane::Tree);
// A right-click on the sticky band context-menus the
// PINNED directory, not the covered row (#117): the band
// hit wins the row resolution and the menu flow proceeds
// for that node.
let node_idx = self
.tree
.sticky_row_at(m.row)
.or_else(|| self.tree.node_at_y(m.row));
if let Some(idx) = node_idx {
let path_clicked = self.tree.nodes[idx].path.clone();
let already_marked = self.tree.marked.contains(&path_clicked);
if already_marked {
self.tree.selected = idx;
} else {
self.tree.select_replace(idx);
}
}
let node = node_idx.and_then(|i| self.tree.nodes.get(i));
let target_dir =
crate::widgets::file_tree::create_target_dir_for(node, &self.tree.root);
let selection = self.tree.action_paths();
let mut items = build_tree_context_menu_items_in_dir(
&self.config_dir,
node,
&self.tree.root,
&selection,
&target_dir,
self.tree_clipboard.as_ref(),
self.compare_anchor.as_deref(),
);
let clicked = node.map(|n| n.path.clone());
maybe_add_reveal_in_finder(
&mut items,
clicked.as_deref(),
!self.is_remote && cfg!(target_os = "macos"),
);
self.context_menu =
Some(ContextMenu::flat((m.column, m.row), items, target_dir));
return;
}
// Editor gutter: right-click in the glyph margin / line-number
// column opens the breakpoint menu (Add / Remove Breakpoint,
// Add Conditional / Edit Condition), mirroring VS Code's
// glyph-margin context menu. Routed before the body branch so a
// gutter click never falls through to the symbol menu. Diff /
// sheet / image tabs have no debuggable source lines.
if in_editor
&& self.editor.diff.is_none()
&& self.editor.sheet.is_none()
&& self.editor.image.is_none()
&& let Some(line0) = self.editor.gutter_line_at(m.column, m.row)
{
self.focus_pane(Pane::Editor);
let line = line0 + 1; // 1-based, as breakpoints are stored
let (has_bp, has_cond, has_log) = self
.editor
.path
.as_ref()
.map(|p| {
let has_bp = self
.editor
.breakpoints
.get(p)
.is_some_and(|s| s.contains(&line));
let has_cond = self
.editor
.breakpoint_conditions
.get(p)
.is_some_and(|c| c.contains_key(&line));
let has_log = self
.editor
.breakpoint_logs
.get(p)
.is_some_and(|m| m.contains_key(&line));
(has_bp, has_cond, has_log)
})
.unwrap_or((false, false, false));
let toggle_label = if has_bp {
String::from("Remove Breakpoint")
} else {
String::from("Add Breakpoint")
};
let cond_label = if has_cond {
String::from("Edit Condition\u{2026}")
} else {
String::from("Add Conditional Breakpoint\u{2026}")
};
let log_label = if has_log {
String::from("Edit Logpoint")
} else {
String::from("Add Logpoint")
};
let mut items = vec![
(toggle_label, MenuAction::ToggleBreakpointAt { line }),
(cond_label, MenuAction::EditBreakpointConditionAt { line }),
(log_label, MenuAction::EditLogpointAt { line }),
];
// The resident navigator's line-scoped ask, only while
// one is seated (`line` here is 1-based, the box 0-based).
if self.pair_host.is_some() {
items.push((
String::from("Ask Navigator"),
MenuAction::AskNavigatorAt {
line: line.saturating_sub(1),
},
));
}
self.context_menu = Some(ContextMenu::flat(
(m.column, m.row),
items,
self.tree.root.clone(),
));
return;
}
// Editor body: right-click over a text buffer opens the symbol
// menu (Go to Definition / Rename Symbol / Change All
// Occurrences). Read-only diff / sheet / image tabs have no
// symbols, so they're excluded.
if in_editor
&& self.editor.diff.is_none()
&& self.editor.sheet.is_none()
&& self.editor.image.is_none()
&& let Some((row, col)) = self.editor.buffer_pos_at(m.column, m.row)
{
self.focus_pane(Pane::Editor);
let mut items = vec![(
String::from("Go to Definition"),
MenuAction::GoToDefinitionAt { row, col },
)];
// Only offer "Go to Declaration" when this file's language
// server actually implements `textDocument/declaration`.
// TypeScript's vtsls advertises `declarationProvider: false`,
// so the row is hidden there, exactly as VS Code does.
if self.editor_language_supports_declaration() {
items.push((
String::from("Go to Declaration"),
MenuAction::GoToDeclarationAt { row, col },
));
}
// "Go to Type Definition" is offered only when the server
// implements `textDocument/typeDefinition` (vtsls,
// basedpyright, rust-analyzer and gopls all do), mirroring
// VS Code's ordering right after Go to Declaration.
if self.editor_language_supports_type_definition() {
items.push((
String::from("Go to Type Definition"),
MenuAction::GoToTypeDefinitionAt { row, col },
));
}
// "Go to Implementations" is offered only when the server
// implements `textDocument/implementation` (rust-analyzer,
// gopls, vtsls do), placed right after Type Definition to
// mirror VS Code's Go To submenu order.
if self.editor_language_supports_implementation() {
items.push((
String::from("Go to Implementations"),
MenuAction::GoToImplementationAt { row, col },
));
}
// "Go to References" is offered only when the server
// implements `textDocument/references` (every server croft
// ships does), placed last in the Go To group to mirror VS
// Code's submenu order.
if self.editor_language_supports_references() {
items.push((
String::from("Go to References"),
MenuAction::GoToReferencesAt { row, col },
));
}
// Call hierarchy, one level per invocation: who calls
// this (incoming) and what does this call (outgoing).
if self.editor_language_supports_call_hierarchy() {
items.push((
String::from("Show Incoming Calls"),
MenuAction::ShowCallsAt {
row,
col,
incoming: true,
},
));
items.push((
String::from("Show Outgoing Calls"),
MenuAction::ShowCallsAt {
row,
col,
incoming: false,
},
));
}
items.push((String::from("Go Back"), MenuAction::NavigateBack));
items.push((String::from("Go Forward"), MenuAction::NavigateForward));
items.push((
String::from("Rename Symbol"),
MenuAction::RenameSymbolAt { row, col },
));
items.push((
String::from("Change All Occurrences"),
MenuAction::ChangeAllOccurrencesAt { row, col },
));
if self.editor_language_supports_code_action() {
items.push((
String::from("Quick Fix"),
MenuAction::QuickFixAt { row, col },
));
}
// The navigator's selection-scoped ask (GitHub-review
// style), only while one is seated and lines are selected.
if self.pair_host.is_some()
&& let Some((start, end)) = self.editor.selection_rows()
{
items.push((
String::from("Ask Navigator About Selection"),
MenuAction::AskNavigatorSelection { start, end },
));
}
self.context_menu = Some(ContextMenu::flat(
(m.column, m.row),
items,
self.tree.root.clone(),
));
}
}
MouseEventKind::Down(MouseButton::Left) => {
// Markdown/rendered preview selection (#215): a press inside
// the rendered view starts a drag-selection over what the
// user can SEE, not the source buffer beneath it.
if self.begin_preview_selection(m.column, m.row) {
return;
}
// Before the selection: a Ctrl+click on a printed
// `path:line` follows it rather than starting a drag (#257).
if m.modifiers.contains(KeyModifiers::CONTROL)
&& self.log_file_click(m.column, m.row)
{
return;
}
if self.begin_log_selection(m.column, m.row) {
return;
}
// (H) Go to Definition rides CTRL, matching the terminal pane's
// file/URL clicks. SGR mouse reporting carries no super bit, so
// ALT is left to the editor's Alt+click multi-cursor below.
if in_editor && m.modifiers.contains(KeyModifiers::CONTROL) {
if m.modifiers.contains(KeyModifiers::SHIFT) {
self.nav_back();
} else {
self.trigger_definition_at(m.column, m.row);
}
return;
}
// Merge-conflict accept actions on a conflict header row —
// the [Accept …] spans the editor paints, VS Code's
// merge-conflict CodeLens clicks. Checked before every other
// editor click: the header row is marker text, so a caret
// placement there serves nobody. A stale span cannot
// mis-fire — `resolve_conflict_at` re-validates the row
// against the live conflict set.
if in_editor && self.editor.diff.is_none() {
let hit = self
.editor
.merge_action_spans
.iter()
.find(|(y, xs, _, _)| *y == m.row && xs.contains(&m.column))
.map(|(_, _, row, res)| (*row, *res));
if let Some((row, res)) = hit {
self.focus_pane(Pane::Editor);
self.editor.clear_selection();
self.editor.cursor_row = row;
self.editor.cursor_col = 0;
self.resolve_merge_at_cursor(res);
return;
}
}
// Merge editor (#253): a click on a source pane's
// per-conflict checkbox toggles that side's inclusion
// (both checked = Accept Combination). Any other click in
// the source-pane area is swallowed — the panes are
// read-only; the Result below keeps normal click behavior.
if in_editor && self.editor.merge.is_some() {
let (check_hit, in_panes) = self
.editor
.merge
.as_ref()
.map(|mv| {
(
mv.check_spans
.iter()
.find(|(y, xs, _, _)| *y == m.row && xs.contains(&m.column))
.map(|(_, _, idx, side)| (*idx, *side)),
mv.last_panes_area.contains(ratatui::layout::Position {
x: m.column,
y: m.row,
}),
)
})
.unwrap_or((None, false));
if let Some((idx, side)) = check_hit {
self.focus_pane(Pane::Editor);
self.merge_toggle_side(idx, side);
return;
}
if in_panes {
self.focus_pane(Pane::Editor);
return;
}
}
if !in_editor {
self.editor_click.clear();
}
if !in_tree {
self.tree_click.clear();
}
// Splitter hit-test runs before everything else: clicking the
// single-column seam between sidebar and editor (or the
// single-row seam between editor and terminal) starts a
// resize drag instead of falling through to the underlying
// pane's click handler.
if let Some(x) = self.sidebar_splitter_x {
// Two-column hit-zone: the seam itself (`x`, the editor's
// left edge) and one column to the left (the tree's right
// border). Either grab starts a sidebar drag — a 1-cell
// target is too easy to miss.
//
// The OUTLINE panel draws no right border, so its scrollbar
// sits on the sidebar's rightmost column (`x - 1`), inside
// this zone. Exempt that column when it's the outline bar so
// the press reaches the scrollbar handler below instead of
// being swallowed as a resize.
//
// Likewise a lone terminal pane's left border shares this
// column, and its command decoration dots live there: a
// press on a dot cell must reach the decoration handler,
// not start a resize (the rest of the column still drags).
// The COMMITS graph draws no right border either, so its
// scrollbar shares the same column (Codeberg #41).
// Both scrollbar rects refresh only while their widget
// renders (outline under Explorer, the graph under
// Source Control), so each exemption is gated on its
// view — a stale rect from the last visit must not keep
// deadening the seam after a view switch.
let outline_bar = self.sidebar_view == SidebarView::Explorer
&& rect_contains(self.outline.last_scrollbar, m.column, m.row);
let graph_bar = self.sidebar_view == SidebarView::SourceControl
&& rect_contains(self.commit_graph.last_scrollbar, m.column, m.row);
// A collapsed terminal pane's one-column strip shares this
// zone too (#468): the leftmost pane starts on the seam
// itself, and with the side bar on the right the last
// pane ends one column short of it. The strip's only
// gesture is the click that unfolds it, so the seam must
// not take that click as a resize, or a folded pane on
// that edge can never be brought back. The rects are
// cleared whenever the panel is not painted, so a stale
// strip cannot deaden the seam later.
let on_strip = self
.terminal_strip_rects
.iter()
.any(|r| rect_contains(*r, m.column, m.row));
if (m.column == x || m.column == x.saturating_sub(1))
&& !on_strip
&& !outline_bar
&& !graph_bar
&& self.decoration_dot_at(m.column, m.row).is_none()
{
self.splitter_drag = Some(SplitterDrag::Sidebar);
return;
}
}
// Any seam between editor groups in the grid (any depth). Same
// two-cell hit-zone as the other seams.
if let Some(seam) = self.seam_at(m.column, m.row) {
self.splitter_drag = Some(SplitterDrag::EditorSeam(seam));
return;
}
// OPEN EDITORS: header toggles collapse; a row activates that
// editor's tab; the scrollbar lane starts a thumb drag. Any
// other click is swallowed so it can't fall through to a panel
// visually beneath this one.
if rect_contains(self.open_editors.last_area, m.column, m.row) {
if rect_contains(self.open_editors.last_scrollbar, m.column, m.row) {
self.open_editors.scroll_to_bar_y(m.row);
self.open_editors_scrollbar_drag = true;
} else if self.open_editors.hit_header(m.column, m.row) {
self.open_editors.toggle_collapse();
} else if let Some(idx) = self.open_editors.row_at(m.row)
&& let Some(path) = self.open_editors.path_at(idx)
{
self.activate_open_editor(path);
}
return;
}
// TIMELINE: header toggles collapse; a row opens that commit's
// diff for the file in a read-only editor tab.
if rect_contains(self.timeline.last_area, m.column, m.row) {
if rect_contains(self.timeline.last_scrollbar, m.column, m.row) {
self.timeline.scroll_to_bar_y(m.row);
self.timeline_scrollbar_drag = true;
} else if self.timeline.hit_header(m.column, m.row) {
self.timeline.toggle_collapse();
} else if let Some(idx) = self.timeline.row_at(m.row)
&& let Some((path, hash)) = self.timeline.diff_target(idx)
{
self.open_timeline_diff(path, hash);
}
return;
}
// DEPENDENCIES: display-only, so only the header (collapse)
// and the scrollbar lane are interactive.
if rect_contains(self.dependencies.last_area, m.column, m.row) {
if rect_contains(self.dependencies.last_scrollbar, m.column, m.row) {
self.dependencies.scroll_to_bar_y(m.row);
self.deps_scrollbar_drag = true;
} else if self.dependencies.hit_header(m.column, m.row) {
self.dependencies.toggle_collapse();
}
return;
}
// The OUTLINE section stacks just above the SYSTEM panel. A
// click on its header toggles collapse; a click on a symbol row
// jumps the editor to that symbol (recording nav history, like
// go-to-definition); any other click inside its rect is
// swallowed so it doesn't fall through to the tree above.
if rect_contains(self.outline.last_area, m.column, m.row) {
if rect_contains(self.outline.last_scrollbar, m.column, m.row) {
self.outline.scroll_to_bar_y(m.row);
self.outline_scrollbar_drag = true;
} else if self.outline.hit_header(m.column, m.row) {
self.outline.toggle_collapse();
} else if let Some(idx) = self.outline.row_at(m.row)
&& let Some((path, line, col)) = self.outline.jump_target(idx)
{
self.go_to_definition(path, line, col);
}
return;
}
// The panel group's tabs sit on the splitter row, so they must
// win the hit-test before the splitter-drag handler claims the
// click (same precedence as the "[+]" / "[-]" buttons below).
if rect_contains(self.problems_tab_rect, m.column, m.row) {
self.set_bottom_panel_tab(BottomPanelTab::Problems);
return;
}
if rect_contains(self.output_tab_rect, m.column, m.row) {
self.set_bottom_panel_tab(BottomPanelTab::Output);
return;
}
if rect_contains(self.terminal_tab_rect, m.column, m.row) {
self.set_bottom_panel_tab(BottomPanelTab::Terminal);
return;
}
if rect_contains(self.ports_tab_rect, m.column, m.row) {
self.set_bottom_panel_tab(BottomPanelTab::Ports);
return;
}
if rect_contains(self.captures_tab_rect, m.column, m.row) {
self.set_bottom_panel_tab(BottomPanelTab::Captures);
return;
}
// A click in the OUTPUT view hits its toolbar (dropdown / clear /
// rpc / level) or dropdown list; if it lands in the log body the
// widget doesn't consume it, so we just focus the panel pane.
if self.bottom_panel_tab == BottomPanelTab::Output
&& rect_contains(self.output.last_area, m.column, m.row)
{
if !self.output.click(m.column, m.row) {
self.focus_pane(Pane::Terminal);
}
return;
}
// A click in the PROBLEMS list jumps the editor to that
// diagnostic, or toggles a file group. Checked before the
// terminal/splitter logic because the terminals are not
// painted while this tab is active.
if self.bottom_panel_tab == BottomPanelTab::Problems
&& rect_contains(self.problems.last_area, m.column, m.row)
{
use crate::widgets::problems::ProblemHit;
// Toolbar buttons (severity filter / group toggle) consume
// the click before it resolves to a row.
if self.problems.click(m.column, m.row) {
return;
}
match self.problems.hit_at(m.row) {
Some(ProblemHit::Header(path)) => self.problems.toggle_collapse(&path),
Some(ProblemHit::Diagnostic {
path,
line,
col,
col_utf16,
}) => {
// An LSP diagnostic's column is UTF-16; a build
// tool's is already a character column.
let opened = if col_utf16 {
self.open_at_utf16(&path, line, col)
} else {
self.open_at(&path, line as usize, col as usize)
};
if let Err(e) = opened {
self.status = format!("Open failed: {e}");
}
}
None => self.focus_pane(Pane::Terminal),
}
return;
}
// A click in the PORTS list selects that row (so the keyboard
// actions act on it) or focuses the pane.
if self.bottom_panel_tab == BottomPanelTab::Ports
&& rect_contains(self.ports.last_area, m.column, m.row)
{
match self.ports.row_at(m.column, m.row) {
Some(idx) => {
self.ports.select_index(idx);
// A second click on the same row opens that port,
// the same as pressing Enter on it.
let now = std::time::Instant::now();
if self
.ports_click
.is_double(now, m.column, m.row, m.modifiers)
{
self.ports_open_selected();
self.ports_click.clear();
} else {
self.ports_click.record(now, m.column, m.row, m.modifiers);
}
}
None => self.focus_pane(Pane::Terminal),
}
return;
}
// A click on a CAPTURES row jumps straight to the captured
// line (iTerm2's captured-output click).
if self.bottom_panel_tab == BottomPanelTab::Captures
&& rect_contains(self.captures.last_area, m.column, m.row)
{
match self.captures.row_at(m.column, m.row) {
Some(idx) => {
self.captures.select_index(idx);
self.captures_open_selected();
}
None => self.focus_pane(Pane::Terminal),
}
return;
}
// The "[+]" / "[-]" buttons sit on the same row as the
// editor/terminal splitter, so they have to win the
// hit-test before the splitter-drag handler claims this
// click. Each terminal pane has its own pair so the user
// can kill any pane, not only the active one.
if let Some(idx) = self
.terminal_close_buttons
.iter()
.position(|r| rect_contains(*r, m.column, m.row))
{
if self.close_terminal_at(idx) {
self.status =
format!("Closed terminal: {} remaining", self.terminals.len());
}
return;
}
if let Some(idx) = self
.terminal_profile_buttons
.iter()
.position(|r| rect_contains(*r, m.column, m.row))
{
self.open_terminal_profile_picker(idx);
return;
}
if let Some(idx) = self
.terminal_collapse_buttons
.iter()
.position(|r| rect_contains(*r, m.column, m.row))
{
self.toggle_terminal_collapse(idx);
return;
}
// A strip is one column wide, so it is tested before the
// splitter and the pane body below: anything that claims the
// click first makes a folded pane impossible to unfold.
if let Some(idx) = self
.terminal_strip_rects
.iter()
.position(|r| rect_contains(*r, m.column, m.row))
{
self.toggle_terminal_collapse(idx);
return;
}
if let Some(idx) = self
.terminal_max_buttons
.iter()
.position(|r| rect_contains(*r, m.column, m.row))
{
// Entering maximize mode hands the clicked pane the
// panel; the button on the maximized pane restores.
if !self.terminal_pane_maximized {
self.active_terminal = idx;
self.focus_pane(Pane::Terminal);
}
self.toggle_terminal_pane_maximize();
return;
}
if let Some(idx) = self
.terminal_rail_rects
.iter()
.position(|r| rect_contains(*r, m.column, m.row))
{
self.active_terminal = idx;
self.focus_pane(Pane::Terminal);
// Holding the press arms a drag-reorder: crossing other
// rail rows live-moves this terminal between them.
self.terminal_drag_from = Some(idx);
return;
}
if let Some(idx) = self
.terminal_label_rects
.iter()
.position(|r| rect_contains(*r, m.column, m.row))
{
// The pane name pill is the drag handle for reordering
// side-by-side panes (VS Code drags its terminal tabs the
// same way). The press itself focuses the pane, exactly
// like a click into its body would.
self.active_terminal = idx;
self.focus_pane(Pane::Terminal);
self.terminal_drag_from = Some(idx);
return;
}
if self
.terminal_add_buttons
.iter()
.any(|r| rect_contains(*r, m.column, m.row))
{
match self.split_terminal() {
Ok(()) => {
self.status =
format!("Split terminal: {} active", self.terminals.len());
}
Err(e) => {
self.status = format!("Split terminal failed: {e}");
}
}
return;
}
if let Some(y) = self.terminal_splitter_y {
// Two-row hit-zone: the terminal's top border (`y`) and
// the editor / welcome's bottom border (`y - 1`).
// Symmetric with the sidebar drag — either edge of the
// visible seam grabs the splitter.
//
// Gate by column too: the editor / terminal splitter
// only spans the RIGHT column (everything at or past
// `sidebar_splitter_x`). Without this gate, a click
// on a tree row in the LEFT column whose y lines up
// with the splitter is silently hijacked into a
// splitter-drag and never reaches `node_at_y` -
// exactly the dead-zone the user hit on the last
// two files in the Explorer.
let in_splitter_x_range = self.sidebar_splitter_x.is_none_or(|x| m.column >= x);
if in_splitter_x_range && (m.row == y || m.row == y.saturating_sub(1)) {
self.splitter_drag = Some(SplitterDrag::Terminal);
return;
}
}
// Activity-bar hit-test takes precedence over the side panel.
if rect_contains(self.sidebar_areas.explorer_icon, m.column, m.row) {
self.set_sidebar_view(SidebarView::Explorer);
return;
}
if rect_contains(self.sidebar_areas.search_icon, m.column, m.row) {
self.set_sidebar_view(SidebarView::Search);
return;
}
if rect_contains(self.sidebar_areas.source_control_icon, m.column, m.row) {
self.set_sidebar_view(SidebarView::SourceControl);
return;
}
if rect_contains(self.sidebar_areas.remote_icon, m.column, m.row) {
self.set_sidebar_view(SidebarView::Remote);
return;
}
if rect_contains(self.sidebar_areas.run_debug_icon, m.column, m.row) {
self.set_sidebar_view(SidebarView::RunDebug);
return;
}
if rect_contains(self.sidebar_areas.extensions_icon, m.column, m.row) {
self.set_sidebar_view(SidebarView::Extensions);
return;
}
if rect_contains(self.sidebar_areas.testing_icon, m.column, m.row) {
self.open_testing_view();
return;
}
if rect_contains(self.sidebar_areas.settings_icon, m.column, m.row) {
self.open_settings_menu();
return;
}
if in_tree_scrollbar {
self.focus_pane(Pane::Tree);
self.tree.scroll_to_bar_y(m.row);
self.scrollbar_drag = Some(Pane::Tree);
self.tree_click.clear();
return;
}
if in_remote_scrollbar {
self.focus_pane(Pane::Tree);
self.remote.scroll_to_bar_y(m.row);
self.scrollbar_drag = Some(Pane::Tree);
self.tree_click.clear();
return;
}
if in_search_scrollbar {
self.focus_pane(Pane::Tree);
self.search.scroll_to_bar_y(m.row);
self.scrollbar_drag = Some(Pane::Tree);
self.tree_click.clear();
return;
}
if rect_contains(self.minimap_img_rect, m.column, m.row) {
self.focus_pane(Pane::Editor);
self.minimap_scroll_to_row(m.row);
self.minimap_drag = true;
self.editor_click.clear();
return;
}
if in_editor_scrollbar {
self.focus_pane(Pane::Editor);
self.editor.scroll_to_bar_y(m.row);
self.scrollbar_drag = Some(Pane::Editor);
self.editor_click.clear();
self.poke_cursor();
return;
}
if in_editor_hscrollbar {
self.focus_pane(Pane::Editor);
self.editor.scroll_to_bar_x(m.column);
self.editor_hscrollbar_drag = true;
self.editor_click.clear();
self.poke_cursor();
return;
}
if in_tree && self.sidebar_view == SidebarView::Search {
self.focus_pane(Pane::Tree);
if self.search.paste_button_at(m.column, m.row) {
let text = (self.clipboard_reader)();
self.paste_clipboard_into_search(text.as_deref());
return;
}
// Header "Refresh" re-runs the current query.
if self.search.refresh_at(m.column, m.row) {
self.submit_search_query();
return;
}
// Header "Clear Search Results" wipes the query + results.
if self.search.clear_at(m.column, m.row) {
self.search.clear_all();
return;
}
// Left chevron expands/collapses the Replace row.
if self.search.chevron_at(m.column, m.row) {
self.search.toggle_replace();
return;
}
// "" ellipsis expands/collapses files-to-include/exclude.
if self.search.ellipsis_at(m.column, m.row) {
self.search.toggle_details();
return;
}
// Replace-all action icon runs Replace All across results.
if self.search.replace_all_at(m.column, m.row) {
self.run_search_replace_all();
return;
}
// Click inside one of the input boxes focuses that field.
if let Some(field) = self.search.field_at(m.column, m.row) {
self.search.focus_field(field);
return;
}
if let Some(t) = self.search.toggle_at(m.column, m.row) {
match t {
crate::widgets::search::SearchToggle::CaseSensitive => {
self.search.opts.case_sensitive = !self.search.opts.case_sensitive;
}
crate::widgets::search::SearchToggle::WholeWord => {
self.search.opts.whole_word = !self.search.opts.whole_word;
}
crate::widgets::search::SearchToggle::UseRegex => {
self.search.opts.use_regex = !self.search.opts.use_regex;
}
}
self.submit_search_query();
return;
}
// Click on a result row: open it. Mirrors the Explorer's
// preview/pin gesture — a single click opens the hit in
// the replaceable preview slot, a double-click pins the
// tab so moving on to the next result opens beside it
// instead of replacing the file under review.
if let Some(idx) = self.search.hit_at_y(m.row) {
self.search.selected = idx;
let now = std::time::Instant::now();
let is_double =
self.tree_click.is_double(now, m.column, m.row, m.modifiers);
if let Some(hit) = self.search.selected_hit().cloned() {
self.open_search_hit(&hit);
if is_double {
self.editor.pin_active();
}
}
if is_double {
self.tree_click.clear();
} else {
self.tree_click.record(now, m.column, m.row, m.modifiers);
}
} else {
// Click on the input/header area: just focus search.
}
return;
}
if in_tree && self.sidebar_view == SidebarView::SourceControl {
self.focus_pane(Pane::Tree);
// COMMITS graph: header toggles collapse; a row opens that
// commit's full patch in a read-only tab. Checked first —
// its rect is carved out of the Source Control strip.
if rect_contains(self.commit_graph.last_area, m.column, m.row) {
if rect_contains(self.commit_graph.last_scrollbar, m.column, m.row) {
self.commit_graph.scroll_to_bar_y(m.row);
self.graph_scrollbar_drag = true;
} else if self.commit_graph.hit_header(m.column, m.row) {
self.commit_graph.toggle_collapse();
} else if let Some((hash, short)) = self
.commit_graph
.commit_at(m.row)
.map(|c| (c.hash.clone(), c.short_hash.clone()))
{
self.open_commit_patch(&hash, &short);
}
return;
}
if let Some(root) = self.source_control.click_repository(m.column, m.row) {
// Pin the panel to the clicked repository (#161);
// the next cross-folder focus releases it.
self.scm_pin = Some(root.clone());
self.seed_active_scm(root);
return;
}
if self.source_control.click_more(m.column, m.row) {
self.commit_menu_open = false;
self.scm_menu.open = !self.scm_menu.open;
if !self.scm_menu.open {
self.scm_menu.close();
}
return;
}
if self.source_control.click_header_refresh(m.column, m.row) {
self.refresh_source_control();
self.status = String::from("Refreshed Source Control");
return;
}
if self.commit_menu_open
&& let Some(item) =
self.source_control.click_commit_menu_item(m.column, m.row)
{
self.commit_menu_open = false;
self.dispatch_commit_menu_item(item);
return;
}
if self.source_control.click_commit_caret(m.column, m.row) {
self.commit_menu_open = !self.commit_menu_open;
return;
}
if self.commit_menu_open {
// Any click outside the caret/menu closes the
// dropdown without firing its action; fall through
// so the underlying gesture still applies (the
// user can dismiss-by-clicking-elsewhere instead
// of needing Esc + click).
self.commit_menu_open = false;
}
if self.source_control.click_init_repo_button(m.column, m.row) {
self.initialize_repository();
return;
}
if self.source_control.click_button(m.column, m.row) {
self.commit_source_control();
return;
}
if self.source_control.click_input(m.column, m.row) {
return;
}
if self.source_control.click_branch(m.column, m.row) {
self.open_branch_picker();
return;
}
if let Some(idx) = self.source_control.click_discard_action(m.column, m.row) {
self.request_discard_source_control_entry(idx);
return;
}
if let Some(idx) = self.source_control.click_stage_action(m.column, m.row) {
self.stage_source_control_entry(idx);
return;
}
if let Some(idx) = self.source_control.click_unstage_action(m.column, m.row) {
self.unstage_source_control_entry(idx);
return;
}
if let Some(idx) = self.source_control.entry_at_y(m.row) {
self.open_source_control_entry(idx);
}
return;
}
if in_tree && self.sidebar_view == SidebarView::RunDebug {
self.focus_pane(Pane::Tree);
if self.run_debug.debug_active {
if let Some(widx) = self.run_debug.watch_remove_at(m.column, m.row) {
self.remove_watch_expression(widx);
self.refresh_debug_panel();
} else if let Some(idx) = self.run_debug.debug_row_at(m.row) {
self.debug_panel_click(idx);
}
} else if self.run_debug.click_button(m.column, m.row) {
self.run_debug_button_action();
} else if self.run_debug.click_config(m.column, m.row) {
self.open_debug_config_picker();
}
return;
}
if in_tree && self.sidebar_view == SidebarView::Extensions {
self.focus_pane(Pane::Tree);
// The filter's clear (✕) button empties the search.
if self.extensions.click_clear(m.column, m.row) {
self.extensions.clear_filter();
return;
}
// The refresh (⟳) button re-pulls the signed remote index.
if self.extensions.click_refresh(m.column, m.row) {
self.refresh_extension_index();
return;
}
// Clicking a row selects it; clicking its trash button
// uninstalls it; clicking its toggle switch (the right-edge
// pill) flips the extension. The trash zone sits left of the
// switch, so the two never overlap.
if let Some(idx) = self.extensions.row_at(m.row) {
let on_trash = self.extensions.click_uninstall(m.column, m.row);
let on_switch = self.extensions.click_action(m.column, m.row);
self.extensions.select(idx);
if on_trash {
self.uninstall_selected_extension();
} else if on_switch {
self.toggle_selected_extension();
}
}
return;
}
if in_tree && self.sidebar_view == SidebarView::Testing {
self.focus_pane(Pane::Tree);
// The scrollbar lane starts a thumb drag; elsewhere the play
// glyph runs a case or suite while a case's name reveals its
// source (VS Code's split: the label shows, the icon runs).
// Empty space does nothing.
if rect_contains(self.testing.last_scrollbar, m.column, m.row) {
self.testing.scroll_to_bar_y(m.row);
self.testing_scrollbar_drag = true;
} else {
match self.testing.hit_at(m.column, m.row) {
Some(crate::widgets::testing::RowHit::RunCase(name)) => {
self.run_test(name)
}
Some(crate::widgets::testing::RowHit::ShowCase(name)) => {
self.jump_to_test_source(name)
}
Some(crate::widgets::testing::RowHit::RunSuite(suite)) => {
self.run_suite(suite)
}
None => {}
}
}
return;
}
if in_tree && self.sidebar_view == SidebarView::Remote {
self.focus_pane(Pane::Tree);
if rect_contains(self.remote.header_chevron_btn, m.column, m.row) {
self.remote.toggle_collapsed();
self.status = if self.remote.collapsed {
String::from("Collapsed SSH section")
} else {
String::from("Expanded SSH section")
};
return;
}
if rect_contains(self.remote.header_add_btn, m.column, m.row)
|| rect_contains(self.remote.empty_primary_btn, m.column, m.row)
|| rect_contains(self.remote.empty_secondary_btn, m.column, m.row)
{
self.open_ssh_config_in_editor();
return;
}
if rect_contains(self.remote.header_refresh_btn, m.column, m.row) {
self.remote.refresh();
self.status = String::from("Reloaded SSH hosts from ~/.ssh/config");
return;
}
if rect_contains(self.remote.empty_learn_link, m.column, m.row) {
self.open_ssh_learn_more();
return;
}
if let Some(idx) = self.remote.target_at_y(m.row) {
self.remote.select(idx);
let now = std::time::Instant::now();
let is_double =
self.tree_click.is_double(now, m.column, m.row, m.modifiers);
if is_double {
if let Some(target) = self.remote.selected_target().cloned() {
self.request_remote_launch(target.alias, None);
}
self.tree_click.clear();
} else {
self.tree_click.record(now, m.column, m.row, m.modifiers);
}
}
return;
}
if in_tree && self.sidebar_view == SidebarView::Explorer {
self.focus_pane(Pane::Tree);
// Header toolbar (root folder row): New File / New Folder /
// Refresh / Collapse Folders. Checked before row hit-testing
// so a click on an icon never falls through to the node.
if rect_contains(self.tree.header_new_file_btn, m.column, m.row) {
let target = self.explorer_create_target_dir();
self.open_create_prompt(CreateKind::File, target);
return;
}
if rect_contains(self.tree.header_new_folder_btn, m.column, m.row) {
let target = self.explorer_create_target_dir();
self.open_create_prompt(CreateKind::Folder, target);
return;
}
if rect_contains(self.tree.header_refresh_btn, m.column, m.row) {
self.tree.refresh_children(0);
self.status = String::from("Refreshed Explorer");
return;
}
if rect_contains(self.tree.header_collapse_btn, m.column, m.row) {
self.tree.collapse_all();
self.status = String::from("Collapsed all folders");
return;
}
// The ⋯ "Views and More Actions" button on the EXPLORER
// title line opens the menu that toggles which sub-views
// (Open Editors / Folders / Outline / Timeline /
// Dependencies) are stacked in the panel.
if rect_contains(self.tree.header_views_btn, m.column, m.row) {
self.open_explorer_views_menu();
return;
}
// A left-click on the sticky band jumps: select the
// pinned ancestor and scroll it to the top of the tree
// (#117). Checked before the row map, which would answer
// for the covered row.
if let Some(idx) = self.tree.sticky_row_at(m.row) {
self.tree.select_replace(idx);
self.tree.scroll = idx;
self.tree_click.clear();
return;
}
if let Some(idx) = self.tree.node_at_y(m.row) {
let now = std::time::Instant::now();
let is_double =
self.tree_click.is_double(now, m.column, m.row, m.modifiers);
let has_shift = m.modifiers.contains(KeyModifiers::SHIFT);
// macOS terminals (iTerm2, Terminal.app) never put the
// Cmd bit on mouse events — the SGR mouse encoding only
// carries Shift/Alt/Ctrl. Treat Alt (Option on macOS)
// and Ctrl as the cherry-pick modifier so the gesture
// actually reaches the app.
let has_toggle_mod = m.modifiers.contains(KeyModifiers::ALT)
|| m.modifiers.contains(KeyModifiers::CONTROL);
// Shift-click extends the range from the anchor. No
// activation, no drag.
if has_shift {
self.tree.extend_to(idx);
self.tree_click.clear();
self.tree_drag = None;
return;
}
// Alt/Ctrl-click: defer the toggle until mouse-up so a
// movement in between can promote the gesture into an
// Alt-drag (copy) instead. Don't activate (no file
// open, no folder toggle) and don't include the row
// in the multi-selection yet.
if has_toggle_mod {
self.tree_click.clear();
let mut drag_paths = self.tree.action_paths();
let path_clicked = self.tree.nodes[idx].path.clone();
if !drag_paths.iter().any(|p| p == &path_clicked) {
drag_paths.push(path_clicked);
}
self.tree_drag = Some(ExplorerDrag {
paths: drag_paths,
target_idx: None,
armed: false,
started_at: (now, m.column, m.row),
start_idx: idx,
toggle_on_release: true,
});
return;
}
// Plain click: if the row is already in the marked set,
// keep the marks intact so a subsequent drag carries
// every selected entry; otherwise collapse selection
// to this single row.
let already_marked = self.tree.marked.contains(&self.tree.nodes[idx].path);
if !already_marked {
self.tree.select_replace(idx);
} else {
self.tree.selected = idx;
self.tree.anchor = idx;
}
let clicked_is_dir =
self.tree.nodes.get(idx).is_some_and(|node| node.is_dir);
if clicked_is_dir && is_double {
self.tree_click.clear();
self.tree_drag = None;
return;
}
// Arm a potential drag-source. Movement off this cell
// promotes it into a real drag in the Drag handler;
// a stationary release keeps the click semantics.
let drag_paths = self.tree.action_paths();
if !drag_paths.is_empty() {
self.tree_drag = Some(ExplorerDrag {
paths: drag_paths,
target_idx: None,
armed: false,
started_at: (now, m.column, m.row),
start_idx: idx,
toggle_on_release: false,
});
}
if let Some(path) = self.tree.activate() {
let result = if is_double {
self.editor.open_pinned(&path)
} else {
self.editor.open_preview(&path)
};
match result {
Ok(()) => {
self.sync_open_file_poll_mtime();
self.status = self.editor.status.clone();
// Opening a FILE hands the keyboard to the
// editor (VS Code parity), single click or
// double: otherwise the new tab's own
// navigation keys are dead and a PDF sits
// frozen on page 1 while the arrows walk
// the file list. `activate()` returns None
// for a folder, so a folder click never
// reaches here and browsing keeps focus.
self.focus_pane(Pane::Editor);
self.poke_cursor();
}
Err(e) => self.status = format!("Error: {e}"),
}
}
if is_double {
self.tree_click.clear();
} else {
self.tree_click.record(now, m.column, m.row, m.modifiers);
}
}
} else if in_editor_pane && !in_editor {
if let Some((line, col)) = self.editor.breadcrumb_target_at(m.column, m.row) {
// A click on a symbol crumb jumps to that symbol (same
// file); path crumbs return None and fall through.
self.focus_pane(Pane::Editor);
if let Some(path) = self.editor.path.clone() {
self.go_to_definition(path, line, col);
}
self.poke_cursor();
} else if let Some(idx) = self.editor.close_at(m.column, m.row) {
// The close cell of a pinned tab is an unpin button (it
// shows a thumb-tack, not the close cross), matching VS
// Code: a pinned tab is never closed by that click.
if self.editor.is_pinned(idx) {
self.editor.toggle_pin(idx);
self.status = String::from("Unpinned tab");
self.poke_cursor();
} else {
self.record_closed_tab_at(idx);
if self.editor.close_tab(idx) {
self.sync_open_file_poll_mtime();
self.status = String::from("Closed tab");
self.poke_cursor();
self.collapse_split_if_empty();
}
}
} else if let Some(idx) = self.editor.tab_at(m.column, m.row) {
self.focus_pane(Pane::Editor);
if self.editor.active_index() != idx {
self.editor.select(idx);
self.sync_open_file_poll_mtime();
}
self.poke_cursor();
}
} else if in_editor {
self.focus_pane(Pane::Editor);
// A click on a pinned sticky-scroll header jumps to that
// scope instead of moving the caret into the covered line.
if let Some(line) = self.editor.sticky_line_at(m.column, m.row) {
if let Some(path) = self.editor.path.clone() {
self.go_to_definition(path, line, 0);
}
self.poke_cursor();
return;
}
// Mirror of the terminal branch: a selection lives in one
// pane only, so anchoring one in the editor drops any
// leftover terminal selection (issue #23).
self.terminal_mut().clear_selection();
// Sheet tab (#177): a click selects the cell under the
// pointer; the second click on the SAME selected cell
// opens the in-grid editor (editable kinds only).
if let Some(view) = self.editor.sheet.as_mut() {
if let Some((r, c)) = sheet_cell_at(view, m.column, m.row) {
let editable = matches!(
view.kind,
crate::sheet::SheetKind::Csv
| crate::sheet::SheetKind::Tsv
| crate::sheet::SheetKind::Xlsx
);
let current = view.current_sheet;
// An in-progress edit COMMITS when the
// click lands elsewhere (the spreadsheet
// convention; #193 review - discarding it
// silently lost the typed value).
let (pr, pc) = {
let d = &view.sheets[current];
(d.cur_row, d.cur_col)
};
let was_here = pr == r && pc == c;
if !was_here && let Some(edit) = view.editing.take() {
view.sheets[current].set_cell(pr, pc, edit.value);
view.dirty = true;
self.editor.dirty = true;
}
let view = self.editor.sheet.as_mut().expect("checked");
let data = &mut view.sheets[current];
data.cur_row = r;
data.cur_col = c;
if was_here && editable && view.editing.is_none() {
let value = view.sheets[current].cell(r, c).to_string();
let cursor = value.len();
view.editing = Some(crate::sheet::CellEdit { value, cursor });
}
}
self.poke_cursor();
return;
}
// Archive browser (#179): click selects; a second
// click on the selected row opens the member.
if let Some(view) = self.editor.archive.as_mut() {
if view.rows_visible > 0
&& m.row >= view.rows_top
&& m.row < view.rows_top + view.rows_visible
{
let idx = view.scroll + (m.row - view.rows_top) as usize;
if idx < view.entries.len() {
if view.selected == idx {
self.open_selected_archive_member();
} else {
view.selected = idx;
}
}
}
self.poke_cursor();
return;
}
// Hex tab (#172): a click on a byte cell — hex grid or
// ASCII gutter — parks the cursor there; Shift extends
// the selection; a drag from here extends it live.
if let Some(view) = self.editor.hex.as_mut() {
let rows = (view.layout.data_rows as usize).max(1);
if let Some(off) = view.hit_test(m.column, m.row) {
let select = m.modifiers.contains(KeyModifiers::SHIFT);
view.set_cursor(off, select, rows);
}
self.poke_cursor();
return;
}
// PDF preview: a plain click activates the link under the
// pointer — an external URL opens in the browser, an
// internal target flips to its page — matching every
// desktop PDF viewer. Only links anchored to text are
// found (pdftohtml reports link annotations through the
// text runs they cover), which is what hyperref/beamer
// emit. A non-link click just focuses the pane, above.
if self.editor.image.as_ref().is_some_and(|i| i.pdf.is_some()) {
match self.pdf_link_target_at(m.column, m.row) {
Some(crate::pdf::LinkTarget::Url(url)) => {
self.status = match open_url(&url) {
Ok(()) => format!("Opened {url}"),
Err(e) => format!("Could not open {url}: {e}"),
};
}
Some(crate::pdf::LinkTarget::Page(page)) => self.jump_pdf_page(page),
None => {}
}
return;
}
// Diff header arrows: take precedence over selection so a
// click on the ‹ / › glyph jumps to prev/next change
// instead of anchoring a selection at the header row.
if self.editor.diff.is_some() {
if rect_contains(self.editor.diff_prev_arrow, m.column, m.row) {
self.jump_diff_change(false);
return;
}
if rect_contains(self.editor.diff_next_arrow, m.column, m.row) {
self.jump_diff_change(true);
return;
}
let now = std::time::Instant::now();
let is_double =
self.editor_click
.is_double(now, m.column, m.row, m.modifiers);
let last_inner = self.editor.last_inner;
if let Some(diff) = self.editor.diff.as_mut() {
if let Some((side, row_idx, char_col)) =
crate::widgets::editor::diff_hit_test(
diff, last_inner, m.column, m.row,
)
{
if is_double {
diff.select_word_at(side, row_idx, char_col);
} else {
diff.start_selection(side, row_idx, char_col);
}
} else {
diff.clear_selection();
}
}
if is_double {
self.editor_click.clear();
} else {
self.editor_click.record(now, m.column, m.row, m.modifiers);
}
self.poke_cursor();
return;
}
// AI-stream stop button in the sign margin: cancel the
// pilot's stream (it reverts the streamed text). Checked
// before the play glyph, whose cell it borrows while a
// stream is live.
if self.editor.stream_stop_at(m.column, m.row) {
self.collab_cancel_stream();
return;
}
// Comment-box surfaces: ✕ Ignore dismisses the box; the
// footer's reply field (or the body) focuses it, placing
// the caret where the click landed in the field.
if let Some((id, hit)) = self.editor.comment_box_hit(m.column, m.row) {
use crate::widgets::editor::CommentHit;
match hit {
CommentHit::Ignore => self.ignore_comment_box(id),
CommentHit::Reply | CommentHit::Body => {
let keep = self.editor.comment_focus.take().filter(|f| f.id == id);
let mut focus =
keep.unwrap_or(crate::widgets::editor::CommentFocus {
id,
reply: String::new(),
cursor: 0,
});
if hit == CommentHit::Reply {
let text_x = self.editor.last_inner.x
+ self.editor.last_gutter_width
+ 1;
// `╰ ❯ ` occupies 4 cells before the field.
let rel = (m.column.saturating_sub(text_x) as usize)
.saturating_sub(4);
focus.cursor = rel.min(focus.reply.chars().count());
} else {
focus.cursor = focus.reply.chars().count();
}
self.editor.comment_focus = Some(focus);
}
}
return;
}
// Any other editor press releases a focused reply field.
if self.editor.comment_focus.is_some() {
self.editor.comment_focus = None;
}
// Gutter play glyph: run the test fn defined on the
// clicked line (VS Code's run bead); Alt+click debugs it
// instead. Sits in the sign margin one cell left of the
// fold chevron, checked before the editor-body Alt+click
// caret so the modifier never adds a caret here.
if let Some(name) = self.editor.test_glyph_at(m.column, m.row) {
if m.modifiers.contains(KeyModifiers::ALT) {
self.debug_named_test(name);
} else {
self.run_named_test(name);
}
return;
}
// Fold chevron in the gutter: toggle the fold, don't anchor
// a selection or move the cursor into the (possibly hidden)
// body.
if self.editor.fold_chevron_at(m.column, m.row) {
self.poke_cursor();
return;
}
// VS Code Shift+Alt+drag: start a column (box) selection.
// Checked before the plain Alt+click caret so the two
// modifiers don't both fire.
if m.modifiers.contains(KeyModifiers::ALT)
&& m.modifiers.contains(KeyModifiers::SHIFT)
&& self.editor.begin_box_select(m.column, m.row)
{
self.poke_cursor();
return;
}
// VS Code Alt+click: add (or toggle off) a secondary caret
// at the click instead of moving the single cursor.
if m.modifiers.contains(KeyModifiers::ALT)
&& !m.modifiers.contains(KeyModifiers::SHIFT)
&& self.editor.add_caret_at_screen(m.column, m.row)
{
self.poke_cursor();
return;
}
let now = std::time::Instant::now();
let is_double = self
.editor_click
.is_double(now, m.column, m.row, m.modifiers);
if is_double {
self.editor.select_word_at(m.column, m.row);
self.editor_click.clear();
} else {
// Anchor a fresh selection at the click; a drag widens it,
// a clean click ends up cleared on mouse-up.
self.editor.mouse_down(m.column, m.row);
self.editor_click.record(now, m.column, m.row, m.modifiers);
}
self.poke_cursor();
} else if let Some(idx) = terminal_hit {
self.activate_terminal_pane(idx);
self.focus_pane(Pane::Terminal);
// Click on a gutter decoration dot (the pane's left
// border): open the command's action menu (VS Code's
// decoration menu), headed by its outcome.
if let Some(d) = self.terminal().decoration_at_screen(m.column, m.row) {
self.open_command_decoration_menu((m.column, m.row), d);
return;
}
// Cmd/Ctrl+click on a printed URL opens it (forwarding a
// remote dev-server port first), mirroring the editor's
// go-to-definition modifier. Consumes the click so it
// doesn't also start a text selection.
if (m.modifiers.contains(KeyModifiers::SUPER)
|| m.modifiers.contains(KeyModifiers::CONTROL))
&& (self.terminal_url_click(m.column, m.row)
|| self.terminal_file_click(m.column, m.row))
{
return;
}
// A child tracking the mouse (Claude Code's diff panel,
// htop, lazygit, vim with `mouse=a`) gets the click
// itself (#474): an SGR/X10 press now, motion under
// 1002/1003 as the drag goes, and the release on
// mouse-up, all aimed at THIS pane via
// `terminal_pointer_forwarded`. Shift is the bypass,
// the same one the wheel has: croft's own selection when
// held. `report_mouse` is the whole gate -- it declines
// when the child is not tracking or the cell is on the
// border, and either way the click falls through to the
// selection below. The Cmd/Ctrl link-open above still
// wins, as in VS Code and iTerm2: the modifier is
// croft's, and Cmd has no mouse-report encoding anyway.
// A stale croft highlight goes, as it does for a plain
// click anywhere else -- the user is aiming at the TUI,
// not at the text under it -- and the double-click
// tracker is not armed: the pair, if any, is the child's.
if !m.modifiers.contains(KeyModifiers::SHIFT)
&& self.terminal_mut().report_mouse(
MouseButtonKind::Left,
MouseAction::Press,
m.column,
m.row,
mouse_mods(&m),
)
{
self.terminal_mut().clear_selection();
self.editor.clear_selection();
self.terminal_pointer_forwarded = Some(ForwardedPointer {
pane: self.terminals[idx].uid(),
press: (m.column, m.row),
selecting: false,
});
self.terminal_click.clear();
return;
}
// Shift+click extends the existing selection to the
// clicked cell (VS Code / iTerm2) instead of starting a
// fresh one.
if m.modifiers.contains(KeyModifiers::SHIFT)
&& self.terminal().selection().is_some()
{
self.terminal_mut().extend_selection_to(m.column, m.row);
self.terminal_click.clear();
return;
}
// A selection belongs to exactly one pane: starting one in
// the terminal drops any leftover editor selection so the
// two panes never paint a highlight at once (issue #23).
self.editor.clear_selection();
let now = std::time::Instant::now();
let is_double =
self.terminal_click
.is_double(now, m.column, m.row, m.modifiers);
if is_double {
self.terminal_mut().select_word_at(m.column, m.row);
self.terminal_click.clear();
} else {
// Begin a fresh selection at the click cell. Without a
// drag this is a single cell (no area), so the selection
// ends up cleared on mouse-up. With a drag, this is the
// selection anchor.
self.terminal_mut().start_selection_at(m.column, m.row);
self.terminal_click
.record(now, m.column, m.row, m.modifiers);
}
}
}
MouseEventKind::Drag(MouseButton::Left) => {
if let Some(from) = self.terminal_drag_from {
// Live reorder: the moment the pointer crosses another
// pane (side-by-side) or rail row (maximize mode), the
// dragged terminal moves there and the drag follows it.
// No ghost or indicator needed - the panes themselves
// rearrange under the pointer, and `move_terminal` keeps
// the dragged pane active.
let target = if self.terminal_pane_maximized && self.terminals.len() > 1 {
self.terminal_rail_rects
.iter()
.position(|r| rect_contains(*r, m.column, m.row))
} else {
self.terminal_at_pos(m.column, m.row)
};
if let Some(to) = target
&& to != from
{
self.move_terminal(from, to);
self.terminal_drag_from = Some(to);
}
return;
}
if let Some(kind) = self.splitter_drag.clone() {
self.handle_splitter_drag(kind, m.column, m.row);
return;
}
if self.minimap_drag {
self.minimap_scroll_to_row(m.row);
return;
}
if self.editor_hscrollbar_drag {
self.editor.scroll_to_bar_x(m.column);
self.poke_cursor();
return;
}
if self.outline_scrollbar_drag {
self.outline.scroll_to_bar_y(m.row);
return;
}
if self.open_editors_scrollbar_drag {
self.open_editors.scroll_to_bar_y(m.row);
return;
}
if self.timeline_scrollbar_drag {
self.timeline.scroll_to_bar_y(m.row);
return;
}
if self.deps_scrollbar_drag {
self.dependencies.scroll_to_bar_y(m.row);
return;
}
if self.testing_scrollbar_drag {
self.testing.scroll_to_bar_y(m.row);
return;
}
if self.graph_scrollbar_drag {
self.commit_graph.scroll_to_bar_y(m.row);
return;
}
if let Some(pane) = self.scrollbar_drag {
match pane {
Pane::Tree => match self.sidebar_view {
SidebarView::Explorer => {
self.tree.scroll_to_bar_y(m.row);
}
SidebarView::Remote => {
self.remote.scroll_to_bar_y(m.row);
}
SidebarView::SourceControl => {
self.source_control.scroll_to_bar_y(m.row);
}
SidebarView::Search => {
self.search.scroll_to_bar_y(m.row);
}
SidebarView::RunDebug => {}
SidebarView::Extensions => {}
SidebarView::Testing => {}
},
Pane::Editor => {
self.editor.scroll_to_bar_y(m.row);
self.poke_cursor();
}
Pane::Terminal => {}
}
return;
}
// Some terminals emit a Drag at the same cell as the Down even
// when the user hasn't actually dragged. Only forget the prior
// click when the pointer has truly moved off that cell.
self.editor_click.clear_if_moved(m.column, m.row);
self.tree_click.clear_if_moved(m.column, m.row);
self.terminal_click.clear_if_moved(m.column, m.row);
// The modified tracker gets the same cancellation. It was left
// out when it was added, so a bound `ctrl+double_click` fired
// across a drag where the built-in double correctly did not —
// the one tracker not on this list behaved differently from
// every other one for no reason a user could discover.
self.modified_click.clear_if_moved(m.column, m.row);
// A drag after a press that went to a mouse-tracking child
// (#474) belongs to whoever can use it. A child that asked
// for motion (1002/1003) gets it, at the pane that got the
// press, clamped to that pane's grid so a pointer that
// wanders out reports the edge cell instead of vanishing. A
// child that asked only for clicks (1000: Claude Code) has
// no use for a drag, so the drag is croft's text selection,
// anchored at the PRESS cell on its first motion so nothing
// is lost by the press having been forwarded, then extended
// here -- on the ORIGIN pane, found by uid, not through
// `terminal_mut()`: Cmd+] can move the active pane while the
// button is held, and the generic drag path below would then
// extend the wrong pane's selection and leave this one at its
// one-cell anchor. Edge auto-scroll is armed only while the
// origin is still the active pane, because the tick that
// services it scrolls the active one. The child still gets
// the release either way. A gesture whose pane is gone ends
// here with nothing to deliver.
if let Some(fp) = self.terminal_pointer_forwarded {
let Some(idx) = self.forwarded_pane_index(fp) else {
self.terminal_pointer_forwarded = None;
self.terminal_select_autoscroll = None;
return;
};
if self.terminals[idx].mouse_motion_reporting() {
let (col, row) = self.terminals[idx].clamp_to_grid(m.column, m.row);
// Motion reporting was just checked, so the verdict
// is known; `let _` says "already decided", not
// "ignored". The encoder re-checks the same modes
// as its own guard; the two are intentional.
let _ = self.terminals[idx].report_mouse(
MouseButtonKind::Left,
MouseAction::Motion,
col,
row,
mouse_mods(&m),
);
return;
}
if !fp.selecting {
self.terminals[idx].start_selection_at(fp.press.0, fp.press.1);
self.terminal_pointer_forwarded = Some(ForwardedPointer {
selecting: true,
..fp
});
}
let dir = self.terminals[idx].drag_select_to(m.column, m.row);
self.terminal_select_autoscroll = (dir != 0 && idx == self.active_terminal)
.then_some(TerminalSelectAutoScroll {
dir,
col: m.column,
last: std::time::Instant::now(),
});
return;
}
// Terminal drag-selection is handled before the per-pane
// branches so it keeps extending even when the pointer
// leaves the pane: dragging past the bottom edge is how the
// user grows a selection down through scrollback. The
// returned direction arms edge auto-scroll (serviced each
// main-loop tick); a pointer back inside the pane disarms it.
if self.focus == Pane::Terminal && self.terminal().selection().is_some() {
let dir = self.terminal_mut().drag_select_to(m.column, m.row);
self.terminal_select_autoscroll =
(dir != 0).then_some(TerminalSelectAutoScroll {
dir,
col: m.column,
last: std::time::Instant::now(),
});
return;
}
if in_editor {
if self.editor.diff.is_some() {
let last_inner = self.editor.last_inner;
if let Some(diff) = self.editor.diff.as_mut()
&& let Some((_, row_idx, char_col)) =
crate::widgets::editor::diff_hit_test(
diff, last_inner, m.column, m.row,
)
{
diff.extend_selection_to(row_idx, char_col);
}
self.poke_cursor();
return;
}
if let Some(view) = self.editor.hex.as_mut() {
let rows = (view.layout.data_rows as usize).max(1);
if let Some(off) = view.hit_test(m.column, m.row) {
view.set_cursor(off, true, rows);
}
self.poke_cursor();
return;
}
if self.editor.box_selecting() {
self.editor.box_drag_to_screen(m.column, m.row);
self.poke_cursor();
return;
}
self.editor.mouse_drag(m.column, m.row);
self.poke_cursor();
} else if in_tree {
match self.sidebar_view {
SidebarView::Explorer => {
// Promote to a real drag-and-drop the moment the
// pointer leaves the initiating cell.
if let Some(drag) = self.tree_drag.as_mut() {
let (_, sx, sy) = drag.started_at;
if m.column != sx || m.row != sy {
drag.armed = true;
}
if drag.armed {
drag.target_idx =
drag_target_index(&self.tree, m.row, &drag.paths);
self.tree.drag_target = drag.target_idx;
}
}
// While not dragging, treat continued movement as a
// range-extend from the initial anchor — just like
// VS Code's drag-to-select.
if self.tree_drag.as_ref().is_none_or(|d| !d.armed)
&& self.tree.sticky_row_at(m.row).is_none()
&& let Some(idx) = self.tree.node_at_y(m.row)
{
// Never extend the selection onto rows the
// sticky band covers — they are invisible
// under it (#126).
self.tree.select(idx);
}
}
SidebarView::Remote => {
if let Some(idx) = self.remote.target_at_y(m.row) {
self.remote.select(idx);
}
}
SidebarView::Search
| SidebarView::SourceControl
| SidebarView::RunDebug
| SidebarView::Extensions
| SidebarView::Testing => {}
}
} else if in_terminal {
self.terminal_mut().extend_selection_to(m.column, m.row);
} else if self.tree_drag.is_some() {
// Pointer dragged outside the tree pane: still keep the drag
// alive so dropping back inside lands; just clear the drop
// highlight so the user knows nothing will happen here.
if let Some(drag) = self.tree_drag.as_mut() {
drag.target_idx = None;
}
self.tree.drag_target = None;
}
}
MouseEventKind::Up(MouseButton::Left) => {
// The release of a press that was forwarded to a tracking
// child goes to the same pane (#474), clamped to its grid
// like the drag. `report_mouse` may decline if the child
// dropped tracking mid-press, which is the child's own
// choice; there is nothing croft should do with the release
// instead. The pane is found by uid, so one closed under
// the held button is simply gone rather than mistaken for
// its neighbour. The whole gesture ends here, aimed at the
// ORIGIN pane and never the active one: a click, or a drag
// the child asked for, gets no copy-on-select, click-to-move,
// annotation or secret popup; a drag the Drag arm turned into
// croft's selection is finalised on that pane (`end_drag`,
// then copy-on-select), the same tail the ordinary mouse-up
// below runs for the active pane.
if let Some(fp) = self.terminal_pointer_forwarded.take() {
if let Some(idx) = self.forwarded_pane_index(fp) {
let (col, row) = self.terminals[idx].clamp_to_grid(m.column, m.row);
self.terminals[idx].report_mouse(
MouseButtonKind::Left,
MouseAction::Release,
col,
row,
mouse_mods(&m),
);
if fp.selecting {
self.terminals[idx].end_drag();
if self.copy_on_select
&& self.terminals[idx]
.selection()
.is_some_and(|s| s.has_area())
{
let text = self
.terminal_text_for_copy(self.terminals[idx].selection_text());
if !text.is_empty() {
copy_to_clipboard(&text);
}
}
}
}
self.terminal_select_autoscroll = None;
return;
}
// Releasing the button ends any terminal edge auto-scroll
// and finalizes a drag-selection (the alt-screen content
// anchor is captured at release).
self.terminal_select_autoscroll = None;
if self.focus == Pane::Terminal {
self.terminal_mut().end_drag();
}
// Copy-on-select (VS Code's terminal.integrated.copyOnSelection,
// iTerm2's default): a finished terminal drag-selection lands
// on the clipboard without the explicit Cmd+C. Silent — this
// fires on every selection, so no status churn.
if self.copy_on_select
&& self.focus == Pane::Terminal
&& self.terminal().selection().is_some_and(|s| s.has_area())
{
let text = self.terminal_text_for_copy(self.terminal().selection_text());
if !text.is_empty() {
copy_to_clipboard(&text);
}
}
// A plain click on a redacted span shows the real value in
// a popup (#360): the mask is paint-only, so this is the
// one way to read it without a reveal window. Checked
// before click-to-move, like the annotation popup: on the
// prompt row a masked token yields its value rather than a
// caret move, which is the useful answer for a secret.
if self.focus == Pane::Terminal
&& !self.terminal().selection().is_some_and(|s| s.has_area())
&& let Some(secret) = self.terminal().redacted_at(m.column, m.row)
{
self.terminal_drag_from = None;
if self.terminal().selection().is_some() {
self.terminal_mut().clear_selection();
}
self.hover_popup = Some(crate::widgets::hover_popup::HoverPopup::new(
secret,
(m.column, m.row),
));
return;
}
// A plain click on an annotated span pops its note (checked
// before click-to-move so a note near the prompt is still
// readable).
if self.focus == Pane::Terminal
&& !self.terminal().selection().is_some_and(|s| s.has_area())
&& let Some((_, note)) = self.terminal().annotation_at(m.column, m.row)
{
// This early return skips the shared mouse-up tail, so
// run its cleanup here too: drop the pane-drag latch and
// the zero-area selection the mouse-down planted, or the
// clicked cell stays painted as a one-cell highlight.
self.terminal_drag_from = None;
if self.terminal().selection().is_some() {
self.terminal_mut().clear_selection();
}
self.hover_popup = Some(crate::widgets::hover_popup::HoverPopup::new(
note,
(m.column, m.row),
));
return;
}
// Ghostty's click-to-move-cursor: a plain click (no drag
// selection, no reordering, program not tracking the mouse)
// on the shell's prompt row walks its cursor to the clicked
// cell with synthesized arrow keys. Pane-local input: a
// click is not typing, so broadcast never mirrors it.
if self.focus == Pane::Terminal
&& self.terminal_drag_from.is_none()
&& self.terminal_copy_mode.is_none()
&& !self.terminal().selection().is_some_and(|s| s.has_area())
&& !self.terminal().mouse_reporting()
&& let Some(bytes) = self.terminal().prompt_click_arrows(m.column, m.row)
{
self.terminal_mut().write_input(&bytes);
}
// Releasing ends a pane drag-reorder; the order is already
// final because the reorder is live during the drag.
self.terminal_drag_from = None;
// Finish a column (box) selection, keeping the carets it built.
if self.editor.box_selecting() {
self.editor.end_box_select();
return;
}
if self.splitter_drag.take().is_some() {
return;
}
if std::mem::take(&mut self.minimap_drag) {
return;
}
if self.scrollbar_drag.take().is_some() {
return;
}
if std::mem::take(&mut self.editor_hscrollbar_drag) {
return;
}
if std::mem::take(&mut self.outline_scrollbar_drag) {
return;
}
if std::mem::take(&mut self.open_editors_scrollbar_drag) {
return;
}
if std::mem::take(&mut self.timeline_scrollbar_drag) {
return;
}
if std::mem::take(&mut self.deps_scrollbar_drag) {
return;
}
if std::mem::take(&mut self.testing_scrollbar_drag) {
return;
}
if std::mem::take(&mut self.graph_scrollbar_drag) {
return;
}
if let Some(drag) = self.tree_drag.take() {
self.tree.drag_target = None;
if drag.armed {
// Drag while Alt/Ctrl is held copies; default is move.
let copy = drag.toggle_on_release
|| m.modifiers.contains(KeyModifiers::ALT)
|| m.modifiers.contains(KeyModifiers::CONTROL);
let mode = if copy {
ExplorerClipMode::Copy
} else {
ExplorerClipMode::Cut
};
if let Some(target_idx) = drag.target_idx {
let target_dir = drop_target_dir(&self.tree, target_idx);
self.apply_paste_or_drop(&target_dir, &drag.paths, mode);
} else {
self.status = String::from("Drop cancelled");
}
return;
}
if drag.toggle_on_release {
// Stationary Alt/Ctrl-click: now perform the toggle.
self.tree.toggle_mark(drag.start_idx);
return;
}
}
// Mouse-up never auto-copies. The selection stays highlighted
// so the user can hit Cmd/Ctrl+C themselves; a click without
// drag (zero-area selection) is silently dropped.
if in_terminal {
if let Some(sel) = self.terminal().selection()
&& !sel.has_area()
{
self.terminal_mut().clear_selection();
}
} else if in_editor
&& let Some(sel) = self.editor.selection
&& !sel.has_area()
{
self.editor.clear_selection();
}
}
MouseEventKind::ScrollDown => {
if in_outline {
self.outline.scroll_down(3);
} else if in_open_editors {
self.open_editors.scroll_down(3);
} else if in_timeline {
self.timeline.scroll_down(3);
} else if in_deps {
self.dependencies.scroll_down(3);
} else if in_problems {
self.problems.scroll_down(3);
} else if in_output {
self.output.scroll_down(3);
} else if in_tree {
match self.sidebar_view {
SidebarView::Explorer => self.tree.scroll_down(3),
SidebarView::Remote => self.remote.scroll_down(3),
SidebarView::SourceControl => {
if rect_contains(self.commit_graph.last_area, m.column, m.row) {
self.commit_graph.scroll_down(3);
} else {
self.source_control.scroll_down(3);
}
}
SidebarView::Search => self.search.scroll_down(3),
SidebarView::RunDebug => {}
SidebarView::Extensions => self.extensions.scroll_down(3),
SidebarView::Testing => self.testing.scroll_down(3),
}
} else if in_editor {
if let Some(diff) = self.editor.diff.as_mut() {
diff.scroll_down_by(3);
} else if self.editor.pdf_page().is_some() {
self.wheel_pdf_page(1);
} else if let Some(view) = self.editor.hex.as_mut() {
let rows = (view.layout.data_rows as usize).max(1);
view.scroll_by(3, rows);
} else {
self.editor.scroll_down(3);
}
} else if rect_contains(self.terminal_rail_area, m.column, m.row) {
// The rail is its own scrollable list, like VS Code's
// terminal tabs. Paint clamps the offset.
self.terminal_rail_scroll = self.terminal_rail_scroll.saturating_add(1);
} else if let Some(idx) = terminal_hit {
let shift = m.modifiers.contains(KeyModifiers::SHIFT);
let t = &mut self.terminals[idx];
// A child tracking the mouse (Claude Code, htop, vim) gets
// a real wheel report so it scrolls its own content. Shift
// bypasses that for croft's scrollback. A report that
// could not be delivered (the wheel sat on the pane
// BORDER, outside the inner grid) falls through like any
// non-tracking pane instead of swallowing the notch.
if t.mouse_reporting()
&& !shift
&& t.report_mouse(
MouseButtonKind::WheelDown,
MouseAction::Press,
m.column,
m.row,
mouse_mods(&m),
)
{
} else if !t.scroll_down(3) {
if t.app_cursor_keys() {
t.write_input(b"\x1bOB\x1bOB\x1bOB");
} else {
t.write_input(b"\x1b[B\x1b[B\x1b[B");
}
}
}
}
MouseEventKind::ScrollUp => {
if in_outline {
self.outline.scroll_up(3);
} else if in_open_editors {
self.open_editors.scroll_up(3);
} else if in_timeline {
self.timeline.scroll_up(3);
} else if in_deps {
self.dependencies.scroll_up(3);
} else if in_problems {
self.problems.scroll_up(3);
} else if in_output {
self.output.scroll_up(3);
} else if in_tree {
match self.sidebar_view {
SidebarView::Explorer => self.tree.scroll_up(3),
SidebarView::Remote => self.remote.scroll_up(3),
SidebarView::SourceControl => {
if rect_contains(self.commit_graph.last_area, m.column, m.row) {
self.commit_graph.scroll_up(3);
} else {
self.source_control.scroll_up(3);
}
}
SidebarView::Search => self.search.scroll_up(3),
SidebarView::RunDebug => {}
SidebarView::Extensions => self.extensions.scroll_up(3),
SidebarView::Testing => self.testing.scroll_up(3),
}
} else if in_editor {
if let Some(diff) = self.editor.diff.as_mut() {
diff.scroll_up_by(3);
} else if self.editor.pdf_page().is_some() {
self.wheel_pdf_page(-1);
} else if let Some(view) = self.editor.hex.as_mut() {
let rows = (view.layout.data_rows as usize).max(1);
view.scroll_by(-3, rows);
} else {
self.editor.scroll_up(3);
}
} else if rect_contains(self.terminal_rail_area, m.column, m.row) {
self.terminal_rail_scroll = self.terminal_rail_scroll.saturating_sub(1);
} else if let Some(idx) = terminal_hit {
let shift = m.modifiers.contains(KeyModifiers::SHIFT);
let t = &mut self.terminals[idx];
// Same border fall-through as the WheelDown arm below.
if t.mouse_reporting()
&& !shift
&& t.report_mouse(
MouseButtonKind::WheelUp,
MouseAction::Press,
m.column,
m.row,
mouse_mods(&m),
)
{
} else if !t.scroll_up(3) {
if t.app_cursor_keys() {
t.write_input(b"\x1bOA\x1bOA\x1bOA");
} else {
t.write_input(b"\x1b[A\x1b[A\x1b[A");
}
}
}
}
MouseEventKind::ScrollLeft if in_editor => {
if let Some(diff) = self.editor.diff.as_mut() {
diff.scroll_left_by(4);
} else {
self.editor.scroll_left_by(4);
}
}
MouseEventKind::ScrollRight if in_editor => {
if let Some(diff) = self.editor.diff.as_mut() {
diff.scroll_right_by(4);
} else {
self.editor.scroll_right_by(4);
}
}
_ => {}
}
}
/// Whether formatting the current buffer is supported by an active server.
/// Gates format-on-save so a file whose server advertises no formatter is
/// saved directly rather than waiting on a reply that never mutates it.
fn editor_language_supports_formatting(&self) -> bool {
let Some(lang) = self
.editor
.path
.as_deref()
.and_then(|p| p.extension())
.and_then(|e| e.to_str())
.and_then(crate::lsp::Language::from_extension)
else {
return false;
};
self.lsp
.as_ref()
.and_then(|lsp| lsp.language_supports_formatting(lang))
.unwrap_or(false)
}
/// Whether `Cmd+S` should format before writing: the pref is on, a
/// formatter is available, and the active tab is a real editable code file
/// (not a diff/sheet/image preview). `supports_formatting` is passed in so
/// the decision is pure and unit-testable.
fn format_on_save_eligible(&self, supports_formatting: bool) -> bool {
self.format_on_save
&& supports_formatting
&& self.editor.path.is_some()
&& self.editor.diff.is_none()
&& self.editor.sheet.is_none()
&& self.editor.image.is_none()
}
/// Arm the deferred write for the active tab, ahead of the format request
/// whose reply will complete it.
///
/// The latch holds one path because the manager tracks one
/// `format_request_id`: arming a second file abandons the first reply, so
/// simply overwriting the latch dropped the first file's save entirely,
/// leaving it dirty and unwritten with nothing reported. Flush it here
/// instead. It goes to disk unformatted, which is the honest outcome once
/// its formatter reply can no longer arrive.
fn arm_deferred_save(&mut self) {
if let Some(pending) = std::mem::take(&mut self.save_after_format)
&& self.editor.path.as_deref() != Some(pending.as_path())
{
self.write_tab_to_disk(&pending);
}
self.save_after_format = self.editor.path.clone();
}
/// Write the deferred buffer to disk once its format reply has landed.
/// A no-op unless [`Self::save`] armed `save_after_format`.
fn complete_pending_save(&mut self) {
let Some(path) = std::mem::take(&mut self.save_after_format) else {
return;
};
// Write the tab the save was ASKED for. The reply can land long after
// the user moved on, and `write_current_to_disk` targets whatever is
// active — which wrote an unrequested file and left this one dirty.
if self.editor.path.as_deref() == Some(path.as_path()) {
self.write_current_to_disk();
return;
}
self.write_tab_to_disk(&path);
}
/// Flip `editor.formatOnSave`, persist it, and report the new state.
/// Persistence is skipped under test so the suite never writes the
/// developer's `~/.config/croft/config.json` (mirrors the layout prefs).
/// The auto-save delay after the last edit, VS Code's
/// `files.autoSaveDelay` default.
const AUTO_SAVE_DELAY: std::time::Duration = std::time::Duration::from_millis(1000);
/// Write every dirty, conflict-free buffer whose last edit is older
/// than the delay — the whole `files.autoSave: afterDelay` feature.
/// Runs every frame; returns true when anything was saved so the
/// caller redraws (dirty markers, badges, status).
pub fn tick_auto_save(&mut self) -> bool {
// `onFocusChange` fires on the transition, so the signature is
// sampled every tick regardless of which modes are enabled.
let focus_changed = self.note_focus_signature();
let mut changed = false;
if self.auto_save_on_focus_change && focus_changed {
changed = self.sweep_auto_save(false);
}
if self.auto_save {
changed |= self.sweep_auto_save(true);
}
changed
}
/// Sample the current focus (pane, active tab, active path) and report
/// whether it moved since the last sample. The first sample never
/// counts as a change, so launching croft writes nothing on its own.
fn note_focus_signature(&mut self) -> bool {
let pane = match self.focus {
Pane::Tree => 0usize,
Pane::Editor => 1,
Pane::Terminal => 2,
};
let sig = (pane, self.editor.active_index(), self.editor.path.clone());
match self.last_focus_signature.replace(sig.clone()) {
None => false,
Some(prev) => prev != sig,
}
}
/// The shared auto-save sweep. `require_delay` selects the mode:
/// `afterDelay` waits out [`Self::AUTO_SAVE_DELAY`] since the last
/// edit and writes every dirty buffer; `onFocusChange` writes
/// immediately but skips the editor that currently HAS focus (it has
/// not lost it yet). Returns true when anything changed on screen.
fn sweep_auto_save(&mut self, require_delay: bool) -> bool {
// Each saved tab's own map rides along (#349): the recorder must not
// look it up by path afterwards, since a split can hold the same file
// in a second buffer with a different map.
let mut saved_paths: Vec<(PathBuf, crate::provenance::Provenance, Option<Vec<u8>>)> =
Vec::new();
// The tab that still holds focus is not saved by the focus-change
// mode: only buffers that LOST focus are written.
let keep_focused =
(!require_delay && self.focus == Pane::Editor).then(|| self.editor.active_index());
// Collab guests never write shared (workspace) files; the session
// owner is the single writer (docs/MULTIPLAYER.md, Phase D).
let guest = self.is_collab_guest();
let root = self.tree.root.clone();
let due = |e: &crate::widgets::editor::Editor| {
e.dirty
&& e.path.is_some()
// Preview-kind edits (hex bytes, sheet cells) are
// EXPLICIT-save only: an automatic write mid-edit could
// land a half-updated byte sequence, and the serialising
// kinds normalise quoting the user did not ask to touch.
// (They also never set last_edit_at, so this guard makes
// an implicit exclusion structural - #191 review.)
&& !e.has_non_text_view()
&& !e.disk_conflict
// A latched encoding refusal: only an explicit Cmd+S can
// consent to the lossy write, so retrying here would just
// re-refuse every tick.
&& !e.encoding_loss
&& !(guest
&& e.path
.as_ref()
.is_some_and(|p| collab_file_key(&root, p).is_some()))
&& (!require_delay
|| e.last_edit_at
.is_some_and(|t| t.elapsed() >= Self::AUTO_SAVE_DELAY))
};
let mut conflicted: Vec<PathBuf> = Vec::new();
// "name (encoding)" per refused tab: the refusal message names each
// tab's OWN encoding, which need not be the active tab's.
let mut lossy: Vec<String> = Vec::new();
let mut sweep = |editors: &mut [crate::widgets::editor::Editor], skip: Option<usize>| {
for (i, e) in editors
.iter_mut()
.enumerate()
.filter(|(i, e)| Some(*i) != skip && due(e))
{
let _ = i;
// `save_to_disk` re-checks the disk and flags (never
// overwrites) an external change; auto save must not
// arm the force-overwrite path an explicit Cmd+S offers.
match e.save_to_disk() {
Ok(crate::widgets::editor::SaveOutcome::Saved) => {
if let Some(p) = e.path.clone() {
// The bytes this editor just wrote, so the
// recorder can tell whether they are still the
// ones on disk when its worker reads (#349).
saved_paths.push((p, e.provenance_to_record(), e.bytes_for_disk()));
}
}
// The latch also removes the tab from `due`, so this is
// the ONLY chance to tell the user: the FS sweep's
// prompt fires on the transition into disk_conflict,
// which this save just consumed.
Ok(crate::widgets::editor::SaveOutcome::DiskConflict) => {
conflicted.extend(e.path.clone());
}
// Same transition-only reporting as the conflict arm:
// the latch just set removes the tab from `due`, so
// this tick is the one chance to say why it stopped
// saving. Never arms the lossy write — consent is the
// explicit path's alone.
Ok(crate::widgets::editor::SaveOutcome::EncodingLoss) => {
if let Some(name) = e.path.as_ref().and_then(|p| p.file_name()) {
lossy.push(format!(
"{} ({})",
name.to_string_lossy(),
e.encoding.name()
));
}
}
Err(_) => {}
}
}
};
sweep(&mut self.editor.editors, keep_focused);
for group in self.editor_layout.inactive_groups_mut() {
sweep(&mut group.editors, None);
}
let had_conflicts = !conflicted.is_empty();
if had_conflicts {
self.prompt_disk_conflict(conflicted);
}
let had_lossy = !lossy.is_empty();
if had_lossy {
// The status line, not the modal prompt: nothing was lost and
// nothing is racing, so an auto-save refusal must not steal the
// keyboard mid-typing burst.
self.status = format!(
"Auto save paused for {}: the buffer has characters the encoding cannot represent - open the tab and press Cmd+S to resolve",
lossy.join(", ")
);
}
if saved_paths.is_empty() {
// A conflict-only (or refusal-only) tick still changed the UI:
// returning false would defer it to the next incidental redraw.
return had_conflicts || had_lossy;
}
// Mirror the explicit-save path: a config file written by auto save
// must take effect exactly like one written by Cmd+S — including one
// saved in a background tab or an inactive split.
for (path, ..) in &saved_paths {
self.reload_config_for_path(path);
}
if let Some(lsp) = self.lsp.as_ref() {
for (path, ..) in &saved_paths {
lsp.save_doc(path.clone());
}
}
for (path, seats, described) in saved_paths {
self.record_history_snapshot_of(&path, seats, described);
}
true
}
fn toggle_auto_save(&mut self) {
self.auto_save = !self.auto_save;
self.status = if self.auto_save {
String::from("Auto Save: on")
} else {
String::from("Auto Save: off")
};
if !cfg!(test) {
let _ = crate::prefs::save_auto_save(self.auto_save);
}
}
/// Flip `files.autoSave: onFocusChange` and persist it, like
/// [`Self::toggle_auto_save`] does for the delay mode.
fn toggle_auto_save_on_focus_change(&mut self) {
self.auto_save_on_focus_change = !self.auto_save_on_focus_change;
self.status = if self.auto_save_on_focus_change {
String::from("Auto Save on Focus Change: on")
} else {
String::from("Auto Save on Focus Change: off")
};
if !cfg!(test) {
let _ = crate::prefs::save_auto_save_on_focus_change(self.auto_save_on_focus_change);
}
}
/// `Editor: Toggle Provenance` (#349): flip the lens for the session and
/// push it onto the active editor now (the per-tick sync covers the
/// next tab focused).
fn toggle_provenance(&mut self) {
self.provenance_overlay = !self.provenance_overlay;
self.editor.provenance_overlay = self.provenance_overlay;
self.status = if self.provenance_overlay {
String::from("Provenance: on")
} else {
String::from("Provenance: off")
};
}
fn toggle_inline_blame(&mut self) {
self.inline_blame_enabled = !self.inline_blame_enabled;
self.editor.blame_enabled = self.inline_blame_enabled;
// Re-enabling refetches (the sync marker was left set); disabling
// keeps the data so a later re-enable can be instant if unchanged.
if self.inline_blame_enabled {
self.blame_fetched = None;
}
self.status = if self.inline_blame_enabled {
String::from("Inline Blame: on")
} else {
String::from("Inline Blame: off")
};
if !cfg!(test) {
let _ = crate::prefs::save_inline_blame(self.inline_blame_enabled);
}
}
fn toggle_render_whitespace(&mut self) {
self.whitespace_mode = self.whitespace_mode.next();
self.editor.whitespace_mode = self.whitespace_mode;
if !cfg!(test) {
let _ = crate::prefs::save_render_whitespace(self.whitespace_mode.pref_id());
}
self.status = format!("Render Whitespace: {}", self.whitespace_mode.label());
}
/// Rebuild the inline-value trailers (#135) from the current stop's
/// already-fetched VARIABLES data, on every editor showing the stopped
/// file (inactive split groups render too).
fn refresh_inline_values(&mut self) {
use crate::dap::session::SessionPhase;
if !self.inline_values_enabled {
return;
}
let Some(session) = self.dap_session.as_ref() else {
return;
};
if session.phase != SessionPhase::Stopped {
return;
}
let Some((path, line)) = session.current_location.clone() else {
return;
};
let locals = crate::dap::session::inline_locals(&session.scopes, &session.variables);
for ed in self.editor.editors.iter_mut() {
if ed.path.as_deref() == Some(path.as_path()) {
ed.set_inline_values_from_locals(line, &locals);
}
}
for group in self.editor_layout.inactive_groups_mut() {
for ed in group.editors.iter_mut() {
if ed.path.as_deref() == Some(path.as_path()) {
ed.set_inline_values_from_locals(line, &locals);
}
}
}
}
/// Drop every inline-value trailer, in every editor of every group —
/// called wherever the stop arrow clears (resume, step, terminate).
fn clear_inline_values(&mut self) {
for ed in self.editor.editors.iter_mut() {
ed.inline_values.clear();
}
for group in self.editor_layout.inactive_groups_mut() {
for ed in group.editors.iter_mut() {
ed.inline_values.clear();
}
}
}
fn toggle_inline_values(&mut self) {
self.inline_values_enabled = !self.inline_values_enabled;
if self.inline_values_enabled {
self.refresh_inline_values();
} else {
self.clear_inline_values();
}
if !cfg!(test) {
let _ = crate::prefs::save_inline_values(self.inline_values_enabled);
}
self.status = format!(
"Debug Inline Values: {}",
if self.inline_values_enabled {
"on"
} else {
"off"
}
);
}
fn toggle_bracket_colors(&mut self) {
self.bracket_colors_enabled = !self.bracket_colors_enabled;
self.editor.show_bracket_colors = self.bracket_colors_enabled;
if !cfg!(test) {
let _ = crate::prefs::save_bracket_colors(self.bracket_colors_enabled);
}
self.status = format!(
"Bracket Pair Colorization: {}",
if self.bracket_colors_enabled {
"on"
} else {
"off"
}
);
}
fn toggle_indent_guides(&mut self) {
self.indent_guides_enabled = !self.indent_guides_enabled;
self.editor.show_indent_guides = self.indent_guides_enabled;
if !cfg!(test) {
let _ = crate::prefs::save_indent_guides(self.indent_guides_enabled);
}
self.status = format!(
"Indent Guides: {}",
if self.indent_guides_enabled {
"on"
} else {
"off"
}
);
}
fn toggle_auto_close_pairs(&mut self) {
self.auto_close_pairs = !self.auto_close_pairs;
self.editor.auto_close_pairs = self.auto_close_pairs;
if !cfg!(test) {
let _ = crate::prefs::save_auto_close_pairs(self.auto_close_pairs);
}
self.status = format!(
"Auto Closing Pairs: {}",
if self.auto_close_pairs { "on" } else { "off" }
);
}
/// VS Code's `editor.formatOnType` toggle (#254), persisted like the
/// other editor preferences.
fn toggle_format_on_type(&mut self) {
self.format_on_type = !self.format_on_type;
self.status = if self.format_on_type {
String::from("Format on Type: on")
} else {
String::from("Format on Type: off")
};
if !cfg!(test) {
let _ = crate::prefs::save_format_on_type(self.format_on_type);
}
}
fn toggle_format_on_save(&mut self) {
self.format_on_save = !self.format_on_save;
self.status = if self.format_on_save {
String::from("Format on Save: on")
} else {
String::from("Format on Save: off")
};
if !cfg!(test) {
let _ = crate::prefs::save_format_on_save(self.format_on_save);
}
}
/// Palette "Log: Toggle Highlighting (tailspin)" and the Settings row
/// (#466): flip tailspin colouring for every open rendered log, steer
/// the default for logs opened later, and persist the preference.
pub fn toggle_log_highlight(&mut self) {
self.set_log_highlight(!self.log_highlight);
self.status = if self.log_highlight {
String::from("Log highlighting (tailspin): on")
} else {
String::from("Log highlighting (tailspin): off")
};
if !cfg!(test) {
let _ = crate::prefs::save_disable_log_highlight(!self.log_highlight);
}
}
/// Apply a log-highlight setting everywhere it lives (#466): the app's
/// field, the log view's opening default for logs opened later, and
/// every log view already open in any split group. Shared by the
/// palette / Settings toggle and by a settings remerge (a workspace
/// layer setting `disable_log_highlight`), so the two cannot drift.
fn set_log_highlight(&mut self, on: bool) {
self.log_highlight = on;
seed_log_highlight_default(on);
for group in
std::iter::once(&mut self.editor).chain(self.editor_layout.inactive_groups_mut())
{
for ed in &mut group.editors {
if let Some(log) = ed.log.as_mut() {
log.set_highlight(on);
}
}
}
}
fn toggle_copy_on_select(&mut self) {
self.copy_on_select = !self.copy_on_select;
self.status = if self.copy_on_select {
String::from("Copy on Selection: on")
} else {
String::from("Copy on Selection: off")
};
if !cfg!(test) {
let _ = crate::prefs::save_copy_on_select(self.copy_on_select);
}
}
fn save(&mut self) {
// A hex tab with pending overwrites saves through its own byte
// path (#173) — never `write_buffer_to_disk`, whose #185 guard
// refuses every preview kind. Same disk-conflict double-press
// contract as text saves.
if self.editor.hex.as_ref().is_some_and(|v| v.has_edits()) {
use crate::widgets::editor::SaveOutcome;
let force = std::mem::take(&mut self.force_save_armed);
match self.editor.hex_save(force) {
Ok(SaveOutcome::Saved) => {
self.status = self.editor.status.clone();
// Local history captures the new bytes like every
// other successful save path (#191 review).
if let Some(path) = self.editor.path.clone() {
let seats = self.editor.provenance_to_record();
let described = self.editor.bytes_for_disk();
self.record_history_snapshot_of(&path, seats, described);
}
}
Ok(SaveOutcome::DiskConflict) => {
self.force_save_armed = true;
let name = self
.editor
.path
.as_ref()
.map(|p| p.display().to_string())
.unwrap_or_default();
self.status = format!(
"{name} changed on disk since you opened it - press Cmd+S again to overwrite the changed bytes"
);
}
Ok(_) => unreachable!("hex_save reports Saved or DiskConflict"),
Err(e) => self.status = format!("Save failed: {e}"),
}
return;
}
// A CSV/TSV sheet with grid edits saves through its own
// serialisation path (#177), same shape as the hex branch above.
if self.editor.sheet.as_ref().is_some_and(|v| v.dirty) {
use crate::widgets::editor::SaveOutcome;
let force = std::mem::take(&mut self.force_save_armed);
// Distinct consents (#194 review): overwriting an external
// disk change and replacing a FORMULA are different
// decisions, each armed by its own refusal message.
let overwrite_formulas = std::mem::take(&mut self.formula_overwrite_armed);
match self.editor.sheet_save(force, overwrite_formulas) {
Ok(SaveOutcome::Saved) => {
self.status = self.editor.status.clone();
if let Some(path) = self.editor.path.clone() {
let seats = self.editor.provenance_to_record();
let described = self.editor.bytes_for_disk();
self.record_history_snapshot_of(&path, seats, described);
}
// Formula cells held back (#178): the NEXT Cmd+S is
// the explicit consent, same double-press contract
// as disk conflicts.
if self.editor.sheet.as_ref().is_some_and(|v| v.dirty) {
self.formula_overwrite_armed = true;
}
}
Ok(SaveOutcome::DiskConflict) => {
self.force_save_armed = true;
let name = self
.editor
.path
.as_ref()
.map(|p| p.display().to_string())
.unwrap_or_default();
self.status = format!(
"{name} changed on disk since you opened it - press Cmd+S again to overwrite"
);
}
Ok(_) => unreachable!("sheet_save reports Saved or DiskConflict"),
Err(e) => self.status = format!("Save failed: {e}"),
}
return;
}
// A preview tab has nothing to save (and #185: letting the write
// proceed truncated the previewed file). Friendly no-op here; the
// choke-point guard in `write_buffer_to_disk` backstops every
// other path.
if self.editor.has_non_text_view() {
self.status = String::from("Nothing to save: this tab is a read-only preview");
return;
}
// Guests in a collab session never write shared files: the owner is
// the single writer, so the FS watcher and history snapshots see one
// author. The guest's edits already flowed to the owner as ops.
// Except a file whose bootstrap gave up (no owner answered): the
// guest is its only author, and refusing meant the work could never
// persist anywhere. Same when there is NO session at all (relay
// link down, reconnect pending): with nobody to defer to, blocking
// strands the offline work in RAM for the whole outage.
if self.is_collab_guest()
&& self
.editor
.path
.as_ref()
.and_then(|p| collab_file_key(&self.tree.root, p))
.is_some_and(|file| {
self.collab
.as_ref()
.is_some_and(|s| !s.is_local_only(&file))
})
{
self.status =
String::from("Shared file: the session owner saves (your edits are already live)");
return;
}
// A previously-refused save arms a one-shot override: the very next
// Cmd+S overwrites the external change. Consume it here so it never
// lingers past the press it was meant for.
if std::mem::take(&mut self.force_save_armed) {
use crate::widgets::editor::SaveOutcome;
match self.editor.save_to_disk_force() {
Ok(SaveOutcome::Saved) => {
self.status = self.editor.status.clone();
if let Some(path) = self.editor.path.clone() {
let seats = self.editor.provenance_to_record();
let described = self.editor.bytes_for_disk();
self.record_history_snapshot_of(&path, seats, described);
}
self.lsp_notify_saved();
self.reload_config_if_needed();
}
// Overwriting the external change was consented to; mangling
// the buffer's characters was not. Route the refusal through
// the same prompt-and-rearm as a plain save, keeping the
// overwrite consent so the NEXT Cmd+S resolves both at once.
Ok(SaveOutcome::EncodingLoss) => {
self.force_save_armed = true;
self.prompt_encoding_loss();
}
Ok(SaveOutcome::DiskConflict) => {
unreachable!("force save never reports a conflict")
}
Err(e) => self.status = format!("Save failed: {e}"),
}
return;
}
// Format-on-save: defer the write until the format reply arrives, then
// `drain_lsp_format` calls `complete_pending_save`.
if self.format_on_save_eligible(self.editor_language_supports_formatting()) {
self.arm_deferred_save();
self.start_format_document();
return;
}
self.write_current_to_disk();
}
/// After a save, if the file was one of croft's JSON configs, re-read it so
/// the change applies without a relaunch (VS Code applies keybindings and
/// snippets on save). settings.json fields are read at startup, so that one
/// leaves its own "next launch" note rather than reloading here.
fn reload_config_if_needed(&mut self) {
let Some(path) = self.editor.path.clone() else {
return;
};
self.reload_config_for_path(&path);
}
/// Reload whichever of croft's own config files `path` is, if any.
/// Shared by the explicit-save path (active tab) and the auto-save
/// sweep (every written tab, background and inactive splits included).
fn reload_config_for_path(&mut self, path: &std::path::Path) {
if path == crate::keymap::keybindings_path() {
// The non-reporting loader: this path needs the warnings itself
// for the status summary below, and `load` would print each one to
// OUTPUT a second time.
let (map, warns) = crate::keymap::Keymap::load_with_warnings(path);
self.keymap = map;
// Refused rows used to vanish, which makes a mistyped binding
// feel like croft is broken. Same treatment the settings loader
// gives its warnings: OUTPUT for the detail, a status summary so
// the user knows to look (#259).
for w in &warns {
crate::output::push("Keybindings", crate::output::OutputLevel::Warn, w);
}
self.status = keybindings_reload_status(&warns);
} else if path == crate::snippets::snippets_path() {
self.snippets = crate::snippets::SnippetSet::load(path);
self.status = String::from("Snippets reloaded");
} else if path == crate::agents::agents_path() {
self.agents = crate::agents::AgentTable::load(path);
let dropped = self.agents.dropped_patterns();
self.status = format!(
"Agent lanes reloaded ({} agents known{})",
self.agents.names().len(),
if dropped > 0 {
format!(
", {dropped} prompt pattern{} did not compile",
if dropped == 1 { "" } else { "s" }
)
} else {
String::new()
}
);
} else if path == crate::triggers::triggers_path() {
self.triggers = load_trigger_set(self.secret_redaction);
self.status = format!(
"Triggers reloaded ({} active)",
self.triggers.triggers.len()
);
} else if path == crate::problem_matchers::matchers_path()
|| path == crate::problem_matchers::workspace_matchers_path(self.workspace_root())
{
self.reload_matchers();
} else if path == crate::prefs::config_path()
|| self.settings_chain.iter().any(|p| p == path)
{
self.remerge_settings();
}
}
/// Re-run the layered settings merge (#251) and apply everything that can
/// apply live: theme, editor toggles, save behavior, host accents. Called
/// when any file of the chain is saved in the editor; layout and other
/// startup-read settings still say "next launch".
fn remerge_settings(&mut self) {
let merged = crate::config_layers::load_merged(Some(self.roots.primary()));
for w in &merged.warnings {
crate::output::push("Settings", crate::output::OutputLevel::Warn, w);
}
self.settings_chain = merged.chain;
self.settings_provenance = merged.provenance;
self.apply_merged_settings(&merged.prefs);
self.status = if merged.warnings.is_empty() {
String::from("Settings reloaded")
} else {
format!(
"Settings reloaded with {} warning{} — see OUTPUT · Settings",
merged.warnings.len(),
if merged.warnings.len() == 1 { "" } else { "s" }
)
};
}
/// Apply a merged settings view to the live session. Mirrors what the
/// individual toggles do, minus their persistence (the values already
/// live in config files) and minus their status chatter.
fn apply_merged_settings(&mut self, p: &crate::prefs::Prefs) {
self.notifier = crate::notifications::Notifier::new(&p.notifications);
let theme = p.theme();
if theme != self.theme {
// Visuals only: a workspace-set theme must not be written back
// into the user's config.
self.apply_theme_visuals(theme);
}
self.format_on_save = p.format_on_save;
self.format_on_type = p.format_on_type;
self.auto_save = p.auto_save;
self.auto_save_on_focus_change = p.auto_save_on_focus_change;
self.copy_on_select = p.copy_on_select;
// The ssh-pane offer's switches apply live like every other pref
// here (#364); turning it off also takes down an offer on screen.
self.remote_offer_disabled = p.disable_remote_offer;
self.lane_agent = p.lane_agent.clone();
// Live like every other pref here (#363): editing a group in
// config.json takes effect on the next fleet run without a restart.
self.fleet_groups = p.fleet_groups.clone();
let was_excluded = std::mem::replace(
&mut self.remote_offer_excluded,
p.remote_offer_excluded_hosts.clone(),
);
// Sampling stops while the offer is off, so the per-pane memory stops
// tracking reality; kept, it would make the first session seen after
// a re-enable look like a continuation of the last one seen before
// it, and that pane would never be offered that host again (#364).
if self.remote_offer_disabled {
self.ssh_offer_seen.clear();
}
// A host taken OFF the exclusion list: a pane already on it was seen
// while excluded and would otherwise never be offered for the
// session it is in. Forgetting what those panes were seen on makes
// the next sample read as a session start, which is the moment the
// user asked to be offered at.
let freed: Vec<&String> = was_excluded
.iter()
.filter(|h| {
!self
.remote_offer_excluded
.iter()
.any(|n| n.eq_ignore_ascii_case(h))
})
.collect();
if !freed.is_empty() {
self.ssh_offer_seen.retain(|_, seen| {
!seen
.as_deref()
.is_some_and(|h| freed.iter().any(|f| f.eq_ignore_ascii_case(h)))
});
}
if let Some(o) = self.ssh_offer.as_ref()
&& !crate::remote::offer_allowed(
&o.host,
self.remote_offer_disabled,
&self.remote_offer_excluded,
&self.remote_offer_refused,
std::time::SystemTime::now(),
)
{
self.dismiss_ssh_offer();
}
// Only on a real change: the startup remerge runs before any log is
// open and the field already holds the preference, and writing the
// process-wide default from here under test would race the tests
// that read it (see `seed_log_highlight_default`).
let want_highlight = !p.disable_log_highlight;
if want_highlight != self.log_highlight {
self.set_log_highlight(want_highlight);
}
self.auto_close_pairs = !p.disable_auto_close_pairs;
self.editor.auto_close_pairs = self.auto_close_pairs;
if !p.disable_inline_blame && !self.inline_blame_enabled {
// Re-enabling refetches, like toggle_inline_blame.
self.blame_fetched = None;
}
self.inline_blame_enabled = !p.disable_inline_blame;
self.editor.blame_enabled = self.inline_blame_enabled;
self.indent_guides_enabled = !p.disable_indent_guides;
self.editor.show_indent_guides = self.indent_guides_enabled;
self.bracket_colors_enabled = !p.disable_bracket_colors;
self.editor.show_bracket_colors = self.bracket_colors_enabled;
self.whitespace_mode =
crate::widgets::editor::WhitespaceMode::from_pref(&p.render_whitespace);
self.editor.whitespace_mode = self.whitespace_mode;
if !p.disable_inlay_hints && !self.inlay_hints_enabled {
self.inlay_hints_enabled = true;
self.request_inlay_hints_for_open_editors();
} else if p.disable_inlay_hints && self.inlay_hints_enabled {
self.inlay_hints_enabled = false;
self.editor.clear_inlay_hints();
for group in self.editor_layout.inactive_groups_mut() {
group.clear_inlay_hints();
}
}
if p.disable_inline_values && self.inline_values_enabled {
self.inline_values_enabled = false;
self.clear_inline_values();
} else if !p.disable_inline_values && !self.inline_values_enabled {
self.inline_values_enabled = true;
self.refresh_inline_values();
}
self.explorer_views = ExplorerViewVisibility::from_prefs(p.explorer_views);
self.set_host_accents(&p.host_accents);
}
/// Tell the language servers the focused file hit the disk. rust-analyzer
/// re-runs its check-on-save (`cargo check`, which produces the Rust
/// PROBLEMS entries) only on `textDocument/didSave`; without this the
/// panel never refreshes after a save (issue #37).
fn lsp_notify_saved(&mut self) {
if let (Some(lsp), Some(path)) = (self.lsp.as_ref(), self.editor.path.clone()) {
lsp.save_doc(path);
}
}
/// Restore persisted provenance maps onto the open buffers (#349), each
/// once per buffer generation: when a tab is a clean text buffer that
/// knows nothing yet, and the newest history snapshot holds exactly the
/// bytes on disk, the seats recorded beside that snapshot describe this
/// very text and come back. Any difference (an edit since, a save croft
/// never saw, a file with no history) leaves every line unknown: a map is
/// never applied to text it did not describe. Every tab of every group,
/// not only the focused one: the lens paints in every pane
/// (`sync_focus_flags` carries the flag there), so a map restored onto
/// the focused tab alone would leave a split showing blanks beside it.
fn sync_provenance(&mut self) {
let root = self.history_root.clone();
let groups =
std::iter::once(&mut self.editor).chain(self.editor_layout.inactive_groups_mut());
for ed in groups.flat_map(|g| g.editors.iter_mut()) {
Self::sync_provenance_for(&root, ed);
}
}
/// The per-buffer body of [`Self::sync_provenance`].
fn sync_provenance_for(root: &Path, ed: &mut crate::widgets::editor::Editor) {
let Some(path) = ed.path.clone() else {
return;
};
let seq = ed.edit_seq;
if ed.provenance_synced_seq == Some(seq) {
return;
}
// Not eligible yet is not the same as considered: a dirty buffer, one
// that already knows its seats, or a viewer tab (the file shown
// through its own path, `lines` a placeholder no map should credit;
// a markdown preview is NOT one, its `lines` are the file's own text)
// leaves the marker unset, so a later tick, after a save or a swap
// back to text, reconsiders instead of staying burnt for the session.
if ed.dirty || ed.provenance.attributed() > 0 || ed.has_non_text_view() {
return;
}
let Some(newest) = crate::history::entries_in(root, &path).into_iter().next() else {
return;
};
// The sidecar first: most files have a snapshot and no record, and
// the reads below are only worth paying on the UI thread when there
// is a map to apply. Nothing above this point burns the marker: a
// save records its snapshot and then its sidecar from a worker
// thread, so a tick landing in that window must be free to look
// again rather than deciding this buffer has no map.
let Some(mut seats) = crate::history::seats_for(root, &path, newest.millis) else {
return;
};
ed.provenance_synced_seq = Some(seq);
// Then sizes: this runs on the render thread, and two whole-file
// reads of a large file on the frame a tab is switched to would be a
// visible stall for what is usually a mismatch.
let (Ok(disk_meta), Ok(snap_meta)) =
(std::fs::metadata(&path), std::fs::metadata(&newest.file))
else {
return;
};
if disk_meta.len() != snap_meta.len() {
return;
}
let (Ok(on_disk), Ok(snapshot)) = (std::fs::read(&path), std::fs::read(&newest.file))
else {
return;
};
if on_disk != snapshot {
return;
}
// And this buffer holds that very text. A clean buffer can still be
// stale: when one tab of a split saves, the other keeps the pre-save
// lines, and the snapshot then matches DISK while describing text
// that tab never held. The disk stamp cannot tell the two apart when
// both writes land inside one filesystem timestamp tick, so the
// comparison is against the buffer's own bytes.
if !ed.holds_exactly(&snapshot) {
return;
}
seats.truncate(ed.lines.len());
ed.provenance = seats;
}
/// Record a local-history snapshot of a file that just hit the disk, and
/// refresh the TIMELINE when it's the active file so the new version shows.
/// Reads back what was written so the snapshot matches the on-disk bytes
/// exactly (encoding / EOL included). The IO runs off-thread — with auto
/// save this fires every second, and a large file's read+write on the
/// render thread is a visible stall.
///
/// `seats` is who typed each line of the buffer that was saved, recorded
/// beside the snapshot (#349). The caller reads it off that tab
/// (`Editor::provenance_to_record`) at the save, on the UI thread: never
/// looked up by path here, since a split can hold the same file in a
/// second buffer with a different map, and a snapshot restore records
/// the restored snapshot's own seats, which no tab holds at that moment.
fn record_history_snapshot(&mut self, path: &Path, seats: crate::provenance::Provenance) {
self.record_history_snapshot_of(path, seats, None);
}
/// [`Self::record_history_snapshot`] with the bytes the map describes.
/// The worker re-reads the file, which is what makes the snapshot
/// byte-exact, and between the save and that read another tab's save of
/// the same path can land - so the map is recorded only while the bytes
/// on disk are still the ones it describes.
///
/// `described` comes from the caller because only the caller knows WHICH
/// buffer the map came from: a search by path finds the focused tab,
/// which need not be the tab that saved. `None` records the map
/// unconditionally, for a caller whose map has no live buffer - a
/// snapshot restore, whose seats come from the restored snapshot and
/// describe the bytes it has just written itself.
fn record_history_snapshot_of(
&mut self,
path: &Path,
seats: crate::provenance::Provenance,
described: Option<Vec<u8>>,
) {
let root = self.history_root.clone();
let path = path.to_path_buf();
let tx = self.history_done_tx.clone();
let millis = now_millis();
std::thread::spawn(move || {
if let Ok(bytes) = std::fs::read(&path) {
// Someone else's bytes are on disk now: record the snapshot
// alone, every line unknown, which is the safe direction.
let seats = match described {
Some(want) if want != bytes => crate::provenance::Provenance::new(),
_ => seats,
};
let _ = crate::history::record_with_seats_in(&root, &path, &bytes, millis, &seats);
}
let _ = tx.send(path);
});
}
/// Save the open tab for `path` wherever it lives — background tab of the
/// focused group, or any inactive split — without disturbing the focus.
/// Used by the deferred format-on-save write when the user has moved on.
fn write_tab_to_disk(&mut self, path: &std::path::Path) {
use crate::widgets::editor::SaveOutcome;
let found = self
.editor
.editors
.iter_mut()
.chain(
self.editor_layout
.inactive_groups_mut()
.into_iter()
.flat_map(|g| g.editors.iter_mut()),
)
.find(|e| e.path.as_deref() == Some(path));
let Some(editor) = found else {
// The tab was closed while the formatter was thinking; there is no
// buffer left to write and the disk file is untouched.
self.status = String::from("Save skipped: the tab was closed");
return;
};
match editor.save_to_disk() {
Ok(SaveOutcome::Saved) => {
let seats = editor.provenance_to_record();
let described = editor.bytes_for_disk();
self.status = editor.status.clone();
self.record_history_snapshot_of(path, seats, described);
if let Some(lsp) = self.lsp.as_ref() {
lsp.save_doc(path.to_path_buf());
}
self.reload_config_for_path(path);
}
Ok(SaveOutcome::DiskConflict) => {
self.status = format!(
"{} changed on disk since you opened it - open the tab and press Cmd+S twice to overwrite, or close it to keep the disk version",
path.display()
);
}
Ok(SaveOutcome::EncodingLoss) => {
// Both callers route a still-focused tab to
// `write_current_to_disk`, which arms the press-again consent
// itself; this function only ever runs for a tab the user
// moved away from, and such a tab never gets lossy consent —
// resolving needs it back in front of them.
self.status = format!(
"{} not saved: it has characters {} cannot represent - open the tab and press Cmd+S to resolve",
path.display(),
editor.encoding.name()
);
}
Err(e) => self.status = format!("Save failed: {e}"),
}
}
fn write_current_to_disk(&mut self) {
use crate::widgets::editor::SaveOutcome;
match self.editor.save_to_disk() {
Ok(SaveOutcome::Saved) => {
self.status = self.editor.status.clone();
if let Some(path) = self.editor.path.clone() {
let seats = self.editor.provenance_to_record();
let described = self.editor.bytes_for_disk();
self.record_history_snapshot_of(&path, seats, described);
}
self.lsp_notify_saved();
self.reload_config_if_needed();
}
Ok(SaveOutcome::DiskConflict) => {
self.force_save_armed = true;
let name = self
.editor
.path
.as_ref()
.map(|p| p.display().to_string())
.unwrap_or_default();
self.status = format!(
"{name} changed on disk since you opened it - press Cmd+S again to overwrite, or close the tab to keep the disk version"
);
}
Ok(SaveOutcome::EncodingLoss) => self.prompt_encoding_loss(),
Err(e) => self.status = format!("Save failed: {e}"),
}
}
/// An explicit save was refused because the encoding cannot represent the
/// buffer (`SaveOutcome::EncodingLoss`). Arm the one-shot lossy consent
/// and spell out exactly what the next Cmd+S will destroy, mirroring the
/// press-again flow of a disk conflict. The alternative exits are the
/// same two the refusal preserved: reopen the status-bar encoding picker
/// (a clean buffer switches encodings losslessly) or edit the characters
/// out.
fn prompt_encoding_loss(&mut self) {
self.editor.lossy_save_armed = true;
let chars = self.editor.unmappable_chars();
let shown: String = chars.iter().map(|c| format!("{c} ")).collect();
self.status = format!(
"Not saved: {} cannot represent {}- press Cmd+S again to replace them with &#…; references (irreversible), or switch encoding via the status bar",
self.editor.encoding.name(),
shown
);
}
/// Whether an open context menu (or its submenu panel) overlaps `rect`
/// on a protocol with no image z-layer (iTerm2 OSC-1337, Sixel), where
/// the image blit would overpaint the menu. Kitty layers images below
/// text, so it never needs this.
fn context_menu_covers_rect(&self, rect: Rect) -> bool {
match self.inline_protocol {
crate::iterm2_inline::InlineImageProtocol::ITerm2
| crate::iterm2_inline::InlineImageProtocol::Sixel => {}
_ => return false,
}
self.menu_rect()
.into_iter()
.chain(self.submenu_rect())
.any(|m| rects_intersect(m, rect))
}
/// Compute the menu's bounding rect from current state.
fn menu_rect(&self) -> Option<Rect> {
let menu = self.context_menu.as_ref()?;
// Use char count (not byte len) so multi-byte glyphs in menu
// labels (e.g. the "" in "Rename", the arrow in "Compare with
// Selected") don't inflate the menu width past what's needed.
// Width must also fit the shortcut hint on the right side, with
// at least 2 cells of gap between label and shortcut.
let widest = menu.items.iter().map(menu_entry_width).max().unwrap_or(0);
let width = (widest + 4).max(18) as u16;
let height = (menu.items.len() + 2) as u16;
let area = self.last_frame_area;
// Clamp identically to `render_context_menu` so hit-testing maps
// clicks to the same row the user actually sees. Without this, a
// menu that has to shift up to fit (right-click low on screen)
// dispatches the row above the one the user clicked.
let x = if area.width > 0 {
menu.origin.0.min(area.width.saturating_sub(width))
} else {
menu.origin.0
};
let y = if area.height > 0 {
menu.origin.1.min(area.height.saturating_sub(height))
} else {
menu.origin.1
};
Some(Rect {
x,
y,
width,
height,
})
}
/// Rect of the open submenu's panel: floated to the RIGHT of its parent
/// row, flipped to the left when it would overflow the screen, with its
/// first row aligned to the parent row. `None` when no submenu is open.
fn submenu_rect(&self) -> Option<Rect> {
let menu = self.context_menu.as_ref()?;
let parent = menu.open_submenu?;
let MenuEntry::Submenu { items, .. } = menu.items.get(parent)? else {
return None;
};
let main = self.menu_rect()?;
let widest = items.iter().map(menu_entry_width).max().unwrap_or(0);
let width = (widest + 4).max(18) as u16;
let height = (items.len() + 2) as u16;
let area = self.last_frame_area;
// Float right of the main panel; flip left if it would overflow.
let mut x = main.x + main.width;
if area.width > 0 && x + width > area.width {
x = main.x.saturating_sub(width);
}
// Align the submenu's top border so its first row sits on the parent row.
let y = (main.y + 1 + parent as u16).saturating_sub(1);
let y = if area.height > 0 {
y.min(area.height.saturating_sub(height))
} else {
y
};
Some(Rect {
x,
y,
width,
height,
})
}
/// If (x, y) hits a top-level menu row, return its index.
fn menu_item_at(&self, x: u16, y: u16) -> Option<usize> {
let r = self.menu_rect()?;
if !rect_contains(r, x, y) {
return None;
}
// Items live inside the 1-cell border.
let inner_y = y.checked_sub(r.y + 1)?;
let menu = self.context_menu.as_ref()?;
let idx = inner_y as usize;
(idx < menu.items.len()).then_some(idx)
}
/// If (x, y) hits a row of the open submenu panel, return that child index.
fn submenu_item_at(&self, x: u16, y: u16) -> Option<usize> {
let r = self.submenu_rect()?;
if !rect_contains(r, x, y) {
return None;
}
let inner_y = y.checked_sub(r.y + 1)?;
let menu = self.context_menu.as_ref()?;
let parent = menu.open_submenu?;
let MenuEntry::Submenu { items, .. } = menu.items.get(parent)? else {
return None;
};
let idx = inner_y as usize;
(idx < items.len()).then_some(idx)
}
fn handle_menu_key(&mut self, key: KeyEvent) {
match key.code {
KeyCode::Esc => {
// Esc backs out of an open submenu first; at the top level it
// dismisses the whole menu.
let closed = self
.context_menu
.as_mut()
.is_some_and(|menu| menu.close_submenu());
if !closed {
self.context_menu = None;
}
}
KeyCode::Up => {
if let Some(menu) = self.context_menu.as_mut() {
menu.move_cursor(false);
}
}
KeyCode::Down => {
if let Some(menu) = self.context_menu.as_mut() {
menu.move_cursor(true);
}
}
KeyCode::Left => {
if let Some(menu) = self.context_menu.as_mut() {
menu.close_submenu();
}
}
KeyCode::Right => {
if let Some(menu) = self.context_menu.as_mut() {
menu.open_cursor_submenu();
}
}
KeyCode::Enter => {
// On a submenu parent, Enter opens it; on an item it dispatches.
let opened = self
.context_menu
.as_mut()
.is_some_and(|menu| menu.open_cursor_submenu());
if opened {
return;
}
if let Some(menu) = self.context_menu.as_ref()
&& let Some(action) = menu.cursor_action()
{
let dir = menu.target_dir.clone();
self.context_menu = None;
self.dispatch_menu_action(action, dir);
}
}
_ => {}
}
}
/// Add `path` as another workspace root (multi-root, #147): the model
/// grows, the Explorer gains the section, every root gets a watcher
/// share, the Cmd+P index and workspace search span the new set, and
/// the LSP layer widens its project-root bound (servers for the new
/// root spawn per (language, project root) exactly like a fresh
/// workspace's — croft's per-project server model needs no
/// didChangeWorkspaceFolders, since no running server's folder set
/// changes). Session/collab identity deliberately stays keyed on the
/// PRIMARY root: adding a folder never changes what the window IS.
pub fn add_workspace_folder(&mut self, path: PathBuf) {
let path = path.canonicalize().unwrap_or(path);
if !path.is_dir() {
self.status = format!("Not a folder: {}", path.display());
return;
}
if !self.roots.add(path.clone()) {
self.status = String::from("Folder is already in the workspace");
return;
}
self.tree.add_root(path.clone());
self.git_extra
.push((path.clone(), GitWorker::spawn(path.clone())));
self.rebind_workspace_watchers();
self.sync_workspace_fanout();
self.refresh_workspace_title();
self.save_workspace_folders();
self.status = format!("Added folder: {}", path.display());
}
/// Remove a SECONDARY workspace root (#147). The primary is refused —
/// it is the launch identity; changing it is Make Root's job. Open
/// tabs under the removed root stay open (they become plain
/// out-of-workspace files, VS Code behavior).
pub fn remove_workspace_folder(&mut self, path: PathBuf) {
if !self.roots.remove(&path) {
self.status = String::from(
"The primary workspace folder cannot be removed (use Make Root to change it)",
);
return;
}
self.tree.remove_root(&path);
// The removed folder's review queue goes with it (#345). Its rows
// leave the tree, so no stale DOT renders — but the status chip
// counts the same set, and a count that outlives the folder it
// describes sends the user looking for rows that are not there.
for gone in self
.agent_ledger
.unreviewed_paths()
.into_iter()
.filter(|p| p.starts_with(&path))
{
self.agent_ledger.forget_path(&gone);
}
self.sync_agent_lane_decorations();
self.git_extra.retain(|(r, _)| r != &path);
self.git_head_oids.remove(&path);
if self.active_scm_root == path {
// The panel was following the removed folder's repo: seed the
// primary's immediately — assigning the field alone left the
// removed repository on screen (#150 review).
let primary = self.roots.primary().to_path_buf();
self.seed_active_scm(primary);
}
self.rebind_workspace_watchers();
self.sync_workspace_fanout();
self.refresh_workspace_title();
self.save_workspace_folders();
self.status = format!("Removed folder: {}", path.display());
}
/// (Re)spawn one watcher per workspace root, splitting the per-OS
/// watch caps across them (#147): the caps bound kernel resources per
/// PROCESS, so N roots share one budget rather than multiplying it.
fn rebind_workspace_watchers(&mut self) {
let shares = self.roots.iter().count();
let primary = self.workspace_root().to_path_buf();
self.fs_watch.rebind_sharing(&primary, &self.tree, shares);
self.fs_watch_extra = self
.roots
.iter()
.skip(1)
.map(|r| FsWatch::spawn_event_only(r, shares))
.collect();
}
/// Push the current root set into the per-root fan-outs that are not
/// watcher-shaped: the Cmd+P index, the search worker + panel, and
/// the LSP project-root bound.
fn sync_workspace_fanout(&mut self) {
self.file_finder_index = None;
self.file_finder = None;
self.kick_file_finder_index_rebuild();
let roots: Vec<PathBuf> = self.roots.iter().map(Path::to_path_buf).collect();
let _ = self
.search_query_tx
.send(SearchRequest::SetRoots(roots.clone()));
self.search.roots = roots.clone();
if let Some(lsp) = &self.lsp {
lsp.set_extra_roots(roots.into_iter().skip(1).collect());
}
}
/// Re-emit the OSC window title for the current folder set: the
/// primary root's name, with VS Code's " (Workspace)" marker while
/// more than one folder is open (#147).
fn refresh_workspace_title(&mut self) {
use std::io::Write;
let mut title = build_title(self.workspace_root());
if self.roots.is_multi() {
title.push_str(" (Workspace)");
}
let mut out = std::io::stdout();
let _ = out.write_all(&set_title_seq(&title));
let _ = out.flush();
}
/// Persist the current secondary-folder list under the primary
/// root's key (#153) — the terminal-session model: an empty list
/// prunes the key.
fn save_workspace_folders(&mut self) {
let primary = self.roots.primary().display().to_string();
let folders: Vec<PathBuf> = self.roots.iter().skip(1).map(Path::to_path_buf).collect();
if let Err(e) =
crate::workspace::save_folders_for_root(&self.workspace_folders_path, &primary, folders)
{
// A corrupt store is refused, never replaced (#156 review):
// the arrangement still works this session, it just won't
// persist until the store is repaired or removed.
self.status = format!("Workspace folders not saved: {e}");
}
}
/// Restore the saved folder set for the current primary root (#153):
/// each surviving folder re-joins through the normal add fan-out; a
/// folder that no longer exists on disk is dropped from the record
/// rather than restored.
pub fn restore_workspace_folders(&mut self) -> usize {
let map = crate::workspace::load_folders(&self.workspace_folders_path);
let primary = self.roots.primary().display().to_string();
let Some(saved) = map.get(&primary).cloned() else {
return 0;
};
let before = self.roots.iter().count();
for folder in saved {
if folder.is_dir() {
self.add_workspace_folder(folder);
}
}
// Rewrites the record from what actually restored, dropping
// vanished folders (and pruning the key if none survived).
self.save_workspace_folders();
// The caller composes the user-facing message: setting status
// here was immediately overwritten on the re-root path (#156
// review).
self.roots.iter().count() - before
}
/// Apply a `.code-workspace` file (#163): re-root to its first folder
/// and install its folder set exactly (the pending set suppresses the
/// automatic store restore for this re-root).
fn open_workspace_file(&mut self, path: &Path) {
match crate::workspace::parse_workspace_file(path) {
Ok(folders) => {
let mut it = folders.into_iter();
let primary = it.next().expect("parse guarantees a folder");
if !primary.is_dir() {
// Refuse before touching the workspace: re-rooting
// into a vanished folder would strand the window
// (#164 review).
self.status = format!("Workspace file: missing folder {}", primary.display());
return;
}
self.pending_workspace_folders = Some(it.collect());
self.change_workspace_root(primary);
}
Err(e) => self.status = format!("Workspace file: {e}"),
}
}
/// Open the fuzzy directory picker in add-folder mode (#147): the
/// same zoxide-backed popup as Cmd+Z, with Enter adding the chosen
/// directory as a workspace root instead of re-rooting.
fn open_add_folder_picker(&mut self) {
self.zoxide_add_folder = true;
self.open_zoxide_jump();
if self.zoxide_jump.is_some() {
self.status =
String::from("Add Folder to Workspace: pick a directory — Enter adds, Esc cancels");
}
}
/// Re-root the workspace at `new_root`. Resets the file tree, updates
/// `workspace_root`, refreshes git status and the source-control
/// panel, and respawns the FS watcher off-thread (a recursive stat
/// walk on a multi-GB monorepo is the dominant cost - blocking the
/// UI thread for it is what froze the app on "Make root"). The
/// polling fallback in `drain_fs_events` keeps the tree fresh until
/// the watcher comes online via `try_install_pending_init`. Open
/// editor tabs are NOT closed - a path that escapes the new root
/// still resolves on disk and the user may want to keep it open.
/// Compare anchor / clipboard / marks are reset because they point
/// into the old workspace.
pub fn change_workspace_root(&mut self, new_root: PathBuf) {
let display = new_root.display().to_string();
// The remembered task belongs to the old workspace; Rerun Last Task
// must rediscover, not rerun the old project's command here.
self.last_task = None;
// Read the panel's untouched-ness BEFORE the cd seed below: the seed
// is an input write, which clears it. Then persist the outgoing
// workspace's pane layout under ITS key while `workspace_root` still
// names it — every save after the swap keys on the new root, which
// both discarded this layout on re-root and filed the old panes
// under the new workspace's entry (#137).
let panel_pristine = self.terminals.len() == 1 && self.terminals[0].is_pristine();
self.save_terminal_session();
let mut shell_synced = true;
if let Some(active) = self.terminals.get_mut(self.active_terminal) {
// cwd_seed_is_safe, not foreground_is_shell: a pane whose shell
// is still starting up (rc files own the tty, no input ever
// written, no prompt yet) must still get the seed — it queues as
// type-ahead for the first prompt (#94).
if active.cwd_seed_is_safe() {
active.change_cwd(&new_root);
} else {
shell_synced = false;
}
}
self.roots.replace_primary(new_root.clone());
// A panel the user never touched — the startup default, one unnamed
// shell with no input ever typed and no launched program — is swapped
// for the incoming workspace's saved layout, the same restore startup
// runs. A panel with any user state instead survives the re-root
// as-is: navigation must never destroy live shells.
if panel_pristine {
self.restore_terminal_session();
}
// Rebind the LSP servers to the new root. The manager captured its
// workspace folder once, at App::new, from croft's launch directory -
// and the Croft.app launcher hardcodes that to ~/Documents. Re-rooting
// into a child repo left rust-analyzer running `cargo metadata` against
// the parent, which has no Cargo.toml, so every opened .rs came back as
// an `unlinked-file` with no hover / completion / semantic tokens.
// Spawn a fresh manager rooted at new_root; assigning over the Option
// drops the old manager, whose Drop shuts its servers down. Clearing
// lsp_last_seen makes the next sync_lsp() re-open every live editor tab
// against the new servers; the stale diagnostics / progress from the
// old root are dropped with it.
self.lsp = match crate::lsp::LspManager::new(new_root.clone()) {
Ok(m) => Some(m),
Err(e) => {
eprintln!("lsp manager rebind failed: {e}");
None
}
};
self.lsp_last_seen.clear();
self.lsp_diagnostics.clear();
self.lsp_progress.clear();
// Build diagnostics describe the OLD workspace's files; a re-root
// that kept them showed the previous project's errors forever.
self.build_diagnostics.clear();
self.build_diag_files_by_pane.clear();
// Refresh the window/icon title: it was emitted once at startup from
// the launch dir and never updated, so after a re-root it kept showing
// the parent (e.g. "Documents") instead of the repo. OSC 0 is
// grid-independent, so writing it straight to stdout between draws is
// safe - the same pattern startup uses.
{
use std::io::Write;
let mut out = std::io::stdout();
let _ = out.write_all(&set_title_seq(&build_title(&new_root)));
let _ = out.flush();
}
self.tree.set_root(new_root.clone());
self.tree_clipboard = None;
self.compare_anchor = None;
// The agent review queue belongs to the workspace that was left
// (#345). `set_root` has just cleared the Explorer's copy; this
// clears the ledger it is drawn from, so the two cannot come back
// apart the moment an agent writes under the new root.
self.agent_ledger = crate::agent_lane::AgentLedger::new();
self.fs_watch.rebind(&new_root, &self.tree);
// A re-root collapses the workspace to one folder: the secondary
// watchers go with their roots (#147).
self.fs_watch_extra.clear();
// A re-root collapses the git side too (#149): the secondary
// workers drop with their roots, the active repo IS the new
// primary, and the per-repo HEAD markers restart.
self.git_extra.clear();
self.active_scm_root = new_root.clone();
self.git_head_oids.clear();
self.git.bypass_debounce();
// Rebind the worker's root before any query, otherwise the next
// Status / Changes request runs against the stale root captured
// at App::new and the Source Control panel keeps reporting the
// OLD repo's state (or "no repo") even after a Make Root that
// landed inside a real git tree.
self.git.set_root(new_root.clone());
self.refresh_git_status_debounced();
// Drop the old repo's graph before the refresh (inside
// refresh_source_control) refetches for the new root; a reply still
// in flight for the old root is dropped by the drain's root tag.
self.commit_graph.clear();
self.refresh_source_control();
// Rebind the test runner too, else `cargo test -- --list` keeps running
// in the launch dir captured at spawn (e.g. ~/Documents, no Cargo.toml)
// and the Testing view stays empty after a Make Root into a child repo.
// Then drop the old project's tree: its cases are unrelated, they keep
// the beaker badge counting dead failures, and a non-empty panel blocks
// open_testing_view's discover-on-empty, so the new project would never
// be discovered. Results still streaming from the old root are dropped
// by the drain's epoch tag (same idea as the commit graph's root tag).
// With the Testing view in front, re-discover right away; otherwise the
// now-empty panel discovers on its next open.
self.active_test_root = new_root.clone();
self.test_worker.set_root(new_root.clone());
self.testing.reset();
// Drop any in-flight `cargo test --no-run`: the drain would refuse
// its root-mismatched binary anyway, but the occupied slot kept
// refusing NEW debug builds until the stale compile finished.
self.disarm_failure_breakpoint();
self.pending_test_debug = None;
if self.sidebar_view == SidebarView::Testing {
self.discover_tests();
}
// Rebind the search worker and the panel's display root to the new
// Explorer root so the next search targets this directory and its
// subdirectories, not the root captured when the worker was spawned.
// Drop the old root's hits so nothing stale lingers in the panel.
let _ = self
.search_query_tx
.send(SearchRequest::SetRoot(new_root.clone()));
self.search.root = new_root.clone();
self.search.roots = vec![new_root.clone()];
self.search.hits.clear();
self.search.selected = 0;
self.search.scroll = 0;
// Drop any in-flight walker for the OLD root so its result is
// discarded when it tries to send. Then kick a fresh walk
// against the new root. file_finder_index keeps the old entries
// for now so a Cmd+P press during the rebuild window shows
// stale-but-immediate results instead of a UI freeze.
self.file_finder_index_rx = None;
self.file_finder_index_dirty = false;
self.kick_file_finder_index_rebuild();
// Rebind the resident navigator: the activation record, relay
// socket, and single-host lock are all keyed by workspace root
// (captured at App::new), so without this a `croft pair` run in the
// NEW root writes a record this window never reads and the
// navigator can never seat again after a re-root. Any seat from the
// old root is torn down with its comment boxes; if this window had
// self-appointed the old root's collab owner, that session goes too
// (a fresh activation self-appoints against the new root).
if let Some(host) = self.pair_host.take() {
let sites = host.caret_sites();
self.collab_carets.retain(|s, _| !sites.contains(s));
self.status = String::from("Navigator unseated (workspace changed)");
}
self.navigator_notes.clear();
self.pair_commentary_buf.clear();
self.pair_turn_origin = None;
self.clear_problem_fix();
self.editor.comment_focus = None;
if self.pair_host_lock.take().is_some() {
self.collab = None;
self.collab_config = None;
}
// Old-root merge bases are keyed by root-relative file, like the
// carets below: never let them merge into a same-named file here.
self.collab_offline_base.clear();
self.pair_record_path = crate::session::pair_record_path(&new_root);
self.pair_socket = crate::session::collab_socket_path(&new_root);
self.pair_host_lock_path = crate::session::pair_host_lock_path(&new_root);
self.navigator_down = false; // the death latch belonged to the old root
self.last_pair_check = None; // read the new record this tick, not in 1s
// Old-workspace carets are keyed by root-relative file, so a
// same-named file under the new root would wear a departed peer's
// caret. The live session repopulates its own on the next poll.
self.collab_carets.clear();
// The new primary's saved folder set comes back with it (#153),
// the same way its terminal layout does: re-rooting into a
// workspace restores that workspace's arrangement.
let restored = match self.pending_workspace_folders.take() {
Some(folders) => {
let before = self.roots.iter().count();
for folder in folders {
self.add_workspace_folder(folder);
}
self.roots.iter().count() - before
}
None => self.restore_workspace_folders(),
};
let folders_note = if restored > 0 {
format!(
" (+{restored} workspace folder{})",
if restored == 1 { "" } else { "s" }
)
} else {
String::new()
};
// The workspace settings layers follow the primary root (#251): the
// old repo's .croft/config.json must stop applying and the new one
// start, without a relaunch. Runs after the root swap above so the
// merge reads the new primary. The status write below is deliberate:
// remerge_settings sets its own status, and the re-root message is
// the one that should win here.
self.remerge_settings();
self.status = if shell_synced {
format!("Workspace root: {display}{folders_note}")
} else {
format!("Workspace root: {display}{folders_note} (terminal busy; shell not moved)")
};
}
fn is_explorer_focused(&self) -> bool {
self.focus == Pane::Tree && self.sidebar_view == SidebarView::Explorer
}
/// Dispatch the Explorer-pane keyboard shortcuts (Cmd+F / Cmd+Shift+F /
/// Cmd+R / F2 / Cmd+/). Returns true if the key was handled. The
/// target node is whichever row the user has highlighted; folder-only
/// actions (Make root) are no-ops on file selections.
fn handle_explorer_shortcut(&mut self, key: KeyEvent) -> bool {
if is_tree_zoxide_jump_key(key) {
self.open_zoxide_jump();
return true;
}
if is_tree_new_file_key(key) {
let target = self.explorer_create_target_dir();
self.open_create_prompt(CreateKind::File, target);
return true;
}
if is_tree_new_folder_key(key) {
let target = self.explorer_create_target_dir();
self.open_create_prompt(CreateKind::Folder, target);
return true;
}
if is_tree_rename_key(key) {
if let Some(path) = self.explorer_selected_path() {
self.open_rename_prompt(path);
}
return true;
}
// Reveal in Finder is a local-macOS-only host bridge: on a remote SSH
// session croft runs on a headless host with no Finder, so the chord
// falls through there exactly as the menu entry is withheld.
if !self.is_remote && cfg!(target_os = "macos") && is_reveal_in_finder_key(key) {
if let Some(path) = self.explorer_selected_path() {
self.reveal_in_finder(path);
}
return true;
}
if is_tree_make_root_key(key) {
if let Some(path) = self.explorer_selected_folder() {
self.change_workspace_root(path);
}
return true;
}
if is_tree_make_parent_root_key(key) {
if let Some(path) = self.explorer_parent_for_make_root() {
self.change_workspace_root(path);
}
return true;
}
false
}
/// Resolve the parent folder of the highlighted node for the
/// `Cmd+Shift+/` "Make root at parent" gesture. Works on files
/// (parent = containing directory), folders (parent = its parent),
/// and the tree root itself (parent = one filesystem level up).
/// Returns `None` when the selected path has no parent (filesystem
/// root) or no node is currently selected.
fn explorer_parent_for_make_root(&self) -> Option<PathBuf> {
let n = self.tree.nodes.get(self.tree.selected)?;
n.path.parent().map(|p| p.to_path_buf())
}
fn explorer_selected_path(&self) -> Option<PathBuf> {
self.tree
.nodes
.get(self.tree.selected)
.map(|n| n.path.clone())
}
fn explorer_selected_folder(&self) -> Option<PathBuf> {
let n = self.tree.nodes.get(self.tree.selected)?;
if n.is_dir && n.path != self.tree.root {
Some(n.path.clone())
} else {
None
}
}
fn explorer_create_target_dir(&self) -> PathBuf {
let node = self.tree.nodes.get(self.tree.selected);
crate::widgets::file_tree::create_target_dir_for(node, &self.tree.root)
}
/// VS Code-style type-to-jump for the Explorer. Each printable
/// keystroke arriving while the file tree is focused appends to a
/// short-lived prefix buffer and snaps selection to the first
/// visible node whose name starts with that prefix. Keystrokes
/// further apart than `TREE_TYPEAHEAD_WINDOW` reset the buffer to
/// a single character and cycle to the next match, so re-pressing
/// the same letter walks through siblings beginning with it.
/// `now` is injected for deterministic tests.
fn apply_tree_typeahead(&mut self, c: char, now: std::time::Instant) {
let within_window = self
.tree_typeahead
.as_ref()
.is_some_and(|t| now.duration_since(t.last) < TREE_TYPEAHEAD_WINDOW);
let prefix = if within_window {
let mut p = self.tree_typeahead.as_ref().unwrap().prefix.clone();
p.push(c.to_ascii_lowercase());
p
} else {
c.to_ascii_lowercase().to_string()
};
let n = self.tree.nodes.len();
if n > 0 {
let start = if within_window {
self.tree.selected
} else {
(self.tree.selected + 1) % n
};
if let Some(idx) = self.tree.find_prefix(&prefix, start) {
self.tree.selected = idx;
self.tree.anchor = idx;
self.tree.marked.clear();
}
}
self.tree_typeahead = Some(TreeTypeahead { prefix, last: now });
}
fn dispatch_menu_action(&mut self, action: MenuAction, target_dir: PathBuf) {
match action {
MenuAction::Create(kind) => self.open_create_prompt(kind, target_dir),
MenuAction::Delete { paths } => self.delete_paths(paths),
MenuAction::Rename(path) => self.open_rename_prompt(path),
MenuAction::Cut(paths) => {
let n = paths.len();
self.tree_clipboard = Some(ExplorerClipboard {
mode: ExplorerClipMode::Cut,
paths,
});
self.status = if n == 1 {
String::from("Cut 1 item")
} else {
format!("Cut {n} items")
};
}
MenuAction::Copy(paths) => {
let n = paths.len();
self.tree_clipboard = Some(ExplorerClipboard {
mode: ExplorerClipMode::Copy,
paths,
});
self.status = if n == 1 {
String::from("Copied 1 item")
} else {
format!("Copied {n} items")
};
}
MenuAction::Paste(dest) => self.paste_into(dest),
MenuAction::SelectForCompare(path) => {
let label = path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| path.display().to_string());
self.compare_anchor = Some(path);
self.status = format!("Selected {label} for compare");
}
MenuAction::AddWorkspaceFolder => self.open_add_folder_picker(),
MenuAction::RemoveWorkspaceFolder(path) => self.remove_workspace_folder(path),
MenuAction::MakeRoot(folder) => {
self.change_workspace_root(folder);
}
MenuAction::RevealInFinder(path) => self.reveal_in_finder(path),
MenuAction::OpenInViewer(id, path) => {
// The row was built when the menu opened; an extension
// removed since then must not make the click a silent no-op.
match crate::mcp::registry::viewer_by_id_in_dir(&self.config_dir, &id) {
Some(viewer) => self.open_in_viewer(&viewer, &path),
None => self.status = format!("{id} is no longer available"),
}
}
MenuAction::CopyTabPath(path) => self.copy_path_to_clipboard(path),
MenuAction::CopyTabRelativePath(path) => self.copy_relative_path_to_clipboard(path),
MenuAction::RevealInExplorer(path) => self.reveal_in_explorer(path),
MenuAction::CloseTab(idx) => {
self.record_closed_tab_at(idx);
if self.editor.close_tab(idx) {
self.sync_open_file_poll_mtime();
self.status = String::from("Closed tab");
self.poke_cursor();
self.collapse_split_if_empty();
}
}
MenuAction::CloseOtherTabs(keep_idx) => {
self.record_closed_tabs_where(|i, ed| i != keep_idx && !ed.pinned);
let removed = self.editor.close_others(keep_idx);
if removed > 0 {
self.sync_open_file_poll_mtime();
self.status = if removed == 1 {
String::from("Closed 1 other tab")
} else {
format!("Closed {removed} other tabs")
};
self.poke_cursor();
}
}
MenuAction::CloseTabsToRight(from_idx) => {
self.record_closed_tabs_where(|i, ed| i > from_idx && !ed.pinned);
let removed = self.editor.close_to_right(from_idx);
if removed > 0 {
self.sync_open_file_poll_mtime();
self.status = if removed == 1 {
String::from("Closed 1 tab to the right")
} else {
format!("Closed {removed} tabs to the right")
};
self.poke_cursor();
}
}
MenuAction::CloseAllTabs => self.close_all_tabs(),
MenuAction::CloseSavedTabs => self.close_saved_tabs(),
MenuAction::KeepTabOpen(idx) => {
if self.editor.keep_open(idx) {
self.status = String::from("Kept tab open");
self.poke_cursor();
}
}
MenuAction::ToggleTabPin(idx) => {
let pinned = self.editor.toggle_pin(idx);
self.status = String::from(if pinned { "Pinned tab" } else { "Unpinned tab" });
self.poke_cursor();
}
MenuAction::SplitEditor => self.split_editor(),
MenuAction::SplitEditorLeft => {
self.split_editor_dir(editor_layout::SplitDir::Horizontal, false)
}
MenuAction::SplitEditorUp => {
self.split_editor_dir(editor_layout::SplitDir::Vertical, false)
}
MenuAction::SplitEditorDown => {
self.split_editor_dir(editor_layout::SplitDir::Vertical, true)
}
MenuAction::MoveEditorUp => self.move_active_editor(editor_layout::Dir::Up),
MenuAction::MoveEditorDown => self.move_active_editor(editor_layout::Dir::Down),
MenuAction::MoveEditorLeft => self.move_active_editor(editor_layout::Dir::Left),
MenuAction::MoveEditorRight => self.move_active_editor(editor_layout::Dir::Right),
MenuAction::SplitInGroup => self.split_in_group(),
MenuAction::FocusGroupLeft => self.focus_editor_group(true),
MenuAction::FocusGroupRight => self.focus_editor_group(false),
MenuAction::MoveIntoNewWindow(idx) => self.move_into_new_window(idx),
MenuAction::CopyIntoNewWindow(idx) => self.copy_into_new_window(idx),
MenuAction::CompareWithSelected { anchor, other } => {
match self.editor.open_diff(&anchor, &other) {
Ok(()) => {
self.focus_pane(Pane::Editor);
self.compare_anchor = None;
self.sync_open_file_poll_mtime();
let l = anchor
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| anchor.display().to_string());
let r = other
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| other.display().to_string());
self.status = format!("Diff: {l} \u{2194} {r}");
}
Err(e) => {
self.status = format!("Diff failed: {e}");
}
}
}
MenuAction::RenameSymbolAt { row, col } => {
self.editor.collapse_carets();
self.editor.cursor_row = row;
self.editor.cursor_col = col;
self.focus_pane(Pane::Editor);
self.start_rename_symbol();
}
MenuAction::ChangeAllOccurrencesAt { row, col } => {
self.editor.collapse_carets();
self.editor.cursor_row = row;
self.editor.cursor_col = col;
self.focus_pane(Pane::Editor);
self.start_change_all_occurrences();
}
MenuAction::NavigateBack => self.nav_back(),
MenuAction::NavigateForward => self.nav_forward(),
MenuAction::GoToDefinitionAt { row, col } => {
self.editor.cursor_row = row;
self.editor.cursor_col = col;
self.focus_pane(Pane::Editor);
self.request_definition_at_cursor();
}
MenuAction::GoToDeclarationAt { row, col } => {
self.editor.cursor_row = row;
self.editor.cursor_col = col;
self.focus_pane(Pane::Editor);
self.request_declaration_at_cursor();
}
MenuAction::GoToTypeDefinitionAt { row, col } => {
self.editor.cursor_row = row;
self.editor.cursor_col = col;
self.focus_pane(Pane::Editor);
self.request_type_definition_at_cursor();
}
MenuAction::GoToImplementationAt { row, col } => {
self.editor.cursor_row = row;
self.editor.cursor_col = col;
self.focus_pane(Pane::Editor);
self.request_implementation_at_cursor();
}
MenuAction::QuickFixAt { row, col } => {
self.editor.collapse_carets();
self.editor.cursor_row = row;
self.editor.cursor_col = col;
self.focus_pane(Pane::Editor);
self.start_code_action();
}
MenuAction::GoToReferencesAt { row, col } => {
self.editor.cursor_row = row;
self.editor.cursor_col = col;
self.focus_pane(Pane::Editor);
self.request_references_at_cursor();
}
MenuAction::GoToLocation { path, line, col } => {
self.go_to_definition(path, line, col);
}
MenuAction::ToggleBreakpointAt { line } => {
self.focus_pane(Pane::Editor);
self.debug_toggle_breakpoint_line(line);
}
MenuAction::EditBreakpointConditionAt { line } => {
self.focus_pane(Pane::Editor);
self.debug_edit_condition_line(line);
}
MenuAction::EditLogpointAt { line } => {
self.focus_pane(Pane::Editor);
self.debug_edit_logpoint_line(line);
}
MenuAction::AskNavigatorAt { line } => {
self.focus_pane(Pane::Editor);
self.open_ask_navigator((line, line), String::new());
}
MenuAction::AskNavigatorSelection { start, end } => {
self.focus_pane(Pane::Editor);
let selection = self.editor.selection_text();
self.open_ask_navigator((start, end), selection);
}
MenuAction::AskNavigatorAboutCapture => self.ask_navigator_about_capture(),
MenuAction::FixProblemWithNavigator { path, item } => {
self.fix_problem_with_navigator(path, item, Vec::new());
}
MenuAction::ShowCallsAt { row, col, incoming } => {
self.editor.cursor_row = row;
self.editor.cursor_col = col;
self.focus_pane(Pane::Editor);
self.request_call_hierarchy_at_cursor(incoming);
}
MenuAction::OpenThemePicker => self.open_theme_picker(),
MenuAction::SetTheme(theme) => self.apply_theme(theme),
MenuAction::ToggleExplorerView(view) => self.toggle_explorer_view(view),
MenuAction::OpenCustomizeLayout => self.open_customize_layout_menu(),
MenuAction::ToggleActivityBar => {
self.activity_bar_visible = !self.activity_bar_visible;
// The bar is a structural auto-hide suppression, and unlike Zen
// it flips here on its own. A pending collapse armed against the
// old chrome would otherwise sit armed while `allowed()` declines
// for it, then fire on the first idle tick after the bar comes
// back, with no focus move of the user's own.
//
// Cancel the collapse. And when the bar goes AWAY, drop the pin
// too — for the reason `toggle_side_bar` already refuses to bank
// one in that state: no collapse can fire while the bar is
// hidden, so a pin held across that period is unconsumable, and
// it silently eats the first real collapse after the bar
// returns. Those two sites disagreed about the same question
// until this line; the bank-time answer is the right one.
//
// Revealing the bar leaves any pin alone: a pin banked while the
// bar is visible belongs to a reveal that can still be honoured.
self.sidebar_dwell.disarm();
if !self.activity_bar_visible {
self.sidebar_pinned_open = false;
}
self.persist_layout();
self.after_chrome_visibility_change();
self.open_customize_layout_menu_on(&MenuAction::ToggleActivityBar);
}
MenuAction::ToggleSideBar => {
self.toggle_side_bar();
self.after_chrome_visibility_change();
self.open_customize_layout_menu_on(&MenuAction::ToggleSideBar);
}
MenuAction::ToggleAutoHideSideBar => {
self.toggle_sidebar_auto_hide();
self.open_customize_layout_menu_on(&MenuAction::ToggleAutoHideSideBar);
}
MenuAction::ToggleSecondarySideBar => {
self.toggle_secondary_side_bar();
self.open_customize_layout_menu_on(&MenuAction::ToggleSecondarySideBar);
}
MenuAction::TogglePanel => {
self.toggle_terminal();
self.open_customize_layout_menu_on(&MenuAction::TogglePanel);
}
MenuAction::ToggleStatusBar => {
self.status_bar_visible = !self.status_bar_visible;
self.persist_layout();
self.after_chrome_visibility_change();
self.open_customize_layout_menu_on(&MenuAction::ToggleStatusBar);
}
MenuAction::SetSideBarPosition(pos) => {
self.side_bar_position = pos;
self.persist_layout();
self.after_chrome_visibility_change();
self.open_customize_layout_menu_on(&MenuAction::SetSideBarPosition(pos));
}
MenuAction::SetPanelAlignment(al) => {
self.panel_alignment = al;
self.persist_layout();
self.open_customize_layout_menu_on(&MenuAction::SetPanelAlignment(al));
}
MenuAction::SetQuickInputPosition(pos) => {
self.quick_input_position = pos;
self.persist_layout();
self.open_customize_layout_menu_on(&MenuAction::SetQuickInputPosition(pos));
}
MenuAction::ToggleZenMode => self.toggle_zen_mode(),
MenuAction::RenameTerminal(idx) => self.begin_rename_terminal(idx),
MenuAction::ClearTerminal(idx) => self.clear_terminal_at(idx),
MenuAction::TerminalCopySelection => self.copy_terminal_selection(),
MenuAction::TerminalPaste => self.paste_clipboard_into_terminal(),
MenuAction::TerminalQuickSelect => self.open_terminal_quick_select(),
MenuAction::TerminalCopyMode => self.open_terminal_copy_mode(),
MenuAction::TerminalCommandHistory => self.open_command_history(),
MenuAction::OpenScrollbackInEditor => self.open_scrollback_in_editor(),
MenuAction::ToggleBroadcastInput => self.toggle_broadcast_input(),
MenuAction::ToggleBroadcastExclusion => self.toggle_broadcast_exclusion(),
MenuAction::UndoCloseTerminal => self.undo_close_terminal(),
MenuAction::CopyCommandOutput(idx, d) => self.copy_command_output(idx, d),
MenuAction::SelectCommandOutput(idx, d) => self.select_command_output(idx, d),
MenuAction::RerunCommand(idx, d) => self.rerun_command(idx, d),
MenuAction::ToggleMaximizeTerminal(idx) => {
if !self.terminal_pane_maximized {
self.active_terminal = idx;
}
self.toggle_terminal_pane_maximize();
}
MenuAction::ToggleCollapseTerminal(idx) => self.toggle_terminal_collapse(idx),
MenuAction::NewTerminalWithProfile(shell) => {
let label = std::path::Path::new(&shell)
.file_name()
.and_then(|s| s.to_str())
.unwrap_or(&shell)
.to_string();
match self.split_terminal_with_shell(&shell) {
Ok(()) => self.status = format!("Opened {label} terminal"),
Err(e) => self.status = format!("New terminal failed: {e}"),
}
}
MenuAction::ToggleMinimap => self.toggle_minimap(),
MenuAction::SetMinimapSide(side) => {
self.minimap_side = side;
// The strip jumps columns: evict the old placement so it
// doesn't ghost, and force a rebake at the new position.
self.disable_minimap_image();
}
MenuAction::SetLanguage(lang) => {
self.editor.set_language(lang);
self.status = format!("Language Mode: {}", self.editor.language_label());
}
MenuAction::SetLineEnding(eol) => {
if self.editor.eol != eol {
self.editor.eol = eol;
// The content is unchanged but the on-disk bytes will differ:
// mark dirty so the user saves to apply the new EOL.
self.editor.dirty = true;
}
self.status = format!("End of Line: {}", eol.label());
}
MenuAction::SetEncoding(enc) => {
// Reopening re-reads the file over the buffer and clears both
// history stacks, so unsaved work would be gone with no way
// back through Cmd+Z. The encoding segment sits a few cells
// from the Ln/Col readout in the status bar, and picking the
// encoding already in use looks like a no-op, so this is easy
// to hit by accident. Never discard on its behalf.
if self.editor.dirty {
// Deliberately NOT "save first": the buffer may be showing
// mojibake precisely because it was decoded wrongly, and
// saving writes those replacement characters over the
// original bytes. Undoing is the one route that loses
// nothing on either side.
self.status = String::from(
"Reopen with Encoding replaces the buffer from disk. Undo your unsaved changes first (Cmd+Z), or copy them elsewhere.",
);
} else {
match self.editor.reopen_with_encoding(enc) {
Ok(()) => self.status = format!("Reopened with {}", enc.name()),
Err(e) => self.status = format!("Reopen failed: {e}"),
}
}
}
MenuAction::SetIndentStyle(style) => {
self.editor.set_indent_style(style);
self.status = style.label();
}
MenuAction::ConvertIndentation(to_spaces) => {
if to_spaces {
self.editor.indentation_to_spaces();
self.status = String::from("Converted indentation to spaces");
} else {
self.editor.indentation_to_tabs();
self.status = String::from("Converted indentation to tabs");
}
}
}
}
/// Cmd+K W / tab context "Close All": close every tab in EVERY editor
/// group, not just the focused one, collapsing any split back to a single
/// blank pane. A side-by-side layout (e.g. `cgr duplicates` diffs) would
/// otherwise only empty the clicked group and look like a single close
/// once the blank group collapsed away.
fn close_all_tabs(&mut self) {
let mut removed = self.editor.close_all();
if self.editor_layout.is_split() {
removed += self
.editor_layout
.inactive_groups()
.iter()
.map(|g| g.editors.len())
.sum::<usize>();
self.editor_layout = editor_layout::EditorLayout::single();
self.editor_seams.clear();
self.disable_editor_image(1);
self.sync_focus_flags();
}
self.sync_open_file_poll_mtime();
self.status = if removed == 1 {
String::from("Closed 1 tab")
} else {
format!("Closed {removed} tabs")
};
self.poke_cursor();
}
/// Close every saved (non-dirty) editor tab, keeping any with unsaved
/// changes. Shared by the tab context menu and the `Cmd+K U` chord so both
/// surfaces produce the same status line and split-collapse behavior.
fn close_saved_tabs(&mut self) {
let removed = self.editor.close_saved();
if removed == 0 {
self.status = String::from("No saved tabs to close");
return;
}
self.sync_open_file_poll_mtime();
self.status = if removed == 1 {
String::from("Closed 1 saved tab")
} else {
format!("Closed {removed} saved tabs")
};
self.poke_cursor();
self.collapse_split_if_empty();
}
/// Copy `path` (an editor tab's absolute path) to the system clipboard via
/// the NSPasteboard-first wrapper (OSC 52 fallback on a remote host). Shared
/// by the tab context menu and the `Cmd+Opt+C` chord. Matches VS Code's
/// "Copy Path".
fn copy_path_to_clipboard(&mut self, path: PathBuf) {
let text = path.display().to_string();
self.status = if copy_to_clipboard(&text) {
format!("Copied path: {text}")
} else {
String::from("Could not copy path to clipboard")
};
}
/// VS Code "Copy Relative Path": copy `path` relative to the workspace
/// root. Files outside the root (rare: a tab opened by absolute path above
/// the workspace) fall back to the absolute path so the clipboard never
/// holds a misleading `../../` walk or an empty string.
fn copy_relative_path_to_clipboard(&mut self, path: PathBuf) {
let text = relative_clipboard_text(&path, self.workspace_root());
self.status = if copy_to_clipboard(&text) {
format!("Copied relative path: {text}")
} else {
String::from("Could not copy path to clipboard")
};
}
/// Reveal `path` (an editor tab's file) in the Explorer tree: switch the
/// side bar to the Explorer, expand the file's parent folders, select its
/// row, and focus the tree. Shared by the tab context menu and the
/// `Cmd+K E` chord. Matches VS Code's "Reveal in Explorer View".
fn reveal_in_explorer(&mut self, path: PathBuf) {
self.set_sidebar_view(SidebarView::Explorer);
// A sidebar-targeting command must work even with the sidebar hidden
// (#260). `set_sidebar_view` above already forced it open and focuses
// the tree, so nothing further is required here.
let found = self.tree.reveal_path(&path);
self.focus_pane(Pane::Tree);
self.status = if found {
let name = path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| path.display().to_string());
format!("Revealed {name} in Explorer")
} else {
String::from("File is outside the workspace")
};
}
/// Reveal `path` in macOS Finder by spawning `open -R`, which selects the
/// entry inside its containing folder. Fire-and-forget: `open` hands off to
/// LaunchServices and returns immediately, so the TUI never blocks. Only
/// reachable on a local macOS session because `maybe_add_reveal_in_finder`
/// withholds the menu entry everywhere else; the `cfg` guard keeps the call
/// out of non-macOS builds entirely.
fn reveal_in_finder(&mut self, path: PathBuf) {
#[cfg(target_os = "macos")]
{
self.status = if std::process::Command::new("open")
.arg("-R")
.arg(&path)
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()
.is_ok()
{
String::from("Revealed in Finder")
} else {
String::from("Could not reveal in Finder")
};
}
#[cfg(not(target_os = "macos"))]
{
let _ = path;
}
}
/// The editor group occupying physical column `side` (0 = left,
/// 1 = right). When not split only side 0 exists. `editor` is always
/// the active group, so which physical column it sits in depends on the
/// active leaf's depth-first index in `editor_layout`.
fn group_on_side(&self, side: usize) -> Option<&EditorTabs> {
// Physical column maps directly to depth-first leaf index only in
// the two-column layout. Every other layout - unsplit, or a grid of
// three or more groups - bakes the ACTIVE group into slot 0 and
// leaves slot 1 dark (see the render path), the same clamp
// `focused_image_side` applies: resolving by DFS position here made
// the image gate and the layout key read one group while the baked
// pixels came from another.
if self.editor_layout.leaf_count() != 2 {
return (side == 0).then_some(&self.editor);
}
// The active group is hoisted into `self.editor`.
if side == self.editor_layout.active_dfs_index() {
Some(&self.editor)
} else {
self.editor_layout.group_ref_at_dfs(side)
}
}
/// Step the focused PDF preview by `delta` pages, wrapping at the
/// document ends. The overlay re-bakes on its own (the page is part of
/// its re-emit key). Deliberate gestures only - arrows, menu; the wheel
/// goes through [`Self::wheel_pdf_page`].
fn step_pdf_page(&mut self, delta: i32) {
self.editor.change_pdf_page(delta);
}
/// Wheel paging for the PDF preview. Differs from the key path twice
/// over: it clamps at the document ends (no scroll wheel wraps a PDF),
/// and a same-direction repeat inside the cooldown is dropped - every
/// page step is a synchronous rasteriser run on the UI thread, so a
/// momentum flick's burst of wheel events must coalesce instead of
/// freezing the TUI for one render per event. A reversal is deliberate
/// and always passes.
fn wheel_pdf_page(&mut self, delta: i32) {
const COOLDOWN: std::time::Duration = std::time::Duration::from_millis(150);
let doc = self.editor.path.clone();
if let Some((at, dir, last_doc)) = &self.last_pdf_wheel
&& *dir == delta.signum()
&& *last_doc == doc
&& at.elapsed() < COOLDOWN
{
return;
}
let Some(cur) = self.editor.pdf_page() else {
return;
};
let target = if delta >= 0 {
cur.saturating_add(delta as u32)
} else {
cur.saturating_sub(delta.unsigned_abs()).max(1)
};
self.editor.set_pdf_page(target);
// Stamped AFTER the rasterise: the flick's remaining events queued
// while the render ran, so a stamp taken at entry had already aged
// by the render's duration when they were processed — a render
// slower than the cooldown let every queued event through, one
// blocking render each.
self.last_pdf_wheel = Some((std::time::Instant::now(), delta.signum(), doc));
}
fn jump_pdf_page(&mut self, page: u32) {
self.editor.set_pdf_page(page);
}
/// Resolve the PDF link under a click at screen cell (`col`, `row`) on
/// the focused PDF preview, extracting the current page's link regions
/// on first use (and caching them on the tab until the page changes).
fn pdf_link_target_at(&mut self, col: u16, row: u16) -> Option<crate::pdf::LinkTarget> {
let side = self.focused_image_side();
let (cw_px, ch_px) = self.cell_pixel?;
let frac = {
let image = self.editor.image.as_ref()?;
let pdf = image.pdf.as_ref()?;
let layout = self.overlays.editor[side].layout()?;
// A stale overlay (different tab, or a page flip the next frame
// hasn't baked yet) must not hit-test the wrong page's geometry.
if layout.path != pdf.source_path || layout.page != pdf.current_page {
return None;
}
crate::iterm2_inline::cell_source_fraction(
(
col.checked_sub(layout.cell_x)?,
row.checked_sub(layout.cell_y)?,
),
(cw_px, ch_px),
(layout.cell_w, layout.cell_h),
(image.pixel_w, image.pixel_h),
)?
};
let pdf = self.editor.image.as_mut()?.pdf.as_mut()?;
if pdf.links.is_none() {
match crate::pdf::page_links(&pdf.source_path, pdf.current_page) {
Ok(links) => pdf.links = Some(links),
// Not cached: a mid-write extraction failure (pdflatex
// rebuilding the file) heals on the next click.
Err(e) => {
self.status = format!("PDF links unavailable: {e}");
return None;
}
}
}
Some(pdf.links.as_ref()?.link_at(frac)?.target.clone())
}
fn focused_image_side(&self) -> usize {
// There are physically two overlay slots (left/right column), and
// only the two-column split keys them by group: every other layout -
// unsplit, or a grid of three or more groups - bakes the active
// group into slot 0 (see the render path). Indexing by DFS position
// here panicked on a PDF click in the third group of a grid.
if self.editor_layout.leaf_count() == 2 {
self.editor_layout.active_dfs_index()
} else {
0
}
}
/// Re-bake both editor image slots on the next render. Used when a
/// full-screen modal that covered both panes closes.
fn invalidate_editor_image_layouts(&mut self) {
self.overlays.editor[0].invalidate_layout();
self.overlays.editor[1].invalidate_layout();
}
/// Bake an OSC-1337 inline-image escape sized to one editor column so
/// the active image tab can be painted on top of ratatui's text
/// buffer. `side` selects the physical column (and the overlay slot).
/// Skipped when that column's active tab is text or when the host
/// terminal can't render inline images (Terminal.app, raw SSH); in
/// those cases the metadata header line painted by the editor widget
/// is the entire preview the user sees.
fn update_editor_image_overlay(&mut self, side: usize, editor_area: Rect) {
// Cheap pre-checks that don't touch the (large) image bytes, so
// the common per-frame path skips the clone+bake entirely.
if self.group_on_side(side).is_none_or(|g| g.image.is_none()) {
self.disable_editor_image(side);
return;
}
let Some(path) = self.group_on_side(side).and_then(|g| g.path.clone()) else {
self.disable_editor_image(side);
return;
};
if !self.inline_images_enabled() {
self.disable_editor_image(side);
return;
}
let Some((cw_px, ch_px)) = self.cell_pixel else {
return;
};
// The editor widget paints its own 1-cell border + a 1-row header
// strip; the EditorTabs widget paints a 1-row tab strip above
// that. Carve those off before baking the image so the OSC
// doesn't bleed over the labels.
let tab_strip = 1u16;
let border = 1u16;
let header = 1u16;
if editor_area.height < tab_strip + 2 * border + header + 2
|| editor_area.width < 2 * border + 4
{
self.disable_editor_image(side);
return;
}
let cell_x = editor_area.x + border;
let cell_y = editor_area.y + tab_strip + border + header;
let cell_w = editor_area.width.saturating_sub(2 * border);
let cell_h = editor_area
.height
.saturating_sub(tab_strip + 2 * border + header);
let desired = EditorImageLayout {
cell_x,
cell_y,
cell_w,
cell_h,
path,
page: self
.group_on_side(side)
.and_then(|g| g.image.as_ref())
.and_then(|i| i.pdf.as_ref())
.map_or(1, |p| p.current_page),
generation: self
.group_on_side(side)
.and_then(|g| g.image.as_ref())
.map_or(0, |i| i.generation),
};
// The cell-buffer protocols (iTerm2 OSC-1337, Sixel) have no
// z-layer, so the post-frame image blit would overpaint an open
// context menu (Kitty puts the image at deep-negative z instead).
// Hold the overlay cleared while a menu overlaps it; the layout
// was invalidated, so the first frame after the menu closes or
// moves off re-bakes the picture.
if self.context_menu_covers_rect(Rect {
x: cell_x,
y: cell_y,
width: cell_w,
height: cell_h,
}) {
self.overlays.editor[side].request_clear_if_displayed();
self.overlays.editor[side].invalidate_layout();
return;
}
// Skip the bake when nothing about the layout changed - this is
// the hot path on every frame an image is on screen.
if self.overlays.editor[side].layout_matches(&desired) {
return;
}
self.overlays.editor[side].request_clear_if_displayed();
let canvas_w = cell_w as u32 * cw_px;
let canvas_h = cell_h as u32 * ch_px;
let bg = self.theme_bg_pixel();
// The bytes come from the same `group_on_side` resolution the gate
// and the layout key above used, so all three always describe one
// group; the borrow ends at the last use inside the bake, before we
// store into the slot.
let baked = {
let Some(image) = self.group_on_side(side).and_then(|g| g.image.as_ref()) else {
return;
};
crate::iterm2_inline::fit_image_auto(&image.bytes, canvas_w, canvas_h, bg)
};
if let Ok(baked) = baked
&& let Some(raw) = crate::iterm2_inline::build_inline_image_z(
self.inline_protocol,
&baked,
cell_w,
cell_h,
false,
crate::iterm2_inline::KITTY_ID_EDITOR_BASE + side as u32,
// Below text and below non-default background cells, so a
// right-click menu or any other opaque popup paints fully on
// top. The preview still shows: on Kitty the editor widget
// keeps its canvas at the DEFAULT bg (`image_canvas_bg`),
// which this z stays above — an explicit canvas fill would
// paint over the picture. Same placement the sidebar
// illustrations use.
crate::iterm2_inline::KITTY_Z_BELOW_TEXT_AND_BG,
)
{
let osc = crate::iterm2_inline::maybe_tmux_wrap(
self.inline_protocol,
crate::iterm2_inline::detect_tmux(),
raw,
);
self.overlays.editor[side].set(osc, desired);
}
}
fn disable_editor_image(&mut self, side: usize) {
self.overlays.editor[side].disable();
}
/// Returns true if the cached editor-image cells need to be repainted
/// by ratatui this frame (because the user closed/switched away from
/// the image, or the layout changed). Called from the main loop to
/// force a full redraw before re-emitting. ORs both split slots and
/// consumes BOTH latches (never short-circuits).
pub fn consume_editor_image_clear(&mut self) -> bool {
let left = self.overlays.editor[0].consume_clear();
let right = self.overlays.editor[1].consume_clear();
left || right
}
pub fn editor_image_payload(&self, side: usize) -> Option<(&str, &EditorImageLayout)> {
if self.shortcuts_modal.is_some()
|| self.file_finder.is_some()
|| self.command_palette.is_some()
|| self.go_to_symbol.is_some()
|| self.workspace_symbols.is_some()
|| self.process_picker.is_some()
|| self.zoxide_jump.is_some()
|| self.command_history_popup.is_some()
|| self.branch_picker.is_some()
|| self.input_prompt.is_some()
|| self.list_picker.is_some()
{
return None;
}
self.overlays.editor[side].payload()
}
pub fn mark_editor_image_displayed(&mut self, side: usize) {
self.overlays.editor[side].mark_displayed();
}
/// Bake the active terminal pane's newest captured inline image (imgcat
/// / OSC 1337) into an overlay anchored at its grid row. One slot: older
/// images scroll away like text, and only the active pane shows its
/// picture (focus a pane to see what it printed). alacritty never
/// reserved grid rows for the image, so it floats above any text
/// printed after it — the honest best without forking the engine.
fn update_terminal_image_overlay(&mut self) {
if !self.show_terminal
|| self.bottom_panel_tab != BottomPanelTab::Terminal
|| !self.inline_images_enabled()
{
self.disable_terminal_image();
return;
}
let Some((cw_px, ch_px)) = self.cell_pixel else {
return;
};
let idx = self.active_terminal;
let Some(t) = self.terminals.get(idx) else {
self.disable_terminal_image();
return;
};
let inner = t.last_inner;
// The floors below reject a pane the last frame did not paint ONLY
// because the pane-skip site zeroes `last_inner` first (#510). They
// are magnitude checks, not freshness checks: a pane painted at a
// real size that then stops being painted keeps a full-size rect and
// passes both. That was the bug. Delete the clear and these floors
// will not catch it.
if t.alt_screen() || inner.width < 6 || inner.height < 3 {
self.disable_terminal_image();
return;
}
let Some(img) = t.pane_images().pop() else {
self.disable_terminal_image();
return;
};
// Anchor row in the viewport; off-screen anchors hide the picture.
let vp = img.line + t.scroll_display_offset();
if vp < 0 || vp >= inner.height as i32 {
self.disable_terminal_image();
return;
}
// Image pixels → cells, shrunk (never grown) to fit the pane below
// the anchor. Reading dimensions only decodes the header.
let Ok(Some((px_w, px_h))) =
image::ImageReader::new(std::io::Cursor::new(img.data.as_slice()))
.with_guessed_format()
.map(|r| r.into_dimensions().ok())
else {
self.disable_terminal_image();
return;
};
let want_w = (px_w.div_ceil(cw_px)).max(1) as f32;
let want_h = (px_h.div_ceil(ch_px)).max(1) as f32;
let max_w = (inner.width - 2) as f32;
let max_h = ((inner.height as i32 - vp).max(1) as f32).min(inner.height as f32 - 1.0);
let scale = (max_w / want_w).min(max_h / want_h).min(1.0);
let cell_w = ((want_w * scale) as u16).max(1);
let cell_h = ((want_h * scale) as u16).max(1);
let desired = TerminalImageLayout {
cell_x: inner.x,
cell_y: inner.y + vp as u16,
cell_w,
cell_h,
seq: img.seq,
pane: idx,
};
// An open right-click menu over the picture wins on the protocols
// whose post-frame blit would erase the overlapped menu rows
// (iTerm2/Sixel; Kitty solves this with the below-text z instead).
// The editor preview applies the same rule.
if self.context_menu_covers_rect(Rect {
x: desired.cell_x,
y: desired.cell_y,
width: desired.cell_w,
height: desired.cell_h,
}) {
self.overlays.terminal_image.request_clear_if_displayed();
self.overlays.terminal_image.invalidate_layout();
return;
}
// Hot path: unchanged layout means nothing to rebake and no latch.
if self.overlays.terminal_image.layout_matches(&desired) {
return;
}
// A pure anchor move (output scrolled, viewport scrolled) keeps the
// baked payload: same picture, same cell size, same protocol — only
// the placement row changed. Re-running the decode + resize +
// encode of a full-resolution photo per scrolled row stalled the
// render thread for the whole pane height.
let reusable = self.overlays.terminal_image.has_image()
&& self.overlays.terminal_image.layout().is_some_and(|l| {
l.seq == desired.seq
&& l.pane == desired.pane
&& l.cell_w == desired.cell_w
&& l.cell_h == desired.cell_h
});
self.overlays.terminal_image.request_clear_if_displayed();
if reusable {
self.overlays.terminal_image.set_layout(desired);
return;
}
let bg = self.theme_bg_pixel();
let baked = crate::iterm2_inline::fit_image_auto(
&img.data,
cell_w as u32 * cw_px,
cell_h as u32 * ch_px,
bg,
);
if let Ok(baked) = baked
&& let Some(raw) = crate::iterm2_inline::build_inline_image_z(
self.inline_protocol,
&baked,
cell_w,
cell_h,
true,
crate::iterm2_inline::KITTY_ID_TERMINAL,
// Below text and non-default background cells: the pane's
// default-bg cells are Color::Reset so the picture shows,
// while an opaque popup (the right-click menu) paints fully
// on top. Same placement the editor preview uses.
crate::iterm2_inline::KITTY_Z_BELOW_TEXT_AND_BG,
)
{
let osc = crate::iterm2_inline::maybe_tmux_wrap(
self.inline_protocol,
crate::iterm2_inline::detect_tmux(),
raw,
);
self.overlays.terminal_image.set(osc, desired);
}
}
fn disable_terminal_image(&mut self) {
self.overlays.terminal_image.disable();
}
fn disable_markdown_image(&mut self) {
self.overlays.markdown_image.disable();
}
/// See [`Self::consume_editor_image_clear`]; the markdown twin.
pub fn consume_markdown_image_clear(&mut self) -> bool {
self.overlays.markdown_image.consume_clear()
}
pub fn mark_markdown_image_displayed(&mut self) {
self.overlays.markdown_image.mark_displayed();
}
/// The markdown-preview image escape to flush this frame; same modal
/// gate as the terminal pane picture.
pub fn markdown_image_payload(&self) -> Option<(&str, &MarkdownImageLayout)> {
if self.shortcuts_modal.is_some()
|| self.file_finder.is_some()
|| self.command_palette.is_some()
|| self.go_to_symbol.is_some()
|| self.workspace_symbols.is_some()
|| self.process_picker.is_some()
|| self.zoxide_jump.is_some()
|| self.command_history_popup.is_some()
|| self.branch_picker.is_some()
|| self.input_prompt.is_some()
|| self.list_picker.is_some()
{
return None;
}
self.overlays.markdown_image.payload()
}
/// Bake/refresh the markdown preview's inline image (#176): the
/// TOPMOST reserved block whose anchor row is on screen paints; a
/// bake is keyed on (path, mtime, fitted cells) and a pure scroll
/// reuses the payload (the terminal-pane picture's contract).
fn update_markdown_image_overlay(&mut self) {
if !self.inline_images_enabled() {
self.disable_markdown_image();
return;
}
let Some((cw_px, ch_px)) = self.cell_pixel else {
return;
};
let Some(md) = self.editor.markdown_preview.as_ref() else {
self.disable_markdown_image();
return;
};
let area = md.last_area;
let viewport_rows = self.editor.last_inner.height;
if area.width < 6 || viewport_rows < 3 || md.images.is_empty() {
self.disable_markdown_image();
return;
}
let scroll = md.scroll as usize;
let Some((img, anchor_row)) = md
.images
.iter()
.zip(md.anchor_rows.iter())
.find(|&(_, &row)| row >= scroll && row - scroll < viewport_rows as usize)
.map(|(i, &r)| (i.clone(), r))
else {
self.disable_markdown_image();
return;
};
let Ok(meta) = std::fs::metadata(&img.path) else {
self.disable_markdown_image();
return;
};
let mtime_ms = meta
.modified()
.ok()
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map(|d| d.as_millis())
.unwrap_or(0);
let Ok((px_w, px_h)) = image::image_dimensions(&img.path) else {
self.disable_markdown_image();
return;
};
let vp = (anchor_row - scroll) as u16;
let want_w = (px_w.div_ceil(cw_px)).max(1) as f32;
let want_h = (px_h.div_ceil(ch_px)).max(1) as f32;
let max_w = area.width.saturating_sub(2) as f32;
let max_h = (img.rows.min(viewport_rows.saturating_sub(vp))).max(1) as f32;
let scale = (max_w / want_w).min(max_h / want_h).min(1.0);
let cell_w = ((want_w * scale) as u16).max(1);
let cell_h = ((want_h * scale) as u16).max(1);
let desired = MarkdownImageLayout {
cell_x: area.x,
cell_y: area.y + vp,
cell_w,
cell_h,
path: img.path.clone(),
mtime_ms,
};
if self.context_menu_covers_rect(Rect {
x: desired.cell_x,
y: desired.cell_y,
width: desired.cell_w,
height: desired.cell_h,
}) {
self.overlays.markdown_image.request_clear_if_displayed();
self.overlays.markdown_image.invalidate_layout();
return;
}
if self.overlays.markdown_image.layout_matches(&desired) {
return;
}
let reusable = self.overlays.markdown_image.has_image()
&& self.overlays.markdown_image.layout().is_some_and(|l| {
l.path == desired.path
&& l.mtime_ms == desired.mtime_ms
&& l.cell_w == desired.cell_w
&& l.cell_h == desired.cell_h
});
self.overlays.markdown_image.request_clear_if_displayed();
if reusable {
self.overlays.markdown_image.set_layout(desired);
return;
}
let Ok(bytes) = std::fs::read(&img.path) else {
self.disable_markdown_image();
return;
};
let bg = self.theme_bg_pixel();
let baked = crate::iterm2_inline::fit_image_auto(
&bytes,
cell_w as u32 * cw_px,
cell_h as u32 * ch_px,
bg,
);
if let Ok(baked) = baked
&& let Some(raw) = crate::iterm2_inline::build_inline_image_z(
self.inline_protocol,
&baked,
cell_w,
cell_h,
true,
crate::iterm2_inline::KITTY_ID_MARKDOWN,
crate::iterm2_inline::KITTY_Z_BELOW_TEXT_AND_BG,
)
{
let osc = crate::iterm2_inline::maybe_tmux_wrap(
self.inline_protocol,
crate::iterm2_inline::detect_tmux(),
raw,
);
self.overlays.markdown_image.set(osc, desired);
}
}
/// See [`Self::consume_editor_image_clear`]; the terminal-image twin.
pub fn consume_terminal_image_clear(&mut self) -> bool {
self.overlays.terminal_image.consume_clear()
}
/// The pane image escape to flush this frame, gated off while any modal
/// popup is up so the picture never paints over it.
pub fn terminal_image_payload(&self) -> Option<(&str, &TerminalImageLayout)> {
if self.shortcuts_modal.is_some()
|| self.file_finder.is_some()
|| self.command_palette.is_some()
|| self.go_to_symbol.is_some()
|| self.workspace_symbols.is_some()
|| self.process_picker.is_some()
|| self.zoxide_jump.is_some()
|| self.command_history_popup.is_some()
|| self.branch_picker.is_some()
|| self.input_prompt.is_some()
|| self.list_picker.is_some()
{
return None;
}
self.overlays.terminal_image.payload()
}
pub fn mark_terminal_image_displayed(&mut self) {
self.overlays.terminal_image.mark_displayed();
}
/// Bake/recomposite the editor minimap for `strip` (the text-aligned image
/// rect on the chosen edge). Mirrors `update_editor_image_overlay`: the
/// expensive whole-file raster is cached in `minimap_base` and only rebuilt
/// when its signature (content / size / theme) changes; scrolling reuses the
/// raster and just recomposites the viewport box. The per-frame hot path
/// early-returns at `layout_matches` before any allocation.
fn update_minimap_overlay(&mut self, strip: Rect) {
if !self.minimap_visible || !self.inline_images_enabled() {
self.disable_minimap_image();
return;
}
let Some((cw_px, ch_px)) = self.cell_pixel else {
self.disable_minimap_image();
return;
};
if strip.width == 0 || strip.height == 0 {
self.disable_minimap_image();
return;
}
// The raster is emitted at Kitty z=0 after ratatui's diff, so anything
// ratatui paints over the strip gets painted back over every frame.
// Only a menu that actually reaches the strip may evict it: arming the
// clear latch for every right-click anywhere would wipe and repaint the
// whole screen on the cell-buffer protocols. The layout is kept, so the
// raster comes back without a rebake once the menu closes.
self.minimap_img_rect = strip;
if self.menu_covers(strip) {
self.overlays.minimap.hide_and_request_clear();
return;
}
let cell_w = strip.width;
let cell_h = strip.height;
let bg = self.theme.editor_bg_rgb();
let top = self.editor.scroll;
let rows = self.editor.visible_rows();
let total = self.editor.lines.len();
let edit_seq = self.editor.edit_seq;
let selection = self.editor.selection_rows();
let desired = MinimapLayout {
cell_x: strip.x,
cell_y: strip.y,
cell_w,
cell_h,
top,
rows,
total,
edit_seq,
side: self.minimap_side,
bg,
selection,
};
if self.overlays.minimap.layout_matches(&desired) {
return;
}
// Only a moved or resized strip needs the full-screen eviction (image
// cells outside the new rect would ghost). A content-only change
// (edit, scroll, selection, theme) re-emits over the SAME cells - the
// fixed Kitty id / same-cell OSC-1337 emit replaces the image in
// place - so it must NOT arm the clear: that `2J` + full redraw is a
// whole-app blink on every keystroke over an SSH round trip.
let placement_moved = self.overlays.minimap.layout().is_none_or(|prev| {
(prev.cell_x, prev.cell_y, prev.cell_w, prev.cell_h)
!= (
desired.cell_x,
desired.cell_y,
desired.cell_w,
desired.cell_h,
)
});
if placement_moved {
self.overlays.minimap.request_clear_if_displayed();
}
// Cold path only: clone the path into the rebake signature.
let canvas_w = cell_w as u32 * cw_px;
let canvas_h = cell_h as u32 * ch_px;
// Cap each line's height so a short file stays a compact sliver at the
// top rather than stretching down the whole strip; a file long enough
// to fill the strip naturally reaches `canvas_h` and is unaffected.
let content_h = (total as u32 * MINIMAP_MAX_LINE_PX).min(canvas_h).max(1);
self.minimap_content_h = content_h;
// Luminance picks the default text color and the viewport tint so the
// box reads on either theme.
let light = 0.299 * bg.0 as f32 + 0.587 * bg.1 as f32 + 0.114 * bg.2 as f32 > 140.0;
let sig = (self.editor.path.clone(), edit_seq, canvas_w, canvas_h, bg);
if self.minimap_base.as_ref().map(|b| &b.sig) != Some(&sig) {
let fg = if light {
(0x38, 0x3a, 0x41)
} else {
(0xc5, 0xcd, 0xd9)
};
let rgba = self
.editor
.minimap_rgba(canvas_w, canvas_h, content_h, bg, fg);
self.minimap_base = Some(MinimapBase {
rgba,
w: canvas_w,
h: canvas_h,
sig,
});
}
let Some(base) = self.minimap_base.as_ref() else {
return;
};
let composited = composite_minimap_viewport(
&base.rgba,
base.w,
base.h,
MinimapOverlay {
top,
rows,
total,
light,
selection,
sel_rgb: self.theme.selection_rgb(),
content_h,
},
);
let (bw, bh) = (base.w, base.h);
let Some(png) = rgba_to_png(composited, bw, bh) else {
return;
};
if let Some(raw) = crate::iterm2_inline::build_inline_image(
self.inline_protocol,
&png,
cell_w,
cell_h,
false,
crate::iterm2_inline::KITTY_ID_MINIMAP,
) {
let osc = crate::iterm2_inline::maybe_tmux_wrap(
self.inline_protocol,
crate::iterm2_inline::detect_tmux(),
raw,
);
self.overlays.minimap.set(osc, desired);
}
}
fn disable_minimap_image(&mut self) {
self.overlays.minimap.disable();
self.minimap_img_rect = Rect::default();
}
/// Show/hide the editor minimap (⌥⌘M, the minimap right-click menu, the
/// Customize Layout menu, and the "View: Toggle Minimap" palette command
/// all route here). Hiding evicts the cached strip image so it can't ghost.
fn toggle_minimap(&mut self) {
self.minimap_visible = !self.minimap_visible;
if !self.minimap_visible {
self.disable_minimap_image();
}
self.status = if self.minimap_visible {
String::from("Minimap on")
} else {
String::from("Minimap off")
};
}
/// Carve the minimap strip off `editor_area` when the minimap is on (v1:
/// unsplit, image-capable terminals, enough width). Returns
/// `(editor_rect, full_strip, image_rect)`: the editor renders into
/// `editor_rect`, the whole `full_strip` column is bg-filled, and the
/// raster image occupies `image_rect` (aligned to the editor's text rows).
fn carve_minimap(&self, editor_area: Rect) -> Option<(Rect, Rect, Rect)> {
if !self.minimap_visible
|| self.editor_layout.is_split()
|| !self.inline_images_enabled()
|| self.cell_pixel.is_none()
|| editor_area.width < MINIMAP_WIDTH_CELLS + MINIMAP_MIN_EDITOR_WIDTH
{
return None;
}
let w = MINIMAP_WIDTH_CELLS;
let (ed_x, strip_x) = match self.minimap_side {
MinimapSide::Right => (editor_area.x, editor_area.x + editor_area.width - w),
MinimapSide::Left => (editor_area.x + w, editor_area.x),
};
let ed_rect = Rect {
x: ed_x,
y: editor_area.y,
width: editor_area.width - w,
height: editor_area.height,
};
let full_strip = Rect {
x: strip_x,
y: editor_area.y,
width: w,
height: editor_area.height,
};
// Align the image to the editor's text rows (tab strip + border +
// header above, border below) so it tracks the text vertically.
let (tab, border, header) = (1u16, 1u16, 1u16);
let img = if editor_area.height > tab + 2 * border + header {
Rect {
x: strip_x,
y: editor_area.y + tab + border + header,
width: w,
height: editor_area.height - (tab + 2 * border + header),
}
} else {
full_strip
};
Some((ed_rect, full_strip, img))
}
/// Whether the open context menu (or its submenu, which floats further
/// out) overlaps `r`. Menus are clamped to the frame, not snapped to it, so
/// a right-click far from the minimap leaves the strip untouched.
fn menu_covers(&self, r: Rect) -> bool {
if r.width == 0 || r.height == 0 {
return false;
}
[self.menu_rect(), self.submenu_rect()]
.into_iter()
.flatten()
.any(|m| m.intersects(r))
}
pub fn minimap_image_payload(&self) -> Option<(&str, &MinimapLayout)> {
if self.shortcuts_modal.is_some()
|| self.file_finder.is_some()
|| self.command_palette.is_some()
|| self.go_to_symbol.is_some()
|| self.workspace_symbols.is_some()
|| self.process_picker.is_some()
|| self.zoxide_jump.is_some()
|| self.command_history_popup.is_some()
|| self.branch_picker.is_some()
|| self.input_prompt.is_some()
|| self.list_picker.is_some()
|| self.menu_covers(self.minimap_img_rect)
{
return None;
}
self.overlays.minimap.payload()
}
pub fn consume_minimap_image_clear(&mut self) -> bool {
self.overlays.minimap.consume_clear()
}
pub fn mark_minimap_image_displayed(&mut self) {
self.overlays.minimap.mark_displayed();
}
/// Map a click row inside the minimap strip to a document line and jump
/// there, centered. The vertical mapping uses the raster's `content_h`
/// (the lines occupy only the top `content_h` px for a short file), so a
/// click lands on the line actually under the cursor.
fn minimap_scroll_to_row(&mut self, row: u16) {
let r = self.minimap_img_rect;
let total = self.editor.lines.len();
if r.height == 0 || total == 0 {
return;
}
let ch_px = self.cell_pixel.map(|(_, h)| h).unwrap_or(1).max(1);
let dy_px = (row.saturating_sub(r.y)) as u32 * ch_px;
let content_h = self.minimap_content_h.max(1);
let line = (dy_px as usize * total / content_h as usize).min(total - 1);
self.editor.goto_line_centered(line);
self.poke_cursor();
}
/// Right-click on the minimap strip: a compact menu mirroring VS Code's
/// (Minimap toggle + Side submenu).
/// Build a status-bar popup menu at `(col, row)`. `menu_rect` clamps it up
/// to fit, so opening at the bottom status row renders above the bar.
fn open_status_menu(&mut self, col: u16, row: u16, items: Vec<MenuEntry>) {
self.context_menu = Some(ContextMenu {
origin: (col, row),
items,
selected: 0,
open_submenu: None,
submenu_selected: 0,
target_dir: self.tree.root.clone(),
});
}
/// Status-bar "Change Language Mode" picker. Editor-level only: it re-runs
/// tree-sitter highlighting / indentation / comment rules under the chosen
/// grammar. The LSP stays routed by file extension.
fn open_status_language_menu(&mut self, col: u16, row: u16) {
let check = |on: bool| if on { "\u{2713} " } else { " " };
let current = self.editor.language();
let mut items = vec![MenuEntry::Item {
label: format!("{}Plain Text", check(current.is_none())),
action: MenuAction::SetLanguage(None),
}];
for &lang in crate::widgets::editor::SELECTABLE_LANGUAGES {
items.push(MenuEntry::Item {
label: format!(
"{}{}",
check(current == Some(lang)),
crate::widgets::editor::language_label(Some(lang))
),
action: MenuAction::SetLanguage(Some(lang)),
});
}
self.open_status_menu(col, row, items);
}
/// Status-bar EOL picker (LF / CRLF). Converts on the next save.
fn open_status_eol_menu(&mut self, col: u16, row: u16) {
use crate::widgets::editor::LineEnding;
let check = |on: bool| if on { "\u{2713} " } else { " " };
let cur = self.editor.eol;
let items = vec![
MenuEntry::Item {
label: format!("{}LF", check(cur == LineEnding::Lf)),
action: MenuAction::SetLineEnding(LineEnding::Lf),
},
MenuEntry::Item {
label: format!("{}CRLF", check(cur == LineEnding::Crlf)),
action: MenuAction::SetLineEnding(LineEnding::Crlf),
},
];
self.open_status_menu(col, row, items);
}
/// Status-bar "Reopen with Encoding" picker over a common set; selecting one
/// re-decodes the file (and re-encodes it on the next save).
fn open_status_encoding_menu(&mut self, col: u16, row: u16) {
use encoding_rs::{
BIG5, EUC_JP, EUC_KR, GBK, KOI8_R, SHIFT_JIS, UTF_8, UTF_16BE, UTF_16LE, WINDOWS_1251,
WINDOWS_1252,
};
let check = |on: bool| if on { "\u{2713} " } else { " " };
let cur = self.editor.encoding;
let encs: [&'static encoding_rs::Encoding; 11] = [
UTF_8,
UTF_16LE,
UTF_16BE,
WINDOWS_1252,
WINDOWS_1251,
SHIFT_JIS,
EUC_JP,
GBK,
BIG5,
EUC_KR,
KOI8_R,
];
let items = encs
.iter()
.map(|&enc| MenuEntry::Item {
label: format!("{}{}", check(std::ptr::eq(enc, cur)), enc.name()),
action: MenuAction::SetEncoding(enc),
})
.collect();
self.open_status_menu(col, row, items);
}
/// Status-bar indentation picker, mirroring VS Code's "Select Indentation"
/// quick pick: switch spaces-vs-tabs for future typing, change the width,
/// and convert the buffer's existing indentation.
fn open_status_indent_menu(&mut self, col: u16, row: u16) {
use crate::widgets::editor::IndentStyle;
let check = |on: bool| if on { "\u{2713} " } else { " " };
let cur = self.editor.indent_style();
let mut items = vec![
MenuEntry::Item {
label: format!("{}Indent Using Spaces", check(cur.use_spaces)),
action: MenuAction::SetIndentStyle(IndentStyle {
width: cur.width,
use_spaces: true,
}),
},
MenuEntry::Item {
label: format!("{}Indent Using Tabs", check(!cur.use_spaces)),
action: MenuAction::SetIndentStyle(IndentStyle {
width: cur.width,
use_spaces: false,
}),
},
MenuEntry::Separator,
];
for width in [2u32, 4, 8] {
items.push(MenuEntry::Item {
label: format!("{}Tab Size: {width}", check(cur.width == width)),
action: MenuAction::SetIndentStyle(IndentStyle {
width,
use_spaces: cur.use_spaces,
}),
});
}
items.push(MenuEntry::Separator);
items.push(MenuEntry::Item {
label: String::from(" Convert Indentation to Spaces"),
action: MenuAction::ConvertIndentation(true),
});
items.push(MenuEntry::Item {
label: String::from(" Convert Indentation to Tabs"),
action: MenuAction::ConvertIndentation(false),
});
self.open_status_menu(col, row, items);
}
fn open_minimap_menu(&mut self, col: u16, row: u16) {
let check = |on: bool| if on { "\u{2713} " } else { " " };
let items = vec![
MenuEntry::Item {
label: format!("{}Minimap", check(self.minimap_visible)),
action: MenuAction::ToggleMinimap,
},
MenuEntry::Submenu {
label: String::from("Side"),
items: vec![
MenuEntry::Item {
label: format!("{}Left", check(self.minimap_side == MinimapSide::Left)),
action: MenuAction::SetMinimapSide(MinimapSide::Left),
},
MenuEntry::Item {
label: format!("{}Right", check(self.minimap_side == MinimapSide::Right)),
action: MenuAction::SetMinimapSide(MinimapSide::Right),
},
],
},
];
self.context_menu = Some(ContextMenu {
origin: (col, row),
items,
selected: 0,
open_submenu: None,
submenu_selected: 0,
target_dir: self.tree.root.clone(),
});
}
pub fn welcome_image_emit_payload(&self) -> Option<(&str, &WelcomeLayout)> {
if self.shortcuts_modal.is_some()
|| self.file_finder.is_some()
|| self.command_palette.is_some()
|| self.go_to_symbol.is_some()
|| self.workspace_symbols.is_some()
|| self.process_picker.is_some()
|| self.zoxide_jump.is_some()
|| self.command_history_popup.is_some()
|| self.branch_picker.is_some()
|| self.input_prompt.is_some()
|| self.list_picker.is_some()
|| self.context_menu.is_some()
|| self.connect_dialog.is_some()
|| !self.editor.is_blank_initial()
|| self.terminal_maximized
{
return None;
}
self.overlays.welcome.emit_payload()
}
pub fn mark_welcome_image_emitted(&mut self) {
self.overlays.welcome.mark_emitted();
}
/// Keyboard navigation for spreadsheet preview tabs. All gestures are
/// scroll-only: arrows pan one row/column, PageUp/PageDown jump by a
/// full viewport, Home/End jump to the first/last row, Tab/Shift+Tab
/// switch worksheets. Anything else is swallowed so a stray keystroke
/// can't insert characters into a buffer the user can't see.
/// Scroll the active diff to the next change hunk (forward=true) or
/// the previous one (forward=false), wrapping around the ends so a
/// user can keep clicking the same arrow to cycle through every
/// hunk. Mirrors the F7 / Shift+F7 key path so click and keybinding
/// stay in sync.
fn jump_diff_change(&mut self, forward: bool) {
let Some(diff) = self.editor.diff.as_mut() else {
return;
};
if forward {
diff.jump_next_change();
} else {
diff.jump_prev_change();
}
}
/// Open the working-tree file the diff caret sits on at its line, the
/// Enter action in the diff view. Resolves the row to a (file, line)
/// via `DiffData::jump_target`, then reuses the explorer's pinned-tab
/// open so the diff tab is left intact beside the opened file.
fn jump_to_diff_file_under_caret(&mut self) {
let target = {
let Some(diff) = self.editor.diff.as_ref() else {
return;
};
// A git-produced diff carries toplevel-relative `+++ b/` paths
// (#139); croft's own snapshot diffs stay workspace-anchored.
let root = if diff.left_is_git_head {
self.scm_root()
} else {
self.tree.root.clone()
};
let row = diff.caret_row().unwrap_or(diff.scroll);
diff.jump_target(row, &root)
};
let Some(j) = target else {
return;
};
match self.editor.open_pinned(&j.path) {
Ok(()) => {
self.editor.goto_line(j.line);
self.focus_pane(Pane::Editor);
self.sync_open_file_poll_mtime();
self.poke_cursor();
self.status = format!("{}:{}", self.status_path(&j.path), j.line);
}
Err(err) => {
self.status = format!("Could not open {}: {err}", j.path.display());
}
}
}
fn handle_diff_key(&mut self, key: KeyEvent) {
// Cmd+C / Ctrl+Shift+C on a diff selection: copy the dragged
// substring of whichever column the selection is anchored on.
// Must run BEFORE the scroll match below so the keystroke isn't
// dropped as "no scroll mapping". The general editor key handler
// short-circuits to this function when a diff is open, so without
// this branch Cmd+C in a diff view literally never copies.
if is_editor_copy_key(key) {
self.copy_editor_selection();
return;
}
// Enter opens the file under the caret at the matching line. The
// caret is the selection head a click leaves behind; with no
// selection yet we fall back to the top visible row.
if matches!(key.code, KeyCode::Enter) {
self.jump_to_diff_file_under_caret();
return;
}
// Hunk actions on the change under the caret (VS Code's Stage /
// Unstage / Discard Selected Ranges, one keystroke each since the
// diff pane owns no text input). R is destructive and routes
// through the confirm popup.
if let KeyCode::Char(c) = key.code
&& (key.modifiers.is_empty() || key.modifiers == KeyModifiers::SHIFT)
{
match c.to_ascii_lowercase() {
's' => {
self.stage_hunk_at_caret();
return;
}
'u' => {
self.unstage_hunk_at_caret();
return;
}
'r' => {
self.request_revert_hunk_at_caret();
return;
}
_ => {}
}
}
// Page = inner viewport rows minus the header + footer the diff
// renderer reserves. Falls back to a sane default when the editor
// hasn't laid out yet.
let page = (self.editor.last_inner.height as usize)
.saturating_sub(2)
.max(1);
let Some(diff) = self.editor.diff.as_mut() else {
return;
};
// F7 / Shift+F7: jump to next / previous change hunk. Matches the
// VS Code keybinding for "Next/Previous Change in Diff Editor" so
// users can scan a long diff without scrolling line-by-line.
if matches!(key.code, KeyCode::F(7)) {
// Shared backend with the click arrows: the jump anchors on the
// hunk the previous jump landed on (tracked in `nav_anchor`),
// not on `scroll` — `render_diff` clamps `scroll` at the bottom,
// which used to pin the forward arrow on the last hunk. Both
// directions wrap so F7 at the last hunk loops to the first.
if key.modifiers.contains(KeyModifiers::SHIFT) {
diff.jump_prev_change();
} else {
diff.jump_next_change();
}
return;
}
match key.code {
KeyCode::Up => diff.scroll_up_by(1),
KeyCode::Down => diff.scroll_down_by(1),
KeyCode::PageUp => diff.scroll_up_by(page),
KeyCode::PageDown => diff.scroll_down_by(page),
KeyCode::Home => diff.scroll_home(),
KeyCode::End => diff.scroll_end(),
KeyCode::Left => diff.scroll_left_by(4),
KeyCode::Right => diff.scroll_right_by(4),
_ => {}
}
}
fn handle_sheet_key(&mut self, key: KeyEvent) {
let visible = sheet_visible_rows(self.editor.last_inner);
let Some(sheet) = self.editor.sheet.as_mut() else {
return;
};
// Cell editing covers CSV/TSV and (via the umya write path,
// #178) xlsx; the legacy binary kinds stay read-only.
let editable = matches!(
sheet.kind,
crate::sheet::SheetKind::Csv
| crate::sheet::SheetKind::Tsv
| crate::sheet::SheetKind::Xlsx
);
let total_sheets = sheet.sheets.len();
let current = sheet.current_sheet;
let plain = !key.modifiers.contains(KeyModifiers::CONTROL)
&& !key.modifiers.contains(KeyModifiers::SUPER)
&& !key.modifiers.contains(KeyModifiers::ALT);
// In-grid cell editor (#177): it owns every key while open.
if sheet.editing.is_some() {
let (commit, next) = {
let edit = sheet.editing.as_mut().expect("checked");
match key.code {
KeyCode::Esc => {
sheet.editing = None;
return;
}
KeyCode::Enter => (true, (1i64, 0i64)),
KeyCode::Tab => (true, (0, 1)),
KeyCode::BackTab => (true, (0, -1)),
KeyCode::Backspace => {
if edit.cursor > 0 {
let i = floor_char(&edit.value, edit.cursor - 1);
edit.value.remove(i);
edit.cursor = i;
}
(false, (0, 0))
}
KeyCode::Delete => {
if edit.cursor < edit.value.len() {
edit.value.remove(edit.cursor);
}
(false, (0, 0))
}
KeyCode::Left => {
if edit.cursor > 0 {
edit.cursor = floor_char(&edit.value, edit.cursor - 1);
}
(false, (0, 0))
}
KeyCode::Right => {
if edit.cursor < edit.value.len() {
edit.cursor = ceil_char(&edit.value, edit.cursor + 1);
}
(false, (0, 0))
}
KeyCode::Home => {
edit.cursor = 0;
(false, (0, 0))
}
KeyCode::End => {
edit.cursor = edit.value.len();
(false, (0, 0))
}
KeyCode::Char(c) if plain => {
edit.value.insert(edit.cursor, c);
edit.cursor += c.len_utf8();
(false, (0, 0))
}
_ => (false, (0, 0)),
}
};
if commit {
if !editable {
// Belt-and-braces (#201 review): editing should never
// start on a read-only kind, but a commit must not
// mutate one either.
sheet.editing = None;
self.status = String::from("This view is read-only");
return;
}
let edit = sheet.editing.take().expect("checked");
let (r, c) = {
let data = &mut sheet.sheets[current];
data.set_cell(data.cur_row, data.cur_col, edit.value);
(data.cur_row, data.cur_col)
};
if !sheet.cell_edits.contains(&(current, r, c)) {
sheet.cell_edits.push((current, r, c));
}
sheet.dirty = true;
self.editor.dirty = true;
let data = &mut self.editor.sheet.as_mut().expect("checked").sheets[current];
data.cur_row = r
.saturating_add_signed(next.0 as isize)
.min(data.row_count().saturating_sub(1));
data.cur_col = c
.saturating_add_signed(next.1 as isize)
.min(data.col_count().saturating_sub(1));
sheet_follow_cursor(
self.editor.sheet.as_mut().expect("checked"),
current,
visible,
);
}
return;
}
let data = match sheet.sheets.get_mut(current) {
Some(d) => d,
None => return,
};
let row_count = data.rows.len();
let col_count = data.col_widths.len();
match key.code {
KeyCode::Down => {
data.cur_row = (data.cur_row + 1).min(row_count.saturating_sub(1));
}
KeyCode::Up => data.cur_row = data.cur_row.saturating_sub(1),
KeyCode::Right => {
data.cur_col = (data.cur_col + 1).min(col_count.saturating_sub(1));
}
KeyCode::Left => data.cur_col = data.cur_col.saturating_sub(1),
KeyCode::PageDown => {
// SQLite (#201 review): at the bottom of the loaded
// batch, fetch the NEXT page instead of stopping.
if sheet.kind == crate::sheet::SheetKind::Sqlite
&& data.cur_row + visible.max(1) >= row_count
{
self.sqlite_page_step(1);
return;
}
data.cur_row = (data.cur_row + visible).min(row_count.saturating_sub(1));
}
KeyCode::PageUp => {
if sheet.kind == crate::sheet::SheetKind::Sqlite
&& data.cur_row == 0
&& data.scroll_row == 0
{
self.sqlite_page_step(-1);
return;
}
data.cur_row = data.cur_row.saturating_sub(visible);
}
KeyCode::Home => {
data.cur_col = 0;
if key.modifiers.contains(KeyModifiers::CONTROL)
|| key.modifiers.contains(KeyModifiers::SUPER)
{
data.cur_row = 0;
}
}
KeyCode::End => {
data.cur_col = col_count.saturating_sub(1);
if key.modifiers.contains(KeyModifiers::CONTROL)
|| key.modifiers.contains(KeyModifiers::SUPER)
{
data.cur_row = row_count.saturating_sub(1);
}
}
KeyCode::Enter | KeyCode::F(2) => {
if editable {
if row_count > 0 {
let value = data.cell(data.cur_row, data.cur_col).to_string();
let cursor = value.len();
sheet.editing = Some(crate::sheet::CellEdit { value, cursor });
}
} else {
self.status = String::from("This workbook format is read-only (xls/ods/xlsb)");
}
return;
}
KeyCode::Delete if !editable => {
self.status = String::from("This view is read-only");
return;
}
KeyCode::Delete if editable && row_count > 0 => {
let (r, c) = (data.cur_row, data.cur_col);
data.set_cell(r, c, String::new());
if !sheet.cell_edits.contains(&(current, r, c)) {
sheet.cell_edits.push((current, r, c));
}
sheet.dirty = true;
self.editor.dirty = true;
return;
}
KeyCode::Tab if total_sheets > 1 => {
sheet.current_sheet = (current + 1) % total_sheets;
return;
}
KeyCode::BackTab if total_sheets > 1 => {
sheet.current_sheet = (current + total_sheets - 1) % total_sheets;
return;
}
KeyCode::Char(c) if plain && (' '..='~').contains(&c) => {
if editable {
if row_count > 0 {
// Spreadsheet convention: typing REPLACES the cell.
sheet.editing = Some(crate::sheet::CellEdit {
value: String::from(c),
cursor: c.len_utf8(),
});
}
} else {
self.status = String::from("This workbook format is read-only (xls/ods/xlsb)");
}
return;
}
_ => return,
}
sheet_follow_cursor(sheet, current, visible);
}
/// Archive browser keys (#179): selection movement, Enter extracts
/// the member to scratch and opens it through the normal dispatch,
/// E prompts for an extraction folder.
fn handle_archive_key(&mut self, key: KeyEvent) {
let Some(view) = self.editor.archive.as_mut() else {
return;
};
let rows = (view.rows_visible as usize).max(1);
let last = view.entries.len().saturating_sub(1);
match key.code {
KeyCode::Down => view.selected = (view.selected + 1).min(last),
KeyCode::Up => view.selected = view.selected.saturating_sub(1),
KeyCode::PageDown => view.selected = (view.selected + rows).min(last),
KeyCode::PageUp => view.selected = view.selected.saturating_sub(rows),
KeyCode::Home => view.selected = 0,
KeyCode::End => view.selected = last,
KeyCode::Enter => self.open_selected_archive_member(),
KeyCode::Char('e') | KeyCode::Char('E') => self.open_archive_extract_prompt(),
_ => {}
}
}
/// Extract the selected member into the session scratch dir and open
/// the extracted FILE through the standard dispatch, so text, images,
/// PDFs, sheets, and binaries all render with their real viewers.
fn open_selected_archive_member(&mut self) {
let Some((path, kind, member, dir)) = self.editor.archive.as_ref().and_then(|v| {
let e = v.entries.get(v.selected)?;
Some((self.editor.path.clone()?, v.kind, e.path.clone(), e.dir))
}) else {
return;
};
if dir {
self.status = String::from("Directories only group members; open a file");
return;
}
// Session-unique (#198 review): a shared path let another croft
// instance overwrite a member between extraction and open.
let dest = std::env::temp_dir().join(format!("croft-archive-{}", std::process::id()));
match crate::archive::extract_member(&path, kind, &member, &dest) {
Ok(extracted) => {
if let Err(e) = self.open_at(&extracted, 0, 0) {
self.status = format!("Member open failed: {e}");
} else {
self.status = format!("Opened {member} (extracted copy)");
}
}
Err(e) => self.status = format!("Member open failed: {e}"),
}
}
fn open_archive_extract_prompt(&mut self) {
use crate::widgets::input_prompt::{InputPrompt, InputPurpose};
let Some((member, dir)) = self
.editor
.archive
.as_ref()
.and_then(|v| v.entries.get(v.selected))
.map(|e| (e.path.clone(), e.dir))
else {
return;
};
if dir {
// extract_member extracts ONE member, not a subtree (#198
// review): the prompt would fail or write an empty folder.
self.status = String::from("Directories only group members; extract a file");
return;
}
let suggestion = self.workspace_root().display().to_string();
self.open_input_prompt(
InputPrompt::new(
InputPurpose::ArchiveExtract { member },
String::from("Extract Member To"),
"destination folder",
)
.with_value(&suggestion),
);
}
/// Hex-tab navigation (#172): cursor movement over bytes, Shift
/// extending the selection, F3 repeating the last find. The viewport
/// row count comes from the last painted frame's layout (frame
/// truth), so PageUp/PageDown match what the user sees.
fn handle_hex_key(&mut self, key: KeyEvent) {
// Cmd/Ctrl+F never reaches here — `is_editor_find_key` routes to
// `open_editor_find` earlier in the dispatch, which forwards hex
// tabs to the byte-query popup.
let Some(view) = self.editor.hex.as_mut() else {
return;
};
let rows = (view.layout.data_rows as usize).max(1);
let bpr = view.bytes_per_row as i64;
let select = key.modifiers.contains(KeyModifiers::SHIFT);
let jump = key.modifiers.contains(KeyModifiers::CONTROL)
|| key.modifiers.contains(KeyModifiers::SUPER);
// Editing (#173): undo/redo chords, then plain typing. The
// chord check comes first so Cmd+Z is never read as the letter.
if jump && matches!(key.code, KeyCode::Char('z') | KeyCode::Char('Z')) {
let did = if select {
view.redo_edit()
} else {
view.undo_edit()
};
if did {
self.editor.dirty = self.editor.hex.as_ref().is_some_and(|v| v.has_edits());
} else {
self.status = String::from(if select {
"Nothing to redo"
} else {
"Nothing to undo"
});
}
return;
}
if let KeyCode::Char(c) = key.code
&& !jump
&& !key.modifiers.contains(KeyModifiers::ALT)
{
if view.read_only {
self.status = String::from("Read-only file: no write permission");
return;
}
let mut wrote = false;
if view.ascii_focus {
if (' '..='~').contains(&c) {
let off = view.cursor;
view.apply_edit(off, c as u8);
view.move_cursor(1, false, rows);
wrote = true;
}
} else if let Some(d) = c.to_digit(16) {
if view.type_hex_digit(d as u8) {
view.move_cursor(1, false, rows);
}
wrote = true;
}
if wrote {
self.editor.dirty = self.editor.hex.as_ref().is_some_and(|v| v.has_edits());
return;
}
// Not a typable char for this pane: fall through to the
// navigation matches below (F3 etc. are KeyCode variants,
// never Char, so nothing else claims chars).
return;
}
match key.code {
KeyCode::Tab => {
view.ascii_focus = !view.ascii_focus;
view.pending_nibble = None;
return;
}
KeyCode::Backspace => {
view.pending_nibble = None;
view.move_cursor(-1, false, rows);
return;
}
KeyCode::Delete => {
let off = view.cursor;
view.revert_edit(off);
self.editor.dirty = self.editor.hex.as_ref().is_some_and(|v| v.has_edits());
return;
}
_ => {}
}
let Some(view) = self.editor.hex.as_mut() else {
return;
};
match key.code {
KeyCode::Left => view.move_cursor(-1, select, rows),
KeyCode::Right => view.move_cursor(1, select, rows),
KeyCode::Up => view.move_cursor(-bpr, select, rows),
KeyCode::Down => view.move_cursor(bpr, select, rows),
KeyCode::PageUp => view.move_cursor(-bpr * rows as i64, select, rows),
KeyCode::PageDown => view.move_cursor(bpr * rows as i64, select, rows),
KeyCode::Home if jump => view.set_cursor(0, select, rows),
KeyCode::End if jump => view.set_cursor(u64::MAX, select, rows),
KeyCode::Home => {
let row_start = view.cursor - view.cursor % view.bytes_per_row;
view.set_cursor(row_start, select, rows);
}
KeyCode::End => {
let row_end =
view.cursor - view.cursor % view.bytes_per_row + (view.bytes_per_row - 1);
view.set_cursor(row_end, select, rows);
}
KeyCode::Esc => {
view.sel_anchor = None;
view.pending_nibble = None;
}
KeyCode::F(3) => self.hex_find_next(),
_ => {}
}
}
/// Sheet row/column structure ops (#177), palette-driven, anchored
/// on the selected cell. CSV/TSV only; the workbook kinds are still
/// read-only (#178).
fn sheet_structure_op(&mut self, cmd: crate::widgets::command_palette::Command) {
use crate::widgets::command_palette::Command as Cmd;
let Some(view) = self.editor.sheet.as_mut() else {
self.status = String::from("The active tab is not a spreadsheet");
return;
};
if !matches!(
view.kind,
crate::sheet::SheetKind::Csv | crate::sheet::SheetKind::Tsv
) {
self.status = String::from(
"Row/column structure edits are CSV/TSV only; xlsx supports cell edits",
);
return;
}
view.editing = None;
let current = view.current_sheet;
let Some(data) = view.sheets.get_mut(current) else {
return;
};
let (r, c) = (data.cur_row, data.cur_col);
let changed = match cmd {
Cmd::SheetInsertRowBelow => {
let at = if data.row_count() == 0 { 0 } else { r + 1 };
data.insert_row(at);
data.cur_row = at;
true
}
Cmd::SheetDeleteRow => {
let did = data.delete_row(r);
data.cur_row = r.min(data.row_count().saturating_sub(1));
did
}
Cmd::SheetInsertColRight => {
let at = if data.col_count() == 0 { 0 } else { c + 1 };
data.insert_col(at);
data.cur_col = at;
true
}
Cmd::SheetDeleteCol => {
let did = data.delete_col(c);
data.cur_col = c.min(data.col_count().saturating_sub(1));
did
}
_ => false,
};
if changed {
view.dirty = true;
let visible = sheet_visible_rows(self.editor.last_inner);
if let Some(view) = self.editor.sheet.as_mut() {
sheet_follow_cursor(view, current, visible);
}
self.editor.dirty = true;
} else {
self.status = String::from("Nothing to remove there");
}
}
/// Step the active SQLite table to an adjacent page (#201 review),
/// replacing the sheet's rows and keeping the cursor sane.
fn sqlite_page_step(&mut self, delta: i64) {
let Some(path) = self.editor.path.clone() else {
return;
};
let Some(view) = self.editor.sheet.as_mut() else {
return;
};
let idx = view.current_sheet;
let Some((table, page)) = view.sqlite_pages.get(idx).cloned() else {
return;
};
let next = page.saturating_add_signed(delta as isize);
if delta > 0 {
// Do not run past the end: only step when a further page can
// exist per the loaded batch being full.
if view.sheets[idx].row_count() < crate::sqlite_view::ROW_CAP {
self.status = String::from("Last page");
return;
}
} else if page == 0 {
return;
}
match crate::sqlite_view::table_page(&path, &table, next) {
Ok((headers, rows, total)) if !rows.is_empty() || next == 0 => {
let got = rows.len();
let label = crate::sqlite_view::page_label(&table, next, got, total);
view.sheets[idx] = crate::sheet::sheet_data_from_parts(label, headers, rows);
if delta < 0 {
let last = view.sheets[idx].row_count().saturating_sub(1);
view.sheets[idx].cur_row = last;
}
view.sqlite_pages[idx].1 = next;
}
Ok(_) => self.status = String::from("Last page"),
Err(e) => self.status = format!("Page fetch failed: {e}"),
}
}
/// F3 / "Hex: Find Next": repeat the stored query from just past the
/// cursor. The query itself is set by the find prompt
/// (`InputPurpose::HexFind`), whose submit searches cursor-INCLUSIVE
/// via `hex_find_run` directly.
fn hex_find_next(&mut self) {
let Some(view) = self.editor.hex.as_ref() else {
return;
};
if view.last_find.is_none() {
self.status = String::from("Hex: no find query yet (Cmd+F)");
return;
}
self.hex_find_run(view.cursor.saturating_add(1));
}
/// Run the hex tab's stored find query from `from` (wrapping),
/// selecting the match and reporting the outcome in the status line.
fn hex_find_run(&mut self, from: u64) {
let Some(view) = self.editor.hex.as_mut() else {
return;
};
let Some(needle) = view.last_find.clone() else {
return;
};
let rows = (view.layout.data_rows as usize).max(1);
match view.find_forward(&needle, from) {
Ok(crate::hex::FindOutcome::Found(off)) => {
view.set_cursor(off, false, rows);
view.sel_anchor = Some(off + needle.len() as u64 - 1);
self.status = format!("Found at 0x{off:X}");
}
Ok(crate::hex::FindOutcome::NotFound) => {
self.status = String::from("Not found");
}
Ok(crate::hex::FindOutcome::Capped) => {
self.status = format!(
"Not found in the first {} MB scanned",
crate::hex::FIND_SCAN_CAP / (1024 * 1024)
);
}
Err(e) => self.status = format!("Hex find failed: {e}"),
}
}
/// Resize the sidebar / terminal pane while a splitter drag is in
/// progress. The pointer's screen coordinate maps directly to the new
/// edge: dragging horizontally sets the sidebar width to (column −
/// activity-bar width); dragging vertically sets the terminal height
/// to (right-pane bottom − row).
fn handle_splitter_drag(&mut self, kind: SplitterDrag, column: u16, row: u16) {
match kind {
SplitterDrag::Sidebar => {
let activity_w = if self.activity_bar_visible {
ACTIVITY_BAR_WIDTH
} else {
0
};
let secondary_w = if self.secondary_side_bar_visible {
SECONDARY_SIDEBAR_WIDTH
} else {
0
};
// Reconstruct the content width from the live regions rather
// than the frame, so the drag is correct even before a real
// render has stamped `last_frame_area`.
let frame_x = self.last_frame_area.x;
let total = activity_w + secondary_w + self.sidebar_width + self.last_content_width;
let new_w = match self.side_bar_position {
// Left: sidebar starts after the activity bar; the seam is
// its right edge, so width = column - activity offset.
SideBarPosition::Left => {
column.saturating_sub(frame_x).saturating_sub(activity_w)
}
// Right: sidebar ends at the content's right edge (minus the
// activity bar); dragging the seam left grows it.
SideBarPosition::Right => (frame_x + total)
.saturating_sub(activity_w)
.saturating_sub(column),
};
let max_sidebar = total
.saturating_sub(activity_w)
.saturating_sub(secondary_w)
.saturating_sub(RIGHT_PANE_MIN);
self.sidebar_width =
new_w.clamp(SIDEBAR_WIDTH_MIN, max_sidebar.max(SIDEBAR_WIDTH_MIN));
}
SplitterDrag::Terminal => {
let Some(splitter_y) = self.terminal_splitter_y else {
return;
};
// Right pane spans [splitter_y - editor_h, splitter_y +
// current_terminal_h). Compute the right-pane bottom from
// the captured height so a drag past it just clamps.
let bottom = splitter_y + self.terminal_height.unwrap_or(0);
let actual_bottom = if bottom == splitter_y {
// Pre-drag we may have used a percent split; fall back
// to the captured content height.
splitter_y.saturating_add(self.last_content_height)
} else {
bottom
};
let new_h = actual_bottom.saturating_sub(row);
let max_h = self
.last_content_height
.saturating_sub(EDITOR_HEIGHT_MIN)
.max(TERMINAL_HEIGHT_MIN);
self.terminal_height = Some(new_h.clamp(TERMINAL_HEIGHT_MIN, max_h));
}
SplitterDrag::EditorSeam(seam) => {
if !self.editor_layout.is_split() {
return;
}
// Map the pointer onto the seam's axis (column for a vertical
// seam line, row for a horizontal one) and repartition only the
// two groups it separates. The seam carries no dedicated cell,
// so the two groups tile the boundary exactly.
let pointer = match seam.dir {
editor_layout::SplitDir::Horizontal => column,
editor_layout::SplitDir::Vertical => row,
};
self.editor_layout
.drag_seam(&seam, pointer, EDITOR_SPLIT_MIN);
}
}
}
/// Trash every entry in the tree's current action set (the multi-
/// selection if non-empty, otherwise just the focused row). Workspace
/// root rows are filtered by `delete_paths` — the shared choke point —
/// even if some other path in the set proceeds.
fn delete_selection(&mut self) {
let paths = self.tree.action_paths();
if paths.is_empty() {
return;
}
self.delete_paths(paths);
}
fn delete_paths(&mut self, paths: Vec<PathBuf>) {
// No workspace root row is ever a delete target, whichever flow
// assembled the set: the context menu forwards a mixed multi-
// selection wholesale, and Select All marks the root rows too, so
// the per-node `delete_target_for` guard alone cannot protect a
// root riding along in the batch. Filter here — the one choke
// point every delete flow funnels through — with the same
// canonicalized comparison the old primary-root guard used, so a
// root reached through a symlinked path is still refused.
let canon_roots: Vec<PathBuf> = self
.tree
.root_paths()
.filter_map(|r| r.canonicalize().ok())
.collect();
let is_root = |p: &PathBuf| {
self.tree.root_paths().any(|r| r == p)
|| p.canonicalize()
.ok()
.is_some_and(|cp| canon_roots.contains(&cp))
};
let paths: Vec<PathBuf> = paths.into_iter().filter(|p| !is_root(p)).collect();
let total = paths.len();
if total == 0 {
self.status = String::from("Workspace roots cannot be deleted");
return;
}
// Confirm before trashing — Delete (or the context menu's Delete) must
// not remove files from a single action. Enter performs it; Esc keeps
// them. Files go to the OS Trash (recoverable), so the wording reflects that.
use crate::widgets::input_prompt::{InputPrompt, InputPurpose};
let title = if total == 1 {
let name = paths[0]
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| paths[0].display().to_string());
format!("Move '{name}' to Trash?")
} else {
format!("Move {total} items to Trash?")
};
self.open_input_prompt(
InputPrompt::new(
InputPurpose::TreeDelete { paths },
title,
"Enter to trash · Esc to keep",
)
.with_value("trash"),
);
}
/// Perform the confirmed trash of `paths` (the popup's Enter path).
fn perform_delete_paths(&mut self, paths: Vec<PathBuf>) {
let total = paths.len();
if total == 0 {
return;
}
let mut affected_dirs: BTreeSet<PathBuf> = BTreeSet::new();
for path in &paths {
let parent = path
.parent()
.map(Path::to_path_buf)
.unwrap_or_else(|| self.tree.root.clone());
affected_dirs.insert(parent);
}
// One trash call for the whole batch — on macOS this routes through
// Finder so the trash sound effect fires once for the operation
// instead of once per file. The single-path path keeps the cheaper
// NSFileManager backend.
let result = if total == 1 {
crate::widgets::file_tree::move_to_trash(&paths[0])
} else {
crate::widgets::file_tree::move_to_trash_bulk(&paths)
};
match result {
Ok(()) => {
for path in &paths {
if self.editor.matches_open_path(path) {
if !self.editor.close_active() {
*self.editor = Editor::new();
}
self.sync_open_file_poll_mtime();
}
}
for dir in &affected_dirs {
if let Some(idx) = self.tree.index_of_dir(dir) {
self.tree.refresh_children(idx);
}
}
self.tree.clear_marks();
self.status = if total == 1 {
format!("Moved {} to Trash", paths[0].display())
} else {
format!("Moved {total} items to Trash")
};
}
Err(e) => {
for dir in &affected_dirs {
if let Some(idx) = self.tree.index_of_dir(dir) {
self.tree.refresh_children(idx);
}
}
self.status = if total == 1 {
format!("Delete failed: {e}")
} else {
format!("Bulk delete failed: {e}")
};
}
}
}
/// Stash the current action paths into the explorer clipboard. The
/// system text clipboard is left untouched so editor/terminal text
/// copy gestures still work elsewhere in the app.
fn copy_selection_to_explorer_clipboard(&mut self, mode: ExplorerClipMode) {
let paths = self.tree.action_paths();
if paths.is_empty() {
return;
}
let n = paths.len();
self.tree_clipboard = Some(ExplorerClipboard { mode, paths });
self.status = match (mode, n) {
(ExplorerClipMode::Copy, 1) => String::from("Copied 1 item"),
(ExplorerClipMode::Copy, _) => format!("Copied {n} items"),
(ExplorerClipMode::Cut, 1) => String::from("Cut 1 item"),
(ExplorerClipMode::Cut, _) => format!("Cut {n} items"),
};
}
/// Resolve the directory that an explorer paste/drop should land in,
/// based on the currently focused node. Mirrors `create_target_dir_for`
/// but for keyboard paste (no right-click coordinates).
fn paste_target_dir(&self) -> PathBuf {
let node = self.tree.nodes.get(self.tree.selected);
crate::widgets::file_tree::create_target_dir_for(node, &self.tree.root)
}
/// Move (Cut) or copy (Copy) every clipboard path into `dest_dir`,
/// then refresh affected directories and select the freshly-pasted
/// items. Cut clears the explorer clipboard on success; Copy preserves
/// it so the user can paste again.
fn paste_explorer_clipboard(&mut self) {
let dest_dir = self.paste_target_dir();
self.paste_into(dest_dir);
}
/// `Ctrl/Cmd+D` from the explorer: smart toggle that mirrors the right-
/// click "Select for Compare" / "Compare with Selected" / clear-anchor
/// chain in a single key press.
fn toggle_compare_on_selected_file(&mut self) {
let Some(node) = self.tree.nodes.get(self.tree.selected) else {
self.status = String::from("No file selected to compare");
return;
};
if node.is_dir {
self.status = String::from("Compare needs a file, not a folder");
return;
}
let path = node.path.clone();
match self.compare_anchor.as_ref() {
Some(anchor) if anchor == &path => {
self.compare_anchor = None;
self.status = String::from("Cleared compare anchor");
}
Some(anchor) => {
let anchor_clone = anchor.clone();
match self.editor.open_diff(&anchor_clone, &path) {
Ok(()) => {
self.focus_pane(Pane::Editor);
self.compare_anchor = None;
self.sync_open_file_poll_mtime();
let l = anchor_clone
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| anchor_clone.display().to_string());
let r = path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| path.display().to_string());
self.status = format!("Diff: {l} \u{2194} {r}");
}
Err(e) => {
self.status = format!("Diff failed: {e}");
}
}
}
None => {
let label = path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| path.display().to_string());
self.compare_anchor = Some(path);
self.status =
format!("Selected {label} for compare — Ctrl/Cmd+D again on another file");
}
}
}
fn paste_into(&mut self, dest_dir: PathBuf) {
let Some(clip) = self.tree_clipboard.clone() else {
self.status = String::from("Explorer clipboard is empty");
return;
};
self.apply_paste_or_drop(&dest_dir, &clip.paths, clip.mode);
if matches!(clip.mode, ExplorerClipMode::Cut) {
self.tree_clipboard = None;
}
}
/// Shared implementation for explorer paste and drag-drop. `mode`
/// distinguishes a move (Cut/drag) from a copy (Copy/Alt-drag).
fn apply_paste_or_drop(&mut self, dest_dir: &Path, paths: &[PathBuf], mode: ExplorerClipMode) {
let mut affected: BTreeSet<PathBuf> = BTreeSet::new();
affected.insert(dest_dir.to_path_buf());
let mut placed: Vec<PathBuf> = Vec::new();
let mut errors: Vec<String> = Vec::new();
for src in paths {
let result = match mode {
ExplorerClipMode::Cut => {
let parent = src
.parent()
.map(Path::to_path_buf)
.unwrap_or_else(|| self.tree.root.clone());
affected.insert(parent);
crate::widgets::file_tree::move_into(dest_dir, src)
}
ExplorerClipMode::Copy => crate::widgets::file_tree::copy_into(dest_dir, src),
};
match result {
Ok(p) => {
if matches!(mode, ExplorerClipMode::Cut) && self.editor.matches_open_path(src) {
self.editor.rename_open_path(src, &p);
self.rename_review_boxes_path(src, &p);
}
placed.push(p);
}
Err(e) => errors.push(format!("{}: {e}", src.display())),
}
}
for dir in &affected {
if let Some(idx) = self.tree.index_of_dir(dir) {
self.tree.refresh_children(idx);
}
}
self.tree.marked.clear();
for p in &placed {
self.tree.marked.insert(p.clone());
}
if let Some(first) = placed.first()
&& let Some(idx) = self.tree.nodes.iter().position(|n| &n.path == first)
{
self.tree.selected = idx;
self.tree.anchor = idx;
}
let verb = match mode {
ExplorerClipMode::Cut => "Moved",
ExplorerClipMode::Copy => "Copied",
};
if !errors.is_empty() {
self.status = format!(
"{verb} {}/{}; failed: {}",
placed.len(),
paths.len(),
errors.join("; ")
);
} else if placed.len() == 1 {
self.status = format!("{verb} 1 item to {}", self.status_path(dest_dir));
} else {
self.status = format!(
"{verb} {} items to {}",
placed.len(),
self.status_path(dest_dir)
);
}
}
fn open_create_prompt(&mut self, kind: CreateKind, target_dir: PathBuf) {
let label = match kind {
CreateKind::File => format!("New File in {}", self.status_path(&target_dir)),
CreateKind::Folder => format!("New Folder in {}", self.status_path(&target_dir)),
};
self.prompt = Some(Prompt {
label,
buffer: String::new(),
kind: PromptKind::Create(kind),
target_dir,
error: None,
});
}
/// Workspace-relative rendering for status transients and prompt
/// labels: tabs and breadcrumbs already speak root-relative, and an
/// absolute path under a deep root pushed the one informative part —
/// the filename — off the visible end of the bar (#100). Paths outside
/// the root (`~/.ssh/config`, files opened by absolute path) keep
/// their absolute form.
fn status_path(&self, path: &Path) -> String {
// Folder-relative via the OWNING root (#143): identical to a plain
// primary-root strip while the set holds one entry, and already the
// multi-root label rule once it holds more.
let rel = self
.roots
.owning_root(path)
.and_then(|r| path.strip_prefix(r).ok())
.unwrap_or(path);
if rel.as_os_str().is_empty() {
String::from(".")
} else {
rel.display().to_string()
}
}
fn open_rename_prompt(&mut self, path: PathBuf) {
let parent = path
.parent()
.map(Path::to_path_buf)
.unwrap_or_else(|| self.tree.root.clone());
let current = path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
let label = format!("Rename {}", self.status_path(&path));
self.prompt = Some(Prompt {
label,
buffer: current,
kind: PromptKind::Rename(path),
target_dir: parent,
error: None,
});
}
fn handle_prompt_key(&mut self, key: KeyEvent) {
match key.code {
KeyCode::Esc => {
self.prompt = None;
// Abandon any in-flight prepare-rename too: its verdict would
// otherwise reopen this prompt at the caret the user just
// walked away from (#254 item 6).
self.prepare_rename_request = None;
self.status = String::from("Cancelled");
}
KeyCode::Enter => self.commit_prompt(),
KeyCode::Backspace => {
if let Some(p) = self.prompt.as_mut() {
p.buffer.pop();
p.error = None;
}
}
KeyCode::Char(c) => {
if !key.modifiers.contains(KeyModifiers::CONTROL)
&& !key.modifiers.contains(KeyModifiers::ALT)
&& !key.modifiers.contains(KeyModifiers::SUPER)
&& let Some(p) = self.prompt.as_mut()
{
p.buffer.push(c);
p.error = None;
}
}
_ => {}
}
}
fn commit_prompt(&mut self) {
let Some(prompt) = self.prompt.as_ref() else {
return;
};
let kind = prompt.kind.clone();
match kind {
PromptKind::Create(create_kind) => {
let name = prompt.buffer.trim().to_string();
if let Err(msg) = crate::widgets::file_tree::validate_new_name(&name) {
if let Some(p) = self.prompt.as_mut() {
p.error = Some(msg.to_string());
}
return;
}
let target_dir = prompt.target_dir.clone();
let result = match create_kind {
CreateKind::File => {
crate::widgets::file_tree::create_file_in(&target_dir, &name)
}
CreateKind::Folder => {
crate::widgets::file_tree::create_folder_in(&target_dir, &name)
}
};
match result {
Ok(path) => {
self.prompt = None;
self.status = match create_kind {
CreateKind::File => format!("Created file {}", self.status_path(&path)),
CreateKind::Folder => {
format!("Created folder {}", self.status_path(&path))
}
};
if let Some(idx) = self.tree.index_of_dir(&target_dir) {
self.tree.refresh_children(idx);
if let Some(new_idx) =
self.tree.nodes.iter().position(|n| n.path == path)
{
self.tree.select(new_idx);
}
}
if create_kind == CreateKind::File {
if let Err(e) = self.editor.open(&path) {
self.status = format!("Created but could not open: {e}");
} else {
self.sync_open_file_poll_mtime();
self.focus_pane(Pane::Editor);
}
}
}
Err(e) => {
if let Some(p) = self.prompt.as_mut() {
p.error = Some(e.to_string());
}
}
}
}
PromptKind::Rename(old_path) => {
let new_name = prompt.buffer.trim().to_string();
let parent = prompt.target_dir.clone();
match crate::widgets::file_tree::rename_in(&parent, &old_path, &new_name) {
Ok(new_path) => {
self.prompt = None;
self.status = format!("Renamed to {}", self.status_path(&new_path));
if let Some(idx) = self.tree.index_of_dir(&parent) {
self.tree.refresh_children(idx);
if let Some(new_idx) =
self.tree.nodes.iter().position(|n| n.path == new_path)
{
self.tree.select(new_idx);
}
}
self.editor.rename_open_path(&old_path, &new_path);
self.rename_review_boxes_path(&old_path, &new_path);
self.sync_open_file_poll_mtime();
}
Err(e) => {
if let Some(p) = self.prompt.as_mut() {
p.error = Some(e.to_string());
}
}
}
}
PromptKind::RenameSymbol { path, row, col } => {
let new_name = prompt.buffer.trim().to_string();
if new_name.is_empty() {
if let Some(p) = self.prompt.as_mut() {
p.error = Some("Name cannot be empty".to_string());
}
return;
}
// The prompt captured buffer coordinates; the server wants
// UTF-16, so convert here rather than casting the char column.
let (line, character) = self.editor.pos_to_utf16(row, col);
let Some(lsp) = self.lsp.as_mut() else {
if let Some(p) = self.prompt.as_mut() {
p.error = Some("No language server for this file".to_string());
}
return;
};
let id = lsp.request_rename(path, line, character, new_name);
self.rename_request_id = Some(id);
self.prompt = None;
self.status = String::from("Renaming symbol");
}
PromptKind::BreakpointCondition { path, line } => {
let expr = prompt.buffer.clone();
self.prompt = None;
self.commit_breakpoint_condition(path, line, &expr);
}
PromptKind::Logpoint { path, line } => {
let message = prompt.buffer.clone();
self.prompt = None;
self.commit_logpoint(path, line, &message);
}
PromptKind::RenameTerminal(idx) => {
let name = prompt.buffer.trim().to_string();
self.prompt = None;
if let Some(t) = self.terminals.get_mut(idx) {
let cleared = name.is_empty();
t.set_manual_name(if cleared { None } else { Some(name.clone()) });
self.status = if cleared {
String::from("Cleared terminal name")
} else {
format!("Renamed terminal to {name}")
};
self.save_terminal_session();
}
}
PromptKind::AnnotateTerminal {
pane,
line,
clock,
start,
len,
existing,
} => {
let text = prompt.buffer.trim().to_string();
self.prompt = None;
if let Some(t) = self.terminals.get_mut(pane) {
self.status = String::from(match (existing, text.is_empty()) {
(Some(i), true) => {
t.remove_annotation(i);
"Deleted annotation"
}
(Some(i), false) => {
t.set_annotation_text(i, text);
"Updated annotation"
}
(None, true) => "Annotation cancelled (empty note)",
(None, false) => {
t.add_annotation(line, clock, start, len, text);
"Annotated selection (click the span to read it)"
}
});
}
}
}
}
}
/// Kitty keyboard-protocol flags croft requests on startup.
///
/// `DISAMBIGUATE_ESCAPE_CODES` is the bit that makes terminals deliver
/// modifier keys (notably Cmd/Super on macOS in iTerm2 ≥3.5, Ghostty, kitty,
/// WezTerm) as real key events rather than swallowing them or routing them to
/// menus. We deliberately do NOT request `REPORT_ALL_KEYS_AS_ESCAPE_CODES`
/// because that re-encodes ordinary printable input and would break typing.
fn keyboard_enhancement_flags() -> KeyboardEnhancementFlags {
KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES
| KeyboardEnhancementFlags::REPORT_EVENT_TYPES
}
/// The terminal modes croft turns on whenever it takes over a screen: alt
/// screen, mouse tracking, bracketed paste, steady-bar cursor. SINGLE SOURCE
/// OF TRUTH — the startup takeover, the post-scp TUI restore, and the
/// dtach-reattach re-assert all emit exactly this block, so the mode lists
/// can never drift apart. A mode enabled at startup but missing from the
/// reattach re-assert is the "mouse dead after reconnecting to a persisted
/// remote session" bug (0.1.611); add any new startup mode HERE, never as an
/// inline `execute!` at a call site. The kitty keyboard flags are the one
/// deliberate exception: startup pushes them (the push pairs with the
/// teardown pop), while [`mode_reassert_seq`] appends the SET form.
fn takeover_mode_seq() -> Vec<u8> {
let mut seq = Vec::new();
let _ = execute!(
seq,
EnterAlternateScreen,
EnableMouseCapture,
EnableBracketedPaste,
crossterm::cursor::SetCursorStyle::SteadyBar,
);
seq
}
/// Escape bytes re-asserting every terminal mode croft set at startup. A
/// dtach reattach (`-r winch`) delivers only a SIGWINCH: the newly attached
/// terminal never received the startup DECSETs, so the alt screen, mouse
/// tracking, bracketed paste, and kitty keyboard flags are all off — the
/// "mouse dead after reconnecting to a persisted remote session" bug. The
/// main loop emits this on every Resize when `CROFT_SESSION_PERSISTENT` is
/// set (the dtach branch of the remote launch command); every sequence is
/// idempotent on a terminal that already has the mode enabled. The kitty
/// keyboard flags use the SET form (`CSI = flags ; 1 u`), not the push the
/// startup path uses: a push per WINCH would stack entries the single pop at
/// exit can't unwind, leaving the user's shell with enhanced keys on.
fn mode_reassert_seq() -> Vec<u8> {
use std::io::Write;
let mut seq = takeover_mode_seq();
let _ = write!(seq, "\x1b[={};1u", keyboard_enhancement_flags().bits());
seq
}
/// Shrink `s` to at most `max` chars by cutting the middle, keeping roughly
/// a third of the head and two thirds of the tail — for path-shaped
/// messages the tail carries the filename, the part worth keeping. Never
/// appends a trailing ellipsis (the cut is interior by construction).
fn elide_middle(s: &str, max: usize) -> String {
let chars: Vec<char> = s.chars().collect();
if chars.len() <= max {
return s.to_string();
}
if max < 3 {
return chars.iter().take(max).collect();
}
let keep = max - 1; // one cell for the ellipsis
let head = keep / 3;
let tail = keep - head;
let mut out: String = chars[..head].iter().collect();
out.push('\u{2026}');
out.extend(&chars[chars.len() - tail..]);
out
}
/// The excerpt window for a Peek popup: up to `total` lines, at most
/// `above` of them before `target`, clamped to the file. Returns the start
/// line index and the excerpt slice (cloned).
fn peek_excerpt(
lines: &[String],
target: usize,
above: usize,
total: usize,
) -> (usize, Vec<String>) {
if lines.is_empty() {
return (0, Vec::new());
}
let target = target.min(lines.len() - 1);
let start = target.saturating_sub(above);
let end = (start + total).min(lines.len());
let start = end.saturating_sub(total).min(start);
(start, lines[start..end].to_vec())
}
/// True when the "command" modifier is effectively held. That is `Super`
/// (Cmd) everywhere; on Termux (Android, no Cmd key) `Ctrl` stands in for it
/// too, mirroring VS Code's Linux keymap so the Super-only chords stay
/// reachable. `termux` is threaded in explicitly to keep the decision pure
/// and testable.
fn cmd_active(mods: KeyModifiers, termux: bool) -> bool {
mods.contains(KeyModifiers::SUPER) || (termux && mods.contains(KeyModifiers::CONTROL))
}
/// `cmd_active` over the live environment (cached Termux detection).
fn has_cmd(mods: KeyModifiers) -> bool {
cmd_active(mods, crate::iterm2_inline::detect_termux())
}
/// Build the OSC 0 escape sequence that sets the terminal's window/icon title.
///
/// Format: `ESC ] 0 ; <title> BEL`. Control bytes that would break the escape
/// (BEL, ESC, newlines) are stripped from `title` so untrusted input cannot
/// inject further sequences.
fn set_title_seq(title: &str) -> Vec<u8> {
let mut out = Vec::with_capacity(title.len() + 5);
out.extend_from_slice(b"\x1b]0;");
for byte in title.as_bytes() {
match *byte {
0x00..=0x1f | 0x7f => continue,
b => out.push(b),
}
}
out.push(0x07);
out
}
/// iTerm2 proprietary OSC that overrides the *session* (not profile-on-disk)
/// bg colour. The `srgb:` prefix forces iTerm2 to interpret the hex bytes
/// as sRGB regardless of the user's "Use sRGB colour space" profile setting,
/// so combining this with an OSC-1337 PNG canvas filled with the same hex
/// guarantees both surfaces display the same physical pixel.
/// Format: `ESC ] 1 3 3 7 ; SetColors=bg=srgb:RRGGBB BEL`.
fn set_session_bg_srgb_seq(rgb: (u8, u8, u8)) -> String {
format!(
"\x1b]1337;SetColors=bg=srgb:{:02x}{:02x}{:02x}\x07",
rgb.0, rgb.1, rgb.2,
)
}
/// Revert the iTerm2 session bg to the user's profile default. Emitted on
/// exit so the user's shell doesn't inherit croft's forced bg colour.
fn reset_session_bg_seq() -> String {
String::from("\x1b]1337;SetColors=bg=default\x07")
}
/// Standard dynamic-color OSCs setting the HOST terminal's default
/// background (OSC 11) and foreground (OSC 10) to the theme's. iTerm2 gets
/// its proprietary sRGB variant on top, but this portable pair is what
/// recolors Ghostty, Kitty, WezTerm, xterm and friends, so a light theme
/// turns the whole session white (the issue's "including the terminal it
/// runs on") and `Color::Reset` cells inherit the theme on every host. The
/// host fg is the theme's default code foreground, the color plain text
/// renders in anyway.
fn host_colors_seq(theme: crate::theme::Theme) -> String {
let (br, bg, bb) = theme.editor_bg_rgb();
let (fr, fg, fb) = theme.syntax().fg;
format!("\x1b]11;rgb:{br:02x}/{bg:02x}/{bb:02x}\x07\x1b]10;rgb:{fr:02x}/{fg:02x}/{fb:02x}\x07")
}
/// Reset the host terminal's default foreground and background to its own
/// configuration (OSC 110/111), undoing [`host_colors_seq`] on exit.
fn reset_host_colors_seq() -> &'static str {
"\x1b]110\x07\x1b]111\x07"
}
/// The host terminal croft is running inside, for spawning a new window of the
/// SAME terminal (Move/Copy into New Window). Detected from `$TERM_PROGRAM` /
/// `$TERM`, the same signals croft's inline-image detection keys off.
#[cfg(target_os = "macos")]
#[derive(Clone, Debug, PartialEq, Eq)]
enum HostTerminal {
Ghostty,
ITerm2,
AppleTerminal,
/// A terminal we don't know how to drive; carries its reported name so the
/// status line can say which one rather than failing silently.
Unknown(String),
}
#[cfg(target_os = "macos")]
fn detect_host_terminal(term_program: Option<&str>, term: Option<&str>) -> HostTerminal {
match term_program {
Some("ghostty") => HostTerminal::Ghostty,
Some("iTerm.app") => HostTerminal::ITerm2,
Some("Apple_Terminal") => HostTerminal::AppleTerminal,
Some(other) if !other.is_empty() => HostTerminal::Unknown(other.to_string()),
// Some setups only export TERM (e.g. `xterm-ghostty`).
_ if term.is_some_and(|t| t.contains("ghostty")) => HostTerminal::Ghostty,
_ => HostTerminal::Unknown(term.unwrap_or("unknown").to_string()),
}
}
/// Spawn a brand-new OS window of the terminal croft is running in, opening
/// `croft <root> --open-file <file> --zen` — VS Code's "Move/Copy into New
/// Window", realised as a genuine separate window so the originating croft is
/// never disturbed. The new window opens in `--zen` (Explorer + terminal hidden)
/// so it focuses on just the file. The croft binary is referenced by its
/// resolved ABSOLUTE path: a GUI-launched croft inherits a stripped launchd
/// PATH, so the bare name would not resolve in the new window's shell (see the
/// project memory on PATH stripping). macOS only.
#[cfg(target_os = "macos")]
fn spawn_new_window(root: &std::path::Path, file: &std::path::Path) -> std::io::Result<()> {
let exe = std::env::current_exe()?;
let host = detect_host_terminal(
std::env::var("TERM_PROGRAM").ok().as_deref(),
std::env::var("TERM").ok().as_deref(),
);
match host {
// Ghostty on macOS has no IPC (`+new-window` is Linux/GTK-only), so a
// new window must come from `open -na` (a fresh instance). A fresh
// instance would ALSO open its default window → two windows
// (ghostty-org/ghostty#8669; verified empirically). `--initial-window=false`
// suppresses that default (verified: it adds zero windows), so `-e`'s
// command window is the only one. `--quit-after-last-window-closed` makes
// the spawned instance exit once that window closes. `-e` is exec'd
// directly (no shell), so the croft argv is passed token-by-token.
HostTerminal::Ghostty => {
std::process::Command::new("open")
.args(ghostty_open_argv(&exe, root, file))
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()?;
Ok(())
}
// iTerm2 and Terminal have no `open --args` command path; both are driven
// by AppleScript, and both run the `command` / `do script` string through
// a shell, so the croft invocation is shell-quoted.
HostTerminal::ITerm2 => {
std::process::Command::new("osascript")
.arg("-e")
.arg(iterm2_new_window_script(&exe, root, file))
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()?;
Ok(())
}
HostTerminal::AppleTerminal => {
std::process::Command::new("osascript")
.arg("-e")
.arg(apple_terminal_new_window_script(&exe, root, file))
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()?;
Ok(())
}
HostTerminal::Unknown(name) => Err(std::io::Error::new(
std::io::ErrorKind::Unsupported,
format!("unsupported terminal '{name}'"),
)),
}
}
/// `open` argv for a new Ghostty window running croft, focused on the file
/// (`--zen`). `--initial-window=false` stops the fresh instance opening a stray
/// default window beside the `-e` one. Split out so the shape is unit-testable
/// without launching a window.
#[cfg(target_os = "macos")]
fn ghostty_open_argv(
exe: &std::path::Path,
root: &std::path::Path,
file: &std::path::Path,
) -> Vec<std::ffi::OsString> {
use std::ffi::OsString;
vec![
OsString::from("-na"),
OsString::from("Ghostty"),
OsString::from("--args"),
OsString::from("--initial-window=false"),
OsString::from("--quit-after-last-window-closed=true"),
OsString::from("-e"),
exe.as_os_str().to_os_string(),
root.as_os_str().to_os_string(),
OsString::from("--open-file"),
file.as_os_str().to_os_string(),
OsString::from("--zen"),
]
}
/// `croft <root> --open-file <file> --zen` as a single shell command line, with
/// every path single-quoted so spaces and shell metacharacters survive (iTerm2
/// `command` and Terminal `do script` both run it via a shell). `--zen` opens
/// the new window focused on the file (no sidebar/terminal).
#[cfg(target_os = "macos")]
fn new_window_shell_command(
exe: &std::path::Path,
root: &std::path::Path,
file: &std::path::Path,
) -> String {
fn shq(p: &std::path::Path) -> String {
format!("'{}'", p.to_string_lossy().replace('\'', r"'\''"))
}
format!("{} {} --open-file {} --zen", shq(exe), shq(root), shq(file))
}
/// Escape a Rust string for embedding inside an AppleScript double-quoted
/// string literal (backslash and double-quote are the only specials).
#[cfg(target_os = "macos")]
fn applescript_escape(s: &str) -> String {
s.replace('\\', "\\\\").replace('"', "\\\"")
}
/// AppleScript to open a new iTerm2 window running croft. iTerm2's `command`
/// argument overrides the profile's default `login`, running our shell command.
#[cfg(target_os = "macos")]
fn iterm2_new_window_script(
exe: &std::path::Path,
root: &std::path::Path,
file: &std::path::Path,
) -> String {
let cmd = applescript_escape(&new_window_shell_command(exe, root, file));
format!(r#"tell application "iTerm" to create window with default profile command "{cmd}""#)
}
/// AppleScript to open a new Terminal.app window running croft. `do script`
/// with no target opens a fresh window and runs the command there.
#[cfg(target_os = "macos")]
fn apple_terminal_new_window_script(
exe: &std::path::Path,
root: &std::path::Path,
file: &std::path::Path,
) -> String {
let cmd = applescript_escape(&new_window_shell_command(exe, root, file));
format!(r#"tell application "Terminal" to do script "{cmd}""#)
}
/// Non-macOS builds have no supported window-spawn path yet (each terminal's
/// CLI differs per platform); the caller surfaces the error as a status line.
#[cfg(not(target_os = "macos"))]
fn spawn_new_window(_root: &std::path::Path, _file: &std::path::Path) -> std::io::Result<()> {
Err(std::io::Error::new(
std::io::ErrorKind::Unsupported,
"opening a new window is only supported on macOS",
))
}
fn build_title(workspace: &std::path::Path) -> String {
let name = workspace
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.filter(|s| !s.is_empty())
.unwrap_or_else(|| workspace.display().to_string());
format!("{APP_NAME} {name}")
}
/// Returns true if the given key event should copy the terminal pane's
/// current selection to the clipboard. Recognises:
/// * `Ctrl+Shift+C` — universal Linux terminal copy convention; doesn't
/// collide with `Ctrl+C` (SIGINT).
/// * `Cmd+C` — for terminals that deliver Super via the kitty
/// keyboard protocol.
fn is_terminal_copy_key(key: KeyEvent) -> bool {
let KeyCode::Char(c) = key.code else {
return false;
};
if !c.eq_ignore_ascii_case(&'c') {
return false;
}
let ctrl_shift = key.modifiers.contains(KeyModifiers::CONTROL)
&& key.modifiers.contains(KeyModifiers::SHIFT);
let super_only = key.modifiers.contains(KeyModifiers::SUPER)
&& !key.modifiers.contains(KeyModifiers::CONTROL);
ctrl_shift || super_only
}
/// Returns true if the given key event should jump to the Search sidebar
/// view (VS Code's Ctrl/Cmd+Shift+F "Find in Files" gesture).
/// `Ctrl+D` / `Cmd+D` (no Shift). Used in the Explorer to drive the
/// "compare two files" flow:
/// * no anchor yet → stash the highlighted file as the anchor;
/// * anchor + different file → open a side-by-side diff;
/// * anchor + same file → clear the anchor (toggle off).
fn is_compare_key(key: KeyEvent) -> bool {
let KeyCode::Char(c) = key.code else {
return false;
};
if !c.eq_ignore_ascii_case(&'d') {
return false;
}
if key.modifiers.contains(KeyModifiers::SHIFT) || key.modifiers.contains(KeyModifiers::ALT) {
return false;
}
key.modifiers.contains(KeyModifiers::CONTROL) || key.modifiers.contains(KeyModifiers::SUPER)
}
fn is_search_jump_key(key: KeyEvent) -> bool {
let KeyCode::Char(c) = key.code else {
return false;
};
if !c.eq_ignore_ascii_case(&'f') {
return false;
}
let has_shift = key.modifiers.contains(KeyModifiers::SHIFT);
let has_ctrl_or_super = key.modifiers.contains(KeyModifiers::CONTROL)
|| key.modifiers.contains(KeyModifiers::SUPER);
has_shift && has_ctrl_or_super
}
/// VS Code-style `Cmd+F` / `Ctrl+F` inside the editor: open the inline
/// Find bar. Same chord as the Explorer's "New File" — the dispatch in
/// `handle_key` gives the Explorer handler first refusal so this only
/// fires when the editor is the focused pane.
fn is_editor_find_key(key: KeyEvent) -> bool {
let KeyCode::Char(c) = key.code else {
return false;
};
if !c.eq_ignore_ascii_case(&'f') {
return false;
}
if key.modifiers.contains(KeyModifiers::SHIFT) || key.modifiers.contains(KeyModifiers::ALT) {
return false;
}
key.modifiers.contains(KeyModifiers::CONTROL) || key.modifiers.contains(KeyModifiers::SUPER)
}
/// The terminal pane's find chord: Cmd+F everywhere, plus Ctrl+F off macOS
/// only (VS Code's terminal find defaults). On macOS Ctrl+F must reach the
/// child as 0x06 — it is a control byte programs bind — so the editor's
/// looser Ctrl-or-Cmd predicate must not gate the terminal pane there.
fn is_terminal_find_key(key: KeyEvent) -> bool {
if !is_editor_find_key(key) {
return false;
}
cfg!(not(target_os = "macos")) || key.modifiers.contains(KeyModifiers::SUPER)
}
/// VS Code-style `Cmd+Opt+F` / `Ctrl+Alt+F` inside the editor: open the
/// find bar expanded with the replace row (VS Code's
/// `editor.action.startFindReplaceAction`). The iTerm2 / Ghostty
/// forwarders deliver the macOS chord as CSI-u decoding to ALT|SUPER;
/// Linux kitty-protocol terminals report Ctrl+Alt+F as ALT|CONTROL.
/// Shift excluded: `Cmd+Opt+Shift+F` is Format Document.
fn is_editor_replace_key(key: KeyEvent) -> bool {
let KeyCode::Char(c) = key.code else {
return false;
};
if !c.eq_ignore_ascii_case(&'f') {
return false;
}
if key.modifiers.contains(KeyModifiers::SHIFT) || !key.modifiers.contains(KeyModifiers::ALT) {
return false;
}
key.modifiers.contains(KeyModifiers::CONTROL) || key.modifiers.contains(KeyModifiers::SUPER)
}
/// VS Code-style `Cmd+P` / `Ctrl+P`: open the Quick Open file finder.
/// Plain `p` with no modifier (or with Shift / Alt only) falls through so
/// the editor still receives literal `p` keystrokes.
fn is_file_finder_key(key: KeyEvent) -> bool {
let KeyCode::Char(c) = key.code else {
return false;
};
if !c.eq_ignore_ascii_case(&'p') {
return false;
}
if key.modifiers.contains(KeyModifiers::SHIFT) || key.modifiers.contains(KeyModifiers::ALT) {
return false;
}
key.modifiers.contains(KeyModifiers::CONTROL) || key.modifiers.contains(KeyModifiers::SUPER)
}
/// `Ctrl/Cmd+Shift+P`: open the Command Palette from any pane, mirroring VS
/// Code. Shares the `is_cmd_shift_letter` helper with the sidebar-view jumps
/// so the SHIFT / case handling is identical, and sits after
/// `is_file_finder_key` in the dispatch (which rejects SHIFT, so `Cmd+P` and
/// `Cmd+Shift+P` never collide).
fn is_command_palette_key(key: KeyEvent) -> bool {
is_cmd_shift_letter(key, 'p')
}
/// `Cmd+Shift+O` (macOS) / `Ctrl+Shift+O` (Linux): VS Code's "Go to Symbol in
/// Editor". Opens the symbol picker (also Go to Line via a `:` prefix).
fn is_go_to_symbol_key(key: KeyEvent) -> bool {
is_cmd_shift_letter(key, 'o')
}
/// `Cmd+K` (macOS) / `Ctrl+K` (Linux / Termux): the leader for croft's
/// `Cmd+K`-prefixed chords (Color Theme, Close to the Right, Select for /
/// Compare with Selected, Close All). Rejects Shift and Alt so it never
/// shadows a future `Cmd+K`+modifier chord.
fn is_cmd_k_leader_key(key: KeyEvent) -> bool {
let KeyCode::Char(c) = key.code else {
return false;
};
if !c.eq_ignore_ascii_case(&'k') {
return false;
}
if key.modifiers.contains(KeyModifiers::SHIFT) || key.modifiers.contains(KeyModifiers::ALT) {
return false;
}
// SUPER everywhere; CONTROL only on Termux (where Ctrl is the cmd
// surrogate). Off Termux a bare Ctrl+K must fall through to the editor's
// kill-to-end-of-line rather than arming the leader — using `has_cmd`
// keeps this consistent with every other croft chord (e.g. Cmd+\ split).
has_cmd(key.modifiers)
}
/// `Cmd+/` (macOS) / `Ctrl+/` (Linux / Termux): Toggle Line Comment. Rejects
/// Shift and Alt so it never collides with a future chord on `/`.
fn is_toggle_line_comment_key(key: KeyEvent) -> bool {
if key.code != KeyCode::Char('/') {
return false;
}
if key.modifiers.contains(KeyModifiers::ALT) || key.modifiers.contains(KeyModifiers::SHIFT) {
return false;
}
key.modifiers.contains(KeyModifiers::CONTROL) || key.modifiers.contains(KeyModifiers::SUPER)
}
/// `Shift+Alt+A`: Toggle Block Comment (the VS Code default). Requires both
/// Shift and Alt and rejects the command modifier. Also reachable from the
/// Command Palette, which is the parity path on terminals that swallow the
/// Alt+letter chord.
fn is_toggle_block_comment_key(key: KeyEvent) -> bool {
let KeyCode::Char(c) = key.code else {
return false;
};
if !c.eq_ignore_ascii_case(&'a') {
return false;
}
key.modifiers.contains(KeyModifiers::SHIFT)
&& key.modifiers.contains(KeyModifiers::ALT)
&& !key.modifiers.contains(KeyModifiers::SUPER)
&& !key.modifiers.contains(KeyModifiers::CONTROL)
}
/// `Alt+Z`: View: Toggle Word Wrap (the VS Code default). Rejects Shift and
/// the command modifier. Also reachable from the Command Palette.
fn is_toggle_wrap_key(key: KeyEvent) -> bool {
let KeyCode::Char(c) = key.code else {
return false;
};
if !c.eq_ignore_ascii_case(&'z') {
return false;
}
key.modifiers.contains(KeyModifiers::ALT)
&& !key.modifiers.contains(KeyModifiers::SHIFT)
&& !key.modifiers.contains(KeyModifiers::SUPER)
&& !key.modifiers.contains(KeyModifiers::CONTROL)
}
/// Explorer-pane shortcut: `Cmd+Z` — open the zoxide jump popup. `z` for
/// **z**oxide; the user's shell still uses `j` for the same jump. Requires
/// SUPER (iTerm2 already forwards Cmd+Z as `Char('z') + SUPER` for the
/// editor's undo via the `CMD_Z` GlobalKeyMap entry). Off Termux it rejects
/// CONTROL so a terminal `Ctrl+Z` suspend never reaches it and it stays
/// distinct from the Ctrl-based terminal-toggle chords on `j`; on Termux,
/// where Ctrl is the Cmd surrogate, `Ctrl+Z` opens the popup (this predicate
/// only runs while the Explorer is focused, so there is no suspend to clash).
/// SHIFT is rejected because `Cmd+Shift+Z` is the reserved redo chord.
/// Editor-pane `Cmd+Z` is untouched: this predicate is only consulted from
/// `handle_explorer_shortcut`, which runs solely when the Explorer is
/// focused (and gets first refusal in the dispatch chain).
fn is_tree_zoxide_jump_key(key: KeyEvent) -> bool {
let KeyCode::Char(c) = key.code else {
return false;
};
if !c.eq_ignore_ascii_case(&'z') {
return false;
}
if key.modifiers.contains(KeyModifiers::SHIFT) || key.modifiers.contains(KeyModifiers::ALT) {
return false;
}
// `has_cmd` is SUPER-only off Termux (so a terminal `Ctrl+Z` suspend is
// never swallowed); on Termux Ctrl is the command key, and this predicate
// only runs while the Explorer is focused, so there is no suspend to clash.
has_cmd(key.modifiers)
}
/// Explorer-pane shortcut: `Cmd+F` / `Ctrl+F` (no Shift, no Alt) - "New File".
fn is_tree_new_file_key(key: KeyEvent) -> bool {
let KeyCode::Char(c) = key.code else {
return false;
};
if !c.eq_ignore_ascii_case(&'f') {
return false;
}
if key.modifiers.contains(KeyModifiers::SHIFT) || key.modifiers.contains(KeyModifiers::ALT) {
return false;
}
key.modifiers.contains(KeyModifiers::CONTROL) || key.modifiers.contains(KeyModifiers::SUPER)
}
/// Explorer-pane shortcut: `Cmd+Shift+N` / `Ctrl+Shift+N` - "New Folder".
/// The global dispatcher gives the Explorer-context handler first refusal
/// so this only fires when the tree is the focused pane; outside Explorer
/// the chord is unbound and falls through to the focused pane.
fn is_tree_new_folder_key(key: KeyEvent) -> bool {
let KeyCode::Char(c) = key.code else {
return false;
};
if !c.eq_ignore_ascii_case(&'n') {
return false;
}
if !key.modifiers.contains(KeyModifiers::SHIFT) || key.modifiers.contains(KeyModifiers::ALT) {
return false;
}
key.modifiers.contains(KeyModifiers::CONTROL) || key.modifiers.contains(KeyModifiers::SUPER)
}
/// Explorer-pane shortcut: `Cmd+R` / `Ctrl+R` (no Shift) OR plain `F2` -
/// "Rename". F2 is the cross-IDE convention; Cmd+R matches the user-
/// requested chord (overrides iTerm's "Clear buffer" via setup-iterm2).
fn is_tree_rename_key(key: KeyEvent) -> bool {
if matches!(key.code, KeyCode::F(2)) {
return true;
}
let KeyCode::Char(c) = key.code else {
return false;
};
if !c.eq_ignore_ascii_case(&'r') {
return false;
}
if key.modifiers.contains(KeyModifiers::SHIFT) || key.modifiers.contains(KeyModifiers::ALT) {
return false;
}
key.modifiers.contains(KeyModifiers::CONTROL) || key.modifiers.contains(KeyModifiers::SUPER)
}
/// `Cmd+Opt+R` / `Ctrl+Opt+R` - "Reveal in Finder". Used by both the Explorer
/// (reveals the selected entry) and the editor (reveals the active file's path).
/// The Alt requirement keeps this disjoint from `Cmd+R` (Rename), which rejects
/// Alt, so the two R chords never collide. The caller additionally gates this to
/// a local macOS session, matching the context-menu entry.
fn is_reveal_in_finder_key(key: KeyEvent) -> bool {
let KeyCode::Char(c) = key.code else {
return false;
};
if !c.eq_ignore_ascii_case(&'r') {
return false;
}
if !key.modifiers.contains(KeyModifiers::ALT) || key.modifiers.contains(KeyModifiers::SHIFT) {
return false;
}
key.modifiers.contains(KeyModifiers::CONTROL) || key.modifiers.contains(KeyModifiers::SUPER)
}
/// `Cmd+Opt+C` / `Ctrl+Opt+C` - "Copy Path": put the active file's absolute
/// path on the system clipboard. The Alt requirement keeps it disjoint from
/// plain `Cmd+C` (Copy selection), and rejecting Shift keeps it disjoint from
/// `Cmd+Opt+Shift+C` (Copy Relative Path). Mirrors VS Code's binding.
fn is_copy_path_key(key: KeyEvent) -> bool {
let KeyCode::Char(c) = key.code else {
return false;
};
if !c.eq_ignore_ascii_case(&'c') {
return false;
}
if !key.modifiers.contains(KeyModifiers::ALT) || key.modifiers.contains(KeyModifiers::SHIFT) {
return false;
}
key.modifiers.contains(KeyModifiers::CONTROL) || key.modifiers.contains(KeyModifiers::SUPER)
}
/// Explorer-pane shortcut: `Cmd+/` / `Ctrl+/` - "Make root". Re-roots the
/// workspace at the selected folder.
fn is_tree_make_root_key(key: KeyEvent) -> bool {
if !matches!(key.code, KeyCode::Char('/')) {
return false;
}
if key.modifiers.contains(KeyModifiers::SHIFT) || key.modifiers.contains(KeyModifiers::ALT) {
return false;
}
key.modifiers.contains(KeyModifiers::CONTROL) || key.modifiers.contains(KeyModifiers::SUPER)
}
/// Explorer-pane shortcut: `Cmd+Shift+/` / `Ctrl+Shift+/` - "Make root at
/// parent". Re-roots the workspace at the parent of the selected node
/// (file or folder). The selected node itself remains on disk and the
/// new root is one filesystem level up. Terminals that strip Shift on
/// shifted punctuation report `?`; we accept both `/+Shift` and `?` to
/// cover the spread.
fn is_tree_make_parent_root_key(key: KeyEvent) -> bool {
if key.modifiers.contains(KeyModifiers::ALT) {
return false;
}
let has_ctrl_or_super = key.modifiers.contains(KeyModifiers::CONTROL)
|| key.modifiers.contains(KeyModifiers::SUPER);
if !has_ctrl_or_super {
return false;
}
match key.code {
KeyCode::Char('/') => key.modifiers.contains(KeyModifiers::SHIFT),
KeyCode::Char('?') => true,
_ => false,
}
}
/// `Ctrl/Cmd+Shift+E`: jump to the Explorer sidebar view from any pane.
/// Matches VS Code's "View: Show Explorer" command.
fn is_explorer_jump_key(key: KeyEvent) -> bool {
is_cmd_shift_letter(key, 'e')
}
/// `Ctrl/Cmd+Shift+S`: jump to the Source Control sidebar view from any pane.
/// This is croft's Source Control gesture. Croft has no editor Save-As (Cmd+S
/// alone saves), so claiming Cmd+Shift+S is collision-free even while editing.
fn is_source_control_jump_key(key: KeyEvent) -> bool {
is_cmd_shift_letter(key, 's')
}
/// `Ctrl/Cmd+Shift+D`: jump to the Run and Debug sidebar view from any pane.
/// Matches VS Code's "View: Show Run and Debug" command. iTerm2 binds the
/// same chord to "Split Horizontally with Same Profile" — `setup-iterm2`
/// relocates that menu item to Cmd+Opt+Shift+D so this chord reaches croft.
fn is_run_debug_jump_key(key: KeyEvent) -> bool {
is_cmd_shift_letter(key, 'd')
}
/// `Ctrl/Cmd+Shift+R`: jump to the Remote (SSH) sidebar view from any pane.
/// VS Code uses this for "Remote Explorer" in the Remote Development pack —
/// same intent.
fn is_remote_jump_key(key: KeyEvent) -> bool {
is_cmd_shift_letter(key, 'r')
}
/// `Ctrl/Cmd+Shift+X`: jump to the Extensions sidebar view from any pane.
/// Matches VS Code's "View: Show Extensions". Cmd+Shift+X is unbound by any
/// default macOS / iTerm2 menu item, so `setup-iterm2` only needs the
/// GlobalKeyMap forwarder (no menu relocation) to deliver it here.
fn is_extensions_jump_key(key: KeyEvent) -> bool {
is_cmd_shift_letter(key, 'x')
}
/// The TurnDone status fragment for a turn's notes: the file is named only
/// when every note landed in the SAME file. "3 comments in b.rs" was a lie
/// when two of them sat in a.rs (F4 only cycles the active file, so the
/// name tells the user where to look).
fn turn_note_summary(notes: usize, files: &std::collections::BTreeSet<String>) -> String {
let plural = if notes == 1 { "comment" } else { "comments" };
match files.len() {
0 => format!("{notes} {plural}"),
1 => format!(
"{notes} {plural} in {}",
files.iter().next().expect("len checked")
),
n => format!("{notes} {plural} across {n} files"),
}
}
/// Index of the next navigator note to visit from `here` = (row, index of
/// the currently focused note, or `usize::MAX` when the walk starts from a
/// bare caret row): the note with the smallest (row, index) strictly greater
/// than `here`, wrapping to the smallest overall. The index tie-break makes
/// every note on a shared row reachable - the reply flow anchors the
/// navigator's answer on the answered note's own row, and a row-only walk
/// could never step from the first co-anchored note to the second.
fn next_note_by_row(notes: &[(u64, usize, String)], here: (usize, usize)) -> usize {
notes
.iter()
.enumerate()
.filter(|(i, (_, row, _))| (*row, *i) > here)
.min_by_key(|(i, (_, row, _))| (*row, *i))
.or_else(|| {
notes
.iter()
.enumerate()
.min_by_key(|(i, (_, row, _))| (*row, *i))
})
.map(|(i, _)| i)
.unwrap_or(0)
}
fn is_drop_to_local_key(key: KeyEvent) -> bool {
is_cmd_shift_letter(key, 'l')
}
/// `Ctrl/Cmd+Shift+B`: run the project's auto-detected build task, VS
/// Code's "Tasks: Run Build Task" chord. iTerm2 binds the same chord to
/// "Show Toolbelt" — `setup-iterm2` relocates that menu item to
/// Cmd+Ctrl+B so this chord reaches croft.
fn is_run_build_task_key(key: KeyEvent) -> bool {
is_cmd_shift_letter(key, 'b')
}
/// `Cmd/Ctrl+Shift+V`: Markdown: Toggle Preview (the VS Code default chord).
/// iTerm2 binds the same chord to Paste Special > "Paste Selection" —
/// `setup-iterm2` relocates that menu item so this chord reaches croft.
fn is_markdown_preview_key(key: KeyEvent) -> bool {
is_cmd_shift_letter(key, 'v')
}
/// Cmd+Enter (#353): run the shell fence under the caret in a Markdown
/// source buffer.
fn is_run_fence_key(key: KeyEvent) -> bool {
matches!(key.code, KeyCode::Enter)
&& key.modifiers.contains(KeyModifiers::SUPER)
// Cmd+Shift+Enter is "insert line above"; Alt chords stay the
// editor's.
&& !key
.modifiers
.intersects(KeyModifiers::SHIFT | KeyModifiers::ALT)
}
/// The command typed into a pane for a fenced block (#353): a shell block
/// as written (a trailing newline runs its last line); python and node
/// through a quoted heredoc so the block runs whole. The terminator is
/// chosen not to occur in the block, or a line inside it could close the
/// heredoc early and hand the rest to the shell.
fn fence_command(interpreter: &str, code: &str) -> String {
let code = code.trim_end_matches('\n');
match interpreter {
"sh" => format!("{code}\r"),
other => {
let mut end = String::from("CROFT_BLOCK");
let mut n = 0u32;
while code.contains(&end) {
n += 1;
end = format!("CROFT_BLOCK_{n}");
}
format!("{other} - <<'{end}'\n{code}\n{end}\r")
}
}
}
/// Milliseconds since the Unix epoch, for stamping local-history snapshots
/// and dating TIMELINE rows.
fn now_millis() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis() as u64)
.unwrap_or(0)
}
fn is_cmd_shift_letter(key: KeyEvent, letter: char) -> bool {
let KeyCode::Char(c) = key.code else {
return false;
};
if !c.eq_ignore_ascii_case(&letter) {
return false;
}
if key.modifiers.contains(KeyModifiers::ALT) {
return false;
}
let has_shift = key.modifiers.contains(KeyModifiers::SHIFT);
let has_ctrl_or_super = key.modifiers.contains(KeyModifiers::CONTROL)
|| key.modifiers.contains(KeyModifiers::SUPER);
has_shift && has_ctrl_or_super
}
/// The status line shown after a keybindings reload.
///
/// Split out of `reload_config_for_path` so it can be tested against a keymap
/// built in memory. The alternative — a test that writes the real
/// `~/.config/croft/keybindings.json` — would leak into every one of the
/// thousands of concurrent tests that construct an `App`, since `App::new`
/// loads that path unconditionally.
fn keybindings_reload_status(warns: &[String]) -> String {
if warns.is_empty() {
String::from(
"Keybindings reloaded (for new Cmd chords, re-run croft setup-iterm2 / setup-ghostty)",
)
} else {
// One assignment: a second unconditional one below used to clobber
// this, so the user never saw the warning count and a refused row
// looked like croft ignoring them.
format!(
"Keybindings reloaded with {} warning{} — see OUTPUT · Keybindings",
warns.len(),
if warns.len() == 1 { "" } else { "s" }
)
}
}
/// `Cmd+B` (macOS) / `Ctrl+B` (Linux): toggle the primary side bar (left
/// pane) visibility, mirroring VS Code's "View: Toggle Primary Side Bar".
/// Accepts SUPER *or* CONTROL so the chord behaves identically whether
/// iTerm2 forwards `Cmd+B` as the CSI-u Super sequence (see `src/iterm2.rs`)
/// or a raw `Ctrl+B` control byte arrives on a remote Linux session. SHIFT
/// and ALT must not be held, so it never collides with a future bracketed
/// or word-motion chord on `b`.
fn is_sidebar_toggle_key(key: KeyEvent) -> bool {
let KeyCode::Char(c) = key.code else {
return false;
};
if !c.eq_ignore_ascii_case(&'b') {
return false;
}
if key.modifiers.contains(KeyModifiers::ALT) || key.modifiers.contains(KeyModifiers::SHIFT) {
return false;
}
key.modifiers.contains(KeyModifiers::CONTROL) || key.modifiers.contains(KeyModifiers::SUPER)
}
/// `⌥⌘B` (macOS) / `Ctrl+Alt+B` (Linux): toggle the secondary side bar (the
/// Outline), the edge opposite the primary side bar. ALT distinguishes it from
/// the plain ⌘B/Ctrl+B primary-side-bar toggle.
fn is_secondary_sidebar_toggle_key(key: KeyEvent) -> bool {
let KeyCode::Char(c) = key.code else {
return false;
};
if !c.eq_ignore_ascii_case(&'b') {
return false;
}
if !key.modifiers.contains(KeyModifiers::ALT) || key.modifiers.contains(KeyModifiers::SHIFT) {
return false;
}
key.modifiers.contains(KeyModifiers::CONTROL) || key.modifiers.contains(KeyModifiers::SUPER)
}
/// Returns true for `Cmd+Opt+M` (the CSI-u forwarders decode it as ALT|SUPER):
/// VS Code's "View: Toggle Minimap". SHIFT must not be held.
fn is_minimap_toggle_key(key: KeyEvent) -> bool {
let KeyCode::Char(c) = key.code else {
return false;
};
if !c.eq_ignore_ascii_case(&'m') {
return false;
}
if !key.modifiers.contains(KeyModifiers::ALT) || key.modifiers.contains(KeyModifiers::SHIFT) {
return false;
}
key.modifiers.contains(KeyModifiers::CONTROL) || key.modifiers.contains(KeyModifiers::SUPER)
}
/// Returns true if the given key event should toggle the terminal pane.
/// VS Code uses `Ctrl+`` ` `` (backtick); we use `Ctrl+J` to match its
/// "Toggle Terminal Panel" shortcut, which is more reliable to type on
/// non-US keyboards. Case-insensitive on the letter. SHIFT must NOT be
/// held — Ctrl+Shift+J is reserved for the maximize-terminal chord and
/// must not double-fire as a toggle.
fn is_terminal_toggle_key(key: KeyEvent) -> bool {
let KeyCode::Char(c) = key.code else {
return false;
};
if !c.eq_ignore_ascii_case(&'j') {
return false;
}
key.modifiers.contains(KeyModifiers::CONTROL) && !key.modifiers.contains(KeyModifiers::SHIFT)
}
/// `Ctrl+Shift+J`: toggle "maximize terminal" — the editor / welcome pane
/// collapses and the terminal fills the right column next to the Explorer.
/// Pressing it again restores the previous editor↔terminal split.
fn is_terminal_maximize_key(key: KeyEvent) -> bool {
let KeyCode::Char(c) = key.code else {
return false;
};
if !c.eq_ignore_ascii_case(&'j') {
return false;
}
key.modifiers.contains(KeyModifiers::CONTROL)
&& key.modifiers.contains(KeyModifiers::SHIFT)
&& !key.modifiers.contains(KeyModifiers::ALT)
&& !key.modifiers.contains(KeyModifiers::SUPER)
}
/// `Cmd+T` (or legacy `Ctrl+Shift+T`): spawn an additional terminal next
/// to the active one. iTerm2's GlobalKeyMap forwards `Cmd+T` as
/// `ESC [ 116 ; 9 u`, which crossterm decodes to `Char('t') + SUPER`.
/// In the SUPER branch we reject SHIFT so the `Cmd+Shift+T` focus chord
/// (see `is_terminal_focus_key`) does not double-fire as a split, and
/// reject ALT so `Cmd+Opt+T` (iTerm2's relocated New Tab) is left alone.
/// `Ctrl+Shift+Space`: WezTerm's quick-select chord. No Cmd involved, so it
/// needs no host-terminal forwarder — it arrives disambiguated through the
/// kitty keyboard protocol exactly like the Ctrl+Shift+T split chord.
/// One compiled per-host accent rule: hostname glob, accent color, badge.
type HostAccent = (globset::GlobMatcher, (u8, u8, u8), Option<String>);
/// Compile the prefs' host-accent rules: glob matcher + color (danger red
/// when unset) + badge. A rule with an invalid glob is skipped.
fn compile_host_accents(rules: &[crate::prefs::HostAccentRule]) -> Vec<HostAccent> {
rules
.iter()
.filter_map(|r| {
let m = globset::Glob::new(&r.pattern).ok()?.compile_matcher();
let color = r
.accent
.as_deref()
.and_then(crate::prefs::parse_hex)
.unwrap_or((0xf1, 0x4c, 0x4c));
Some((m, color, r.badge.clone()))
})
.collect()
}
fn is_quick_select_key(key: KeyEvent) -> bool {
matches!(key.code, KeyCode::Char(' '))
&& key.modifiers.contains(KeyModifiers::CONTROL)
&& key.modifiers.contains(KeyModifiers::SHIFT)
}
/// `Ctrl+Shift+Y` (Y for yank; WezTerm's Ctrl+Shift+X is croft's
/// Extensions jump). Arrives via the kitty keyboard protocol, so no
/// iTerm2/Ghostty forwarder is needed.
fn is_copy_mode_key(key: KeyEvent) -> bool {
matches!(key.code, KeyCode::Char('y' | 'Y'))
&& key.modifiers.contains(KeyModifiers::CONTROL)
&& key.modifiers.contains(KeyModifiers::SHIFT)
}
/// `Ctrl+Shift+H` (H for history; atuin's Ctrl+R belongs to the shell and
/// Ctrl+Shift+R is croft's Remote jump). Kitty-protocol chord, no
/// forwarder needed.
fn is_command_history_key(key: KeyEvent) -> bool {
matches!(key.code, KeyCode::Char('h' | 'H'))
&& key.modifiers.contains(KeyModifiers::CONTROL)
&& key.modifiers.contains(KeyModifiers::SHIFT)
}
fn is_terminal_split_key(key: KeyEvent) -> bool {
let KeyCode::Char(c) = key.code else {
return false;
};
if !c.eq_ignore_ascii_case(&'t') {
return false;
}
if has_cmd(key.modifiers)
&& !key.modifiers.contains(KeyModifiers::SHIFT)
&& !key.modifiers.contains(KeyModifiers::ALT)
{
return true;
}
key.modifiers.contains(KeyModifiers::CONTROL) && key.modifiers.contains(KeyModifiers::SHIFT)
}
/// `Cmd+\`: split the editor into two side-by-side columns (VS Code's
/// `workbench.action.splitEditor`). iTerm2's GlobalKeyMap forwards it as
/// `ESC [ 92 ; 9 u`, which crossterm decodes to `Char('\\') + SUPER`.
/// SUPER-only; reject SHIFT/ALT so it can't double-fire with a future
/// modified backslash chord.
fn is_editor_split_key(key: KeyEvent) -> bool {
let KeyCode::Char('\\') = key.code else {
return false;
};
// SUPER off Termux; on Termux `Ctrl+\` is the command surrogate (note this
// shadows the shell's SIGQUIT there, the accepted cost of Ctrl parity).
has_cmd(key.modifiers)
&& !key.modifiers.contains(KeyModifiers::SHIFT)
&& !key.modifiers.contains(KeyModifiers::ALT)
}
/// `Cmd+Shift+\`: Go to Bracket (VS Code's `editor.action.jumpToBracket`). The
/// same `\` key as the split chord but with Shift, so the two are disjoint.
fn is_goto_bracket_key(key: KeyEvent) -> bool {
let KeyCode::Char('\\') = key.code else {
return false;
};
has_cmd(key.modifiers)
&& key.modifiers.contains(KeyModifiers::SHIFT)
&& !key.modifiers.contains(KeyModifiers::ALT)
}
/// `Cmd+Opt+\`: Select to Bracket (VS Code's `editor.action.selectToBracket`).
/// The `\` bracket-family key with Opt (not Shift), disjoint from the split
/// chord (`Cmd+\`) and Go to Bracket (`Cmd+Shift+\`).
fn is_select_to_bracket_key(key: KeyEvent) -> bool {
let KeyCode::Char('\\') = key.code else {
return false;
};
has_cmd(key.modifiers)
&& key.modifiers.contains(KeyModifiers::ALT)
&& !key.modifiers.contains(KeyModifiers::SHIFT)
}
/// VS Code "Go Back" (Ctrl+-). The kitty keyboard protocol delivers the
/// chord as `-` + CONTROL; the legacy encoding folds Ctrl+- into 0x1F,
/// which decodes as `_` + CONTROL, so both spellings are accepted.
fn is_navigate_back_key(key: KeyEvent) -> bool {
let KeyCode::Char(c) = key.code else {
return false;
};
(c == '-' || c == '_')
&& key.modifiers.contains(KeyModifiers::CONTROL)
&& !key.modifiers.contains(KeyModifiers::SUPER)
&& !key.modifiers.contains(KeyModifiers::ALT)
&& !key.modifiers.contains(KeyModifiers::SHIFT)
}
/// VS Code "Go Forward" (Ctrl+Shift+-). Only the explicitly SHIFT-tagged
/// spellings count: the kitty protocol reports the chord as `-` (or the
/// shifted `_`) with CONTROL|SHIFT, while the legacy 0x1F byte decodes as
/// `_` + CONTROL with no SHIFT and must stay Go Back (a legacy host cannot
/// distinguish Ctrl+- from Ctrl+Shift+-, and Back is the safer meaning).
fn is_navigate_forward_key(key: KeyEvent) -> bool {
let KeyCode::Char(c) = key.code else {
return false;
};
(c == '-' || c == '_')
&& key.modifiers.contains(KeyModifiers::CONTROL)
&& key.modifiers.contains(KeyModifiers::SHIFT)
&& !key.modifiers.contains(KeyModifiers::SUPER)
&& !key.modifiers.contains(KeyModifiers::ALT)
}
/// `Ctrl+T`: Transpose Characters around the Cursor (VS Code's
/// `editor.action.transpose`). A raw control byte, so it needs no iTerm2 /
/// Ghostty forwarder; the editor intercepts it only when focused, leaving the
/// shell's own `Ctrl+T` intact when the terminal is focused.
fn is_transpose_key(key: KeyEvent) -> bool {
let KeyCode::Char(c) = key.code else {
return false;
};
if !c.eq_ignore_ascii_case(&'t') {
return false;
}
key.modifiers.contains(KeyModifiers::CONTROL)
&& !key.modifiers.contains(KeyModifiers::SUPER)
&& !key.modifiers.contains(KeyModifiers::ALT)
&& !key.modifiers.contains(KeyModifiers::SHIFT)
}
/// `Cmd+Opt+Shift+S`: Convert Indentation to Spaces
/// (`editor.action.indentationToSpaces`).
fn is_indentation_to_spaces_key(key: KeyEvent) -> bool {
is_cmd_alt_shift_letter(key, 's')
}
/// `Cmd+Opt+Shift+T`: Convert Indentation to Tabs
/// (`editor.action.indentationToTabs`).
fn is_indentation_to_tabs_key(key: KeyEvent) -> bool {
is_cmd_alt_shift_letter(key, 't')
}
/// `Cmd+Opt+Shift+N`: Trim Final Newlines (VS Code's `files.trimFinalNewlines`
/// surfaced as a command).
fn is_trim_final_newlines_key(key: KeyEvent) -> bool {
is_cmd_alt_shift_letter(key, 'n')
}
/// `Cmd+Opt+Shift+J`: Join Lines (`editor.action.joinLines`).
fn is_join_lines_key(key: KeyEvent) -> bool {
is_cmd_alt_shift_letter(key, 'j')
}
/// `Cmd+Opt+Shift+U`: Transform to Uppercase (`editor.action.transformToUppercase`).
fn is_transform_upper_key(key: KeyEvent) -> bool {
is_cmd_alt_shift_letter(key, 'u')
}
/// `Cmd+Opt+Shift+L`: Transform to Lowercase (`editor.action.transformToLowercase`).
fn is_transform_lower_key(key: KeyEvent) -> bool {
is_cmd_alt_shift_letter(key, 'l')
}
/// `Cmd+Opt+Shift+C` / `Ctrl+Opt+Shift+C` - "Copy Relative Path": put the
/// active file's path, relative to the workspace root, on the clipboard. The
/// Shift distinguishes it from plain `Cmd+Opt+C` (Copy Path, absolute). Mirrors
/// VS Code's binding; Transform to Title Case keeps its Command Palette entry
/// but gives up this chord (VS Code assigns Title Case no default key).
fn is_copy_relative_path_key(key: KeyEvent) -> bool {
is_cmd_alt_shift_letter(key, 'c')
}
/// `Cmd+Opt+Shift+A`: Sort Lines Ascending (`editor.action.sortLinesAscending`).
fn is_sort_lines_asc_key(key: KeyEvent) -> bool {
is_cmd_alt_shift_letter(key, 'a')
}
/// `Cmd+Opt+Shift+D`: Sort Lines Descending (`editor.action.sortLinesDescending`).
fn is_sort_lines_desc_key(key: KeyEvent) -> bool {
is_cmd_alt_shift_letter(key, 'd')
}
/// `Cmd+Opt+Shift+W`: Trim Trailing Whitespace (`editor.action.trimTrailingWhitespace`).
fn is_trim_trailing_whitespace_key(key: KeyEvent) -> bool {
is_cmd_alt_shift_letter(key, 'w')
}
/// `Cmd+Opt+Shift+F`: Format Document (`editor.action.formatDocument`, VS Code's
/// `Shift+Alt+F`). Reformats the whole buffer through the language server.
fn is_format_document_key(key: KeyEvent) -> bool {
is_cmd_alt_shift_letter(key, 'f')
}
/// The breadcrumb scope chain for `line`: the indices of every outline symbol
/// whose range encloses the caret line, ordered outermost first (the enclosing
/// class before the method inside it). Sibling symbols never overlap, so the
/// enclosing symbols form a single nesting chain and ordering by decreasing
/// span puts the outermost first.
fn breadcrumb_symbol_chain(
symbols: &[crate::lsp::manager::OutlineSymbol],
line: u32,
) -> Vec<usize> {
let mut hits: Vec<usize> = symbols
.iter()
.enumerate()
.filter(|(_, s)| line >= s.range_start_line && line <= s.range_end_line)
.map(|(i, _)| i)
.collect();
hits.sort_by(|&a, &b| {
let span = |i: usize| symbols[i].range_end_line - symbols[i].range_start_line;
span(b).cmp(&span(a)).then(
symbols[a]
.range_start_line
.cmp(&symbols[b].range_start_line),
)
});
hits
}
/// VS Code "Quick Fix": `Cmd+.` on macOS (delivered as `Char('.')` + SUPER by
/// the iTerm2 / Ghostty CSI-u forwarder) and `Ctrl+.` on Linux / Termux. Plain
/// `.`, `Shift+.` ('>'), and `Alt+.` (the shell's last-argument) are excluded.
fn is_quick_fix_key(key: KeyEvent) -> bool {
matches!(key.code, KeyCode::Char('.'))
&& (key.modifiers.contains(KeyModifiers::SUPER)
|| key.modifiers.contains(KeyModifiers::CONTROL))
&& !key.modifiers.contains(KeyModifiers::ALT)
&& !key.modifiers.contains(KeyModifiers::SHIFT)
}
/// True for `Cmd+Opt+Shift+<letter>` (or `Ctrl+Opt+Shift+<letter>` on Termux):
/// the three-modifier sibling of [`is_cmd_shift_letter`], used for editor
/// commands VS Code leaves unbound so croft can still honor "everything has a
/// shortcut" without colliding with the two-modifier `Cmd+Shift+<letter>` set.
fn is_cmd_alt_shift_letter(key: KeyEvent, letter: char) -> bool {
let KeyCode::Char(c) = key.code else {
return false;
};
if !c.eq_ignore_ascii_case(&letter) {
return false;
}
let has_shift = key.modifiers.contains(KeyModifiers::SHIFT);
let has_alt = key.modifiers.contains(KeyModifiers::ALT);
let has_cmd_or_ctrl = key.modifiers.contains(KeyModifiers::CONTROL)
|| key.modifiers.contains(KeyModifiers::SUPER);
has_shift && has_alt && has_cmd_or_ctrl
}
/// `Cmd+Opt+Left`: move keyboard focus to the LEFT editor group while
/// split. Distinct from the plain `Opt+Left` word-left motion (no SUPER)
/// by requiring both SUPER and ALT. iTerm2 forwards it as `ESC [ 1 ; 12 D`.
fn is_focus_group_left_key(key: KeyEvent) -> bool {
let KeyCode::Left = key.code else {
return false;
};
has_cmd(key.modifiers) && key.modifiers.contains(KeyModifiers::ALT)
}
/// `Cmd+Opt+Right`: move keyboard focus to the RIGHT editor group while
/// split. Mirror of `is_focus_group_left_key`. iTerm2 forwards it as
/// `ESC [ 1 ; 12 C`.
fn is_focus_group_right_key(key: KeyEvent) -> bool {
let KeyCode::Right = key.code else {
return false;
};
has_cmd(key.modifiers) && key.modifiers.contains(KeyModifiers::ALT)
}
/// `Cmd+Shift+T` (Mac SUPER+SHIFT+T): focus the Terminal pane from any
/// pane, un-hiding it if it was collapsed via Ctrl+J. SUPER-only so the
/// cross-platform `Ctrl+Shift+T` (split-terminal) chord keeps its
/// historical meaning - the two chords share the same letter but are
/// disambiguated by the modifier.
fn is_terminal_focus_key(key: KeyEvent) -> bool {
let KeyCode::Char(c) = key.code else {
return false;
};
if !c.eq_ignore_ascii_case(&'t') {
return false;
}
if key.modifiers.contains(KeyModifiers::ALT) || key.modifiers.contains(KeyModifiers::CONTROL) {
return false;
}
key.modifiers.contains(KeyModifiers::SUPER) && key.modifiers.contains(KeyModifiers::SHIFT)
}
/// `Cmd+W` (or legacy `Ctrl+Shift+W`): close the active terminal (no-op if
/// it's the only one). Plain `Ctrl+W` is intentionally excluded so the shell's
/// delete-word-backward keeps working; the close action requires either the
/// Super (Cmd) modifier or the Ctrl+Shift pair.
fn is_terminal_close_key(key: KeyEvent) -> bool {
let KeyCode::Char(c) = key.code else {
return false;
};
if !c.eq_ignore_ascii_case(&'w') {
return false;
}
let cmd_w =
key.modifiers.contains(KeyModifiers::SUPER) || key.modifiers.contains(KeyModifiers::META);
let ctrl_shift_w = key.modifiers.contains(KeyModifiers::CONTROL)
&& key.modifiers.contains(KeyModifiers::SHIFT);
cmd_w || ctrl_shift_w
}
/// `Cmd+]`: cycle to the next (right) terminal in the pane. iTerm2's
/// GlobalKeyMap forwards it as `ESC [ 93 ; 9 u` (modifier 9 = base +
/// Super), which crossterm decodes to `Char(']') + SUPER`. Brackets are
/// used because every arrow option is blocked: Ctrl+arrows by macOS
/// Spaces, Option+arrows by shell word-motion, Cmd+arrows by user choice.
/// Accepts the shifted glyph `}` defensively in case a terminal pre-applies
/// the shift.
fn is_terminal_cycle_key(key: KeyEvent) -> bool {
let KeyCode::Char(c) = key.code else {
return false;
};
(c == ']' || c == '}') && has_cmd(key.modifiers)
}
/// `Cmd+[`: cycle to the previous (left) terminal in the pane. Mirror of
/// `is_terminal_cycle_key` for the reverse direction.
fn is_terminal_cycle_back_key(key: KeyEvent) -> bool {
let KeyCode::Char(c) = key.code else {
return false;
};
(c == '[' || c == '{') && has_cmd(key.modifiers)
}
/// Returns true if the given key event should trash the currently-selected
/// node in the file tree. Recognises:
///
/// * `KeyCode::Delete` — the Forward-Delete key on full-size keyboards
/// (and `fn+Delete` on Mac laptops).
/// * `KeyCode::Backspace` — the key labeled "delete" on every Mac keyboard.
/// The tree pane has no text input that needs Backspace, so plain
/// Backspace is safe here.
/// * `Cmd+Backspace` — the macOS Finder gesture for trashing.
///
/// This helper is only called from `handle_tree_key`, so plain Backspace is
/// only swallowed when the tree pane has focus; the editor and terminal panes
/// continue to consume Backspace for their own purposes.
fn is_delete_node_key(key: KeyEvent) -> bool {
matches!(key.code, KeyCode::Delete | KeyCode::Backspace)
}
/// Returns true if the given key event should trigger "Save".
/// Recognises Ctrl+S (cross-platform) and Cmd/Super+S (macOS-style).
/// Case-insensitive on the letter so Shift+Ctrl+S also works.
fn is_word_continuation(c: char) -> bool {
c.is_alphanumeric() || c == '_'
}
/// Characters that open or advance a call, triggering parameter hints.
fn is_signature_help_trigger(c: char) -> bool {
c == '(' || c == ','
}
/// Which starter contents to seed when a JSON config file is opened for the
/// first time from the palette.
#[derive(Debug, Clone, Copy)]
enum ConfigFileSeed {
Settings,
/// A settings overlay layer (#251): `.croft/config.json`, its gitignored
/// `.local` sibling, or the machine-local user overlay. Seeded with a
/// commented template rather than a full prefs dump — overlays should
/// carry only the keys they actually set.
SettingsLayer,
Keybindings,
Snippets,
Triggers,
Matchers,
Agents,
}
/// Starter contents for a fresh settings overlay layer.
const SETTINGS_LAYER_TEMPLATE: &str = r#"{
// A croft settings overlay: later layers win key-by-key over the user
// config (see docs/SETTINGS.md for the chain, "extends", and platform
// blocks). Workspace files may set appearance and editor/terminal
// behavior keys only; trust-related settings are user-config only and
// warn in OUTPUT · Settings.
}
"#;
/// Build a completion-popup item for a user snippet: the row shows the prefix,
/// filters on it, and carries the snippet body as `is_snippet` insertion text
/// the accept path expands through the editor's tab-stop engine.
fn snippet_completion_item(snip: &crate::snippets::Snippet) -> crate::lsp::CompletionItem {
crate::lsp::CompletionItem {
label: snip.prefix.clone(),
detail: Some(String::from("snippet")),
insert_text: Some(snip.body.clone()),
filter_text: Some(snip.prefix.clone()),
kind: Some(lsp_types::CompletionItemKind::SNIPPET),
is_snippet: true,
}
}
/// Which mouse region a binding's `when` context refers to, or `None` when
/// the pointer is somewhere no context covers (a panel, a seam, the status
/// bar) — a user binding must not fire there.
fn mouse_context_for(
m: &MouseEvent,
in_editor: bool,
in_terminal: bool,
in_tree: bool,
app: &App,
) -> Option<crate::keymap::MouseContext> {
use crate::keymap::MouseContext;
// The tab strip has no focus notion, so it is recognised positionally and
// checked first: it overlaps the editor pane's full area.
if app.editor.tab_at(m.column, m.row).is_some() {
return Some(MouseContext::TabStrip);
}
if in_terminal {
return Some(MouseContext::Terminal);
}
// `in_tree` is true anywhere in the ACTIVE SIDEBAR, whichever view it is
// showing, so it alone would make a `file_tree` binding fire over Search
// results, the Remote list, the Testing panel and the commit graph. The
// context is named for the file tree and documented as the file tree, so
// it is narrowed to the view that actually is one; the other sidebar
// views have their own row semantics and no binding context yet, and
// firing a tree binding over them would act on a row it never meant.
if in_tree && app.sidebar_view == SidebarView::Explorer {
return Some(MouseContext::FileTree);
}
if in_editor {
return Some(MouseContext::Editor);
}
None
}
/// The gesture a mouse event spells, or `None` for events that are not
/// bindable (motion, drags, button releases).
///
/// A left press reports `DoubleClick` when croft's own click tracker already
/// considers it one, so a binding agrees with the built-in select-word
/// behaviour rather than disagreeing about the same physical click. Triple
/// click is NOT reported: the tracker distinguishes single from double only,
/// and inventing a third level here would make `triple_click` bindings fire
/// on the second click. `Gesture::parse` therefore rejects it with a load
/// warning rather than accepting a binding that could never behave.
fn gesture_for(
m: &MouseEvent,
app: &App,
ctx: crate::keymap::MouseContext,
now: std::time::Instant,
) -> Option<crate::keymap::Gesture> {
use crate::keymap::{Gesture, GestureKind, MouseContext};
// Only the three modifiers a terminal actually reports for mouse; Super
// is never present (see `Gesture::parse`).
let mods = m.modifiers & (KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SHIFT);
let kind = match m.kind {
MouseEventKind::Down(MouseButton::Left) if !mods.is_empty() => {
// A modified click reads its OWN tracker. The unmodified ones are
// shared with built-ins that ignore modifiers, so the dispatch
// deliberately never records a modified click into them — which
// left `ctrl+double_click` unable to fire at all, since nothing
// remembered the first click of the pair.
if app.modified_click.is_double(now, m.column, m.row, mods) {
GestureKind::DoubleClick
} else {
GestureKind::Click
}
}
MouseEventKind::Down(MouseButton::Left) => {
// The tracker has to match the region: each pane records into its
// own, so consulting `editor_click` everywhere left `double_click`
// permanently false in the tree, tab strip, and terminal — a
// binding there would silently never match.
let tracker = match ctx {
MouseContext::Terminal => &app.terminal_click,
MouseContext::FileTree => &app.tree_click,
MouseContext::Editor => &app.editor_click,
// The tab strip writes to no tracker of its own, so a double
// there can only be seen because the dispatch itself records
// into `editor_click` above. Sharing it with the editor body
// is acceptable: a double needs both clicks within 500ms at
// the SAME cell, and the strip and the body do not overlap.
MouseContext::TabStrip => &app.editor_click,
};
// `mods` is empty in this arm by construction (the modified case
// is matched above and reads its own tracker), and passing it
// rather than a literal keeps that true if the guard ever moves:
// #317 makes the built-in tracker refuse a modified pair, which is
// exactly what should happen if a modified click ever reached here.
if tracker.is_double(now, m.column, m.row, mods) {
GestureKind::DoubleClick
} else {
GestureKind::Click
}
}
MouseEventKind::Down(MouseButton::Middle) => GestureKind::MiddleClick,
MouseEventKind::Down(MouseButton::Right) => GestureKind::RightClick,
MouseEventKind::ScrollUp => GestureKind::WheelUp,
MouseEventKind::ScrollDown => GestureKind::WheelDown,
_ => return None,
};
Some(Gesture { kind, mods })
}
/// A chord eligible for a user rebind: it carries a real modifier
/// (Ctrl/Alt/Super) or is a function key. Bare keys, unmodified letters, and
/// Shift-only chords (which are just typing) are excluded so the user keymap
/// can never shadow plain text entry. Intentionally not named `is_*_key`: it is
/// a gate, not a shortcut the F1 overlay documents.
fn is_rebindable_chord(key: KeyEvent) -> bool {
matches!(key.code, KeyCode::F(_))
|| key
.modifiers
.intersects(KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SUPER)
}
/// Whether a key should keep an active snippet tab-stop session alive: plain
/// typing (an unmodified char), Backspace, and Tab (which advances the session).
/// Every other key ends it so Tab reverts to indenting.
fn snippet_key_continues(key: KeyEvent) -> bool {
match key.code {
KeyCode::Tab | KeyCode::Backspace => true,
KeyCode::Char(_) => !key
.modifiers
.intersects(KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SUPER),
_ => false,
}
}
fn is_completion_trigger_key(key: KeyEvent) -> bool {
let KeyCode::Char(c) = key.code else {
return false;
};
if c != ' ' {
return false;
}
key.modifiers.contains(KeyModifiers::CONTROL) || key.modifiers.contains(KeyModifiers::SUPER)
}
fn is_save_key(key: KeyEvent) -> bool {
let KeyCode::Char(c) = key.code else {
return false;
};
if !c.eq_ignore_ascii_case(&'s') {
return false;
}
if key.modifiers.contains(KeyModifiers::ALT) {
return false;
}
let has_super = key.modifiers.contains(KeyModifiers::SUPER);
let has_ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
let has_shift = key.modifiers.contains(KeyModifiers::SHIFT);
// Cmd+Shift+S is reserved for the Source Control jump
// (`is_source_control_jump_key`), so reject Shift when Super is
// held. Ctrl+Shift+S still triggers Save because some terminals
// capitalise the letter when Ctrl is held and the user genuinely
// means Ctrl+S — that's the existing `shift_ctrl_s_is_save_key`
// contract we want to preserve.
if has_super && has_shift {
return false;
}
has_super || has_ctrl
}
/// Read the system clipboard. Used by the search input when Cmd+V arrives as
/// a key event rather than bracketed paste content.
fn read_system_clipboard() -> Option<String> {
crate::clipboard::read_string()
}
/// Copy `text` to the host system clipboard.
///
/// Order of attempts:
/// 1. **macOS native** — `clipboard::write_string` posts directly to
/// `NSPasteboard.generalPasteboard` (with `pbcopy` as a process-level
/// fall-back inside the same helper). This is the canonical Cocoa
/// clipboard API and is the *only* path that survives every iTerm2
/// configuration we have seen in the wild. OSC 52 is, empirically,
/// silently dropped by iTerm2 in some setups even with
/// `AllowClipboardAccess` enabled in `com.googlecode.iterm2` — and
/// writing escape bytes directly to the alt-screen stdout always
/// risks racing with the next ratatui frame.
/// 2. **OSC 52 fall-back** — only if the native write returned false
/// (non-macOS croft binary on a Linux remote host, where the only
/// hand-shake with the user's local terminal is via escape bytes
/// through the SSH PTY). The fall-back is best-effort.
///
/// Returns true when the native path acknowledged the write so the call
/// site can downgrade the status message if it ever needs to. Today all
/// call sites discard the boolean; the return value is here so future
/// code can branch on it.
/// VS Code "Copy Relative Path" text: `path` relative to the workspace `root`,
/// or the absolute `path` when it lives outside the root (never a `../` walk).
/// Pure so the relativization is unit-tested without touching the clipboard.
fn relative_clipboard_text(path: &Path, root: &Path) -> String {
path.strip_prefix(root)
.unwrap_or(path)
.display()
.to_string()
}
/// The text a lane's Explorer root row wears after its name (#348): the
/// branch, then the seated agent as the pane pill shows it (`◆ claude ●`),
/// or the configured agent's bare name while nothing is seated yet, or
/// nothing more for a plain-shell lane.
fn lane_root_badge(
branch: &str,
seated: Option<&crate::agents::AgentLane>,
configured: Option<&str>,
) -> String {
match (seated, configured) {
(Some(agent), _) => format!(
"{branch} \u{b7} \u{25c6} {} {}",
agent.name,
agent.status.glyph()
),
(None, Some(agent)) => format!("{branch} \u{b7} {agent}"),
(None, None) => branch.to_string(),
}
}
/// What a lane pane's fresh shell is fed to start its agent (#348):
/// Ctrl-E + Ctrl-U first, as `run_project_task` does, so a half-typed line
/// cannot concatenate with the command.
fn lane_launch_input(cmd: &str) -> String {
format!("\x05\x15{cmd}\r")
}
/// Whether `t` is the idle pane named `pane_name` whose shell is standing
/// at `root` — or whose directory croft cannot read at all. The one
/// predicate behind every "reuse a pane rather than stack a new one"
/// decision (#430).
///
/// Shared deliberately. This guard existed as two copies, and when #392
/// fixed the runnable-fence copy the task copy kept both defects: a
/// `starts_with` that accepted any DESCENDANT, so a shell that had `cd`'d
/// into a subdirectory was reused and the command ran there; and an
/// `is_none_or` that opened the guard whenever the cwd could not be read.
/// One predicate means a future correction cannot land on one caller and
/// miss the other.
///
/// The comparison is exact on purpose. Both sides are resolved paths — the
/// kernel reports the shell's cwd fully resolved, and `canonicalize()`
/// resolves symlinks and never emits a trailing separator — so equality
/// holds wherever reuse is genuinely wanted, including through a
/// `/tmp` -> `/private/tmp` symlink. When it does not hold, the caller
/// opens a fresh pane at the right directory, so the worst case is a spare
/// pane rather than a command run somewhere the user was not told about.
///
/// When `canonicalize()` itself fails — a root deleted or renamed under a
/// live session — `unwrap_or` leaves an unresolved path and the comparison
/// cannot match, which costs a spare pane and never a misdirected command.
///
/// The cwd decision itself lives in [`cwd_matches`], which distinguishes a
/// shell that moved from a platform that cannot say where it is.
///
/// A DEAD shell never reaches that decision: `foreground_is_shell` is
/// checked first and answers false for one (#155), so the unreadable arm
/// only ever sees panes croft cannot ask about. Relaxing that check would
/// make identity-fallback start reusing corpses, so the two belong
/// together.
fn pane_is_idle_at(
t: &crate::widgets::terminal::PtyTerminal,
pane_name: &str,
root: &Path,
) -> bool {
t.label() == pane_name
&& t.foreground_is_shell()
&& cwd_matches(t.kernel_shell_cwd().as_deref(), root, cwd_is_observable())
}
use crate::widgets::terminal::cwd_is_observable;
/// The cwd half of [`pane_is_idle_at`], as a pure function so both arms are
/// testable on any platform (#430).
///
/// Three cases, not two. A cwd croft READ and that differs is a shell that
/// wandered off — refuse. A cwd croft read and that matches is this
/// command's pane — reuse. A cwd croft could not read splits on whether
/// the platform can read one at all: where it can, `None` is the failure
/// the guard exists for and stays closed; where it cannot (Android), a
/// closed guard would stack a new pane on every single run, so reuse falls
/// back to the pane's identity, which is all croft had before the guard
/// existed.
fn cwd_matches(cwd: Option<&Path>, root: &Path, observable: bool) -> bool {
match cwd {
Some(c) => c == root,
None => !observable,
}
}
fn copy_to_clipboard(text: &str) -> bool {
if crate::clipboard::write_string(text) {
return true;
}
use std::io::Write;
let bytes = crate::widgets::terminal::osc52_copy_seq(text);
let mut out = std::io::stdout();
let _ = out.write_all(&bytes);
let _ = out.flush();
false
}
/// Returns true if the given key event should copy the editor's current
/// selection to the system clipboard. Recognises plain `Ctrl+C` and `Cmd+C`
/// — there's no SIGINT collision since the editor pane is not a shell.
fn is_editor_copy_key(key: KeyEvent) -> bool {
let KeyCode::Char(c) = key.code else {
return false;
};
if !c.eq_ignore_ascii_case(&'c') {
return false;
}
key.modifiers.contains(KeyModifiers::CONTROL) || key.modifiers.contains(KeyModifiers::SUPER)
}
/// Cut: `Ctrl+X` / `Cmd+X`.
fn is_editor_cut_key(key: KeyEvent) -> bool {
let KeyCode::Char(c) = key.code else {
return false;
};
if !c.eq_ignore_ascii_case(&'x') {
return false;
}
key.modifiers.contains(KeyModifiers::CONTROL) || key.modifiers.contains(KeyModifiers::SUPER)
}
/// Paste in the search input. Normal terminal paste is handled via
/// `Event::Paste`; `setup-iterm2` maps Cmd+V to a CSI-u Cmd+V sequence, and
/// the raw Ctrl+V byte is accepted as a fallback for older setups.
fn is_search_paste_key(key: KeyEvent) -> bool {
is_clipboard_paste_key(key)
}
/// Human-readable name of a Search input field, for status-line messages.
fn search_field_name(field: crate::widgets::search::SearchField) -> &'static str {
use crate::widgets::search::SearchField;
match field {
SearchField::Query => "search",
SearchField::Replace => "replace",
SearchField::Include => "files-to-include",
SearchField::Exclude => "files-to-exclude",
}
}
fn is_editor_paste_key(key: KeyEvent) -> bool {
is_clipboard_paste_key(key)
}
fn is_clipboard_paste_key(key: KeyEvent) -> bool {
let KeyCode::Char(c) = key.code else {
return false;
};
if c == '\u{16}' {
return true;
}
if !c.eq_ignore_ascii_case(&'v') {
return false;
}
key.modifiers.contains(KeyModifiers::CONTROL) || key.modifiers.contains(KeyModifiers::SUPER)
}
fn is_search_editing_shortcut(key: KeyEvent) -> bool {
is_search_paste_key(key)
|| is_editor_select_all_key(key)
|| is_editor_copy_key(key)
|| is_editor_cut_key(key)
}
/// Select-all: `Ctrl+A` / `Cmd+A`.
fn is_editor_select_all_key(key: KeyEvent) -> bool {
let KeyCode::Char(c) = key.code else {
return false;
};
if !c.eq_ignore_ascii_case(&'a') {
return false;
}
key.modifiers.contains(KeyModifiers::CONTROL) || key.modifiers.contains(KeyModifiers::SUPER)
}
/// Undo: `Ctrl+Z` / `Cmd+Z`. Plain Shift is rejected so it stays distinct from
/// the redo chord `Shift+Cmd+Z` / `Shift+Ctrl+Z` (see `is_editor_redo_key`).
fn is_editor_undo_key(key: KeyEvent) -> bool {
let KeyCode::Char(c) = key.code else {
return false;
};
if !c.eq_ignore_ascii_case(&'z') {
return false;
}
if key.modifiers.contains(KeyModifiers::SHIFT) {
return false;
}
key.modifiers.contains(KeyModifiers::CONTROL) || key.modifiers.contains(KeyModifiers::SUPER)
}
/// Redo: `Shift+Cmd+Z` / `Shift+Ctrl+Z` (VS Code's default). `Cmd+Y` is not a
/// redo alias here because it is already the `Cmd+y y` yank-line leader.
fn is_editor_redo_key(key: KeyEvent) -> bool {
let KeyCode::Char(c) = key.code else {
return false;
};
if !c.eq_ignore_ascii_case(&'z') {
return false;
}
if !key.modifiers.contains(KeyModifiers::SHIFT) {
return false;
}
key.modifiers.contains(KeyModifiers::CONTROL) || key.modifiers.contains(KeyModifiers::SUPER)
}
/// Editor-pane Rename Symbol: plain `F2` (VS Code's binding). In the Explorer
/// tree the same key renames the selected file (`is_tree_rename_key`); the
/// pane in focus decides which fires.
fn is_rename_symbol_key(key: KeyEvent) -> bool {
matches!(key.code, KeyCode::F(2))
&& !key.modifiers.contains(KeyModifiers::SUPER)
&& !key.modifiers.contains(KeyModifiers::CONTROL)
&& !key.modifiers.contains(KeyModifiers::SHIFT)
&& !key.modifiers.contains(KeyModifiers::ALT)
}
/// True for `.ts`/`.tsx`/`.js`/`.jsx` paths — the languages served by the
/// croft-managed vtsls, used to re-open just those docs after vtsls installs.
/// Collapse a language to the server "family" it shares a managed server with.
/// vtsls serves the whole TypeScript/JS family but reports its config language
/// as `TypeScript`, so all four map together; every other language is its own
/// family. Used to decide which open docs to re-open after a managed install.
fn lsp_server_family(lang: crate::lsp::Language) -> crate::lsp::Language {
lang.server_family()
}
/// True when `path`'s language is served by one of the just-installed servers,
/// so its LSP sync state should be dropped to force a re-open + re-probe.
fn just_installed_covers_path(installed: &[crate::lsp::Language], path: &Path) -> bool {
let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
let Some(lang) = crate::lsp::Language::from_extension(ext) else {
return false;
};
installed
.iter()
.any(|&i| lsp_server_family(i) == lsp_server_family(lang))
}
/// Editor-pane Change All Occurrences: `Cmd+F2` (macOS) or `Ctrl+F2` (Linux),
/// matching VS Code on each platform so local and remote behave identically.
/// iTerm2 may deliver Cmd folded onto the Meta/ALT bit (the same reason
/// Cmd+click arrives as ALT for go-to-definition), so any of SUPER / CONTROL /
/// ALT alongside F2 counts. Plain F2 (no modifiers) stays Rename Symbol.
fn is_change_all_occurrences_key(key: KeyEvent) -> bool {
matches!(key.code, KeyCode::F(2))
&& (key.modifiers.contains(KeyModifiers::SUPER)
|| key.modifiers.contains(KeyModifiers::CONTROL)
|| key.modifiers.contains(KeyModifiers::ALT))
}
/// VS Code "Add Selection to Next Find Match" (`Cmd+D` on macOS, `Ctrl+D`
/// elsewhere). Neither Shift nor Alt may be held, so this never collides with
/// `Cmd+Shift+D` (Run and Debug) or `Cmd+Opt+Shift+D` (Sort Lines Descending).
fn is_select_next_occurrence_key(key: KeyEvent) -> bool {
matches!(key.code, KeyCode::Char('d') | KeyCode::Char('D'))
&& (key.modifiers.contains(KeyModifiers::SUPER)
|| key.modifiers.contains(KeyModifiers::CONTROL))
&& !key.modifiers.contains(KeyModifiers::SHIFT)
&& !key.modifiers.contains(KeyModifiers::ALT)
}
/// VS Code "Delete Line" (`Cmd+Shift+K` on macOS, `Ctrl+Shift+K` elsewhere).
/// Requires Shift (to distinguish it from the `Cmd+K` chord leader) and no Alt.
fn is_delete_line_key(key: KeyEvent) -> bool {
matches!(key.code, KeyCode::Char('k') | KeyCode::Char('K'))
&& (key.modifiers.contains(KeyModifiers::SUPER)
|| key.modifiers.contains(KeyModifiers::CONTROL))
&& key.modifiers.contains(KeyModifiers::SHIFT)
&& !key.modifiers.contains(KeyModifiers::ALT)
}
/// Editor-pane Go to Definition: plain `F12` (VS Code's binding). The F12
/// navigation family splits on the modifier, matching VS Code: bare F12 is
/// Definition, `Shift+F12` is Declaration, `Ctrl+F12` is Type Definition, and
/// `Cmd+F12` (SUPER) is Implementations. Definition therefore requires F12 with
/// none of Shift / Ctrl / Super held. (Alt is still accepted: iTerm2 can fold a
/// held Cmd onto the Meta/Alt bit for some events, and Option+F12 is otherwise
/// unused, so leaving Alt on Definition is harmless.)
fn is_go_to_definition_key(key: KeyEvent) -> bool {
matches!(key.code, KeyCode::F(12))
&& !key.modifiers.contains(KeyModifiers::SHIFT)
&& !key.modifiers.contains(KeyModifiers::CONTROL)
&& !key.modifiers.contains(KeyModifiers::SUPER)
&& !key.modifiers.contains(KeyModifiers::ALT)
}
/// Editor-pane Peek Definition: `Alt+F12`, VS Code's default (#115). This
/// claims the ALT bit Definition used to tolerate as iTerm2 Cmd-fold noise —
/// on those rare folded events the user now gets a peek popup instead of a
/// jump, strictly less disruptive than the old mis-jump.
fn is_peek_definition_key(key: KeyEvent) -> bool {
matches!(key.code, KeyCode::F(12))
&& key.modifiers.contains(KeyModifiers::ALT)
&& !key.modifiers.contains(KeyModifiers::SHIFT)
&& !key.modifiers.contains(KeyModifiers::CONTROL)
&& !key.modifiers.contains(KeyModifiers::SUPER)
}
/// Editor-pane Go to References: `Shift+F12`, VS Code's real binding for this
/// action. This is the chord croft previously gave to Go to Declaration; with
/// References taking its rightful VS Code default, Declaration moved one
/// modifier over to `Ctrl+Shift+F12`. References therefore requires F12 with
/// Shift held but neither Ctrl (that is Declaration) nor Super (Implementations).
fn is_go_to_references_key(key: KeyEvent) -> bool {
matches!(key.code, KeyCode::F(12))
&& key.modifiers.contains(KeyModifiers::SHIFT)
&& !key.modifiers.contains(KeyModifiers::CONTROL)
&& !key.modifiers.contains(KeyModifiers::SUPER)
}
/// Editor-pane Go to Declaration: `Ctrl+Shift+F12`. VS Code leaves Declaration
/// unbound, so croft assigns it within the F12 navigation family. It moved off
/// the bare `Shift+F12` it once held when Go to References (added later) claimed
/// that VS Code default, so Declaration now needs both Shift and Ctrl (Super
/// would be Implementations). iTerm2 emits `CSI 24 ; 6 ~` for Ctrl+Shift+F12,
/// which crossterm decodes to `F(12) + SHIFT + CONTROL`; `iterm2.rs` also
/// installs a defensive GlobalKeyMap forwarder emitting exactly those bytes so a
/// future iTerm2 default cannot swallow the chord.
fn is_go_to_declaration_key(key: KeyEvent) -> bool {
matches!(key.code, KeyCode::F(12))
&& key.modifiers.contains(KeyModifiers::SHIFT)
&& key.modifiers.contains(KeyModifiers::CONTROL)
&& !key.modifiers.contains(KeyModifiers::SUPER)
}
/// Editor-pane Go to Type Definition: `Ctrl+F12`. VS Code leaves Type
/// Definition unbound, so croft assigns it within the F12 navigation family.
/// iTerm2 emits `CSI 24 ; 5 ~` for Ctrl+F12, which crossterm decodes to
/// `F(12) + CONTROL` (the same legacy-tilde path that delivers plain F12 and
/// Shift+F12), so no iTerm2 GlobalKeyMap forwarder is needed.
fn is_go_to_type_definition_key(key: KeyEvent) -> bool {
matches!(key.code, KeyCode::F(12))
&& key.modifiers.contains(KeyModifiers::CONTROL)
&& !key.modifiers.contains(KeyModifiers::SHIFT)
}
/// Editor-pane Go to Implementations: `Cmd+F12` (SUPER), VS Code's real macOS
/// binding for this action. Unlike its F12-family siblings, Cmd+F12 is captured
/// by macOS, so `iterm2.rs` installs a GlobalKeyMap forwarder emitting
/// `CSI 24 ; 9 ~`; crossterm decodes that to `F(12) + SUPER`. This must not
/// collide with the three siblings: bare F12 is Definition, `Shift+F12` is
/// Declaration, `Ctrl+F12` is Type Definition.
fn is_go_to_implementation_key(key: KeyEvent) -> bool {
matches!(key.code, KeyCode::F(12))
&& key.modifiers.contains(KeyModifiers::SUPER)
&& !key.modifiers.contains(KeyModifiers::SHIFT)
&& !key.modifiers.contains(KeyModifiers::CONTROL)
}
fn chord_status_text(op: char, count: usize) -> String {
if count > 0 {
format!("Pending: {op} (count {count})")
} else {
format!("Pending: {op}")
}
}
fn is_vim_chord_letter(key: KeyEvent, letter: char) -> bool {
let KeyCode::Char(c) = key.code else {
return false;
};
if c != letter {
return false;
}
if key.modifiers.contains(KeyModifiers::SHIFT) || key.modifiers.contains(KeyModifiers::ALT) {
return false;
}
key.modifiers.contains(KeyModifiers::SUPER) || key.modifiers.contains(KeyModifiers::CONTROL)
}
fn is_vim_chord_g(key: KeyEvent) -> bool {
is_vim_chord_letter(key, 'g')
}
fn is_vim_chord_y(key: KeyEvent) -> bool {
is_vim_chord_letter(key, 'y')
}
fn is_vim_goto_bottom(key: KeyEvent) -> bool {
let KeyCode::Char(c) = key.code else {
return false;
};
if !c.eq_ignore_ascii_case(&'g') {
return false;
}
if !key.modifiers.contains(KeyModifiers::SHIFT) {
return false;
}
key.modifiers.contains(KeyModifiers::SUPER) || key.modifiers.contains(KeyModifiers::CONTROL)
}
fn chord_digit_value(key: KeyEvent) -> Option<usize> {
let KeyCode::Char(c) = key.code else {
return None;
};
let d = c.to_digit(10)? as usize;
if key.modifiers.contains(KeyModifiers::ALT) || key.modifiers.contains(KeyModifiers::SHIFT) {
return None;
}
Some(d)
}
fn cmd_only_digit_value(key: KeyEvent) -> Option<usize> {
let d = chord_digit_value(key)?;
if !key.modifiers.contains(KeyModifiers::SUPER) {
return None;
}
Some(d)
}
/// Cmd+E toggles native modal (vim) editing in the editor pane. A plain
/// Cmd+letter reaches croft reliably as SUPER (the same path as Cmd+S / Cmd+C),
/// unlike Option+letter which emits a glyph on macOS; and it stays out of the
/// Cmd+Shift+letter space reserved for activity-bar view jumps.
fn is_vim_toggle_key(key: KeyEvent) -> bool {
matches!(key.code, KeyCode::Char('e') | KeyCode::Char('E'))
&& key.modifiers.contains(KeyModifiers::SUPER)
&& !key.modifiers.contains(KeyModifiers::SHIFT)
}
fn reverse_find(kind: crate::vim::FindKind) -> crate::vim::FindKind {
use crate::vim::FindKind;
match kind {
FindKind::CharForward => FindKind::CharBackward,
FindKind::CharBackward => FindKind::CharForward,
FindKind::TillForward => FindKind::TillBackward,
FindKind::TillBackward => FindKind::TillForward,
}
}
/// Vertical / whole-file motions operate linewise under an operator (`dj`,
/// `dG`), unlike the charwise horizontal and word motions.
fn vim_motion_is_linewise(motion: crate::vim::Motion) -> bool {
use crate::vim::Motion;
matches!(
motion,
Motion::Up | Motion::Down | Motion::FileStart | Motion::FileEnd | Motion::GotoLine(_)
)
}
/// `f`/`t`/`e` land on a char that the operator should include, so the
/// deletion range needs to extend one past the landing column.
fn vim_motion_is_forward_inclusive(motion: crate::vim::Motion) -> bool {
use crate::vim::{FindKind, Motion};
matches!(
motion,
Motion::WordEnd
| Motion::Find(FindKind::CharForward, _)
| Motion::Find(FindKind::TillForward, _)
)
}
/// First char index `>= from` where `term` begins in `line`, comparing by
/// char (not byte) so the result indexes the editor's char-based cursor.
fn find_char_index(line: &str, term: &str, from: usize) -> Option<usize> {
let chars: Vec<char> = line.chars().collect();
let needle: Vec<char> = term.chars().collect();
let tlen = needle.len();
if tlen == 0 || chars.len() < tlen {
return None;
}
(from..=chars.len() - tlen).find(|&i| chars[i..i + tlen] == needle[..])
}
/// Last char index `< limit` where `term` begins in `line`.
fn rfind_char_index(line: &str, term: &str, limit: usize) -> Option<usize> {
let chars: Vec<char> = line.chars().collect();
let needle: Vec<char> = term.chars().collect();
let tlen = needle.len();
if tlen == 0 || chars.len() < tlen {
return None;
}
let upper = limit.min(chars.len() - tlen + 1);
(0..upper).rev().find(|&i| chars[i..i + tlen] == needle[..])
}
fn is_plain_letter(key: KeyEvent, letter: char) -> bool {
let KeyCode::Char(c) = key.code else {
return false;
};
if c != letter {
return false;
}
!(key.modifiers.contains(KeyModifiers::CONTROL)
|| key.modifiers.contains(KeyModifiers::SUPER)
|| key.modifiers.contains(KeyModifiers::ALT))
}
fn is_editor_line_home_key(key: KeyEvent) -> bool {
let KeyCode::Char(c) = key.code else {
return false;
};
if !c.eq_ignore_ascii_case(&'a') {
return false;
}
key.modifiers.contains(KeyModifiers::CONTROL)
&& !key.modifiers.contains(KeyModifiers::SUPER)
&& !key.modifiers.contains(KeyModifiers::ALT)
}
fn is_editor_line_end_key(key: KeyEvent) -> bool {
let KeyCode::Char(c) = key.code else {
return false;
};
if !c.eq_ignore_ascii_case(&'e') {
return false;
}
key.modifiers.contains(KeyModifiers::CONTROL)
&& !key.modifiers.contains(KeyModifiers::SUPER)
&& !key.modifiers.contains(KeyModifiers::ALT)
}
fn is_editor_kill_to_eol_key(key: KeyEvent) -> bool {
let KeyCode::Char(c) = key.code else {
return false;
};
if !c.eq_ignore_ascii_case(&'k') {
return false;
}
key.modifiers.contains(KeyModifiers::CONTROL)
&& !key.modifiers.contains(KeyModifiers::SUPER)
&& !key.modifiers.contains(KeyModifiers::ALT)
}
fn is_editor_kill_to_bol_key(key: KeyEvent) -> bool {
let KeyCode::Char(c) = key.code else {
return false;
};
if !c.eq_ignore_ascii_case(&'u') {
return false;
}
key.modifiers.contains(KeyModifiers::CONTROL)
&& !key.modifiers.contains(KeyModifiers::SUPER)
&& !key.modifiers.contains(KeyModifiers::ALT)
}
fn is_editor_open_line_below_key(key: KeyEvent) -> bool {
let KeyCode::Char(c) = key.code else {
return false;
};
if c != 'o' {
return false;
}
if key.modifiers.contains(KeyModifiers::SHIFT) || key.modifiers.contains(KeyModifiers::ALT) {
return false;
}
key.modifiers.contains(KeyModifiers::SUPER) || key.modifiers.contains(KeyModifiers::CONTROL)
}
/// Insert line above: `Cmd+Shift+Enter` (macOS) / `Ctrl+Shift+Enter` (Linux),
/// matching VS Code's `editor.action.insertLineBefore`. (Previously bound to
/// `Cmd+Shift+O`, which VS Code reserves for Go to Symbol; relocated to its
/// real chord so `Cmd+Shift+O` can open the symbol picker.)
fn is_editor_open_line_above_key(key: KeyEvent) -> bool {
if !matches!(key.code, KeyCode::Enter) {
return false;
}
if !key.modifiers.contains(KeyModifiers::SHIFT) {
return false;
}
if key.modifiers.contains(KeyModifiers::ALT) {
return false;
}
key.modifiers.contains(KeyModifiers::SUPER) || key.modifiers.contains(KeyModifiers::CONTROL)
}
/// Close active tab: `Ctrl+W` / `Cmd+W`.
fn is_close_tab_key(key: KeyEvent) -> bool {
let KeyCode::Char(c) = key.code else {
return false;
};
if !c.eq_ignore_ascii_case(&'w') {
return false;
}
key.modifiers.contains(KeyModifiers::CONTROL)
|| key.modifiers.contains(KeyModifiers::SUPER)
|| key.modifiers.contains(KeyModifiers::META)
}
/// Cmd+1..9 / Ctrl+1..9 — jump straight to that tab (1-based; returns the
/// 0-based index). Anything outside that range returns `None`.
fn jump_to_tab_index(key: KeyEvent) -> Option<usize> {
let KeyCode::Char(c) = key.code else {
return None;
};
if !key.modifiers.contains(KeyModifiers::SUPER)
&& !key.modifiers.contains(KeyModifiers::META)
&& !key.modifiers.contains(KeyModifiers::CONTROL)
{
return None;
}
let d = c.to_digit(10)?;
if !(1..=9).contains(&d) {
return None;
}
Some((d - 1) as usize)
}
/// Map a screen row to the tree row that should be highlighted as a drop
/// target. Hovering a directory targets that directory; hovering a file
/// targets its parent directory (so dragging onto a file row drops the
/// payload as siblings of that file). Returns `None` when the pointer is
/// over empty tree space, when the row would be a no-op (hovering an
/// item that's part of the drag set), or when the resolved directory is
/// inside one of the dragged folders.
fn drag_target_index(
tree: &crate::widgets::file_tree::FileTree,
y: u16,
drag_paths: &[PathBuf],
) -> Option<usize> {
// The sticky band wins the row resolution: a drop on a pinned ancestor
// targets THAT directory, not whatever row the band covers (#126 — files
// used to land in the covered row's directory, silently).
let idx = tree.sticky_row_at(y).or_else(|| tree.node_at_y(y))?;
let node = tree.nodes.get(idx)?;
let dir_idx = if node.is_dir {
idx
} else {
let parent = node.path.parent()?;
tree.index_of_dir(parent)?
};
let dir_path = tree.nodes.get(dir_idx)?.path.clone();
for src in drag_paths {
if crate::widgets::file_tree::is_descendant_or_same(&dir_path, src) {
return None;
}
if let Some(parent) = src.parent()
&& parent == dir_path
&& drag_paths.len() == 1
{
// Dropping a single source onto its own parent is a no-op;
// don't show a highlight so the user knows nothing will move.
return None;
}
}
Some(dir_idx)
}
fn drop_target_dir(tree: &crate::widgets::file_tree::FileTree, target_idx: usize) -> PathBuf {
tree.nodes
.get(target_idx)
.map(|n| n.path.clone())
.unwrap_or_else(|| tree.root.clone())
}
/// Parse a bracketed-paste payload that originated from a Finder-style
/// drag-and-drop into the host terminal. Returns the absolute existing
/// paths the user dropped, or an empty Vec when the payload is plain text
/// (in which case the caller falls back to the normal paste path). Each
/// candidate token survives only if it resolves to an existing absolute
/// path on disk, so a stray paste of "/usr/bin" worth of typed text still
/// behaves like text.
pub fn parse_dropped_paths(s: &str) -> Vec<PathBuf> {
parsed_drop_tokens(s)
.into_iter()
.filter(|p| p.is_absolute() && p.exists())
.filter(|p| !is_iterm2_inline_image_drop(p))
.collect()
}
/// Parse a bracketed-paste payload as candidate filesystem paths WITHOUT
/// requiring the paths to exist on this machine. Used by the remote-
/// launched croft to recognise drops whose paths refer to files on the
/// user's local Mac, which the relay will fetch over scp.
pub fn parse_foreign_dropped_paths(s: &str) -> Vec<PathBuf> {
parsed_drop_tokens(s)
.into_iter()
.filter(|p| p.is_absolute())
.filter(|p| !is_iterm2_inline_image_drop(p))
.collect()
}
/// True when every token in a bracketed-paste payload normalises to an absolute
/// path (and there is at least one). This is the signature of a genuine Finder
/// drag, which carries only the dragged file path(s). A real drag does NOT move
/// keyboard focus to the Explorer tree, so a focus-only gate silently dropped
/// every drag where the user had last clicked the terminal or editor. A text
/// paste that merely *contains* a path — a shell command like `cat /etc/hosts`,
/// a pasted code snippet — always has at least one non-path token, so it returns
/// false and is left to land as ordinary text rather than being hijacked into a
/// relay pull that has no local file to fetch.
fn is_pure_path_payload(s: &str) -> bool {
let trimmed = s.trim();
if trimmed.is_empty() {
return false;
}
let tokens = shell_split_drop_payload(trimmed);
if tokens.is_empty() {
return false;
}
tokens.iter().all(|t| {
normalise_dropped_token(t)
.map(|p| p.is_absolute())
.unwrap_or(false)
})
}
/// True when the dropped path is iTerm2's temp file for an inline-image
/// drag. iTerm2 lets the user drag any OSC-1337 inline image out of the
/// terminal; on mouse-up it writes the image bytes to `$TMPDIR/iTerm2.<rand>.png`
/// and re-injects the path into the same terminal as a bracketed paste.
/// Croft renders the activity-bar icons, welcome wordmark, run-debug
/// hero, no-repo hero, and SSH empty-state hero as OSC-1337 image cells,
/// so a click-with-microdrag on any of those triggers iTerm2's drag-
/// handler and croft would otherwise open the resulting PNG as an image
/// preview tab or import it into the Explorer. Filtering these paths is
/// always safe — the user has no legitimate reason to drop iTerm2's own
/// temp image into croft, and matching by filename pattern is iTerm2-
/// specific enough that it cannot collide with real user assets.
fn is_iterm2_inline_image_drop(p: &Path) -> bool {
let Some(name) = p.file_name().and_then(|n| n.to_str()) else {
return false;
};
if !name.starts_with("iTerm2.") || !name.ends_with(".png") {
return false;
}
let middle = &name["iTerm2.".len()..name.len() - ".png".len()];
if middle.is_empty() || !middle.chars().all(|c| c.is_ascii_alphanumeric()) {
return false;
}
// Defence in depth: only treat it as an iTerm2 drag artefact when
// the file lives under a temp directory. macOS puts iTerm2's drag
// temp under `/var/folders/.../TemporaryItems/` or `$TMPDIR`; both
// resolve through `std::env::temp_dir()` ancestry. The starts_with
// chain is forgiving because the path may be a symlinked variant
// (e.g. `/private/var/...` vs `/var/...`).
let parent = p.parent().unwrap_or(p);
let parent_str = parent.to_string_lossy();
parent_str.contains("/T/")
|| parent_str.contains("/TemporaryItems")
|| parent_str.starts_with("/tmp")
|| parent_str.starts_with("/var/folders")
|| parent_str.starts_with("/private/var/folders")
}
fn parsed_drop_tokens(s: &str) -> Vec<PathBuf> {
let trimmed = s.trim();
if trimmed.is_empty() {
return Vec::new();
}
shell_split_drop_payload(trimmed)
.into_iter()
.filter_map(|raw| normalise_dropped_token(&raw))
.collect()
}
/// Split a Finder / iTerm2 drag-drop payload into individual path tokens
/// the way a POSIX-ish shell would. Backslash escapes the next char (so
/// `\ ` keeps a literal space inside a filename); single- and double-
/// quoted runs stay intact; unescaped whitespace (space, tab, CR, LF)
/// separates tokens. Quote/backslash characters are *retained* in the
/// emitted token so downstream `normalise_dropped_token` can reuse its
/// existing un-escape + un-quote logic.
fn shell_split_drop_payload(s: &str) -> Vec<String> {
let mut tokens: Vec<String> = Vec::new();
let mut cur = String::new();
let mut in_double = false;
let mut in_single = false;
let mut chars = s.chars().peekable();
while let Some(c) = chars.next() {
if c == '\\' && !in_single {
// Carry the backslash and its escapee through verbatim;
// `normalise_dropped_token` strips them later.
cur.push('\\');
if let Some(next) = chars.next() {
cur.push(next);
}
continue;
}
if c == '"' && !in_single {
in_double = !in_double;
cur.push(c);
continue;
}
if c == '\'' && !in_double {
in_single = !in_single;
cur.push(c);
continue;
}
if (c == ' ' || c == '\t' || c == '\n' || c == '\r') && !in_single && !in_double {
if !cur.is_empty() {
tokens.push(std::mem::take(&mut cur));
}
continue;
}
cur.push(c);
}
if !cur.is_empty() {
tokens.push(cur);
}
tokens
}
/// Strip surrounding quotes, decode `file://` URLs (with %xx escapes), and
/// unescape `\<space>` style backslash escapes that some shells / drag
/// sources produce. Anything that isn't a plausible filesystem path
/// returns None and is dropped by the caller.
fn normalise_dropped_token(raw: &str) -> Option<PathBuf> {
let mut s = raw.trim().to_string();
if (s.starts_with('"') && s.ends_with('"') && s.len() >= 2)
|| (s.starts_with('\'') && s.ends_with('\'') && s.len() >= 2)
{
s = s[1..s.len() - 1].to_string();
}
if let Some(rest) = s.strip_prefix("file://") {
// Decode into BYTES and build the string once. A `%xx` escape is one
// byte of a UTF-8 sequence, not a character; pushing it `as char`
// read it as Latin-1 and opened a path that does not exist (#414).
// A sequence that is not valid UTF-8 names no path this process can
// open, so per this function's contract the token is dropped rather
// than turned into a plausible-looking path of replacement
// characters, which would pass every caller's "is this a path"
// screen and open the wrong thing.
let decoded = crate::shell_integration::percent_decode(rest.as_bytes());
s = String::from_utf8(decoded).ok()?;
}
let mut unescaped = String::with_capacity(s.len());
let mut chars = s.chars();
while let Some(c) = chars.next() {
if c == '\\'
&& let Some(next) = chars.next()
{
unescaped.push(next);
continue;
}
unescaped.push(c);
}
if unescaped.is_empty() {
return None;
}
Some(PathBuf::from(unescaped))
}
/// Cap a string at `max` characters by inserting an ellipsis in the
/// end so the start (scheme/host) stays visible. No ellipsis marker anywhere in
/// croft, so overflow is cut plainly from the right rather than elided in the
/// middle. `max <= 8` returns the original.
fn truncate_for_display(s: &str, max: usize) -> String {
if s.chars().count() <= max || max <= 8 {
return s.to_string();
}
s.chars().take(max).collect()
}
fn append_to_relay_log(log_path: &Path, payload: &str) -> std::io::Result<()> {
use std::io::Write;
let mut f = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(log_path)?;
f.write_all(payload.as_bytes())?;
f.sync_data().ok();
Ok(())
}
/// Map a screen cell to a sheet grid cell (#177) using the frame-truth
/// layout the render wrote: row from the vertical band, column by
/// walking the visible column widths from `scroll_col`.
fn sheet_cell_at(view: &crate::sheet::SheetView, col: u16, row: u16) -> Option<(usize, usize)> {
let g = view.grid;
if g.data_rows == 0 || row < g.data_top || row >= g.data_top + g.data_rows {
return None;
}
let data = view.sheets.get(view.current_sheet)?;
let r = data.scroll_row + (row - g.data_top) as usize;
if r >= data.row_count() {
return None;
}
if col < g.body_x {
return None;
}
let mut x_off = 0u16;
for (c, w) in data.col_widths.iter().enumerate().skip(data.scroll_col) {
if x_off + w + 1 > g.body_w {
break;
}
if col >= g.body_x + x_off && col < g.body_x + x_off + w {
return Some((r, c));
}
x_off += w + 1;
}
None
}
/// Char-boundary helpers for the in-grid cell editor (#177): byte
/// cursor stepped to valid boundaries.
fn floor_char(s: &str, i: usize) -> usize {
let mut i = i.min(s.len());
while i > 0 && !s.is_char_boundary(i) {
i -= 1;
}
i
}
fn ceil_char(s: &str, i: usize) -> usize {
let mut i = i.min(s.len());
while i < s.len() && !s.is_char_boundary(i) {
i += 1;
}
i
}
/// Keep the selected cell visible: rows directly, columns by advancing
/// `scroll_col` until the cumulative widths place `cur_col` inside the
/// last painted body width (frame truth from the render).
fn sheet_follow_cursor(view: &mut crate::sheet::SheetView, idx: usize, visible: usize) {
let body_w = view.grid.body_w.max(8) as usize;
let Some(data) = view.sheets.get_mut(idx) else {
return;
};
if data.cur_row < data.scroll_row {
data.scroll_row = data.cur_row;
} else if visible > 0 && data.cur_row >= data.scroll_row + visible {
data.scroll_row = data.cur_row + 1 - visible;
}
if data.cur_col < data.scroll_col {
data.scroll_col = data.cur_col;
} else {
// Advance until the cursor column's right edge fits.
while data.scroll_col < data.cur_col {
let used: usize = data.col_widths[data.scroll_col..=data.cur_col]
.iter()
.map(|&w| w as usize + 1)
.sum();
if used <= body_w {
break;
}
data.scroll_col += 1;
}
}
}
fn sheet_visible_rows(inner: Rect) -> usize {
// Renderer reserves 1 row for the header line, 1 row for the column
// labels, and 1 row for the bottom status. Anything left is data.
inner.height.saturating_sub(3) as usize
}
/// Whether a semantic-token reply may be applied, given the newest request
/// generation already applied for that path. Replies for one path overlap:
/// `sync_lsp` and a server-driven refresh can both have a full request in
/// flight at the same `seq`, and the request's retry loop emits an EMPTY
/// batch once its backoff is exhausted. Without this ordering check a late
/// empty loser blanks a good overlay and — being `is_full` — is persisted to
/// the content-keyed cache and replayed on every future open.
fn semantic_reply_is_current(seen: Option<u64>, incoming: u64) -> bool {
seen.is_none_or(|s| incoming >= s)
}
/// The absolute (line, char column) a screen cell lands on in a rendered log
/// body. The body starts one row below the header and the view scrolls by
/// whole lines, so the mapping is a straight offset.
///
/// A cell is mapped back to a character through the same `CellMap` the
/// renderer painted with (#404): a double-width character is two cells and
/// one column, and a click on either half is a click on that character.
/// The two must move together; a mapping that measured width differently
/// from the painter would disagree with what is actually on screen.
fn log_cell_at(
log: &crate::log_view::LogView,
scroll: usize,
col: u16,
row: u16,
) -> (usize, usize) {
let body = log.last_body;
let line = (scroll + row.saturating_sub(body.y) as usize).min(log.len().saturating_sub(1));
let cell = col.saturating_sub(body.x);
// Clamp the COLUMN to the line's own length, not just the line to the
// file's. The renderer paints to the endpoint it is given while the copy
// reads `min(len)`, so an unclamped column let a drag past the end of a
// short line paint sixty cells and copy three characters. Clamping here
// means both readers see one value rather than each clamping its own way.
// `char_at_cell` already answers the character count for a cell past
// the end, which is that clamp.
//
// A line outside the parsed window has no text to map through; the raw
// cell stands as the column, which is what the old behaviour was
// everywhere.
let column = log
.visible_text(line)
.map(|t| crate::cell_map::CellMap::new(t).char_at_cell(cell))
.unwrap_or(cell as usize);
(line, column)
}
/// Create `dir` (0700) if needed and write `contents` to `file` (0600). On
/// non-unix hosts the modes do not exist and the plain write is used.
fn write_private(dir: &Path, file: &Path, contents: &str) -> std::io::Result<()> {
#[cfg(unix)]
{
use std::io::Write;
use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt, PermissionsExt};
// `recursive` also creates any missing parent (`~/.cache/croft`
// itself on a first run) at 0700. Its other tenants are `sessions/`
// (session.rs), `tmp/` (pdf.rs) and the MCP registry cache
// (registry_index.rs), every one of them private per-user state
// that gains nothing from a wider parent.
std::fs::DirBuilder::new()
.recursive(true)
.mode(0o700)
.create(dir)?;
// A pre-existing dir is tightened, a link is refused: `create` adopts
// an existing symlink to a dir, `symlink_metadata` reports the link's
// own mode (always loose), and `set_permissions` follows the link, so
// without this check a scrollback dir pointed at any dir the user
// owns would silently re-mode that dir on the first dump.
let meta = std::fs::symlink_metadata(dir)?;
if meta.file_type().is_symlink() {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!(
"{} is a symlink; refusing to write through it",
dir.display()
),
));
}
if meta.permissions().mode() & 0o077 != 0 {
std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))?;
}
// The same for the file: `create(true).truncate(true)` follows a link
// planted where the dump goes, and the chmod below would re-mode its
// target after the truncate had emptied it. The dir is 0700, so the
// planter is this user's own tooling or a restored backup, and the
// answer is still a refusal rather than a destroyed file.
if let Ok(fmeta) = std::fs::symlink_metadata(file)
&& fmeta.file_type().is_symlink()
{
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!(
"{} is a symlink; refusing to write through it",
file.display()
),
));
}
// `O_NOFOLLOW` makes the open itself refuse a link, so a link swapped
// in between the check above and this open cannot be followed either
// (the same pair config_layers.rs uses); the check above only buys
// the clearer error. `mode` applies on creation alone, hence the
// chmod below for a file left by an earlier dump.
let mut opts = std::fs::OpenOptions::new();
opts.write(true).create(true).truncate(true).mode(0o600);
opts.custom_flags(libc::O_NOFOLLOW);
let mut f = opts.open(file)?;
f.set_permissions(std::fs::Permissions::from_mode(0o600))?;
f.write_all(contents.as_bytes())
}
#[cfg(not(unix))]
{
std::fs::create_dir_all(dir)?;
std::fs::write(file, contents)
}
}
/// Remove the dumps under `dir` whose croft process is gone. A dump is named
/// `<pane>-<pid>-<uid>-scrollback.log` and is overwritten only by the process
/// that wrote it, so every exited croft would otherwise leave its dumps
/// behind for good, each the size of a pane's scrollback; the other cache
/// dirs here all bound themselves the same way. Anything not shaped like a
/// dump is left alone, and so is every live process's file.
fn reap_dead_scrollback_dumps(dir: &Path) {
let Ok(entries) = std::fs::read_dir(dir) else {
return;
};
let me = std::process::id();
for entry in entries.flatten() {
let name = entry.file_name();
let Some(stem) = name
.to_str()
.and_then(|n| n.strip_suffix("-scrollback.log"))
else {
continue;
};
// `<pane>-<pid>-<uid>`, read from the right since a pane label may
// itself contain dashes.
let mut parts = stem.rsplitn(3, '-');
let (Some(_uid), Some(pid), Some(_pane)) = (parts.next(), parts.next(), parts.next())
else {
continue;
};
let Ok(pid) = pid.parse::<u32>() else {
continue;
};
if pid != me && !process_is_alive(pid) {
let _ = std::fs::remove_file(entry.path());
}
}
}
/// Whether a process with `pid` exists. Signal 0 delivers nothing and only
/// checks; a process this user may not signal still exists, so `EPERM`
/// reads as alive. Off unix nothing is reaped, on the conservative side.
/// Existence, not liveness, is enough here (unlike `session::is_alive`,
/// which probes by connecting): a pid that was reused reads as alive and
/// only leaks a file, and every wrong answer this can give errs that way.
#[cfg(unix)]
fn process_is_alive(pid: u32) -> bool {
let Ok(pid) = libc::pid_t::try_from(pid) else {
return true;
};
// SAFETY: `kill` with signal 0 only checks for the process; no signal is
// delivered and no memory is touched.
if unsafe { libc::kill(pid, 0) } == 0 {
return true;
}
std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
}
#[cfg(not(unix))]
fn process_is_alive(_pid: u32) -> bool {
true
}
/// Whether a scrollback dump goes to the rendered log view or to the plain
/// scratch buffer (#257). Must agree with the open path's own sniff, which
/// reads only the first 8 KiB of the file: a dump this says is a log but the
/// sniff says is text would open as an editable file full of raw escapes.
fn scrollback_opens_as_log(rows: &[String]) -> bool {
// The same 8 KiB the file sniff reads, over the same bytes it will read.
let mut prefix = String::new();
for row in rows {
if prefix.len() >= 8192 {
break;
}
prefix.push_str(row);
prefix.push('\n');
}
let cut = prefix.floor_char_boundary(prefix.len().min(8192));
crate::ansi_text::looks_like_ansi(&prefix[..cut])
}
fn rect_contains(r: Rect, x: u16, y: u16) -> bool {
r.width > 0 && r.height > 0 && x >= r.x && x < r.x + r.width && y >= r.y && y < r.y + r.height
}
/// Push a log-highlight setting into the log view's process-wide opening
/// default (#466), from the toggle and from a settings remerge.
pub(crate) fn seed_log_highlight_default(on: bool) {
crate::log_view::set_default_highlight(on);
}
/// The startup seed of that default from the saved preference (#466). In
/// the shipped binary it is the same write; under test it RECORDS the value
/// per thread instead, because the suite builds hundreds of apps on
/// parallel threads and each write would race the tests that read the
/// process-wide default. The record keeps the call site observable: a test
/// asserts what `App::new` decided to seed, not merely that a setter sets.
#[cfg(not(test))]
fn seed_log_highlight_default_at_startup(on: bool) {
crate::log_view::set_default_highlight(on);
}
#[cfg(test)]
thread_local! {
/// What the most recent `App::new` on this thread would have seeded.
pub(crate) static STARTUP_LOG_HIGHLIGHT_SEED: std::cell::Cell<Option<bool>> =
const { std::cell::Cell::new(None) };
}
#[cfg(test)]
fn seed_log_highlight_default_at_startup(on: bool) {
STARTUP_LOG_HIGHLIGHT_SEED.with(|cell| cell.set(Some(on)));
}
/// Build the up-to-date version of an open diff view from its recorded
/// source (#471), or `None` when there is nothing new to build: a `Static`
/// view, a file-backed view whose sides have not moved on disk, a git-command
/// view on a filesystem-only trigger, or a side that can no longer be read
/// (the reader keeps the last good view). The result carries fresh disk
/// stamps but none of the reader's view state; `DiffData::carry_view_from`
/// adds that.
fn rebuild_diff_view(
old: &crate::widgets::diff::DiffData,
git_too: bool,
heads_moved: &[PathBuf],
touched: &[PathBuf],
) -> Option<crate::widgets::diff::DiffData> {
use crate::widgets::diff::{DiffData, DiffSource, GitDiffKind};
// A side the watcher just reported written, matched on the canonical
// path so a symlinked root cannot hide it. Bypasses the stamp gate.
let written = |side: &Path| {
if touched.is_empty() {
return false;
}
let canon = std::fs::canonicalize(side).unwrap_or_else(|_| side.to_path_buf());
touched.iter().any(|t| *t == canon || t == side)
};
let lines = |t: &str| -> Vec<String> { t.lines().map(str::to_string).collect() };
let two_sided = |left_text: &str, right_text: &str| {
DiffData::build_with_byte_check(
old.left_path.clone(),
old.right_path.clone(),
lines(left_text),
lines(right_text),
Some(left_text),
Some(right_text),
)
};
let mut fresh = match &old.source {
DiffSource::Static => return None,
DiffSource::HeadVsWorking { root, rel } => {
// Canonical on both sides: git canonicalises `--show-toplevel`
// (macOS's /tmp -> /private/tmp), while a root the app carries
// as typed may not be, so the same repository can be spelled two
// ways between the tag and the drain's record.
let canon = |p: &Path| std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf());
let head_moved = git_too
&& heads_moved
.iter()
.any(|r| r == root || canon(r) == canon(root));
if !head_moved && !written(&old.right_path) && !old.sides_moved_on_disk() {
return None;
}
let head = crate::git::read_file_at_head(root, rel).ok()?;
let right = std::fs::read_to_string(&old.right_path).ok()?;
two_sided(&head, &right)
}
DiffSource::FixedLeft { left_text } => {
if !written(&old.right_path) && !old.sides_moved_on_disk() {
return None;
}
let right = std::fs::read_to_string(&old.right_path).ok()?;
two_sided(left_text, &right)
}
DiffSource::TwoFiles => {
if !written(&old.left_path) && !written(&old.right_path) && !old.sides_moved_on_disk() {
return None;
}
let left = std::fs::read_to_string(&old.left_path).ok()?;
let right = std::fs::read_to_string(&old.right_path).ok()?;
DiffData::build(
old.left_path.clone(),
old.right_path.clone(),
lines(&left),
lines(&right),
)
}
DiffSource::GitCommand { root, kind } => {
if !git_too {
return None;
}
let raw = match kind {
GitDiffKind::Staged => crate::git::diff_staged(root),
GitDiffKind::AgainstBranch(branch) => crate::git::diff_against_branch(root, branch),
GitDiffKind::PreviousCommit => crate::git::diff_previous_commit(root),
}
.ok()?;
DiffData::build_side_by_side_from_git_text(old.left_path.clone(), &raw)
}
};
fresh.source = old.source.clone();
fresh.left_is_real_file = old.left_is_real_file;
fresh.stamp_sides();
Some(fresh)
}
/// Fold a mouse event's Shift/Alt/Ctrl state into the form `report_mouse`
/// wants, so a forwarded wheel notch or left-button event carries the same
/// modifiers the child would have seen natively.
fn mouse_mods(m: &MouseEvent) -> MouseMods {
MouseMods {
shift: m.modifiers.contains(KeyModifiers::SHIFT),
alt: m.modifiers.contains(KeyModifiers::ALT),
ctrl: m.modifiers.contains(KeyModifiers::CONTROL),
}
}
/// The SGR prefix (reset + truecolor fg/bg) for one ratatui cell, used when
/// blitting a buffer region straight to the terminal in
/// `flush_tooltip_over_image`. The tooltip only uses RGB and reset colors, so
/// other `Color` variants fall through to the terminal default.
fn sgr_for_cell(cell: &ratatui::buffer::Cell) -> String {
let mut s = String::from("\x1b[0m");
if let Color::Rgb(r, g, b) = cell.fg {
s.push_str(&format!("\x1b[38;2;{r};{g};{b}m"));
}
if let Color::Rgb(r, g, b) = cell.bg {
s.push_str(&format!("\x1b[48;2;{r};{g};{b}m"));
}
s
}
/// True when two cell rectangles share at least one cell. Used to decide
/// whether a text overlay (the chrome tooltip) lands on top of an OSC-1337
/// inline image; since terminal images composite ABOVE text cells, the
/// overlapping tooltip must be re-painted last to win those cells.
fn rects_intersect(a: Rect, b: Rect) -> bool {
a.width > 0
&& a.height > 0
&& b.width > 0
&& b.height > 0
&& a.x < b.x.saturating_add(b.width)
&& b.x < a.x.saturating_add(a.width)
&& a.y < b.y.saturating_add(b.height)
&& b.y < a.y.saturating_add(a.height)
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RunSpec {
pub program: String,
pub args: Vec<String>,
pub cwd: PathBuf,
}
/// Walk from `start` up to and including `workspace_root` looking for a
/// venv-style Python interpreter. Returns `(interpreter_path, owning_dir)`
/// where `owning_dir` is the directory that contains the venv folder — the
/// natural cwd for the run.
///
/// The walk stops at `workspace_root`: a venv that lives ABOVE the workspace
/// would belong to a different project the user has not opened, and using it
/// silently would surprise them.
fn find_python_venv(start: &Path, workspace_root: &Path) -> Option<(PathBuf, PathBuf)> {
let mut probe = start.to_path_buf();
loop {
for venv_name in [".venv", "venv", ".env"] {
let py = probe.join(venv_name).join("bin").join("python");
if py.is_file() {
return Some((py, probe));
}
}
if probe == workspace_root {
return None;
}
match probe.parent() {
Some(parent) if parent != probe => {
if !parent.starts_with(workspace_root) && parent != workspace_root {
return None;
}
probe = parent.to_path_buf();
}
_ => return None,
}
}
}
const TERMINAL_ADD_LABEL: &str = " + ";
const TERMINAL_CLOSE_LABEL: &str = " - ";
/// Codicon chevron-down, matching the OUTPUT dropdown caret. Opens the terminal
/// profile picker (VS Code's `∨` beside `+`).
const TERMINAL_PROFILE_LABEL: &str = " \u{eab4} ";
/// Codicon screen-full (Nerd Fonts `cod-screen_full` = U+EB4C): maximize this
/// terminal pane across the panel, parking the other panes in the right rail.
const TERMINAL_MAX_LABEL: &str = " \u{eb4c} ";
/// Codicon screen-normal (Nerd Fonts `cod-screen_normal` = U+EB4D): restore
/// the even split. Swapped in for the `⛶` while a pane is maximized.
const TERMINAL_RESTORE_LABEL: &str = " \u{eb4d} ";
/// Codicon chevron-left (Nerd Fonts `cod-chevron_left` = U+EAB5): fold this
/// pane to a strip and hand its width to the panes still expanded (#313).
///
/// Its own button rather than a new meaning for `-`: `-` closes, and it goes
/// on closing. A control that destroys on one build and folds on the next is
/// the kind of change muscle memory finds out the hard way.
const TERMINAL_COLLAPSE_LABEL: &str = " \u{eab5} ";
/// Codicon chevron-right (U+EAB6), on the header row of a collapsed pane's
/// strip: the way back out. It points the opposite way to the button that put
/// the pane there, which is the whole of the affordance in one column.
const TERMINAL_EXPAND_GLYPH: char = '\u{eab6}';
/// Stands in for a character too wide for the one column a strip owns. A
/// CJK glyph or an emoji is two cells and would paint over the pane next
/// door; dropping it outright left a pane named entirely in them with a
/// blank strip, which is the one thing the strip exists to prevent.
const TERMINAL_STRIP_WIDE_STANDIN: char = '\u{b7}';
/// A collapsed pane's entire width: one column, carrying the expand chevron
/// and the pane's name set vertically.
const TERMINAL_STRIP_W: u16 = 1;
/// Codicon terminal (Nerd Fonts `cod-terminal` = U+EA85), leading each
/// maximize-rail row the way VS Code's terminal tabs list does.
/// Cells the pane's header buttons occupy, measured in from its right edge:
/// `‹`, `⛶`, `-`, `∨` and `+` at three each, plus the one blank column right
/// of `+`. The name pill paints after the buttons and would win the shared
/// cells, so it is clipped to the width left of this strip.
/// `a_long_pane_label_never_overpaints_the_maximize_button` pins it, so adding
/// a SIXTH button fails a test rather than quietly erasing a glyph again -
/// which is how the collapse button (#313) was caught needing this widened
/// from 13 instead of silently sharing the pill's cells.
const TERMINAL_BUTTON_STRIP_W: u16 = 16;
/// Width constraints for the terminal row, given which panes are collapsed
/// (#313).
///
/// A collapsed pane keeps a one-column strip; the panes still expanded divide
/// everything left over. Split out as a pure function of the flags because
/// the apportioning is the whole of the layout risk here, and this way it is
/// asserted directly - a constraint vector measured against expected widths -
/// rather than only through a rendered frame.
///
/// `Fill` rather than `Ratio` for the expanded panes: `Ratio(1, k)` is a
/// share of the WHOLE row, so mixing it with the strips' `Length(1)` asks the
/// solver for more columns than exist and it settles that overflow by shaving
/// the panes. `Fill` divides what the strips leave, which is the arithmetic
/// actually wanted.
///
/// With nothing collapsed every pane is `Fill(1)`, which apportions the row
/// evenly - the same split as before the feature existed, so the common case
/// pays nothing for it.
///
/// Every pane collapsed is unreachable through the UI ([`App::toggle_terminal_collapse`]
/// and [`App::close_terminal_at`] both keep one expanded), but it is answered
/// here rather than left to divide by zero.
fn terminal_pane_constraints(collapsed: &[bool]) -> Vec<Constraint> {
let any_expanded = collapsed.iter().any(|c| !c);
collapsed
.iter()
.map(|&c| {
if c && any_expanded {
Constraint::Length(TERMINAL_STRIP_W)
} else {
Constraint::Fill(1)
}
})
.collect()
}
const TERMINAL_RAIL_ICON: char = '\u{ea85}';
/// How many label characters a rail row shows. Fixed and deliberately tiny:
/// the rail is a switcher, not a directory, so four letters identify a pane.
const TERMINAL_RAIL_LABEL_W: u16 = 4;
/// The rail's fixed total width: leading space + icon + gap + the 4 label
/// characters. The rail never grows past this, whatever the names are.
const TERMINAL_RAIL_W: u16 = 3 + TERMINAL_RAIL_LABEL_W;
/// True when croft was invoked over an SSH login (or otherwise inside a
/// remote shell). Used to throttle PTY-driven redraws further so the SSH
/// pipe never saturates and starves input handling on the same thread.
fn is_remote_session() -> bool {
std::env::var_os("SSH_CONNECTION").is_some()
|| std::env::var_os("SSH_TTY").is_some()
|| std::env::var_os("SSH_CLIENT").is_some()
}
/// Status-line advisory for a remote croft session that will not survive an
/// SSH transport drop. `croft remote` launches the remote croft under dtach
/// and exports `CROFT_SESSION_PERSISTENT=1`; when that marker is absent on a
/// remote (SSH) session the host has no dtach, so croft tells the user how to
/// turn persistence on. Local sessions never see it. Returned as a status
/// string only (the bottom line is info-only; no input).
fn remote_persistence_status(is_remote: bool, persistent: bool) -> Option<&'static str> {
if is_remote && !persistent {
Some("Persistence off: install dtach")
} else {
None
}
}
/// Test-only redirect for [`croft_cache_dir`], so the relay tests steer the
/// relay rendezvous without repointing the process-global `$HOME` (#37):
/// every concurrent test thread resolves `$HOME` at call time (the PDF
/// rasteriser's scratch dir, the session paths), and a substituted value
/// leaking across threads made unrelated tests fail inside the fake home.
#[cfg(test)]
pub static CACHE_DIR_OVERRIDE_FOR_TEST: std::sync::Mutex<Option<PathBuf>> =
std::sync::Mutex::new(None);
/// The user's `triggers.json`, with the built-in secret redactions in front
/// of it when redaction is on (#360).
fn load_trigger_set(redact_secrets: bool) -> std::sync::Arc<crate::triggers::TriggerSet> {
let set = crate::triggers::TriggerSet::load(&crate::triggers::triggers_path());
std::sync::Arc::new(if redact_secrets {
set.with_builtin_redactions()
} else {
set
})
}
/// What the `.http` worker hands back (#370): the file it ran from, the
/// RAW request line (variables unresolved, so a secret can never land in a
/// status line, history entry, or response tab through it), and the result.
struct HttpRunOutcome {
file: PathBuf,
raw_line: String,
result: Result<crate::http_file::HttpResponse, String>,
}
/// Bind the `croft view` socket and put it in the mode the frame loop needs.
///
/// Split out so the tests seat a listener through the SAME function rather
/// than building one themselves. A test that set `set_nonblocking` itself
/// would be asserting against its own setup: production could drop the call
/// and the "the drain does not block" test would still pass, which is a
/// check that cannot fail.
fn prepare_view_listener(path: &Path) -> std::io::Result<std::os::unix::net::UnixListener> {
let listener = crate::session::bind_socket_0600(path)?;
// Polled from the frame loop, so a blocking accept would stall every
// redraw until somebody happened to run `croft view`.
listener.set_nonblocking(true)?;
Ok(listener)
}
/// Why the `croft view` socket could not be bound, if it could not.
///
/// A `static` because `bind_view_socket` runs before an `App` exists to hold
/// it: `App::new` reads it once, right after the call, and puts it on the
/// status line.
static VIEW_BIND_ERROR: std::sync::Mutex<Option<String>> = std::sync::Mutex::new(None);
/// The status line a fresh `App` opens on, given whatever `bind_view_socket`
/// latched (#362).
///
/// Split out so it can be tested at all: `bind_view_socket` returns early
/// under `cfg(test)`, so nothing in the suite reaches the latch, and the arm
/// that reports a bind failure was the half that had never once run.
fn view_status(view_bind_error: Option<&str>) -> String {
match view_bind_error {
// The one startup failure that would otherwise be invisible until a
// user ran `croft view` and got told to do what they were doing.
Some(e) => format!("croft view is unavailable: {e}"),
None => String::from("Ready"),
}
}
/// Remove `view-<pid>-<nonce>.sock` files whose croft is gone (#362).
///
/// A Unix socket is not auto-unlinked, so every croft that dies leaves its
/// file behind. An `impl Drop` would clean up the tidy exits and none of the
/// others (a SIGKILL, an OOM kill, a panic in another thread), and those are
/// exactly the cases that litter, so the sweep is the mechanism that has to
/// exist and Drop would only duplicate its easy half.
///
/// Liveness is judged from the PID IN THE NAME rather than by connecting.
/// A connect probe races a concurrent bind: the other croft can be between
/// `bind_socket_0600`'s stale-file removal and its `bind`, where the probe
/// reads "dead" correctly and the unlink then lands on the socket it creates
/// a moment later. `kill(pid, 0)` has no such window. The cost is that a
/// recycled PID keeps one dead file indefinitely, which is a stale byte
/// rather than a stolen socket.
pub(crate) fn sweep_dead_view_sockets(dir: &Path) {
let Ok(entries) = std::fs::read_dir(dir) else {
return;
};
// Listed once. `sweep_dead_bind_stages` runs per dead socket and used to
// re-read the directory each time.
let names: Vec<(String, PathBuf)> = entries
.flatten()
.filter_map(|e| Some((e.file_name().to_str()?.to_string(), e.path())))
.collect();
let me = std::process::id();
for (name, entry_path) in &names {
// A croft that died between `bind_socket_0600`'s lock creation and its
// rename leaves a `.bind.lock` with no socket beside it. The
// socket-keyed pass below can never reach one, because
// `pid_of_socket` requires the `.sock` suffix, so those leaked
// permanently. Judging the lock by the pid in its own name closes it.
let sock_name = match name.as_str().strip_suffix(".bind.lock") {
Some(stem) => std::borrow::Cow::Owned(format!("{stem}.sock")),
None => std::borrow::Cow::Borrowed(name),
};
let Some(pid) = crate::view_ipc::pid_of_socket(&sock_name) else {
continue;
};
// Signal 0 checks existence and permission without delivering
// anything; ESRCH is the only answer that means "gone".
let gone = pid != me
&& unsafe { libc::kill(pid as libc::pid_t, 0) } != 0
&& std::io::Error::last_os_error().raw_os_error() == Some(libc::ESRCH);
if gone {
let _ = std::fs::remove_file(entry_path);
// `bind_socket_0600` binds inside a `.s<pid>-<n>` dir and removes
// it on both paths, but a croft killed inside that window strands
// one, and nothing else ever looks at it again. Same argument as
// the orphan lock below: it is litter only this sweep can reach.
sweep_dead_bind_stages(&names, pid);
// Derived from the SOCKET's name rather than from this entry's,
// so sweeping a lock entry does not compose a second suffix onto
// itself. Removing both from either entry is idempotent.
let _ = std::fs::remove_file(dir.join(sock_name.as_ref()).with_extension("bind.lock"));
}
}
sweep_staged_stdin(dir);
}
/// Remove `.s<pid>-<n>` bind staging directories belonging to a dead croft.
///
/// `crate::session::bind_socket_0600` creates one, binds inside it, renames
/// the socket out and removes the directory on both the success and failure
/// paths. A croft killed between the create and the remove strands it, and
/// the counter in that function restarts with the process, so the name is
/// reused rather than accumulating without bound - but the stranded directory
/// is never revisited by anything else.
///
/// Keyed on the same pid the socket sweep just judged dead, so a LIVE croft's
/// staging directory is never touched: removing one mid-bind would take the
/// socket it is about to rename out with it. "Never" modulo the pid-recycling
/// window the socket unlink above already accepts, which needs the pid space
/// to wrap between the `kill` and the removal.
///
/// Takes the directory listing rather than reading it: this is called once per
/// dead socket, and a cache dir holding N stale sockets was costing N full
/// listings at launch.
fn sweep_dead_bind_stages(names: &[(String, PathBuf)], pid: u32) {
let prefix = format!(".s{pid}-");
for (name, path) in names {
if name.starts_with(&prefix) && name[prefix.len()..].parse::<u64>().is_ok() {
let _ = std::fs::remove_dir_all(path);
}
}
}
/// How long a staged stdin file outlives the pipe that wrote it (#362).
///
/// Generous, because the cost of keeping a file too long is disk and the cost
/// of dropping one too early is a broken tab. It still bounds the pile: the
/// module's own rationale names `vault read … | croft view -`, and without any
/// sweep every such pipe left a permanent copy on disk the user was never told
/// about.
const STAGED_STDIN_RETENTION: std::time::Duration = std::time::Duration::from_secs(60 * 60 * 24);
/// Drop staged stdin that no live croft holds and that has aged out (#362).
///
/// TWO signals, and the order matters: a live holder spares a file at any age,
/// and age only ever reaches files nobody holds.
///
/// Age alone was the whole mechanism, for a reason that still stands as far as
/// it goes. `stage_stdin` runs inside [`crate::view_ipc::run`] - the
/// short-lived `croft view` CLIENT process, which exits milliseconds later —
/// so the pid baked into every staged name belongs to something that is always
/// already dead. A liveness check therefore matched EVERY staged file,
/// including one a running croft had open in a tab, and launching a second
/// croft deleted it. That is not litter: `sqlite_view::table_page` re-opens the
/// file by path on every page turn, so the tab breaks on the next page.
///
/// But age alone still deleted a file a croft was showing, once that session
/// outlived the window: `sqlite_view::table_page` re-opens by path on every
/// page turn, so the tab breaks, and piped input cannot be regenerated by
/// re-running anything. So the SERVER stamps its pid into the name when it
/// opens the file ([`crate::view_ipc::claim_staged`]), which is the one point
/// where a live holder is known, and this reads it back.
///
/// Runs at launch, from `sweep_dead_view_sockets`, so a file staged inside a
/// long-lived session survives until the next croft starts, and now survives
/// that too for as long as its holder is running.
fn sweep_staged_stdin(dir: &Path) {
let staged = dir.join("view-stdin");
let Ok(entries) = std::fs::read_dir(&staged) else {
return;
};
for entry in entries.flatten() {
// Only croft's own staging names, so a file dropped in this directory
// by anything else is left alone rather than deleted on a guess.
let name = entry.file_name();
let Some(name) = name.to_str() else { continue };
if !name.starts_with("stdin-") && !name.starts_with(crate::view_ipc::HELD_PREFIX) {
continue;
}
// A file a LIVE croft is showing is never swept, whatever its age.
// `apply_view_request` stamps its own pid in at open time, which is
// the one moment a live holder is known; the name a client staged
// carries a pid that is dead by construction, which is why age was
// the only signal here before. Signal 0 checks existence and
// permission without delivering anything, and ESRCH is the only
// answer that means gone, exactly as the socket sweep judges it.
if let Some(holder) = crate::view_ipc::holder_of_staged(name) {
let alive = holder == std::process::id()
|| unsafe { libc::kill(holder as libc::pid_t, 0) } == 0
|| std::io::Error::last_os_error().raw_os_error() != Some(libc::ESRCH);
if alive {
continue;
}
}
// Age still bounds the pile, but now it only ever reaches files no
// live croft holds: a client that staged bytes nobody opened, and a
// holder that has since exited.
let too_old = entry
.metadata()
.and_then(|m| m.modified())
.and_then(|t| t.elapsed().map_err(std::io::Error::other))
.is_ok_and(|age| age > STAGED_STDIN_RETENTION);
if too_old {
let _ = std::fs::remove_file(entry.path());
}
}
}
/// How long an ssh-pane offer stays up untouched (#364) before it clears
/// itself: long enough to read and act on, short enough not to be stale
/// when the user next looks at the status bar.
const SSH_OFFER_TTL: std::time::Duration = std::time::Duration::from_secs(90);
pub(crate) fn croft_cache_dir() -> PathBuf {
#[cfg(test)]
if let Some(dir) = CACHE_DIR_OVERRIDE_FOR_TEST.lock().unwrap().clone() {
return dir;
}
let home = std::env::var_os("HOME")
.map(PathBuf::from)
.unwrap_or_else(|| PathBuf::from("."));
home.join(".cache").join("croft")
}
/// The per-process self-install log: two drift-armed croft instances on one
/// machine must not overwrite each other's build diagnostics (#245).
fn self_install_log_path() -> PathBuf {
croft_cache_dir().join(format!("self-install-{}.log", std::process::id()))
}
/// The staged release build's log (#333): its own file, since a drift
/// rebuild may run in the same process and must not overwrite it.
fn staged_install_log_path() -> PathBuf {
croft_cache_dir().join(format!("staged-install-{}.log", std::process::id()))
}
/// Resolve the binary to re-exec into after an update. A local self-install
/// re-execs the exact path cargo reported writing (which honors an
/// `install.root` from cargo config that env resolution can't see), falling
/// back to cargo's env-level root (`CARGO_INSTALL_ROOT` / `CARGO_HOME` /
/// `~/.cargo`); the remote installer always rsyncs to the literal
/// `~/.cargo/bin/croft`. Either way the fresh file is preferred over
/// `current_exe`, which may resolve to the now-replaced inode.
fn reexec_binary_path(local_install: Option<&crate::update_watch::SelfInstall>) -> PathBuf {
let installed = if let Some(install) = local_install {
install
.installed_path()
.or_else(crate::update_watch::cargo_install_bin)
} else {
std::env::var_os("HOME")
.map(|home| PathBuf::from(home).join(".cargo").join("bin").join("croft"))
};
if let Some(p) = installed
&& p.exists()
{
return p;
}
std::env::current_exe().unwrap_or_else(|_| PathBuf::from("croft"))
}
fn sidebar_view_label(view: SidebarView) -> &'static str {
match view {
SidebarView::Explorer => "Explorer",
SidebarView::Search => "Search",
SidebarView::SourceControl => "SourceControl",
SidebarView::Remote => "Remote",
SidebarView::RunDebug => "RunDebug",
SidebarView::Extensions => "Extensions",
SidebarView::Testing => "Testing",
}
}
fn sidebar_view_from_label(label: &str) -> Option<SidebarView> {
match label {
"Explorer" => Some(SidebarView::Explorer),
"Search" => Some(SidebarView::Search),
"SourceControl" => Some(SidebarView::SourceControl),
"Remote" => Some(SidebarView::Remote),
"RunDebug" => Some(SidebarView::RunDebug),
"Extensions" => Some(SidebarView::Extensions),
"Testing" => Some(SidebarView::Testing),
_ => None,
}
}
/// Collect the bundled and user-installed extension manifests, project them to
/// the panel's row list, and stamp each with its enabled state from `disabled`.
/// The bundled set ships in the binary; user extensions are read fresh from
/// `~/.config/croft/extensions/` each call so a newly dropped-in extension shows
/// up without a relaunch.
fn build_extension_items(
disabled: &std::collections::BTreeSet<String>,
vscode: &[crate::vscode_extensions::Comparison],
) -> Vec<crate::widgets::extensions::ExtensionItem> {
use crate::lsp::manifest;
let user = manifest::read_extension_sources(&manifest::user_extensions_dir());
let mut sources: Vec<&str> = manifest::BUNDLED_MANIFESTS.to_vec();
sources.extend(user.iter().map(String::as_str));
let summaries = manifest::summaries(&sources);
let mut items = crate::widgets::extensions::items_from_summaries(summaries, disabled);
// Flag installed catalog entries as removable: croft wrote their manifest
// (so uninstall is reversible), while a hand-dropped user manifest is the
// user's own file and is never deleted. Drives the per-row trash button.
for it in &mut items {
it.removable = !it.builtin && !it.available && crate::mcp::catalog::is_removable(&it.id);
}
// Append the curated MCP catalog's not-yet-installed entries under AVAILABLE.
items.extend(crate::widgets::extensions::items_from_available(
crate::mcp::catalog::available(),
));
// And what VS Code has that croft covers, or does not (#352).
items.extend(crate::widgets::extensions::items_from_vscode(vscode));
items
}
/// Resolve the program to spawn for a sidecar server: PATH-first / pinned
/// managed install (reusing the LSP provisioning), or `None`+kick the install
/// when not yet present. Returns the command plus extra PATH dirs it needs.
fn resolve_mcp_program(
server: &crate::mcp::registry::ServerSpawn,
) -> Result<(String, Vec<PathBuf>), String> {
let Some(provision) = &server.provision else {
// PATH-only server (no croft-managed provisioning declared).
return Ok((server.command.clone(), Vec::new()));
};
if let Some(found) = crate::lsp::install::provisioned_command(&server.id, provision) {
return Ok(found);
}
// Not installed: kick the one-shot managed install (leaking the id to
// 'static once, only on this first-install path — `resolve_managed` keys its
// install-started gate on it), and ask the user to retry once it lands.
let name: &'static str = Box::leak(server.id.clone().into_boxed_str());
let config = crate::lsp::config::ServerConfig {
name,
command: server.command.clone(),
args: server.args.clone(),
language: crate::lsp::config::Language("mcp"),
initialization_options: None,
provision: Some(provision.clone()),
};
crate::lsp::install::resolve_managed(&config, provision, true);
// First run: the managed install runs in the background. Block here (on the
// worker thread — the UI stays responsive) until it lands, then resolve, so a
// single invocation installs AND runs the command instead of erroring with
// "run again" and dropping the user's argument. spawn_mcp_command shows a
// first-run status meanwhile.
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(180);
loop {
std::thread::sleep(std::time::Duration::from_millis(500));
if let Some(found) = crate::lsp::install::provisioned_command(&server.id, provision) {
return Ok(found);
}
if std::time::Instant::now() >= deadline {
return Err(format!(
"Installing {} timed out — check your network and try again",
server.id
));
}
}
}
/// Run a resolved MCP command to completion on a worker thread: provision +
/// spawn the server, verify the tool definition (trust-on-first-use rug-pull
/// guard), call the tool, and return its text. Pure blocking; the caller sends
/// the [`crate::mcp::McpOutcome`] back over a channel.
fn run_mcp_command_blocking(
resolved: &crate::mcp::registry::ResolvedCommand,
arg: Option<String>,
cwd: &Path,
version: &str,
) -> crate::mcp::McpOutcome {
use serde_json::json;
let title = resolved.title.clone();
let body = (|| -> Result<String, String> {
let (program, extra_paths) = resolve_mcp_program(&resolved.server)?;
// Least-privilege env: the declared vars plus a PATH (extra dirs first,
// then the inherited PATH) so the launcher resolves its interpreter.
let mut env = resolved.server.env.clone();
let mut path_parts: Vec<String> = extra_paths
.iter()
.map(|p| p.display().to_string())
.collect();
if let Ok(sys) = std::env::var("PATH") {
path_parts.push(sys);
}
env.insert("PATH".to_string(), path_parts.join(":"));
let client = crate::mcp::client::McpClient::connect(
&program,
&resolved.server.args,
cwd,
&env,
"croft",
version,
)
.map_err(|e| e.to_string())?;
// Trust-on-first-use: fingerprint the tool definition and refuse if it
// changed since the user first ran this command (rug-pull / MCPoison).
let list = client
.call("tools/list", json!({}))
.map_err(|e| e.to_string())?;
// Validate the declared tool is actually advertised before calling it.
let tools = crate::mcp::client::parse_tools(&list);
if !tools.iter().any(|t| t.name == resolved.tool) {
return Err(format!(
"the server does not advertise a '{}' tool",
resolved.tool
));
}
let fingerprint = crate::mcp::client::tool_fingerprint(&list, &resolved.tool);
let prefs = crate::prefs::Prefs::load_or_default();
match prefs.mcp_tool_fingerprints.get(&resolved.command_id) {
Some(prev) if prev != &fingerprint => {
return Err(format!(
"refusing to run: the '{}' tool definition changed since you approved it (possible rug-pull); toggle the extension off and on to re-approve",
resolved.tool
));
}
Some(_) => {}
None => {
let _ = crate::prefs::save_mcp_tool_fingerprint(&resolved.command_id, &fingerprint);
}
}
let arguments = match (resolved.arg.as_ref(), arg) {
(Some(name), Some(value)) => json!({ name.as_str(): value }),
_ => json!({}),
};
let result = client
.call_tool(&resolved.tool, arguments)
.map_err(|e| e.to_string())?;
let text = crate::mcp::client::tool_result_text(&result);
Ok(if text.trim().is_empty() {
String::from("(the tool returned no text content)")
} else {
text
})
})();
crate::mcp::McpOutcome { title, body }
}
/// Paint the terminal pane's header buttons on its top border and return
/// their hit-test rectangles. Any of them is `None` when the pane is too
/// narrow or short for the label to fit, and the three that act on ONE pane
/// among several (`-`, `⛶`, `‹`) are absent when a lone terminal is open and
/// there is nothing to drop, maximize against, or fold away from.
///
/// Right to left: `+`, `∨`, `-`, `⛶`, `‹`. The collapse button (#313) went on
/// the far LEFT deliberately: every button already there keeps the exact
/// column it had, so a user reaching for `-` by position still lands on `-`
/// and not on a gesture that merely looks similar.
fn paint_terminal_pane_buttons(
frame: &mut ratatui::Frame,
area: Rect,
show_close_button: bool,
pane_maximized: bool,
theme: crate::theme::Theme,
pointer: Option<(u16, u16)>,
) -> TerminalPaneButtons {
let add_w = TERMINAL_ADD_LABEL.chars().count() as u16;
let caret_w = TERMINAL_PROFILE_LABEL.chars().count() as u16;
let close_w = TERMINAL_CLOSE_LABEL.chars().count() as u16;
let max_w = TERMINAL_MAX_LABEL.chars().count() as u16;
let fold_w = TERMINAL_COLLAPSE_LABEL.chars().count() as u16;
let mut out = TerminalPaneButtons::default();
if area.height == 0 {
return out;
}
let y = area.y;
// Styling is the shared header-action look (see `header_pill::action_style`):
// quiet teal icons under Black with a teal hover pill, navy chips under
// Croft Dark. The Explorer `⋯` button draws from the same source of truth.
let style_at = |x: u16, w: u16| -> Style {
let hovered = pointer.is_some_and(|(px, py)| py == y && px >= x && px < x + w);
crate::widgets::header_pill::action_style(theme, hovered)
};
// Right to left: [+] at the edge, the profile caret just left of it, then
// [-]. The caret mirrors VS Code's `∨` next to `+`.
if area.width >= add_w + 2 {
let x = area.x + area.width - add_w - 1;
frame
.buffer_mut()
.set_string(x, y, TERMINAL_ADD_LABEL, style_at(x, add_w));
out.add = Some(Rect {
x,
y,
width: add_w,
height: 1,
});
}
if area.width >= add_w + caret_w + 2 {
let x = area.x + area.width - add_w - caret_w - 1;
frame
.buffer_mut()
.set_string(x, y, TERMINAL_PROFILE_LABEL, style_at(x, caret_w));
out.profile = Some(Rect {
x,
y,
width: caret_w,
height: 1,
});
}
if show_close_button && area.width >= add_w + caret_w + close_w + 2 {
let x = area.x + area.width - add_w - caret_w - close_w - 1;
frame
.buffer_mut()
.set_string(x, y, TERMINAL_CLOSE_LABEL, style_at(x, close_w));
out.close = Some(Rect {
x,
y,
width: close_w,
height: 1,
});
}
// The maximize / restore button sits left of `-` and shares its
// visibility: with a single terminal there is nothing to maximize
// against, just as there is nothing to close.
if show_close_button && area.width >= add_w + caret_w + close_w + max_w + 2 {
let x = area.x + area.width - add_w - caret_w - close_w - max_w - 1;
let label = if pane_maximized {
TERMINAL_RESTORE_LABEL
} else {
TERMINAL_MAX_LABEL
};
frame
.buffer_mut()
.set_string(x, y, label, style_at(x, max_w));
out.max = Some(Rect {
x,
y,
width: max_w,
height: 1,
});
}
// Collapse sits left of `⛶`, putting the two layout gestures beside each
// other and leaving the destructive `-` where it was. Maximize already
// owns the whole panel and ignores the collapse flags, so while it is on
// the button would be a control that does nothing: it is not painted.
if show_close_button
&& !pane_maximized
&& area.width >= add_w + caret_w + close_w + max_w + fold_w + 2
{
let x = area.x + area.width - add_w - caret_w - close_w - max_w - fold_w - 1;
frame
.buffer_mut()
.set_string(x, y, TERMINAL_COLLAPSE_LABEL, style_at(x, fold_w));
out.collapse = Some(Rect {
x,
y,
width: fold_w,
height: 1,
});
}
out
}
/// Hit rects for one terminal pane's header buttons, as laid out by the most
/// recent render. Any may be `None` when the pane is too narrow.
#[derive(Default)]
struct TerminalPaneButtons {
add: Option<Rect>,
profile: Option<Rect>,
close: Option<Rect>,
max: Option<Rect>,
collapse: Option<Rect>,
}
/// `app_cursor` is the pane's DECCKM state: cursor keys switch from the
/// normal CSI form (`\e[A`) to SS3 (`\eOA`), the form terminfo advertises —
/// apps that bind keys from terminfo (Python's REPL, less) only match SS3.
fn key_to_bytes(key: KeyEvent, app_cursor: bool) -> Vec<u8> {
use KeyCode::*;
let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
let alt = key.modifiers.contains(KeyModifiers::ALT);
let cursor =
|app: &'static [u8], normal: &'static [u8]| if app_cursor { app } else { normal }.to_vec();
match key.code {
Enter => vec![b'\r'],
Tab => vec![b'\t'],
BackTab => b"\x1b[Z".to_vec(),
Backspace => vec![0x7f],
Esc => vec![0x1b],
Up => cursor(b"\x1bOA", b"\x1b[A"),
Down => cursor(b"\x1bOB", b"\x1b[B"),
Right if alt => b"\x1bf".to_vec(),
Left if alt => b"\x1bb".to_vec(),
Right => cursor(b"\x1bOC", b"\x1b[C"),
Left => cursor(b"\x1bOD", b"\x1b[D"),
Home => cursor(b"\x1bOH", b"\x1b[H"),
End => cursor(b"\x1bOF", b"\x1b[F"),
PageUp => b"\x1b[5~".to_vec(),
PageDown => b"\x1b[6~".to_vec(),
Insert => b"\x1b[2~".to_vec(),
Delete => b"\x1b[3~".to_vec(),
F(n) => match n {
1 => b"\x1bOP".to_vec(),
2 => b"\x1bOQ".to_vec(),
3 => b"\x1bOR".to_vec(),
4 => b"\x1bOS".to_vec(),
5 => b"\x1b[15~".to_vec(),
6 => b"\x1b[17~".to_vec(),
7 => b"\x1b[18~".to_vec(),
8 => b"\x1b[19~".to_vec(),
9 => b"\x1b[20~".to_vec(),
10 => b"\x1b[21~".to_vec(),
11 => b"\x1b[23~".to_vec(),
12 => b"\x1b[24~".to_vec(),
_ => Vec::new(),
},
Char(c) => {
if ctrl {
let lc = c.to_ascii_lowercase();
if lc.is_ascii_lowercase() {
return vec![(lc as u8) - b'a' + 1];
}
match c {
'@' => vec![0x00],
'\\' => vec![0x1c],
']' => vec![0x1d],
_ => Vec::new(),
}
} else if alt {
let mut v = vec![0x1b];
let mut buf = [0u8; 4];
v.extend_from_slice(c.encode_utf8(&mut buf).as_bytes());
v
} else {
let mut buf = [0u8; 4];
c.encode_utf8(&mut buf).as_bytes().to_vec()
}
}
_ => Vec::new(),
}
}
/// Divider drawn between the diagnostic block and the language hover content,
/// mirroring the horizontal rule VS Code renders between hover sections.
const HOVER_DIVIDER: &str = "────────";
/// Render the diagnostics under the hovered point into a single labelled text
/// block, errors first (so the most severe message leads), each line prefixed
/// with its severity. `None` when there are no diagnostics. The severity word
/// answers the user's "what type of error is it" directly, since a TUI can't
/// show VS Code's coloured marker icon.
fn format_diagnostics(
diags: &[(crate::lsp::manager::DiagnosticSeverity, String)],
) -> Option<String> {
use crate::lsp::manager::DiagnosticSeverity;
if diags.is_empty() {
return None;
}
let rank = |s: &DiagnosticSeverity| match s {
DiagnosticSeverity::Error => 0,
DiagnosticSeverity::Warning => 1,
DiagnosticSeverity::Information => 2,
DiagnosticSeverity::Hint => 3,
};
let label = |s: &DiagnosticSeverity| match s {
DiagnosticSeverity::Error => "Error",
DiagnosticSeverity::Warning => "Warning",
DiagnosticSeverity::Information => "Info",
DiagnosticSeverity::Hint => "Hint",
};
let mut ordered: Vec<&(DiagnosticSeverity, String)> = diags.iter().collect();
ordered.sort_by_key(|(s, _)| rank(s));
Some(
ordered
.iter()
.map(|(s, m)| format!("{}: {}", label(s), m))
.collect::<Vec<_>>()
.join("\n\n"),
)
}
/// Stack the diagnostic block above the language hover content, divided by a
/// rule, matching VS Code (PR microsoft/vscode#166560 put marker hovers on
/// top). Either side may be absent; `None` when both are.
fn compose_hover(diagnostic: Option<&str>, hover: Option<&str>) -> Option<String> {
match (diagnostic, hover) {
(Some(d), Some(h)) => Some(format!("{d}\n{HOVER_DIVIDER}\n{h}")),
(Some(d), None) => Some(d.to_string()),
(None, Some(h)) => Some(h.to_string()),
(None, None) => None,
}
}
#[cfg(test)]
mod tests;
/// Stdout wrapper that tallies every byte ratatui flushes through the
/// backend. The main loop reads + resets the counter once per frame to
/// Action verb parsed from a participant-action row id (`grant:3` etc.).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum ParticipantVerb {
Grant,
Revoke,
Kick,
}
/// One participant's parked caret in a multiplayer session: where they were
/// when someone else took over typing (docs/MULTIPLAYER.md).
#[derive(Clone, Debug, PartialEq, Eq)]
struct SessionCaret {
path: PathBuf,
row: usize,
col: usize,
}
/// How long a peer's caret keeps its name tag after it last moved (VS Code
/// Live Share shows the name while the cursor works, then collapses to the
/// bare colored cell).
const CARET_LABEL_FADE: std::time::Duration = std::time::Duration::from_secs(2);
/// The typing pause that arms a proactive navigator look: long enough that
/// mid-thought keystrokes never fire it, short enough to feel like a pair
/// partner glancing over (double the 1s auto-save delay).
const PROACTIVE_PAUSE: std::time::Duration = std::time::Duration::from_secs(2);
/// A collab peer's last-known caret: where it is, whose it is, and when it
/// last moved (the name tag shows while `last_moved` is inside
/// [`CARET_LABEL_FADE`]). Keyed by site id, which is per-file, so one peer
/// legitimately holds one entry per shared file.
struct CollabCaret {
file: String,
row: usize,
col: usize,
name: String,
last_moved: std::time::Instant,
}
/// A live AI stream announced over the relay (`CollabMsg::StreamState`):
/// who is streaming, into which file, and the pilot's site id in that file
/// (keys the pilot's ghost caret for the gutter stop button's row).
struct CollabStreamInfo {
file: String,
name: String,
site: u64,
}
/// The name this participant broadcasts on its carets: `CROFT_COLLAB_NAME`
/// when set, else the mux's user@host. Truncated here (and again at ingest
/// for remote names) so a tag can never paint a whole row.
fn collab_display_name() -> String {
std::env::var("CROFT_COLLAB_NAME")
.ok()
.filter(|s| !s.trim().is_empty())
.unwrap_or_else(crate::session_host::client_name)
.chars()
.take(24)
.collect()
}
/// The stable color a participant's ghost caret wears, from a small palette
/// keyed by their id (also the join order, so the first guest is always
/// green, the second magenta, and so on).
fn participant_color(id: u64) -> Color {
const PALETTE: [Color; 6] = [
Color::Rgb(0x8c, 0xc2, 0x65), // green
Color::Rgb(0xd6, 0x6b, 0xd0), // magenta
Color::Rgb(0x56, 0xb6, 0xc2), // cyan
Color::Rgb(0xe0, 0x9a, 0x4e), // amber
Color::Rgb(0x9a, 0x86, 0xfd), // purple
Color::Rgb(0xe0, 0x6c, 0x75), // red
];
PALETTE[(id % PALETTE.len() as u64) as usize]
}
/// The color a collab caret paints in: the seated navigator's carets wear
/// its fixed identity accent (the same orange as its comment boxes) so the
/// AI's presence is unmistakable; humans keep the join-order palette.
/// Identity is the seat's site ids, never its display name — names are
/// neither unique nor length-stable (truncated to 24 chars at ingest).
fn collab_caret_color(navigator_sites: &[u64], site: u64) -> Color {
if navigator_sites.contains(&site) {
crate::widgets::editor::NAVIGATOR_ACCENT
} else {
participant_color(site)
}
}
/// The workspace-relative key a file replicates under in a collab session
/// (docs/MULTIPLAYER.md, Phase D). None outside the workspace: only
/// workspace files are shared.
fn collab_file_key(root: &Path, path: &Path) -> Option<String> {
path.strip_prefix(root)
.ok()
.map(|p| p.to_string_lossy().into_owned())
}
/// Parse a participants action-picker row id back into (verb, participant).
fn parse_participant_action(id: &str) -> Option<(ParticipantVerb, u64)> {
let (verb, id) = id.split_once(':')?;
let id = id.parse().ok()?;
let verb = match verb {
"grant" => ParticipantVerb::Grant,
"revoke" => ParticipantVerb::Revoke,
"kick" => ParticipantVerb::Kick,
_ => return None,
};
Some((verb, id))
}
/// The roster row shown for one participant: name, window size, role.
fn participant_row(p: &crate::session_host::Participant) -> crate::widgets::list_picker::ListRow {
let role = if p.control { "write" } else { "read-only" };
let size = if p.cols > 0 && p.rows > 0 {
format!("{}\u{d7}{}", p.cols, p.rows)
} else {
String::from("size unknown")
};
crate::widgets::list_picker::ListRow {
id: p.id.to_string(),
label: format!("{} {} ({})", p.name, size, role),
}
}
/// surface the per-frame payload size in the F8 perf HUD.
struct CountingWriter {
inner: Stdout,
bytes: std::sync::Arc<std::sync::atomic::AtomicUsize>,
}
impl std::io::Write for CountingWriter {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
let n = self.inner.write(buf)?;
self.bytes
.fetch_add(n, std::sync::atomic::Ordering::Relaxed);
Ok(n)
}
fn flush(&mut self) -> std::io::Result<()> {
self.inner.flush()
}
}
type CroftTerminal = Terminal<CrosstermBackend<CountingWriter>>;
pub fn run(
root: PathBuf,
restore_session: Option<PathBuf>,
open_file: Option<PathBuf>,
zen: bool,
workspace_folders: Vec<PathBuf>,
) -> Result<()> {
// zoxide is a hard dependency of the Cmd+Z jump popup. Probe for it
// and install it in the background if missing, off the launch path so
// the first frame is never blocked. Runs on every host croft starts
// on — the local Mac and the remote Linux box both reach `run` — so
// the dependency is satisfied identically on both (GOLDEN RULE).
crate::zoxide::ensure_installed_in_background();
// Termux ships no font with codicon glyphs, so the activity-bar glyph
// fallback renders blank cells out of the box. Install the Meslo Nerd
// Font Mono into ~/.termux/font.ttf in the background (no-op on every
// other host, and when the user already has a font.ttf).
crate::termux::ensure_codicon_font_in_background();
// Build the tree-sitter highlight configurations on a background thread so
// the first file open paints its syntax (keywords, strings, comments)
// instantly without the per-tab query-compilation snap, yet the ~80ms of
// query compilation never blocks the cold-start path before the first
// frame. The configs land in a process-wide cache, so the UI thread reads
// the finished build straight out of it on first open (or builds on demand
// if the user opens a file before the prewarm finishes).
std::thread::spawn(crate::highlight::prewarm_configs);
let title = build_title(&root);
let mut app = App::new(root.clone())?;
// Resurrect this workspace's terminal panel from the last session
// (pane layout, cwds, names, focus) before the first frame paints.
app.restore_terminal_session();
// A launch from a .code-workspace file (#163) defines the folder set
// exactly; otherwise the automatic per-primary store restores.
if workspace_folders.is_empty() {
let restored_folders = app.restore_workspace_folders();
if restored_folders > 0 {
app.status = format!("Restored {restored_folders} workspace folder(s)");
}
} else {
for folder in workspace_folders {
app.add_workspace_folder(folder);
}
}
// Restore the tabs / layout carried across a self-update re-exec, then
// delete the handoff file so a later normal launch starts clean.
if let Some(session_path) = restore_session.as_ref() {
if let Ok(state) = crate::session_state::SessionState::load(session_path) {
app.apply_session_state(&state);
}
let _ = std::fs::remove_file(session_path);
}
// `--zen`: hide the Explorer sidebar and terminal so the editor fills the
// window. "Move/Copy into New Window" launches the new window this way so it
// opens focused on just the handed-off file. Toggle back with Cmd+B / Cmd+J.
if zen {
app.show_tree = false;
app.show_terminal = false;
}
// `croft <root> --open-file <path>`: open the handed-off file (used by the
// new window that Move / Copy into New Window spawns).
if let Some(file) = open_file.as_ref() {
app.open_file_at_launch(file);
}
app.start_update_watch_if_remote();
app.start_drift_probe_if_local();
app.start_update_check_if_local();
enable_raw_mode().context("enable raw mode")?;
// Sixel has no env var, so when neither iTerm2 nor Kitty was detected from
// the environment, probe the host with a DA1 query. This runs in raw mode
// but before the alt-screen switch and long before the event loop's first
// poll, so crossterm's (lazily-started) event reader can't swallow the
// reply. A non-sixel terminal (e.g. Apple Terminal) answers DA1 without
// attribute 4 and the probe returns instantly; init_graphics then promotes
// the protocol to Sixel only when this is true.
#[cfg(unix)]
if app.inline_protocol == crate::iterm2_inline::InlineImageProtocol::None {
app.sixel_supported = crate::iterm2_inline::probe_sixel_support();
}
let mut out = stdout();
// Alt screen + mouse + bracketed paste + SteadyBar cursor (thin vertical
// line, no hardware blink: the blink is done in software so it works even
// when the host terminal's own "Blinking cursor" preference is off). The
// shared takeover block keeps this list identical to the dtach-reattach
// re-assert; add new modes in takeover_mode_seq, not here.
{
use std::io::Write;
out.write_all(&takeover_mode_seq())
.and_then(|()| out.flush())
.context("enter alt screen")?;
}
// From here the tty is in raw mode + alt-screen + mouse + bracketed
// paste. The normal teardown below restores all of it, but a panic
// unwinds straight past it and would drop the user back to a shell
// with mouse-tracking still on (stray `^[[<35;…M` on every mouse
// move). Install a hook that restores the tty first, then chains to
// the original so the panic message + backtrace still print.
install_terminal_restore_panic_hook();
// Best-effort: terminals that don't speak the kitty keyboard protocol just
// ignore this; ones that do (iTerm2 >=3.5, Ghostty, kitty, WezTerm) start
// delivering Cmd/Super as a real modifier so cmd+s reaches the app.
let kbd_enhanced = execute!(
out,
PushKeyboardEnhancementFlags(keyboard_enhancement_flags())
)
.is_ok();
{
use std::io::Write;
out.write_all(&set_title_seq(&title)).ok();
// Force iTerm2's session bg to sRGB(EDITOR_BG_RGB). Combined with
// `Color::Reset` on welcome-pane cells and the same sRGB hex baked
// into the OSC-1337 PNG canvas, both surfaces flow through iTerm2's
// sRGB → display path and the welcome image bg matches the
// surrounding pane bg pixel-for-pixel
// (https://gitlab.com/gnachman/iterm2/-/issues/12529).
let theme = crate::prefs::Prefs::load_or_default().theme();
out.write_all(host_colors_seq(theme).as_bytes()).ok();
if crate::iterm2_inline::detect_iterm2_inline_support() {
out.write_all(set_session_bg_srgb_seq(theme.editor_bg_rgb()).as_bytes())
.ok();
}
out.flush().ok();
}
// Env-var-only iTerm2 detection: no stdin queries, so this can't
// contend with the crossterm event reader.
app.init_graphics();
// With the inline-image protocol fully resolved (env detection + the sixel
// DA1 probe above), decide whether to nudge the user toward a terminal that
// can render croft's icons and images. Runs identically on the local Mac
// and the remote Linux box (GOLDEN RULE): both reach `run`, and `croft
// remote` forwards the local terminal's identity so an SSH session from
// iTerm2/Ghostty is never falsely warned.
app.arm_terminal_warning();
// Wrap stdout so we can count exactly how many bytes ratatui's diff
// ships per frame — over SSH that byte count, alongside the per-frame
// render time, is the signal that tells a fat repaint from a slow
// remote CPU. Toggled on screen with F8.
let perf_bytes = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
app.perf.attach_counter(perf_bytes.clone());
let backend = CrosstermBackend::new(CountingWriter {
inner: out,
bytes: perf_bytes,
});
let mut terminal: CroftTerminal = Terminal::new(backend).context("create terminal")?;
let result = main_loop(&mut app, &mut terminal);
// Snapshot the terminal panel for the next launch (cwds are read live
// here, so plain `cd`s during the session are captured at quit).
app.save_terminal_session();
disable_raw_mode().ok();
{
use std::io::Write;
let mut out = stdout();
out.write_all(&set_title_seq("")).ok();
// Revert the host terminal's default colors (OSC 110/111, plus the
// iTerm2 sRGB override where present) so the user's shell after
// croft exits doesn't keep our forced theme colours.
out.write_all(reset_host_colors_seq().as_bytes()).ok();
if crate::iterm2_inline::detect_iterm2_inline_support() {
out.write_all(reset_session_bg_seq().as_bytes()).ok();
}
out.flush().ok();
}
if kbd_enhanced {
execute!(terminal.backend_mut(), PopKeyboardEnhancementFlags).ok();
}
execute!(
terminal.backend_mut(),
crossterm::cursor::SetCursorStyle::DefaultUserShape,
LeaveAlternateScreen,
DisableMouseCapture,
DisableBracketedPaste,
)
.ok();
terminal.show_cursor().ok();
// Reap the navigator's claude child before any exit: drop-to-local
// (process::exit) and self-update (exec) below both bypass Drop, and even
// a normal return races the detached Drop thread against process exit.
// shutdown_blocking reverts, hangs up, and grace-kills synchronously.
if let Some(host) = app.pair_host.take() {
host.shutdown_blocking();
}
// And every teardown a recent unseat DETACHED (toggle off, record
// disabled, pilot death): those threads race process exit, and a thread
// that dies mid-grace-kill leaves the claude child running.
crate::pair_host::join_teardowns();
result?;
if app.drop_to_local {
std::process::exit(crate::remote::DROP_TO_LOCAL_EXIT_CODE);
}
// A background self-update landed: serialize the session and replace
// this process image with the freshly-installed binary. The unix
// process-image swap keeps the same controlling tty (the ssh PTY), so
// there is no reconnect - the user sees a redraw, not a dropped
// session. No shell is involved; args are passed as an argv vector.
if app.pending_reexec {
let state = app.capture_session_state();
let session_path = crate::session_state::handoff_path();
let _ = state.save(&session_path);
use std::os::unix::process::CommandExt;
// A staged release (#333) is swapped over the installed binary
// only now, on the user's Relaunch: until this line PATH still
// held the old version.
let target = reexec_binary_path(app.self_install.as_ref());
if let Some(staged) = app.staged_update_binary()
&& let Err(err) = crate::update_check::apply_staged(&staged, &target)
{
// The installed binary is untouched (copy-beside + rename), so
// relaunching it is still right: the editor must never simply
// exit because an update could not be applied.
eprintln!(
"croft update failed: could not replace {} with {}: {err} - relaunching the current version",
target.display(),
staged.display()
);
}
let mut cmd = std::process::Command::new(target);
cmd.arg(app.workspace_root())
.arg("--restore-session")
.arg(&session_path);
let err = CommandExt::exec(&mut cmd);
eprintln!("croft self-relaunch failed: {err}");
return Ok(());
}
if let Some(remote) = app.remote_launch.take() {
app.fs_watch.disable();
let launch_result = if let Some(adopted) = remote.adopted {
crate::remote::launch_only(adopted, remote.path.as_deref())
} else {
crate::remote::launch_croft_with(&remote.host, remote.path.as_deref(), None, false)
};
restore_host_terminal_state();
match launch_result? {
crate::remote::RemoteOutcome::ReturnToLocal => {
return run(root, None, None, false, Vec::new());
}
crate::remote::RemoteOutcome::Exited => return Ok(()),
}
}
Ok(())
}
/// Re-send the terminal-restore escape sequences after a remote ssh
/// session ends. The remote croft enables alt-screen, mouse tracking,
/// and bracketed paste on the local tty; if it crashed or exited
/// abnormally those modes can leak back into the user's shell. Re-
/// emitting the disable sequences here ensures the host shell is
/// always returned to a clean state.
fn restore_host_terminal_state() {
use std::io::Write;
let mut out = stdout();
let _ = out.write_all(TERMINAL_RESTORE_SEQ);
let _ = out.flush();
}
// Disable every mouse-tracking mode crossterm knows about (1000/1002/1003
// normal+button+any-motion, 1015/1006 urxvt+SGR encodings), bracketed
// paste (2004), exit any leftover alt-screen (1049l), reset the cursor
// style, and reset the host's default fg/bg (OSC 110/111, undoing the
// theme's dynamic colors). Written as raw bytes because the callers that
// need it (the panic hook, the post-remote-ssh restore) no longer hold a
// crossterm Backend handle for `execute!`. Both callers are done with the
// tty (a return from remote re-enters `run`, which re-applies the theme's
// host colors), so the color reset can't strand a live session.
const TERMINAL_RESTORE_SEQ: &[u8] =
b"\x1b[?1000l\x1b[?1002l\x1b[?1003l\x1b[?1006l\x1b[?1015l\x1b[?2004l\x1b[?1049l\x1b[ q\x1b]110\x07\x1b]111\x07";
fn install_terminal_restore_panic_hook() {
static HOOK: std::sync::Once = std::sync::Once::new();
HOOK.call_once(|| {
let original = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
use std::io::Write;
// Persist the panic BEFORE touching the terminal: the TUI teardown
// can garble or scroll away the message printed to stderr, so a file
// is the only reliable record (read with `cat ~/.cache/croft/panic.log`).
log_panic_to_file(info);
let _ = disable_raw_mode();
let mut out = stdout();
let _ = out.write_all(TERMINAL_RESTORE_SEQ);
let _ = out.write_all(b"\x1b[?25h");
let _ = out.flush();
original(info);
}));
});
}
/// Append a panic record (version, thread, location, message, backtrace) to
/// `~/.cache/croft/panic.log`. Best-effort and silent on any I/O failure.
fn log_panic_to_file(info: &std::panic::PanicHookInfo<'_>) {
use std::io::Write;
let Some(home) = std::env::var_os("HOME") else {
return;
};
let dir = std::path::PathBuf::from(home).join(".cache").join("croft");
let _ = std::fs::create_dir_all(&dir);
let Ok(mut f) = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(dir.join("panic.log"))
else {
return;
};
let payload = info.payload();
let message = payload
.downcast_ref::<&str>()
.map(|s| s.to_string())
.or_else(|| payload.downcast_ref::<String>().cloned())
.unwrap_or_else(|| String::from("<non-string panic payload>"));
let location = info
.location()
.map(|l| format!("{}:{}:{}", l.file(), l.line(), l.column()))
.unwrap_or_else(|| String::from("<unknown>"));
let thread = std::thread::current()
.name()
.unwrap_or("<unnamed>")
.to_string();
let backtrace = std::backtrace::Backtrace::force_capture();
let _ = writeln!(
f,
"=== croft {} panicked ===\nthread: {thread}\nlocation: {location}\nmessage: {message}\nbacktrace:\n{backtrace}\n",
env!("CARGO_PKG_VERSION"),
);
}
/// Suspend the alt-screen, run every queued scp upload with the host
/// shell's stdin / stdout / stderr inherited (so the user sees scp's
/// progress and can answer any prompt it raises), then prompt for Enter
/// and restore the alt-screen. The local source is removed only on a
/// successful upload — if scp fails, the local copy stays put so the
/// user can retry without losing data.
fn run_pending_scp_uploads(app: &mut App, terminal: &mut CroftTerminal) -> Result<()> {
use std::io::Write;
let uploads = app.take_pending_scp_uploads();
if uploads.is_empty() {
return Ok(());
}
// Tear down the TUI surface so scp can use the real terminal.
disable_raw_mode().ok();
execute!(
terminal.backend_mut(),
LeaveAlternateScreen,
DisableMouseCapture,
DisableBracketedPaste,
crossterm::cursor::SetCursorStyle::DefaultUserShape,
)
.ok();
terminal.show_cursor().ok();
let total = uploads.len();
let mut moved = 0usize;
let mut error_count = 0usize;
let mut affected_dirs: Vec<PathBuf> = Vec::new();
{
let mut out = stdout();
let _ = writeln!(out);
let _ = writeln!(out, "── croft: uploading {total} item(s) via scp ──");
let _ = writeln!(
out,
"(scp prompts for password / passphrase / host-key will appear below)"
);
let _ = writeln!(out);
let _ = out.flush();
}
for (i, upload) in uploads.iter().enumerate() {
if let Some(parent) = upload.src.parent() {
affected_dirs.push(parent.to_path_buf());
}
{
let mut out = stdout();
let _ = writeln!(
out,
"[{}/{}] scp -r {} {}:",
i + 1,
total,
upload.src.display(),
upload.alias,
);
let _ = out.flush();
}
if !upload.src.exists() {
eprintln!(" ! source no longer exists, skipping");
error_count += 1;
continue;
}
let dest = format!("{}:", upload.alias);
let status = std::process::Command::new("scp")
.arg("-r")
.arg(&upload.src)
.arg(&dest)
.status();
match status {
Ok(s) if s.success() => {
moved += 1;
}
Ok(s) => {
eprintln!(" ! scp exited with {s}; local source preserved");
error_count += 1;
}
Err(e) => {
eprintln!(" ! could not spawn scp: {e}");
error_count += 1;
}
}
}
{
let mut out = stdout();
let _ = writeln!(out);
let _ = writeln!(
out,
"── done: {moved}/{total} uploaded, {error_count} error(s) ──"
);
let _ = write!(out, "Press Enter to return to croft ");
let _ = out.flush();
}
let mut line = String::new();
let _ = std::io::stdin().read_line(&mut line);
// Restore the TUI via the shared takeover block (same modes as startup
// and the dtach-reattach re-assert).
enable_raw_mode().ok();
{
use std::io::Write;
let out = terminal.backend_mut();
let _ = out.write_all(&takeover_mode_seq());
let _ = out.flush();
}
terminal.clear().ok();
app.overlays.activity.mark_dirty();
app.overlays.welcome.mark_dirty();
app.report_scp_results(moved, total, error_count, &affected_dirs);
Ok(())
}
/// Consume every overlay's one-shot image-clear latch; true when any fired.
/// Shared by the pre-draw and post-draw eviction checks in [`main_loop`].
fn consume_any_image_clear(app: &mut App) -> bool {
let fired = [
app.consume_welcome_image_clear(),
app.consume_editor_image_clear(),
app.consume_terminal_image_clear(),
app.consume_markdown_image_clear(),
app.consume_run_debug_image_clear(),
app.consume_problems_badge_image_clear(),
app.consume_no_repo_hero_image_clear(),
app.consume_shortcuts_image_clear(),
app.consume_file_finder_image_clear(),
app.consume_command_palette_image_clear(),
app.consume_process_picker_image_clear(),
app.consume_zoxide_jump_image_clear(),
app.consume_branch_picker_image_clear(),
app.consume_input_prompt_image_clear(),
app.consume_list_picker_image_clear(),
app.consume_ssh_empty_state_image_clear(),
app.consume_minimap_image_clear(),
app.consume_activity_image_clear(),
];
fired.into_iter().any(|f| f)
}
fn main_loop(app: &mut App, terminal: &mut CroftTerminal) -> Result<()> {
// Force the very first frame to render so the user sees the UI even
// before the first event arrives or any timer fires.
let mut needs_redraw = true;
let mut last_blink_visible = app.cursor_visible_phase();
// Advances every UPDATE_SPINNER_FRAME_MS while a background update runs;
// forces a status-bar redraw so the spinner animates. Constant otherwise.
let mut last_spinner_phase = app.update_spinner_phase();
// Frame-rate accounting for the F8 HUD: count draws over a rolling 1s
// window so a high idle FPS (always-dirty redraw loop saturating the
// SSH link) is visible at a glance.
let mut fps_window_start = std::time::Instant::now();
let mut frames_in_window: u32 = 0;
let mut keys_in_window: u32 = 0;
let mut iters_in_window: u32 = 0;
let mut work_max_us: u128 = 0;
let mut poll_max_us: u128 = 0;
// PTY-only redraws are capped so a chatty embedded shell (Claude Code,
// npm install, log streams) cannot saturate stdout and starve mouse /
// key events on the same thread. Input + FS + search + git + remote
// signals always bypass the cap, so clicks and keystrokes stay at 0ms.
// Over SSH the user's link is the bottleneck, so we drop further to
// ~20 Hz; locally ~30 Hz is plenty for shell text.
let pty_min_interval = if is_remote_session() {
Duration::from_millis(50)
} else {
Duration::from_millis(33)
};
// A keystroke echo, a shell line-rewrite, or an input-box update
// advances only a handful of bytes into the grid; a bulk stream (cat,
// build logs, a full-pane scroll, a TUI's streaming output) advances
// many. We let small updates redraw immediately so echo feels native
// even when croft itself is the remote end of an SSH link, and keep
// the cap on large updates so a flood can't saturate the pipe and
// starve input. A full-pane repaint runs tens of KB; interactive
// echo stays well under this, so the two never alias.
const PTY_SMALL_UPDATE_BYTES: usize = 4096;
let mut last_pty_redraw = std::time::Instant::now()
.checked_sub(pty_min_interval)
.unwrap_or_else(std::time::Instant::now);
while !app.quit {
iters_in_window += 1;
if fps_window_start.elapsed() >= Duration::from_secs(1) {
app.perf.record_window(
frames_in_window,
keys_in_window,
iters_in_window,
work_max_us,
poll_max_us,
);
frames_in_window = 0;
keys_in_window = 0;
iters_in_window = 0;
work_max_us = 0;
poll_max_us = 0;
fps_window_start = std::time::Instant::now();
}
let iter_start = std::time::Instant::now();
// If the user dropped files onto the Remote Explorer, suspend the
// alt-screen and run scp in the host shell so the user sees its
// progress, can answer password / FIDO / known_hosts prompts,
// and gets explicit success / failure output before we resume.
if !app.pending_scp_uploads.is_empty() {
run_pending_scp_uploads(app, terminal)?;
needs_redraw = true;
}
// Pull in any filesystem-watcher events first so the tree reflects
// disk reality on the very next frame.
let fs_changed = app.drain_fs_events();
// Peek without clearing so we can coalesce PTY-only redraws without
// losing bytes that the reader thread has already advanced into the
// terminal grid.
let pty_pending = app.peek_terminals_dirty();
let blink_visible = app.cursor_visible_phase();
let blink_changed = blink_visible != last_blink_visible;
// Either spinner advancing must wake a redraw; both stay 0 when idle.
let spinner_phase =
app.update_spinner_phase() + app.mcp_spinner_phase() + app.problems_fix_spinner_phase();
let spinner_changed = spinner_phase != last_spinner_phase;
let ext_index_changed = app.drain_ext_index_refresh();
let search_changed = app.drain_search_results();
let log_index_changed = app.poll_log_index();
let remote_changed = app.refresh_remote_if_config_changed();
let pulls_changed = app.drain_remote_pulls();
let view_changed = app.drain_view_requests();
let ports_changed = app.drain_ports_and_poll();
let session_presence_changed = app.poll_session_presence();
let session_typing_changed = app.poll_session_typing();
let collab_changed = app.poll_collab();
let bells_changed = app.drain_terminal_bells();
// A block whose command has finished gets its output box (#354).
let captures_changed = app.settle_block_captures();
// Every tick, not only when a capture settles: this is what notices
// the editor has moved to another document (#354 review).
app.publish_block_outputs();
let labels_changed =
app.refresh_terminal_labels() | app.drain_agent_events() | app.drain_fleet_results();
app.flush_terminal_session();
let auto_save_changed = app.tick_auto_save();
let connect_changed = app.poll_connect_dialog();
let install_changed = app.poll_install_session();
let update_changed = app.poll_update_watch();
let http_changed = app.drain_http_responses();
let reveal_changed = app.tick_redaction_reveal();
app.sync_lsp();
app.sync_git_gutters();
app.sync_blame();
app.sync_provenance();
let blame_changed = app.drain_blame();
// Request/refresh the OUTLINE for the active file (after sync_lsp so the
// edit-seq it reads is current) and advance follow-cursor.
let outline_sync_changed = app.sync_outline();
let outline_changed = app.drain_lsp_document_symbols();
app.workspace_symbols_dispatch_due();
let ws_symbols_changed = app.drain_lsp_workspace_symbols();
// Refresh the Explorer's other stacked sub-views (Open Editors list,
// Timeline git history, Dependencies) and drain their workers.
let explorer_panels_changed = app.sync_explorer_panels();
app.refresh_semantic_tokens_if_requested();
app.refresh_inlay_hints_if_requested();
app.refresh_workspace_diagnostics_if_requested();
let lsp_changed = app.drain_lsp_completion();
app.refresh_signature_help_if_moved();
let sig_help_changed = app.drain_lsp_signature_help();
app.poll_hover();
let hover_changed = app.drain_lsp_hover();
let tab_hover_changed = app.poll_tab_hover();
let ui_tooltip_changed = app.poll_ui_tooltip();
let definition_changed = app.drain_lsp_definition();
let declaration_changed = app.drain_lsp_declaration();
let type_definition_changed = app.drain_lsp_type_definition();
let implementation_changed = app.drain_lsp_implementation();
let references_changed = app.drain_lsp_references();
let call_hierarchy_changed = app.drain_lsp_call_hierarchy();
let sidebar_hide_changed = app.tick_sidebar_auto_hide();
let occ_tick_changed = app.tick_occurrences();
let linked_tick_changed = app.tick_linked_editing();
let linked_changed = app.drain_lsp_linked_editing();
app.tick_on_type_formatting();
let on_type_changed = app.drain_lsp_on_type_format();
let prepare_rename_changed = app.drain_lsp_prepare_rename();
let occurrences_changed = app.drain_lsp_document_highlights();
let rename_changed = app.drain_lsp_rename();
let format_changed = app.drain_lsp_format();
let code_action_changed = app.drain_lsp_code_actions();
let semantic_changed = app.drain_lsp_semantic_tokens();
let inlay_changed = app.drain_lsp_inlay_hints();
app.drain_lsp_document_links();
let folds_changed = app.drain_lsp_folding_ranges();
let selection_ranges_changed = app.drain_lsp_selection_ranges();
let colors_changed = app.drain_lsp_document_colors();
let color_pres_changed = app.drain_lsp_color_presentations();
let diagnostics_changed = app.drain_lsp_diagnostics();
let progress_changed = app.drain_lsp_progress();
let dap_changed = app.poll_dap();
let tests_changed =
app.test_worker.drain(&mut app.testing) | app.drain_pending_test_debug();
// A queued run the worker refused (runner disabled after the entry
// check) rolled its cases back in the drain; say why nothing ran.
if app.testing.take_refusal() {
app.status = String::from(crate::testing::NO_RUNNER_STATUS);
}
// One notification per red run (#358), from the latch the panel
// sets when a run ends, never per test case.
if app.testing.take_failed_run() {
let (passed, failed, _) = app.testing.counts();
app.notifier.emit(
crate::notifications::Event::TestsFailed {
failed,
passed,
reported: app.testing.run_reported_failed(),
},
app.roots.primary(),
&remote_host_label(),
);
}
let mcp_changed = app.poll_mcp();
let pair_changed =
app.maybe_seat_navigator() | app.poll_pair() | app.tick_proactive_navigator();
let voice_changed = app.drain_voice();
// Surface managed language-server install progress in the status bar so
// the background work (which can take a few seconds) is visible.
let install_status_changed = match crate::lsp::install::take_status() {
Some(msg) => {
app.status = msg;
true
}
None => false,
};
// When a managed install finishes, forget the LSP sync state for the
// docs that language serves so the next `sync_lsp` re-opens them. That
// re-open makes the manager re-probe and spawn the just-installed
// server, so "installed" becomes "working" without a further action.
let just_installed = crate::lsp::install::take_just_installed();
if !just_installed.is_empty() {
app.lsp_last_seen
.retain(|path, _| !just_installed_covers_path(&just_installed, path));
}
let non_pty_dirty = needs_redraw
|| fs_changed
|| mcp_changed
|| pair_changed
|| tests_changed
|| blink_changed
|| spinner_changed
|| ext_index_changed
|| search_changed
|| log_index_changed
|| remote_changed
|| pulls_changed
|| view_changed
|| ports_changed
|| session_presence_changed
|| session_typing_changed
|| collab_changed
|| bells_changed
|| captures_changed
|| labels_changed
|| auto_save_changed
|| ws_symbols_changed
|| connect_changed
|| install_changed
|| update_changed
|| http_changed
|| reveal_changed
|| lsp_changed
|| sig_help_changed
|| hover_changed
|| tab_hover_changed
|| ui_tooltip_changed
|| definition_changed
|| declaration_changed
|| type_definition_changed
|| implementation_changed
|| references_changed
|| call_hierarchy_changed
|| sidebar_hide_changed
|| occ_tick_changed
|| linked_tick_changed
|| linked_changed
|| on_type_changed
|| prepare_rename_changed
|| occurrences_changed
|| rename_changed
|| format_changed
|| code_action_changed
|| semantic_changed
|| inlay_changed
|| folds_changed
|| selection_ranges_changed
|| colors_changed
|| color_pres_changed
|| diagnostics_changed
|| progress_changed
|| voice_changed
|| outline_sync_changed
|| outline_changed
|| explorer_panels_changed
|| install_status_changed
|| blame_changed
|| dap_changed;
let pty_eligible = pty_pending
&& (app.peek_terminals_pending_bytes() <= PTY_SMALL_UPDATE_BYTES
|| last_pty_redraw.elapsed() >= pty_min_interval);
let do_redraw = non_pty_dirty || pty_eligible;
// Consume the PTY dirty flags only when we are actually redrawing.
// Skipping a frame must leave them set so the next eligible tick
// emits the deferred output.
let pty_changed = if do_redraw {
app.drain_terminals_dirty()
} else {
false
};
if do_redraw {
if pty_changed {
last_pty_redraw = std::time::Instant::now();
}
// If the welcome OSC-1337 image was painted earlier and the
// user has just opened a file, wipe the screen so iTerm drops
// its cached image cells AND ratatui repaints every cell on
// the next draw (its diff alone misses cells whose content
// didn't change between welcome and editor buffers).
// A resize/WINCH is not image eviction: it invalidated the text on
// screen (dtach reattach repaints into a blank terminal), so it
// wipes unconditionally, Kitty included. It never fires while the
// user merely types, so the blink fix below is untouched.
let resize_repaint = app.consume_resize_repaint();
if consume_any_image_clear(app) || resize_repaint {
// iTerm2/sixel image cells live in the normal cell buffer, so
// evicting them takes a full `2J` + repaint. Kitty images are
// deleted on their own layer below - wiping the text there
// blanks the whole app for an SSH round trip per latch (the
// every-keystroke blink), so Kitty skips the screen clear.
if resize_repaint || app.image_eviction_needs_screen_wipe() {
terminal.clear()?;
}
app.evict_inline_images_on_clear();
// Activity-bar icons live outside ratatui too; re-emit
// them on the next post-draw flush. The welcome wordmark
// and the source-control hero also live in iTerm's image
// cache that just got wiped - re-arm them so the next
// render re-emits whichever one is currently visible.
app.overlays.activity.mark_dirty();
app.overlays.welcome.mark_dirty();
app.overlays.hero.mark_dirty();
}
let draw_start = std::time::Instant::now();
terminal.draw(|f| {
app.render(f);
})?;
// Record render+flush time and the bytes ratatui shipped this
// frame so the F8 HUD can show where remote latency goes.
app.perf.record_draw(draw_start.elapsed().as_micros());
frames_in_window += 1;
if consume_any_image_clear(app) {
if app.image_eviction_needs_screen_wipe() {
terminal.clear()?;
}
app.evict_inline_images_on_clear();
app.overlays.activity.mark_dirty();
app.overlays.welcome.mark_dirty();
app.overlays.hero.mark_dirty();
terminal.draw(|f| {
app.render(f);
})?;
}
// After ratatui flushes its diff, paint the activity-bar icons
// directly via OSC-1337 on every redraw. We previously gated
// this on a `dirty` flag and only re-emitted on resize / view
// change, but the icons would intermittently vanish: iTerm2
// can drop cached OSC-1337 image cells under heavy SGR traffic
// on adjacent cells (cursor-blink redraws, search updates,
// mouse motion bursts) and the dirty gate had no way to detect
// that. Since `render_activity_bar` writes nothing to the
// buffer in image-mode, ratatui's diff produces zero per-cell
// writes here — re-emitting the pre-encoded OSC bytes every
// frame is cheap and locks the images in.
app.flush_activity_image_overlays();
// Active editor image preview: bake-once-emit-each-frame
// overlay, just like the welcome wordmark. Sent after ratatui
// has finished its diff so the image bytes land on cells
// ratatui won't repaint until layout changes again. One slot
// per editor split column (0 = left, 1 = right); when not
// split only slot 0 ever has a payload.
for side in 0..2 {
if let Some((osc, layout)) = app.editor_image_payload(side)
&& app.overlay_fits_on_screen(
layout.cell_x,
layout.cell_y,
layout.cell_w,
layout.cell_h,
)
{
use std::io::Write;
let mut out = stdout();
let cursor_on = app.cursor_should_be_visible();
let _ = write!(out, "\x1b[?25l\x1b[s");
let _ = write!(out, "\x1b[{};{}H", layout.cell_y + 1, layout.cell_x + 1);
let _ = out.write_all(osc.as_bytes());
let _ = write!(out, "\x1b[u");
if cursor_on {
let _ = write!(out, "\x1b[?25h");
}
let _ = out.flush();
app.mark_editor_image_displayed(side);
}
}
// Terminal-pane inline image (captured imgcat output): same
// bake-once / emit-each-frame overlay, anchored to its grid row.
if let Some((osc, layout)) = app.terminal_image_payload()
&& app.overlay_fits_on_screen(
layout.cell_x,
layout.cell_y,
layout.cell_w,
layout.cell_h,
)
{
use std::io::Write;
let mut out = stdout();
let cursor_on = app.cursor_should_be_visible();
let _ = write!(out, "\x1b[?25l\x1b[s");
let _ = write!(out, "\x1b[{};{}H", layout.cell_y + 1, layout.cell_x + 1);
let _ = out.write_all(osc.as_bytes());
let _ = write!(out, "\x1b[u");
if cursor_on {
let _ = write!(out, "\x1b[?25h");
}
let _ = out.flush();
app.mark_terminal_image_displayed();
}
// Markdown-preview inline image (#176): same bake-once /
// emit-each-frame overlay, anchored at its reserved rows.
if let Some((osc, layout)) = app.markdown_image_payload()
&& app.overlay_fits_on_screen(
layout.cell_x,
layout.cell_y,
layout.cell_w,
layout.cell_h,
)
{
use std::io::Write;
let mut out = stdout();
let cursor_on = app.cursor_should_be_visible();
let _ = write!(out, "\x1b[?25l\x1b[s");
let _ = write!(out, "\x1b[{};{}H", layout.cell_y + 1, layout.cell_x + 1);
let _ = out.write_all(osc.as_bytes());
let _ = write!(out, "\x1b[u");
if cursor_on {
let _ = write!(out, "\x1b[?25h");
}
let _ = out.flush();
app.mark_markdown_image_displayed();
}
// Editor minimap: same bake-once / emit-each-frame overlay, painted
// after ratatui's diff so the raster lands on the strip cells.
if let Some((osc, layout)) = app.minimap_image_payload()
&& app.overlay_fits_on_screen(
layout.cell_x,
layout.cell_y,
layout.cell_w,
layout.cell_h,
)
{
use std::io::Write;
let mut out = stdout();
let cursor_on = app.cursor_should_be_visible();
let _ = write!(out, "\x1b[?25l\x1b[s");
let _ = write!(out, "\x1b[{};{}H", layout.cell_y + 1, layout.cell_x + 1);
let _ = out.write_all(osc.as_bytes());
let _ = write!(out, "\x1b[u");
if cursor_on {
let _ = write!(out, "\x1b[?25h");
}
let _ = out.flush();
app.mark_minimap_image_displayed();
}
// Run-and-Debug headline icon: same re-emit-every-frame trick.
// Only fires while the sidebar is on the Run-Debug view and the
// panel reserved a cell for the icon on its last render. On
// view change the `consume_run_debug_image_clear` gate above
// already armed `terminal.clear()`, evicting the cached
// image cells before the next sidebar paints.
app.flush_run_debug_icon_overlay();
app.flush_problems_badge_overlay();
app.flush_no_repo_hero_overlay();
app.flush_ssh_empty_state_overlay();
// Welcome-screen logo: same OSC-1337 trick, gated by its own
// dirty flag and only emitted while the editor pane is in its
// blank initial state.
if let Some((img, layout)) = app.welcome_image_emit_payload()
&& app.overlay_fits_on_screen(
layout.cell_x,
layout.cell_y,
layout.cell_w,
layout.cell_h,
)
{
use std::io::Write;
let mut out = stdout();
let cursor_on = app.cursor_should_be_visible();
let _ = write!(out, "\x1b[?25l\x1b[s");
let _ = write!(out, "\x1b[{};{}H", layout.cell_y + 1, layout.cell_x + 1);
let _ = out.write_all(img.as_bytes());
let _ = write!(out, "\x1b[u");
if cursor_on {
let _ = write!(out, "\x1b[?25h");
}
let _ = out.flush();
app.mark_welcome_image_emitted();
}
// Last of all: re-paint the chrome tooltip on top of any sidebar
// illustration it overlaps. Must run after every inline-image flush
// above so the box wins those cells (last writer per cell wins).
app.flush_tooltip_over_image();
needs_redraw = false;
last_blink_visible = blink_visible;
last_spinner_phase = spinner_phase;
}
// 8 ms (~125 Hz) keeps echo lag tight when the embedded pty is the
// hot path (remote-launched croft over SSH). Idle cost is still
// negligible because the redraw branch above gates on dirty flags;
// this poll just decides how often we wake up to *check*.
work_max_us = work_max_us.max(iter_start.elapsed().as_micros());
let poll_start = std::time::Instant::now();
if event::poll(Duration::from_millis(8))? {
// Drain every event already queued so a click burst (Down + zero-
// movement Drag + Up, all delivered in <50ms by the terminal)
// coalesces into a single redraw. Otherwise each event triggers
// its own terminal.draw cycle, which Hides+Shows the hardware
// caret each time and the user sees the cursor blink twice
// rapidly before settling into the normal 530ms blink.
loop {
match event::read()? {
Event::Key(key) => {
if key.kind == KeyEventKind::Press || key.kind == KeyEventKind::Repeat {
keys_in_window += 1;
}
app.handle_key(key)?;
}
Event::Mouse(m) => app.handle_mouse(m),
Event::Paste(s) => app.handle_paste(&s),
Event::Resize(_, _) => {
// Alt-screen reflow blanks the activity bar's SGR cells
// but iTerm2's OSC-1337 image layer survives, so a plain
// re-emit ghosts a fresh icon over the stale one. Re-mark
// dirty AND arm a one-shot terminal.clear() to evict it.
app.on_resize();
// Under dtach a reattach arrives as a bare WINCH into a
// terminal that never saw the startup DECSETs: without
// this re-assert the mouse (and bracketed paste, kitty
// keyboard flags, alt screen) stays dead until the next
// F9 reload happens to re-exec croft.
if std::env::var_os("CROFT_SESSION_PERSISTENT").is_some() {
use std::io::Write;
let out = terminal.backend_mut();
let _ = out.write_all(&mode_reassert_seq());
let _ = out.flush();
}
}
_ => {}
}
if !event::poll(Duration::ZERO)? {
break;
}
}
needs_redraw = true;
}
poll_max_us = poll_max_us.max(poll_start.elapsed().as_micros());
// Drive edge auto-scroll for an in-progress terminal drag-selection
// even when the pointer is held still (no fresh events): the poll
// above wakes us every 8 ms, and this advances the selection while
// the pointer stays pinned past the pane edge.
if app.tick_terminal_autoscroll() {
needs_redraw = true;
}
}
Ok(())
}