use anyhow::{Context, Result};
use crossterm::{
event::{
self, DisableBracketedPaste, DisableFocusChange, DisableMouseCapture, EnableBracketedPaste,
EnableFocusChange, 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 memory_report;
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::lsp::manager::{diagnostics_by_source, diagnostics_source, diagnostics_store_key};
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,
/// CodeQL (#578): databases, queries, query history, AST viewer.
CodeQL,
}
/// 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,
AgentLane,
}
impl ExplorerView {
/// Every view, in stacking order — the order the ⋯ menu lists them.
pub const ALL: [ExplorerView; 6] = [
ExplorerView::OpenEditors,
ExplorerView::Folders,
ExplorerView::Outline,
ExplorerView::Timeline,
ExplorerView::Dependencies,
ExplorerView::AgentLane,
];
/// 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",
ExplorerView::AgentLane => "Agent Lane",
}
}
}
/// 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,
ExplorerView::AgentLane => self.flags.agent_lane,
}
}
/// 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,
ExplorerView::AgentLane => &mut self.flags.agent_lane,
};
*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,
CodeQL,
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;
/// Finished history-scrubber views kept for stepping back to (#371): a
/// few either side of the cursor. Each holds a whole file with its
/// highlighting, so this stays small.
const SCRUB_VIEWS_KEPT: usize = 8;
/// Outlines of built history views kept while scrubbing (#371); cleared
/// wholesale past this, and rebuilt with each view the builder lands.
const SCRUB_OUTLINES_KEPT: usize = 256;
/// 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);
/// Why Help: Update croft must not check for a release itself (#1844),
/// for the same reasons the startup check stays off: a remote-launched
/// croft is updated by the croft that launched it, and
/// `CROFT_NO_UPDATE_CHECK` turns checking off altogether.
fn manual_update_check_refusal(remote: bool, disabled: bool) -> Option<&'static str> {
if remote {
Some("No croft update is waiting: this croft is updated by the croft that launched it")
} else if disabled {
Some("No croft update is waiting, and update checks are off (CROFT_NO_UPDATE_CHECK)")
} else {
None
}
}
/// One cell's size in pixels, from a window size report of `cols` x `rows`
/// cells over `width` x `height` pixels; `None` when the terminal reports
/// no pixel size.
fn cell_pixel_of(cols: u16, rows: u16, width: u16, height: u16) -> Option<(u32, u32)> {
(cols > 0 && rows > 0 && width > 0 && height > 0)
.then(|| ((width / cols).max(1) as u32, (height / rows).max(1) as u32))
}
/// 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,
}
impl PanelAlignment {
/// Every alignment with its picker id and label, in the Customize
/// Layout popup's order (View: Set Panel Alignment…, #852).
const OPTIONS: [(PanelAlignment, &'static str, &'static str); 4] = [
(PanelAlignment::Left, "left", "Left"),
(PanelAlignment::Center, "center", "Center"),
(PanelAlignment::Right, "right", "Right"),
(PanelAlignment::Justify, "justify", "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,
}
impl QuickInputPosition {
/// Both positions with their picker id and label, in the Customize
/// Layout popup's order (View: Set Quick Input Position…, #852).
const OPTIONS: [(QuickInputPosition, &'static str, &'static str); 2] = [
(QuickInputPosition::Top, "top", "Top"),
(QuickInputPosition::Center, "center", "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>,
}
/// The editor rect for Centered Layout (#1585): `width` columns in the
/// middle of `area`, or all of `area` when it is no wider than that.
fn centered_editor_rect(area: Rect, width: u16) -> Rect {
if width == 0 || area.width <= width {
return area;
}
Rect {
x: area.x + (area.width - width) / 2,
width,
..area
}
}
/// The words the Zen hint shows, with the platform's command key (#1585).
fn zen_hint_text() -> &'static str {
if cfg!(target_os = "macos") {
"Zen Mode: Cmd+K Z or Esc Esc to exit"
} else {
"Zen Mode: Ctrl+K Z or Esc Esc to exit"
}
}
/// 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
};
// A secondary side bar the window can't seat beside the editor's minimum
// is dropped: reserving it anyway placed it past the frame's right edge,
// where its scrollbar wrote outside the buffer (#1132).
let fits = main.width
>= activity_w
.saturating_add(secondary_w)
.saturating_add(RIGHT_PANE_MIN);
let secondary_w = if secondary_visible && fits {
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 {
project_python_on(root, std::env::var_os("PATH").as_deref())
.unwrap_or_else(|| PathBuf::from("python3"))
}
/// [`project_python`] with `path_var` as `PATH`, None where it would fall
/// back to a bare `python3`: no `.venv` and no `python3` on `path_var`.
fn project_python_on(root: &Path, path_var: Option<&std::ffi::OsStr>) -> Option<PathBuf> {
let venv = root.join(".venv").join("bin").join("python");
if venv.is_file() {
return Some(venv);
}
std::env::split_paths(path_var?)
.map(|dir| dir.join("python3"))
.find(|candidate| candidate.is_file())
}
/// 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 QL icon (#578), last of the view icons so disabling CodeQL moves no
/// other icon.
fn activity_codeql_y(bar: Rect) -> u16 {
activity_testing_y(bar) + ACTIVITY_ICON_HEIGHT + ACTIVITY_ICON_GAP
}
fn activity_codeql_block(bar: Rect) -> Rect {
Rect {
x: bar.x,
y: activity_codeql_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_codeql_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 CodeQL (QL) activity-bar icon; empty while the
/// built-in CodeQL extension is disabled.
codeql_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.
#[cfg_attr(test, derive(Default))]
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,
codeql_active: String,
codeql_inactive: String,
codeql_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 = status.head_label();
spans.push(Span::styled(
label,
Style::default().fg(pill_color).add_modifier(Modifier::BOLD),
));
// The operation git stopped in (#1356), as `main | MERGING`.
if let Some(op) = status.operation {
spans.push(Span::styled(
format!(" | {}", op.label()),
Style::default()
.fg(GIT_DIRTY_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,
}
impl BottomPanelTab {
/// Every tab, in the strip's left-to-right order (VS Code's panel-group
/// order). The strip paints from this list, so a tab cannot be
/// clickable without being in it.
const ALL: [BottomPanelTab; 5] = [
BottomPanelTab::Problems,
BottomPanelTab::Output,
BottomPanelTab::Terminal,
BottomPanelTab::Ports,
BottomPanelTab::Captures,
];
/// The tab's strip label, padded to its click target.
fn label(self) -> &'static str {
match self {
BottomPanelTab::Problems => " PROBLEMS ",
BottomPanelTab::Output => " OUTPUT ",
BottomPanelTab::Terminal => " TERMINAL ",
BottomPanelTab::Ports => " PORTS ",
BottomPanelTab::Captures => " CAPTURES ",
}
}
/// The palette command that shows this tab (#852). No catch-all: a new
/// tab fails to compile until it names one, so no tab ships reachable
/// only by a click on the strip.
fn show_command(self) -> crate::widgets::command_palette::Command {
use crate::widgets::command_palette::Command;
match self {
BottomPanelTab::Terminal => Command::FocusTerminal,
BottomPanelTab::Problems => Command::ShowProblems,
BottomPanelTab::Output => Command::ShowOutput,
BottomPanelTab::Ports => Command::ShowPorts,
BottomPanelTab::Captures => Command::ShowCaptures,
}
}
}
/// 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,
/// Why the last Update did not stage the version (#1844): said in the
/// popup, which then offers Retry.
failed: Option<&'static str>,
/// 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.
/// Labelled Retry once an Update has failed.
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]
}
/// What a breadcrumb crumb stands for (#1608).
#[derive(Clone, Debug, PartialEq, Eq)]
enum CrumbTarget {
Folder(PathBuf),
File(PathBuf),
/// An index into the outline's symbols.
Symbol(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,
},
/// A breadcrumb picker's file (#1608): open it as Quick Open would.
OpenCrumbFile(PathBuf),
/// A breadcrumb picker's folder (#1608): list it in the picker of
/// `crumb`, where the listing started.
BrowseCrumbFolder {
dir: PathBuf,
crumb: 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,
},
/// OUTLINE row: open lines `first..=last` of the Outline's file as a
/// symbol tab named `name` (#369).
OpenSymbolTab {
path: PathBuf,
name: String,
first: usize,
last: usize,
},
/// OUTLINE row: jump to the symbol, as a left click does.
GoToOutlineSymbol {
path: PathBuf,
line: u32,
col: u32,
},
/// 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,
/// Customize Layout: centre the editor (#1585).
ToggleCenteredLayout,
/// Run the active editor's code lens at this index (#608).
RunCodeLens(usize),
/// 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,
/// Editor right-click (#1117): the editor's own Cut, Copy and Paste, as
/// its keys do them. Cut and Copy are offered only with a selection.
EditorCut,
EditorCopy,
EditorPaste,
/// Editor right-click (#1117): open the Command Palette.
ShowCommandPalette,
/// 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,
/// Terminal pane right-click: open another terminal next to the active
/// one, as `Cmd+T` does (#1598).
SplitTerminal,
/// Terminal pane right-click: close the pane at `idx`, as `Cmd+W` does
/// for the active one (#1598).
KillTerminal(usize),
/// 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::OpenSymbolTab { .. } => Some("⌘K ⇧V"),
MenuAction::GoToOutlineSymbol { .. } => Some("Enter"),
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::EditorCut => Some("⌘X"),
MenuAction::EditorCopy => Some("⌘C"),
MenuAction::EditorPaste => Some("⌘V"),
MenuAction::ShowCommandPalette => Some("⌘⇧P"),
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::SplitTerminal => Some("⌘T"),
MenuAction::KillTerminal(_) => Some("⌘W"),
MenuAction::CopyCommandOutput(..) => Some("⌘K ⇧C"),
MenuAction::SelectCommandOutput(..) => Some("⌘K ⇧S"),
MenuAction::RerunCommand(..) => Some("⌘K ⇧R"),
_ => None,
}
}
/// The command a menu row runs, when it is one (#1562), so the row can show
/// the chord a user bound to that command.
fn menu_action_command(action: &MenuAction) -> Option<crate::widgets::command_palette::Command> {
use crate::widgets::command_palette::Command as Cmd;
Some(match action {
MenuAction::ClearTerminal(_) => Cmd::TerminalClear,
MenuAction::RenameTerminal(_) => Cmd::TerminalRename,
MenuAction::TerminalQuickSelect => Cmd::TerminalQuickSelect,
MenuAction::TerminalCopyMode => Cmd::TerminalCopyMode,
MenuAction::TerminalCommandHistory => Cmd::TerminalCommandHistory,
MenuAction::OpenScrollbackInEditor => Cmd::TerminalOpenScrollback,
_ => return None,
})
}
/// The hint on a menu row's right: the user's own chord for the command the
/// row runs, else the built-in one.
fn menu_hint(action: &MenuAction, keymap: &crate::keymap::Keymap) -> Option<String> {
menu_action_command(action)
.and_then(|cmd| keymap.chord_for(cmd))
.or_else(|| shortcut_for(action).map(str::to_string))
}
/// 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, keymap: &crate::keymap::Keymap) -> usize {
match entry {
MenuEntry::Item { label, action } => {
let shortcut = menu_hint(action, keymap)
.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 MULTI-member compound's task just finished: launch every member
/// (#310). Separate from `Member` because the set has to be started
/// together - running them through the single-member path would stop each
/// previous one.
/// Boxed like its siblings: the doc above says they are boxed so none
/// dominates the enum's size, and a list plus a name inline would have
/// dominated it six times over.
Members(Box<CompoundLaunch>),
}
/// A compound's members and the name to report them under (#310).
struct CompoundLaunch {
members: Vec<crate::dap::configs::DebugConfig>,
compound: String,
/// The compound's `stopAll`, carried to the moment the set is replaced.
stop_all: bool,
}
/// What became of one compound member (#310).
#[derive(Clone, Copy, PartialEq)]
enum MemberOutcome {
/// Started, and now in the running set.
Launched,
/// Its `cargo` build is running (#1392); it joins the set when the
/// build lands.
Building,
/// Not started: it declares a `preLaunchTask` of its own, and croft's
/// parking is one-at-a-time, so the task cannot be run as part of a set.
/// Launching regardless would debug whatever the last build left behind.
TaskUnrun,
/// Tried and failed; the reason was already reported against its name.
Failed,
}
/// Whether a launch replaces the running set or joins it (#310).
///
/// Starting a configuration has always terminated whatever was running, and
/// that stays true; a compound MEMBER is the one caller that must not, or the
/// second member would kill the first.
#[derive(Clone, Copy)]
enum LaunchSlot {
Replace,
Add,
}
/// Where the session at `index` sits once every index in `removed` has been
/// taken out of the set: `None` if it was removed itself, otherwise shifted
/// down by one for each removal below it (#567).
fn index_after_removals(index: usize, removed: &[usize]) -> Option<usize> {
(!removed.contains(&index)).then(|| index - removed.iter().filter(|&&r| r < index).count())
}
/// What "open shell here" types for a fleet target (#363): nothing for
/// localhost (the pane is already a shell there), `docker exec -it` for a
/// container, `ssh` for a host. Names are quoted for the pane's shell.
fn fleet_shell_command(host: &str) -> Option<String> {
let quote = |s: &str| format!("'{}'", s.replace('\'', "'\\''"));
if host == "localhost" {
return None;
}
Some(match host.strip_prefix("docker:") {
Some(name) => format!("docker exec -it {} sh", quote(name)),
None => format!("ssh {}", quote(host)),
})
}
/// What an Agent Lane row's `+n −m` was counted from (#345): the reviewed
/// snapshot, the agent's last write, and the file's mtime on disk.
type LaneCountKey = (u64, u64, Option<std::time::SystemTime>);
/// How often an open review tab with running checks re-reads them (#365).
const PR_CHECKS_POLL: std::time::Duration = std::time::Duration::from_secs(30);
/// Where GitHub's viewed state for a review tab arrives (#365): the PR's
/// node id and each file's state, or why it could not be read.
type PrViewedRx = std::sync::mpsc::Receiver<
Result<
(
String,
std::collections::BTreeMap<String, crate::pr_review::ViewedState>,
),
String,
>,
>;
/// One viewed mark waiting to reach GitHub (#365).
struct PrViewedWrite {
/// The review tab's `owner/repo#n`, so a later tab's failure is not
/// reported against this one.
key: String,
pr_id: String,
path: String,
viewed: bool,
}
/// Where `gh`'s answer to one viewed mutation arrives (#365).
type PrViewedWriteRx = std::sync::mpsc::Receiver<Result<String, String>>;
/// A code scanning lookup in flight (#577).
struct CodeScanList {
branch: String,
/// Load what it finds (`on`, or the palette command), rather than only
/// saying it is there (`prompt`).
load: bool,
rx: std::sync::mpsc::Receiver<Result<Vec<crate::sarif::github::Analysis>, String>>,
}
/// Where a pull request checkout's worktree path and commit, or git's
/// refusal, arrive (#365).
type PrCheckoutRx = std::sync::mpsc::Receiver<Result<(PathBuf, crate::git::PrWorktree), String>>;
/// A pull request head checked out into a sibling worktree (#365).
struct PrCheckout {
number: u64,
path: PathBuf,
/// The commit checked out: a HEAD anywhere else means new commits.
oid: String,
/// Whether review mode created the worktree; one that was already there
/// is never removed by leaving.
created: bool,
}
/// What a pull request review tab's `gh` call is fetching (#365).
enum PrGhJob {
/// The PR itself (`gh pr view`), by number or URL.
View { selector: String },
/// The whole patch, then the section for `path` opens.
Diff { path: String },
/// A failing check's log, for OUTPUT > PR Checks.
Log { name: String },
/// The open PRs, for the Review Pull Request picker.
List,
/// A background re-read of the PR while its checks run: only the
/// checks of the open tab for `url` are replaced.
Checks { url: String },
}
/// What a network git operation's worker hands back: the UI-thread half
/// of the operation, applied to the app when it arrives.
type GitNetDone = Box<dyn FnOnce(&mut App) + Send>;
/// The file the OUTLINE shows and the edit seq it was synced at.
type OutlineKey = (PathBuf, Option<u64>);
/// Where an off-thread outline parse delivers its symbols (#1150).
type OutlineParse = std::sync::mpsc::Receiver<Vec<crate::lsp::manager::OutlineSymbol>>;
/// The BREAKPOINTS section of the debug tree (#250): a header and one row per
/// breakpoint, or nothing when there are none.
fn breakpoint_section_rows(count: usize) -> Vec<crate::widgets::run_debug::DebugRow> {
use crate::widgets::run_debug::{DebugRow, DebugRowKind};
if count == 0 {
return Vec::new();
}
let mut rows = vec![DebugRow {
indent: 0,
kind: DebugRowKind::Header {
title: String::from("BREAKPOINTS"),
},
}];
rows.extend((0..count).map(|index| DebugRow {
indent: 1,
kind: DebugRowKind::Breakpoint { index },
}));
rows
}
/// The current user's processes, croft's own excluded, for the attach
/// picker (#250). Empty when `ps` is unavailable.
fn list_user_processes() -> Vec<(i64, String)> {
let out = std::process::Command::new("ps")
.args(["-x", "-o", "pid=,comm="])
.output();
match out {
Ok(o) if o.status.success() => crate::dap::configs::parse_ps_processes(
&String::from_utf8_lossy(&o.stdout),
i64::from(std::process::id()),
),
_ => Vec::new(),
}
}
/// 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>,
}
/// A place Peek References can show: path, 0-based line, UTF-16 column.
type PeekLocation = (PathBuf, u32, u32);
/// An Explorer rename or move, held while the language servers are asked
/// for their `willRenameFiles` edit (#610).
#[derive(Clone, Debug)]
enum FileMove {
Rename {
parent: PathBuf,
old: PathBuf,
new_name: String,
},
Paste {
dest_dir: PathBuf,
paths: Vec<PathBuf>,
},
}
#[derive(Clone, Debug)]
struct PendingFileMove {
request_id: u64,
op: FileMove,
renames: Vec<crate::lsp::manager::FileRenameOp>,
deadline: std::time::Instant,
/// The open buffers' `edit_seq`s when the request went out (#1151).
baseline: Vec<(PathBuf, u64)>,
}
/// A Search Editor tab's label (#615): not a file on disk, so it names the
/// query rather than a path the save path could clobber.
fn search_editor_label(query: &str) -> PathBuf {
let q: String = query.chars().take(40).collect();
PathBuf::from(if q.is_empty() {
String::from("Search Editor")
} else {
format!("Search: {q}")
})
}
/// Whether a tab is a Search Editor by its label, not just by its text: a
/// real file that happens to open with `# Query: ` must keep its Enter key,
/// and must never have a rerun overwrite it.
fn is_search_editor_tab(path: Option<&Path>) -> bool {
path.is_some_and(|p| {
let p = p.to_string_lossy();
p == "Search Editor" || p.starts_with("Search: ")
})
}
/// A query as the status line quotes it, shortened.
fn header_query_for_status(query: &str) -> String {
let q: String = query.chars().take(40).collect();
format!("\u{201c}{q}\u{201d}")
}
/// The longest an Explorer move waits for the servers before it goes
/// ahead without their edit. Just past the manager's per-server timeout,
/// so a slow server's answer still lands when it can.
const FILE_MOVE_DEADLINE: std::time::Duration = std::time::Duration::from_millis(2000);
/// Numbers each App's scratch keybindings file under test (#612), so tests
/// running in parallel never share one.
static TEST_KEYBINDINGS_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
/// How long a buffer must sit unedited before its code lenses are asked
/// for (#608).
const CODE_LENS_SETTLE: std::time::Duration = std::time::Duration::from_millis(600);
/// 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,
/// The breadcrumb whose picker this is (#1608): Left / Right step to
/// the neighbouring crumb's picker.
crumb: Option<usize>,
/// The first top-level row on screen: a menu taller than the terminal
/// (a big folder's breadcrumb picker) scrolls to keep the highlight in
/// view. Kept by [`scroll_for`](Self::scroll_for).
scroll: std::cell::Cell<usize>,
}
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,
crumb: None,
scroll: Default::default(),
}
}
/// Translate every label through the UI catalog (#621). Idempotent: a
/// translated label is not itself a key.
fn localize(&mut self) {
fn walk(items: &mut [MenuEntry]) {
for e in items {
match e {
MenuEntry::Item { label, .. } | MenuEntry::Header(label) => {
if let std::borrow::Cow::Owned(t) = crate::i18n::tr(label) {
*label = t;
}
}
MenuEntry::Submenu { label, items } => {
if let std::borrow::Cow::Owned(t) = crate::i18n::tr(label) {
*label = t;
}
walk(items);
}
MenuEntry::Separator => {}
}
}
}
if crate::i18n::active() {
walk(&mut self.items);
}
}
/// The first top-level row shown when `visible` rows fit: the previous
/// offset, moved only as far as keeps `selected` on screen.
fn scroll_for(&self, visible: usize) -> usize {
let mut top = self.scroll.get();
if visible > 0 {
if self.selected < top {
top = self.selected;
} else if self.selected >= top + visible {
top = self.selected + 1 - visible;
}
top = top.min(self.items.len().saturating_sub(visible));
}
self.scroll.set(top);
top
}
/// 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),
/// File: Save As… (#1203): a path for the active tab's buffer, relative
/// to `target_dir` (the workspace root) unless absolute. `buffer` starts
/// as the tab's own path.
SaveAs,
/// 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,
},
/// Debugger "Add Hit Count Breakpoint" (#611): the DAP `hitCondition`
/// for the breakpoint on 1-based `line` of `path`. Same commit shape as
/// [`PromptKind::BreakpointCondition`].
HitCondition {
path: PathBuf,
line: usize,
},
/// Debugger "Add Function Breakpoint" (#611): a function name to pause
/// on entry to.
FunctionBreakpoint,
/// Debugger "Break When Value Changes" (#611): a variable name from the
/// paused frame's scopes.
DataBreakpoint,
/// Profiles: New Profile (#618): the new profile's name.
NewProfile,
ReviewComment,
ReviewSummary,
StickyNote,
/// 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>,
}
/// A Source Control write that records the files on disk (#1438): a commit
/// variant or a stash. Held while the unsaved-changes prompt is open, and
/// across a format-on-save write, so the choice runs the request it
/// interrupted.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ScmWrite {
Commit,
CommitStaged,
CommitAll,
Amend,
CommitAndSync,
CommitAndPush,
Stash,
StashIncludeUntracked,
StashStaged,
}
impl ScmWrite {
fn is_stash(self) -> bool {
matches!(
self,
Self::Stash | Self::StashIncludeUntracked | Self::StashStaged
)
}
/// The verb the prompt's buttons and status lines use.
fn verb(self) -> &'static str {
if self.is_stash() { "Stash" } else { "Commit" }
}
}
/// The unsaved-changes prompt in front of a commit or stash (#1438): `op`
/// waits while `files` (dirty tabs under the repository) are unsaved.
/// `root` is the repository the request was made against: the mouse stays
/// live while the prompt is open, so focus can move Source Control to
/// another root before the choice, and the write must not follow it.
#[derive(Clone, Debug, PartialEq, Eq)]
struct PendingUnsavedScm {
op: ScmWrite,
root: PathBuf,
files: Vec<PathBuf>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct PendingDiscard {
rel_path: String,
untracked: bool,
staged: 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,
}
/// What an unsaved-changes prompt (#862) goes on to do once it is answered.
/// Everything that would drop a dirty buffer asks first: a quit that goes
/// ahead removes the hot-exit backup, so the prompt is the last chance to
/// save.
#[derive(Clone, Debug, PartialEq, Eq)]
enum UnsavedExit {
/// Quit croft (Ctrl+Q, vim `:qa`).
Quit,
/// Hand a remote croft back to the local one (Cmd+Shift+L), which
/// ends this process as a quit does.
DropToLocal,
/// Leave this croft for a workspace on `host`: the local session ends
/// and a later return starts a fresh one.
RemoteLaunch { host: String, path: Option<String> },
/// The croft on `host` is ready and this one is about to hand it the
/// terminal, ending here. Asked about edits made since the connect was
/// asked for, which can be minutes earlier (an install ran between).
RemoteHandoff { host: String },
/// Close the focused group's tab at `idx`. `path` is the file it showed
/// when asked, so an answer never lands on a tab that moved into its
/// place meanwhile.
CloseTab { idx: usize, path: Option<PathBuf> },
}
impl UnsavedExit {
/// The prompt's name for going on: "Save all and quit", "Did not quit".
fn verb(&self) -> &'static str {
match self {
Self::Quit => "quit",
Self::DropToLocal => "return to local",
Self::RemoteLaunch { .. } | Self::RemoteHandoff { .. } => "connect",
Self::CloseTab { .. } => "close",
}
}
}
/// Whether closing `ed` would lose text only it holds (#862): unsaved
/// changes to a file, or an untitled buffer that was typed into and still
/// holds something.
fn holds_unsaved(ed: &Editor) -> bool {
ed.dirty && (ed.path.is_some() || ed.lines.iter().any(|l| !l.is_empty()))
}
/// 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,
}
/// A tour in progress (#377).
pub struct TourRun {
pub tour: crate::tour::Tour,
pub scratch: PathBuf,
pub previous_root: PathBuf,
/// The current step opened a palette, Quick Open or a picker, whose Esc
/// then leaves the tour rather than only closing it (#863).
pub step_opened_modal: bool,
}
/// 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,
/// The pane's OSC 7 report when the offer appeared, so accepting can
/// tell the remote shell's directory from one left by an earlier shell.
cwd_at_offer: Option<crate::remote::CwdReport>,
}
/// 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 CodeLLDB `cargo` launch building its program on a background thread
/// (#1392): the receiver for the executable (or the build error), the
/// config to launch with it, the slot it launches into, and the workspace
/// root it builds for (so a re-root mid-build discards the binary).
type PendingCargoLaunch = (
std::sync::mpsc::Receiver<Result<PathBuf, String>>,
Box<crate::dap::configs::ResolvedConfig>,
LaunchSlot,
PathBuf,
);
/// The test run Testing: Rerun Last Run repeats (#1535), as it was asked.
#[derive(Clone, Debug, PartialEq, Eq)]
enum LastTestRun {
All,
One(String),
Filter(String),
Suite(String),
Many(Vec<String>),
}
/// A "Running …" status an operation put in the status bar (#856), kept
/// until the operation ends so the bar can say how it went instead of
/// claiming it still runs: a test run, a task, a runnable fenced block.
/// All of them end through [`RunningStatus::settle`].
struct RunningStatus {
/// The status text the operation set; replaced only while the bar
/// still shows it, so a newer message is never clobbered.
shown: String,
/// What ran, as the outcome names it: a test's own name, `suite X`,
/// `CodeQL tests`, a task's label, a fenced block's pane.
label: String,
started: std::time::Instant,
}
impl RunningStatus {
/// The bar shows `shown`, just set by the run of `label`.
fn new(shown: &str, label: String) -> Self {
Self {
shown: shown.to_string(),
label,
started: std::time::Instant::now(),
}
}
/// The run is over: put `outcome(label, time since it started)` in
/// `status`, only if that still shows what the run set. Whether it did.
fn settle(
self,
status: &mut String,
outcome: impl FnOnce(&str, std::time::Duration) -> String,
) -> bool {
if *status != self.shown {
return false;
}
*status = outcome(&self.label, self.started.elapsed());
true
}
}
/// How a command a terminal pane ran ended, for the status bar (#856), from
/// the shell's own command-finished report: `label finished (exit 0, 0.4
/// s)`, or `label failed (exit 2, 1.3 s)`. A shell that reported no exit
/// code gets `label finished (0.4 s)`.
fn pane_run_outcome(label: &str, exit: Option<i32>, dur: std::time::Duration) -> String {
let took = format!("{:.1} s", dur.as_secs_f64());
match exit {
Some(0) => format!("{label} finished (exit 0, {took})"),
Some(code) => format!("{label} failed (exit {code}, {took})"),
None => format!("{label} finished ({took})"),
}
}
/// 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,
/// The CodeQL side bar (#578).
pub codeql: crate::widgets::codeql::CodeqlPanel,
/// Background `cargo test` worker feeding the Testing panel.
test_worker: crate::testing::worker::TestWorker,
/// The run whose "Running test …" status awaits its outcome (#856).
test_run_status: Option<RunningStatus>,
/// The last test run started, for Testing: Rerun Last Run (#1535).
last_test_run: Option<LastTestRun>,
/// Tasks and fenced blocks whose "Running …" status awaits their pane's
/// command-finished report (#856), by pane uid.
pane_run_statuses: Vec<(u64, RunningStatus)>,
/// 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 AGENT LANE section (#345).
pub agent_lane_panel: crate::widgets::agent_lane::AgentLanePanel,
/// Per lane file, the `+n −m` its row shows and what it was counted
/// from: (reviewed snapshot, last agent write, disk mtime).
lane_change_counts: std::collections::HashMap<PathBuf, (LaneCountKey, Option<(usize, usize)>)>,
/// 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,
/// croft's own config files, checked for changes made outside croft,
/// such as a file arriving by config sync (#262).
config_watch: crate::config_sync::ConfigWatch,
/// 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)>,
/// The tab a tab-strip mouse binding was clicked on (#1427), set only
/// for that dispatch and taken by `run_command` as it starts, so only
/// the directly bound command sees it: a command it runs in turn (an
/// aborted rebase closing its tab, a replayed macro) acts on the active
/// tab as it would from the keyboard.
tab_click_target: Option<usize>,
/// 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,
/// The formatter the settings name for every file and per language
/// (VS Code's `editor.defaultFormatter`, #1499). Format on save skips a
/// file whose named formatter croft does not run.
default_formatter: Option<String>,
language_formatters: std::collections::BTreeMap<String, String>,
/// Named formatters whose skipped save has been explained once this
/// session (#1499); later saves say only "Saved".
foreign_formatters_noted: std::collections::BTreeSet<String>,
/// Per-language overrides (#1440), VS Code's `"[python]": { … }`, keyed
/// by VS Code's language id. Read through the `*_for` helpers, which
/// fall back to the global setting.
language_prefs: std::collections::BTreeMap<String, crate::prefs::LanguagePrefs>,
/// 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,
/// The project's `files_exclude` globs (#1345), as last applied to the
/// Explorer, so a settings reload re-lists the tree only on a change.
files_exclude: Vec<String>,
/// 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>,
/// The project's Prettier formatting the active file (#1255), whose
/// reply completes a deferred save like an LSP format reply does.
prettier_job: Option<crate::prettier::Job>,
/// When a format-on-save stops waiting on its formatter and writes the
/// file unformatted (#1491). Set with `save_after_format`.
format_save_deadline: Option<std::time::Instant>,
/// 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>)>,
/// Background folder-size scans for the CodeQL database card (#578): a
/// large database is many files, so the walk stays off the input path.
codeql_size_rx: std::sync::mpsc::Receiver<(PathBuf, Option<u64>)>,
codeql_size_tx: std::sync::mpsc::Sender<(PathBuf, Option<u64>)>,
/// Databases whose size scan is in flight, so a refresh does not start
/// a second walk of the same folder.
codeql_size_pending: std::collections::HashSet<PathBuf>,
/// 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>,
/// When and for which folder the subfolder-repo scan behind the
/// Source Control empty state last ran (#1227); rescanned at most
/// every couple of seconds while that card shows.
nested_repo_scan: Option<(PathBuf, std::time::Instant)>,
/// 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, crate::git::Blame)>,
blame_tx: std::sync::mpsc::Sender<(PathBuf, crate::git::Blame)>,
/// 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>,
/// The network git operation in flight (push, pull, fetch, clone...),
/// named for the status line, and where its finisher arrives.
git_net_job: Option<(String, std::sync::mpsc::Receiver<GitNetDone>)>,
/// A read-only git view being computed off the UI thread (a TIMELINE
/// commit diff, a COMMITS patch): a large repo's `git show` or rename
/// walk froze the editor when run inline. A newer click replaces it.
git_view_job: Option<std::sync::mpsc::Receiver<GitNetDone>>,
/// The `vim_mode` pref as last applied (#1286). A settings reload
/// changes the live mode only when the pref itself changed, so an
/// unrelated edit to config.json does not reset the mode in use.
vim_mode_pref: bool,
/// 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,
/// Save unsaved editors before every debug or run launch (#1400), so
/// the debuggee runs the text its breakpoints were set against. Off
/// only by `disable_save_before_debug` (`debug.saveBeforeStart: none`).
save_before_debug: bool,
/// Auto-closing pairs (#121), persisted; synced onto the active editor
/// beside the blame flag.
auto_close_pairs: bool,
/// Re-indent a multi-line paste under the caret line (#1218), on unless
/// `disable_paste_reindent` is set.
paste_reindent: 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,
/// View: Toggle Centered Layout (#1585), persisted: the editor keeps
/// `centered_layout_width` columns in the middle of its column.
centered_layout: bool,
/// Zen Mode starts centred (`zen_center_layout`, persisted, on by
/// default), as VS Code's `zenMode.centerLayout`.
zen_center_layout: bool,
/// Whether this Zen session is centred: `zen_center_layout` on entry,
/// until Toggle Centered Layout turns it off.
zen_centered: bool,
/// The centred editor's width in columns (#1585).
centered_layout_width: u16,
/// When the last Esc in Zen Mode that did nothing else landed: a
/// second such Esc inside [`ZEN_ESC_WINDOW`] leaves Zen (#1585).
zen_esc_at: Option<std::time::Instant>,
/// Until when the "how to leave Zen" hint shows (#1585). Zen hides the
/// status bar, so the hint draws on its own.
zen_hint_until: Option<std::time::Instant>,
/// 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 press in the editor's breakpoint lane toggled a breakpoint
/// (#1544), so the rest of that gesture belongs to the lane: drags are
/// dropped until the release. Without it the first drag (some terminals
/// send one at the press cell) would anchor a selection at the caret and
/// walk the caret to the clicked line, undoing the caret-preserving
/// click. Cleared on the release and on the next press.
breakpoint_lane_press: 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>>,
/// The `codeql` executable; tests point it at a stand-in (#578).
codeql_program: PathBuf,
/// The query run in flight: its outcome arrives here, and when it
/// started (#578).
codeql_run: Option<(
std::sync::mpsc::Receiver<crate::codeql_query::RunStatus>,
std::time::Instant,
)>,
/// Raised to stop the query run in flight: its `codeql` is killed and
/// the run recorded as cancelled (#578).
codeql_cancel: std::sync::Arc<std::sync::atomic::AtomicBool>,
/// The file name of the query in flight, for its status-bar chip.
codeql_run_name: String,
/// Queries "Run Queries in Pack" has yet to start, in order (#578).
codeql_run_queue: std::collections::VecDeque<crate::codeql_query::QueuedRun>,
/// "Run Query on Multiple Databases" being set up (#578): the query,
/// its text, and the databases checked so far.
codeql_multi_db: Option<(PathBuf, String, Vec<PathBuf>)>,
/// How many queries the pack run holds and how many have failed so
/// far, for the status line; the total is 0 when no pack run is on.
codeql_batch: (usize, usize),
/// The database upgrade or cache cleanup in flight (#578).
codeql_upgrade: Option<CodeqlUpgrade>,
/// The `codeql version` call behind "CodeQL: Copy Version Information"
/// (#578): its bare version number, or why it could not be read.
codeql_version: Option<std::sync::mpsc::Receiver<Result<String, String>>>,
/// The evaluator log summary being generated (#578): where the outcome
/// arrives, and the summary file to open once it lands.
codeql_log_summary: Option<(std::sync::mpsc::Receiver<Result<(), String>>, PathBuf)>,
/// The evaluator log viewer being prepared (#578): where the rendered
/// tree (or why there is none) arrives, and the tab label to show it in.
codeql_log_viewer: Option<CodeqlLogViewerJob>,
/// The Model Editor's endpoints being read (#578): the endpoints or why
/// not, and the database and language they are for.
codeql_model_job: Option<CodeqlModelJob>,
/// The performance comparison being prepared (#578): where the rendered
/// table (or why there is none) arrives, and the tab label to show it in.
codeql_perf_compare: Option<(std::sync::mpsc::Receiver<Result<String, String>>, String)>,
/// The query help being rendered (#578): where the outcome arrives,
/// the Markdown file to preview once it lands, and the query's name.
codeql_query_help: Option<CodeqlQueryHelp>,
/// The pack install or download in flight (#578): where its outcome
/// arrives, and the status lines for success and failure.
codeql_pack_job: Option<CodeqlPackJob>,
/// A database being downloaded or extracted (#1155): what is being
/// added, for the status line, and where its folder arrives.
codeql_db_job: Option<(String, std::sync::mpsc::Receiver<Result<PathBuf, String>>)>,
/// A CodeQL document being made (#578: View CFG, the alert and result
/// views): the file it writes or why not, and the status lines for
/// each.
codeql_doc_job: Option<CodeqlDocJob>,
/// The CodeQL results table last walked (#578), so the walk goes on
/// once the code it opened has the focus.
codeql_results_walk: Option<PathBuf>,
/// The AST being read for the AST Viewer (#578): the tree or why not,
/// and the view it fills in.
codeql_ast_job: Option<(
std::sync::mpsc::Receiver<Result<crate::codeql_ast::AstTree, String>>,
crate::codeql_ast::AstView,
)>,
/// `codeql_cli_path` from settings (#578), kept to notice a reload
/// changing it.
codeql_cli_setting: Option<String>,
/// Where [`Self::codeql_program`] came from (#578).
codeql_cli_source: crate::codeql_cli::Source,
/// The newest CLI release "CodeQL: Check for CLI Updates" found, which
/// "CodeQL: Download CLI" then installs (#578).
codeql_cli_latest: Option<String>,
/// The CLI download in flight (#578).
codeql_cli_download: Option<std::sync::mpsc::Receiver<crate::codeql_cli::JobUpdate>>,
/// The CLI update check in flight (#578): the latest release and the
/// version in use, if it could be read.
codeql_cli_check: Option<std::sync::mpsc::Receiver<CodeqlCliCheck>>,
/// The network calls behind those two, replaced in tests.
codeql_cli_net: crate::codeql_cli::Net,
/// The GitHub Code Search in flight: the list its repositories go
/// into, and its outcome (#578).
codeql_code_search: Option<CodeqlCodeSearch>,
/// The variant analysis being bundled and submitted (#578).
codeql_variant_submit:
Option<std::sync::mpsc::Receiver<Result<crate::codeql_submit::Submitted, String>>>,
/// The read of unfinished variant analyses' progress in flight, and
/// when the last one started (#578).
codeql_variant_poll: Option<std::sync::mpsc::Receiver<Vec<CodeqlRunPoll>>>,
codeql_variant_polled: Option<std::time::Instant>,
/// The fetch of a variant analysis's results in flight (#578).
codeql_variant_results: Option<std::sync::mpsc::Receiver<VariantResults>>,
/// The export of a variant analysis's results in flight (#578): where
/// it went (a folder's summary file or a gist's URL), how many
/// repositories it holds, and those whose results failed.
codeql_variant_export: Option<std::sync::mpsc::Receiver<Result<VariantExport, String>>>,
/// The walk for the workspace's queries in flight (#840): opening the
/// CodeQL view starts it off the UI thread and the packs land here. It is
/// tagged with the root it walks, so a root the workspace has left since
/// never lists its queries.
codeql_queries_job: Option<(
PathBuf,
std::sync::mpsc::Receiver<Vec<crate::codeql_query::QueryPack>>,
)>,
/// 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,
/// When the minimap image was last baked, and whether an edit since then
/// is waiting for the next bake (see [`MINIMAP_EDIT_REBAKE`]).
minimap_baked_at: Option<std::time::Instant>,
minimap_edit_pending: bool,
/// The strip was last drawn as braille text, where the terminal cannot
/// draw images (#1231); `minimap_content_h` then counts dot rows.
minimap_text: bool,
/// The braille cells for the text strip, rebuilt only when the same
/// signature the image bake keys on changes.
minimap_text_cache: Option<(MinimapSig, Vec<BrailleCell>)>,
/// Whether the editor was wide enough for the strip on the last frame,
/// so turning the minimap on can say why it does not show.
minimap_room: bool,
/// The buffer ratatui drew last, and what each small chrome image (the
/// PROBLEMS badge, Run and Debug icon, sidebar illustrations) was sent
/// over, keyed by overlay, for [`App::chrome_image_due`]. Keys not
/// checked in a frame (the image was hidden) are dropped.
drawn_buffer: Option<ratatui::buffer::Buffer>,
chrome_sent: std::collections::HashMap<&'static str, u64>,
chrome_seen: std::collections::HashSet<&'static str>,
/// 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>>,
/// The `code_scanning` setting (#577).
code_scanning: crate::sarif::github::CodeScanningMode,
/// The branch (or detached HEAD) code scanning last looked at, so a
/// checkout of another one is noticed.
code_scan_seen: Option<String>,
/// A code scanning lookup in flight: the branch it is for, whether to
/// load what it finds, and where the chosen analyses arrive.
code_scan_list: Option<CodeScanList>,
/// Chosen analyses fetching as SARIF: where their saved files arrive.
code_scan_fetch: Option<std::sync::mpsc::Receiver<Vec<Result<PathBuf, 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>,
/// The colour depth each frame is fitted to before it is written
/// (#1433): the `color_depth` setting, else what the terminal's
/// environment advertises.
pub(crate) color_depth: crate::color_depth::ColorDepth,
/// 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>,
/// Agent edit approvals (#347): this workspace's hook socket, the
/// proposals waiting on the user in arrival order, and the popup's
/// state for the one at the head (`Some` exactly while one waits).
hook_listener: Option<std::os::unix::net::UnixListener>,
/// The workspace the hook socket was bound for: an approval
/// notification's links name it, so `croft decide` finds this croft
/// (#359).
hook_root: PathBuf,
approvals: std::collections::VecDeque<crate::agent_approval::Pending>,
approval_ui: Option<crate::agent_approval::ApprovalUi>,
/// The language server's check of the proposal at the head of the
/// queue (#347): its diagnostics show in the popup before approval.
approval_check: Option<crate::agent_approval::ProposalCheck>,
/// A proposal being edited before approval (#347): its token, and the
/// scratch file whose save approves the edited text. The popup stays
/// down while it lasts.
approval_edit: Option<(String, PathBuf)>,
/// When that edit is a three-way merge with a dirty tab's unsaved
/// edits, the tab's file: once approved, the tab takes the merged text.
approval_merge_into: Option<PathBuf>,
/// One Jupyter kernel per notebook that has run a cell (#355), by path.
/// Dropping one (the map entry going) shuts its kernel down.
notebook_kernels: std::collections::HashMap<PathBuf, crate::notebook_kernel::NotebookRun>,
/// Notebook: Select Kernel asking for the installed kernels (#1377):
/// the notebook it is for and the bridge listing them.
kernel_listing: Option<(PathBuf, crate::notebook_kernel::KernelSession)>,
/// The kernel picker's notebook, the kernelspecs its rows name, and
/// the kernel the notebook asked for that is not installed, if that is
/// why it opened.
kernel_choice: Option<(
PathBuf,
Vec<crate::notebook_kernel::KernelSpec>,
Option<String>,
)>,
/// When the shown coverage report was taken, the file its editor lens
/// was built for, and the install command a missing coverage tool
/// needs (#263).
coverage_at: Option<std::time::SystemTime>,
coverage_lens_path: Option<PathBuf>,
coverage_install: Option<String>,
/// How long one frame may spend serving `croft view` clients (see
/// `drain_view_requests`). A field so a test on a loaded machine can
/// stretch it: the fixed 20ms is shorter than one file open there.
view_drain_budget: std::time::Duration,
/// 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>,
/// A commit or stash asked for while tabs under the repository held
/// unsaved edits (#1438). The write records the files on disk, so the
/// modal asks first: save them all, go ahead without them, or cancel.
pending_unsaved_scm: Option<PendingUnsavedScm>,
/// The repository the open Delete Remote Tag picker listed (#1582),
/// so the deletion stays bound to it if Source Control moves.
remote_tag_root: Option<PathBuf>,
/// Set for the one call that runs a write the prompt already cleared.
scm_unsaved_cleared: bool,
/// A write waiting on a format-on-save reply: Save All armed the
/// active tab's deferred write, and the commit runs once it lands.
scm_after_format_save: Option<(ScmWrite, PathBuf)>,
/// 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>,
/// An unsaved-changes prompt (#862) waiting on S / D / Esc, holding what
/// it goes on to do. While `Some`, the modal eats every key and click.
pending_unsaved: Option<UnsavedExit>,
/// The unsaved state (see [`App::unsaved_stamp`]) the user chose to
/// leave behind when asked about a remote connect (#862): the handoff
/// that ends this croft later goes without asking again only while
/// nothing has changed since.
remote_handoff_ok: Option<u64>,
/// Hot exit (#862): the directory this croft backs its unsaved buffers
/// up under (`~/.local/state/croft/hot-exit`, see [`user_data_dir`]).
/// `None` keeps no backups, as
/// under test unless a test points it at a tempdir.
pub hot_exit_dir: Option<PathBuf>,
/// The [`App::unsaved_stamp`] this croft's backup on disk was written
/// at, `None` while it has none: the tick writes only when they differ.
/// A write that fails leaves it alone, so a later tick tries again.
hot_exit_written: Option<u64>,
/// When a failed hot-exit write may be tried again (#862): a full disk
/// is retried every [`App::HOT_EXIT_DELAY`], not every frame. `None`
/// once a write lands.
hot_exit_retry_at: Option<std::time::Instant>,
/// Backups of crofts that are gone whose text this croft restored
/// (#862). Removed once its own backup holds that text, so a write that
/// fails never leaves the text in memory only.
hot_exit_consumed: Vec<PathBuf>,
/// Consumed backups that could not be removed once this croft's own
/// backup landed (#862 review). They may still hold text, so the quit
/// tries them again and says which are left.
hot_exit_unremoved: Vec<PathBuf>,
/// Lines for stderr once the terminal is the shell's again, about what
/// the user must still hear after croft has gone: a hot-exit backup a
/// quit could not remove (#862).
exit_notes: Vec<String>,
/// 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>,
/// Index of the editor tab being drag-reordered (#1565), set by a press
/// on a tab and cleared on release. Live like `terminal_drag_from`:
/// crossing another tab moves the dragged one there, and this follows.
editor_tab_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,
/// The command the fleet run in flight is running, for its tab (#363).
fleet_command: String,
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>>,
>,
/// Markdown-lint's own edit-seq cursor, mirroring `lsp_last_seen` but
/// independent of the LSP: `.md` files get linted whether or not any
/// language server is running (there is none for Markdown), so this
/// cannot share the LSP's cursor map. Keyed by path; a path's entry is
/// removed when its tab closes so a later re-open re-lints instead of
/// trusting a stale seq (a different file could reuse a `PathBuf` after
/// a rename-in-place on disk). Each entry holds the lines that were
/// linted as well as their seq, because two split panes count edits
/// separately and can share a seq while holding different text.
markdown_lint_last_seen: std::collections::HashMap<PathBuf, (u64, Vec<String>)>,
/// Live Run (`crate::live_run`): the files armed to run as they are
/// edited. Per file, never global, so no script runs unasked.
live_run_files: std::collections::HashSet<PathBuf>,
/// The buffer text last sent per armed file, so an unchanged buffer is
/// not re-run on every tick.
live_run_sent: std::collections::HashMap<PathBuf, Vec<String>>,
/// The background runner, spawned on the first toggle.
live_run_runner: Option<crate::live_run::Runner>,
/// The last position [`App::sync_markdown_scroll`] pushed across split
/// panes: (path, whether the preview led, source line), so a still
/// viewport costs nothing per tick.
md_scroll_synced: Option<(PathBuf, bool, usize)>,
/// Code lenses on or off (#608, `Editor: Toggle CodeLens`), and the
/// edit seq last requested per path, so a still buffer asks once.
code_lens_enabled: bool,
code_lens_requested: std::collections::HashMap<PathBuf, u64>,
/// Function breakpoints (#611), handed to each session as it launches.
function_breakpoints: Vec<String>,
/// Screen reader mode (#621), its speech command, the announcer, and
/// where the status bar drew the announcement this frame (the cursor's
/// resting place when no text has focus).
screen_reader: bool,
screen_reader_command: Option<String>,
announcer: crate::a11y::Announcer,
announce_pos: Option<(u16, u16)>,
/// Terminal command suggestions (#614): on or off, and the one painted
/// this frame as (pane index, the text Right arrow would type).
term_suggest_enabled: bool,
term_suggestion: Option<(usize, String, String)>,
/// The command whose new shortcut the next keystroke records (#612).
recording_shortcut: Option<(crate::widgets::command_palette::Command, std::time::Instant)>,
/// A recorded chord another command already has (#1482), waiting for
/// Enter to reassign it: the command, the chord, and every command it
/// runs now (a built-in chord can be shared by several).
confirming_shortcut: Option<(
crate::widgets::command_palette::Command,
KeyEvent,
Vec<crate::widgets::command_palette::Command>,
)>,
/// Inline AI suggestions (#607): off until the user turns them on, since
/// they send code to a model. The worker, the backend it was started
/// for, the request in flight (id plus what it answers for), and the
/// last request's key so a still caret asks once.
inline_enabled: bool,
inline_worker: Option<crate::inline_complete::Worker>,
inline_config: Option<crate::inline_complete::Config>,
inline_job: Option<(u64, PathBuf, u64, usize, usize)>,
inline_asked: Option<(PathBuf, u64, usize, usize)>,
inline_next_id: u64,
/// Where recorded shortcuts are written: the user's keybindings.json,
/// or under test a scratch file, so a test run never edits the real one.
keybindings_file: PathBuf,
/// A Search Editor rerun in flight (#615): the tab it lands in, the
/// header it ran, and where its hits arrive.
search_editor_job: Option<(
PathBuf,
crate::search_editor::Header,
std::sync::mpsc::Receiver<Vec<crate::widgets::search::SearchHit>>,
)>,
/// The open SARIF logs (path, disk stamp) the published diagnostics were
/// built from (#577); a different set means publish again.
sarif_diag_signature: Vec<(PathBuf, Option<(std::time::SystemTime, u64)>)>,
/// When the SARIF viewers' added logs were last checked for changes.
sarif_added_polled: Option<std::time::Instant>,
/// The selection and open files the SARIF step marks were drawn for.
sarif_step_signature: Option<SarifStepSignature>,
/// Every (file, source key) SARIF diagnostics were published under, so a
/// closed log's results can be withdrawn exactly.
sarif_published: Vec<(PathBuf, String)>,
/// 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>,
/// Where the caret was (row, char column) when the pending completion was
/// requested: the server's edit ranges describe the line then, and the
/// accept shifts them by what was typed or deleted since.
completion_origin: Option<(usize, usize)>,
/// The pending completion's last reply was marked `isIncomplete` (#1529):
/// each word edit re-asks the server, whether or not any of its old items
/// are still on screen. Lives only while `completion_request_id` does.
completion_incomplete: bool,
/// A word edit in an incomplete session is waiting to re-ask the server;
/// sent after `sync_lsp` so the request follows the edit's `didChange`.
completion_reask_due: bool,
/// The pending completion was asked for (Ctrl+Space), so the words of
/// the open documents fill in when no server offers anything (#1566).
/// A `.` typed asks the server alone: a word list there would open on
/// every full stop of a plain-text note.
completion_words: bool,
/// Ids for completions answered here rather than by a server (#1566),
/// counting down from the top so they never meet the manager's.
local_completion_seq: u64,
/// `word_based_suggestions`: which open documents word completion
/// draws on (#1566).
pub word_suggestions: crate::word_suggest::WordSuggestions,
/// 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)>,
/// Peek References (#616): every reference and the one the popup shows.
/// Up / Down step through them; any close of the popup clears this.
peek_refs: Option<(Vec<PeekLocation>, usize)>,
/// Set when the in-flight references request came from Peek References,
/// so its reply opens the popup instead of the picker.
references_want_peek: bool,
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>)>,
/// A large buffer's syntax outline being parsed off the UI thread
/// (#1150): the `outline_synced` key its snapshot was taken at, and
/// where the symbols land. One at a time; typing meanwhile coalesces
/// into one fresh parse when it lands.
outline_parse: Option<(OutlineKey, OutlineParse)>,
/// The `outline_synced` key the last off-thread parse was started for.
outline_parsed_for: Option<(PathBuf, Option<u64>)>,
/// The file and edit seq whose language-server outline last landed: a
/// syntax parse of that same buffer finishing later must not replace
/// the richer symbols.
outline_lsp_landed: Option<(PathBuf, 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,
/// A request already went out for `linked_observed` (#1299). Kept
/// apart from `linked_request`, which the reply clears: a `null`
/// answer left nothing to say the position was asked, so every UI
/// wake asked again while the caret stayed put.
linked_asked: bool,
/// 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>,
/// The open buffers' `edit_seq`s when the in-flight rename went out
/// (#1151): a reply for a buffer edited since is refused.
rename_baseline: Vec<(PathBuf, u64)>,
/// An Explorer rename or move waiting on the servers' `willRenameFiles`
/// edit (#610); it runs when the answer lands or its deadline passes.
pending_file_move: Option<PendingFileMove>,
/// 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,
/// The `edit_seq` of the tab the in-flight format request was computed
/// against (#1127): a reply for a buffer typed into since is dropped.
format_request_seq: Option<u64>,
/// 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 open buffers' `edit_seq`s when the code-action (or resolve)
/// request whose edits are pending went out (#1151).
code_action_baseline: Vec<(PathBuf, u64)>,
/// 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>)>,
/// Writing reviews (#366): comments not yet submitted and the PR they
/// were written on, the PR last looked up as (repo root, number), each
/// thread's GraphQL node id, the chosen verdict while its summary is
/// typed, the `gh` to run, and where finished jobs report.
review_pending: Vec<crate::review_threads::PendingComment>,
review_pending_pr: Option<(PathBuf, String)>,
/// A Submit Review or export is in flight; another is refused until it
/// reports, so the same comments are never posted twice.
review_submitting: bool,
/// Sticky notes (#367): every note in the workspace, where the owner
/// keeps them (`None` under test), and which box id is which note.
notes: crate::sticky_notes::Notes,
notes_path: Option<PathBuf>,
note_box_ids: std::collections::HashMap<u64, String>,
notes_shown_gen: u64,
/// Export to a PR (#368): the previewed comments and the navigator
/// notes they came from, the sticky notes it would settle, and the
/// prefix that marks the navigator's comments as AI-authored.
review_export: Option<(
Vec<crate::review_threads::PendingComment>,
Vec<u64>,
Vec<crate::widgets::list_picker::ListRow>,
)>,
review_export_sticky: Vec<String>,
/// The PR the export preview named: posting goes there, even if a
/// thread load answered for another PR in between.
review_export_pr: Option<(PathBuf, String)>,
review_ai_prefix: String,
review_pr: Option<(PathBuf, String)>,
/// The branch checked out when `review_pr` was recorded: the number is
/// reused only while it is still the branch, or a `gh pr checkout` of
/// another PR sent comments to the old one.
review_pr_branch: Option<String>,
review_nodes: std::collections::HashMap<u64, String>,
review_verdict: Option<crate::review_threads::ReviewEvent>,
review_gh: String,
/// The review tab's `gh` call in flight (#365): what it is for, and
/// where its answer arrives.
pr_gh: Option<(PrGhJob, std::sync::mpsc::Receiver<Result<String, String>>)>,
/// When the open review tab's checks were last re-read (#365).
pr_checks_polled: Option<std::time::Instant>,
/// GitHub's viewed state being read for the review tab keyed by the
/// first half (#365), and [`Self::pr_viewed_seq`] when the read began.
pr_viewed_fetch: Option<(String, u64, PrViewedRx)>,
/// Viewed marks waiting to reach GitHub, sent one at a time so two
/// quick toggles of one file arrive in order (#365).
pr_viewed_queue: std::collections::VecDeque<PrViewedWrite>,
/// The viewed mutation in flight: its tab's key and file, and gh's
/// answer.
pr_viewed_write: Option<(String, String, PrViewedWriteRx)>,
/// A counter stamped on every viewed write when it is queued and when
/// it finishes (#365).
pr_viewed_seq: u64,
/// Each `(tab key, file)`'s latest stamp from [`Self::pr_viewed_seq`].
/// A viewed-state read that began before a file's write settled may
/// have seen GitHub before the write landed, so its answer does not
/// overwrite that file. Kept on the app, not the review view, so a
/// refresh that replaces the view keeps the protection.
pr_viewed_touched: std::collections::HashMap<(String, String), u64>,
/// The pull request head review mode checked out (#365), removed again
/// when review is left with nothing in it worth keeping.
pr_checkout: Option<PrCheckout>,
/// A checkout still fetching: the PR number, and where the worktree
/// path and commit (or git's refusal) arrive.
pr_checkout_rx: Option<(u64, PrCheckoutRx)>,
review_tx: std::sync::mpsc::Sender<crate::review_ops::Outcome>,
review_rx: std::sync::mpsc::Receiver<crate::review_ops::Outcome>,
/// 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 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>,
/// The active file as it was at the scrubber's commit (#371): a separate
/// read-only editor painted in place of the live one, which is never
/// touched. `None` at the working tree.
pub scrub_view: Option<crate::widgets::editor::Editor>,
/// The file `scrub_view` was built for. Switching tabs while scrubbing
/// rebuilds the view for the new file rather than showing the old one's
/// history over it.
scrub_for: Option<PathBuf>,
/// The file and commit the OUTLINE currently shows while scrubbing
/// (#371), so it is recomputed once per step, and so leaving the
/// scrubber knows to bring the live file's outline back.
outline_scrub_key: Option<(PathBuf, String)>,
/// `a` in the approval popup (#347): the agent whose edits are
/// approved without asking, until when.
auto_approve: Option<(String, std::time::Instant)>,
/// The scrubber slider's track, from the last frame, and whether a
/// drag that started on it is under way (#371).
scrub_slider: Rect,
scrub_dragging: bool,
/// File text per (commit, workspace-relative path) for the scrubber;
/// `None` records that the file did not exist there.
scrub_cache: std::collections::HashMap<(String, String), Option<std::sync::Arc<str>>>,
/// Each scrubbed commit's tree under the workspace root, for the
/// Explorer's dimming (#371); `None` records that the listing failed.
scrub_trees: std::collections::HashMap<String, Option<std::sync::Arc<crate::git::CommitTree>>>,
/// Builds highlighted historical views off the UI thread (#371),
/// started on the first step.
scrub_builder: Option<crate::scrubber::ViewBuilder>,
/// Finished views near the scrubber's cursor, most recently used last,
/// at most `SCRUB_VIEWS_KEPT`.
scrub_views: crate::scrubber::KeptViews,
/// Plain stand-ins near the cursor, ready for the next step, likewise.
scrub_plain: crate::scrubber::KeptViews,
/// Each built view's outline, parsed with it off the UI thread, for the
/// OUTLINE to show while scrubbing. Dropped with the kept views.
scrub_outlines: std::collections::HashMap<
crate::scrubber::ViewKey,
Vec<crate::lsp::manager::OutlineSymbol>,
>,
/// What `scrub_view` shows, and whether it is the finished view rather
/// than the plain stand-in awaiting one.
scrub_view_key: Option<(crate::scrubber::ViewKey, bool)>,
/// The running `croft demo` tour (#377), with its scratch project and
/// the workspace to return to.
pub tour: Option<TourRun>,
/// The tour was finished or skipped once (#377), so the welcome panel
/// no longer offers it.
pub tour_done: bool,
/// The welcome panel's Take the Tour button, from the last frame.
pub welcome_tour_button: Rect,
/// The `gh` executable GitHub features run; tests point it at a stand-in.
gh_program: PathBuf,
/// The SARIF result a code scanning dismissal is for (#577): its log's
/// path and its run and result indices, marked suppressed on success.
dismiss_target: Option<(PathBuf, usize, usize)>,
/// The SARIF location a Locate prompt is open for (#577): its URI and
/// the 1-based line and column to land on.
sarif_locate_pending: Option<(String, i64, i64)>,
/// A SARIF source download in flight (#577): the location's URI, its
/// 1-based line and column, and the body or why it failed.
sarif_download: Option<std::sync::mpsc::Receiver<SarifDownload>>,
/// Fetches a URL's body; a field so tests can stand in for the network.
sarif_fetch: fn(&str) -> Result<Vec<u8>, String>,
/// 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,
/// Where the ledger is saved per workspace (#345); `None` keeps it in
/// memory only (tests, unless one sets it).
agent_ledger_store: Option<PathBuf>,
/// The ledger generation last saved, and when.
agent_ledger_saved: (u64, std::time::Instant),
/// The (agent, file) behind each row of the lane-file picker.
pending_lane_picks: Vec<(String, PathBuf)>,
/// 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>,
/// Whether croft asked the terminal for the kitty keyboard protocol at
/// startup (what `croft keys` reports as `kitty=`). A terminal that
/// honours it reports `Shift` held with `Ctrl` explicitly, so
/// `Ctrl+Shift+S` can be told from `Ctrl+S` (#857); one that ignores it
/// sends the same control byte for both, never a `Shift`. False until
/// `run` asks.
kitty_keys: bool,
/// 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>,
/// The Settings editor (#612).
settings_editor: Option<crate::widgets::settings_editor::SettingsEditor>,
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,
/// The status message's own cells; a click opens the Messages output
/// channel, where every message is kept in full (#1609).
status_message_rect: Rect,
/// The last status message logged to the Messages channel, so each one
/// is logged once, when it first shows (#1609).
status_logged: String,
/// A new status message is showing and nothing has been pressed since,
/// so a message too long for the room left by the right-hand cluster
/// (Ln/Col, encoding, language) takes the whole bar (#1609). The next
/// key or click hands the room back.
status_wide: bool,
/// The running CodeQL query's status-bar chip; a click cancels it (#578).
status_codeql_rect: Rect,
/// The croft update pills ("Update ready", the drift rebuild hint); a
/// click does what the updater chord does (#865).
status_update_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>,
/// True while this croft has stopped its language servers because a
/// source build of croft is compiling on the same host (#694), so the
/// servers are restarted once it ends. Only a remote-launched croft
/// ever sets it.
lsp_paused_for_build: bool,
/// When the build marker was last checked: it is a file read, so at
/// most once a second rather than every loop iteration.
build_marker_checked: Option<std::time::Instant>,
/// 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 "Ctrl+Shift+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 the updater for a retry
/// instead of silently dropping the offer.
local_drift: Option<String>,
/// Background `cargo install --path <repo>` reinstalling the local
/// croft after the user took the drift hint's offer. 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>,
/// A check the user asked for with Help: Update croft when nothing was
/// on offer (#1844), and how it asks the network (stubbed in tests).
manual_update_check: Option<crate::update_check::ManualCheck>,
update_fetch: fn() -> Result<Option<String>, String>,
/// The "vX available" popup, present from the offer landing until the
/// user picks Update, Later, or (once staged) Relaunch.
update_toast: Option<UpdateToast>,
/// Whether this binary may update itself, or belongs to a package
/// manager that must do it (#375). Read once at startup.
install_source: crate::update_check::InstallSource,
/// 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,
/// Whether a restore brings back plain panes whose shells have ended as
/// fresh shells (#1458): only over SSH, where a dropped connection should
/// come back to its panel. Locally they would return empty, so they stay
/// closed.
pub terminal_restore_respawns: bool,
/// 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`.
/// The debug sessions in flight, one FOCUSED (#310). Was a bare
/// `Option`, which made "the session" the only thing a call site could
/// mean; a compound needs several, so every site now says whether it
/// means the focused one or all of them.
pub debug_sessions: crate::dap::session::DebugSessions,
/// 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>,
/// The configuration **Debug: Add Configuration…** is building (#250),
/// between its steps.
debug_config_draft: Option<crate::dap::configs::ConfigDraft>,
/// 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>,
/// Name of the compound F5 starts, when the last picker launch was a
/// compound. Exclusive with `selected_debug_config`: a compound and a
/// configuration may share a name, so one string cannot say which (#567).
selected_debug_compound: Option<String>,
/// The launched compound asked for `stopAll: true` (#567): the first
/// member to end stops the rest. Set on every compound launch, so a
/// single-config launch (one session, no siblings) never reads a stale
/// value in a way that matters.
debug_stop_all: bool,
/// The `postDebugTask`s of the configurations launched into the current
/// run (#250), run once each when the run ends: the user stops it, or
/// the last session terminates. A new launch starts a fresh list.
debug_post_tasks: Vec<String>,
/// The running compound's name, kept past launch so the report rebuilt
/// when one member ends can still say which compound is live (#567).
debug_compound: 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>,
/// An attach launch waiting for the user to pick its process (#250):
/// the resolved config and where it launches once `processId` is known.
pending_attach: Option<(crate::dap::configs::ResolvedConfig, LaunchSlot)>,
/// 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>,
/// CodeLLDB `cargo` launches building their programs on background
/// threads (#1392): each receiver yields the executable (or the build
/// error), and its config launches into its slot when it lands. One per
/// compound member that builds; Stop Debugging drops them all.
pending_cargo_launches: Vec<PendingCargoLaunch>,
/// 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,
/// The stale-client notice the current roster warrants (#626, #652), so
/// it is raised once when it changes, not on every roster churn.
session_stale_notice: Option<String>,
/// 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>>>,
/// Test seam: the kernel bridge Select Kernel starts, by kernel name
/// (the real one runs Python).
#[cfg(test)]
#[allow(clippy::type_complexity)]
kernel_start_override: Option<Box<dyn Fn(&str) -> crate::notebook_kernel::KernelSession>>,
/// 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>>,
/// The HEAD a warned Undo Last Commit (#1350) is armed for: a commit
/// already on its upstream is undone on the second ask at that HEAD.
undo_pushed_commit_armed: Option<String>,
/// 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;
/// While only the text changes, the minimap image is re-baked at most this
/// often: each bake is a fresh PNG of the whole strip (#682).
const MINIMAP_EDIT_REBAKE: std::time::Duration = std::time::Duration::from_millis(300);
/// 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;
/// Source characters folded into one braille dot column of the text minimap,
/// so the 6-cell strip spans 48 columns of code, like the image's 1px a char.
const MINIMAP_TEXT_CHARS_PER_DOT: u32 = 4;
/// One cell of the text minimap: its braille glyph and ink colour, or `None`
/// for a blank cell.
type BrailleCell = Option<(char, (u8, u8, u8))>;
/// Fold a minimap raster into braille cells for terminals that cannot draw
/// images (#1231): each cell is 2x4 dots, each dot `MINIMAP_TEXT_CHARS_PER_DOT`
/// raster columns wide and one raster row tall, lit when any of its pixels is
/// ink (not `bg`). A cell takes the colour of its first lit pixel. Cells come
/// back row-major, `cell_w` to a row.
fn braille_minimap(
rgba: &[u8],
w: u32,
h: u32,
bg: (u8, u8, u8),
cell_w: u16,
cell_h: u16,
) -> Vec<BrailleCell> {
// Braille dot bits by (dot column, dot row), U+2800 + bits.
const BITS: [[u8; 4]; 2] = [[0x01, 0x02, 0x04, 0x40], [0x08, 0x10, 0x20, 0x80]];
let xs = MINIMAP_TEXT_CHARS_PER_DOT;
let ink = |x: u32, y: u32| -> Option<(u8, u8, u8)> {
if x >= w || y >= h {
return None;
}
let i = ((y * w + x) * 4) as usize;
let px = (rgba[i], rgba[i + 1], rgba[i + 2]);
(px != bg).then_some(px)
};
let mut cells = Vec::with_capacity(cell_w as usize * cell_h as usize);
for cy in 0..cell_h as u32 {
for cx in 0..cell_w as u32 {
let mut bits = 0u8;
let mut colour = None;
for (dx, column) in BITS.iter().enumerate() {
for (dy, bit) in column.iter().enumerate() {
let y = cy * 4 + dy as u32;
let x0 = (cx * 2 + dx as u32) * xs;
if let Some(px) = (x0..x0 + xs).find_map(|x| ink(x, y)) {
bits |= bit;
colour.get_or_insert(px);
}
}
}
cells.push(colour.map(|c| (char::from_u32(0x2800 + bits as u32).unwrap_or(' '), c)));
}
}
cells
}
/// 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, lines drawn,
/// highlight generation) — a change rebakes. The lines drawn tell a
/// symbol tab (#369) from its file's tab; the highlight generation moves
/// when a syntax pass lands after its edit (#850).
sig: MinimapSig,
}
type MinimapSig = (
Option<PathBuf>,
u64,
u32,
u32,
(u8, u8, u8),
(usize, usize),
u64,
);
/// 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,
/// The editor's `highlight_generation`: a background syntax pass that
/// lands after the edit (#850) recolors the strip.
highlight_generation: 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)>,
/// Which document and which of its lines the strip draws: a hash of
/// the path (no per-frame allocation) and the drawn span, so switching
/// between two tabs whose other fields agree (two same-length symbol
/// tabs, #369, or two same-length files) still re-emits. A tab without
/// a path is only ever the empty fallback left by closing the last
/// tab, whose strip is the same for every one.
doc: (u64, (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>> {
use image::ImageEncoder as _;
use image::codecs::png::{CompressionType, FilterType, PngEncoder};
if rgba.len() != (w as usize) * (h as usize) * 4 {
return None;
}
// Best compression with adaptive filters: the minimap is a small strip
// of flat colour runs, so this costs well under a millisecond and makes
// each bake about a quarter the size, which is what SSH carries (#682).
let mut out = Vec::new();
PngEncoder::new_with_quality(&mut out, CompressionType::Best, FilterType::Adaptive)
.write_image(&rgba, w, h, image::ExtendedColorType::Rgba8)
.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;
/// Two Escapes in Zen Mode this close together leave it (#1585), the
/// double-press window croft's clicks use too.
const ZEN_ESC_WINDOW: std::time::Duration = std::time::Duration::from_millis(500);
/// How long the "how to leave Zen" hint shows after entering it (#1585).
const ZEN_HINT_FOR: std::time::Duration = std::time::Duration::from_secs(4);
/// 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>,
}
/// A finished SARIF source download (#577).
struct SarifDownload {
uri: String,
/// 1-based position to open at.
line: i64,
col: i64,
body: Result<Vec<u8>, String>,
}
/// GET `url`'s body, up to 64 MiB, for a SARIF location's source.
fn fetch_sarif_source(url: &str) -> Result<Vec<u8>, String> {
use std::io::Read;
let resp = ureq::AgentBuilder::new()
.timeout(std::time::Duration::from_secs(30))
.build()
.get(url)
.set("User-Agent", concat!("croft/", env!("CARGO_PKG_VERSION")))
.call()
.map_err(|e| match e {
ureq::Error::Status(404, _) => String::from("not found (a private repository?)"),
ureq::Error::Status(code, _) => format!("HTTP {code}"),
other => other.to_string(),
})?;
let mut bytes = Vec::new();
resp.into_reader()
.take(64 << 20)
.read_to_end(&mut bytes)
.map_err(|e| e.to_string())?;
Ok(bytes)
}
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,
}
}
/// The config files the [`crate::config_sync::ConfigWatch`] checks for
/// changes made outside croft: the fixed ones, then every file of the
/// settings chain (#1435), so a `git pull` of `.croft/config.json`, an edit
/// in vim, or a dotfiles sync applies like a save from inside croft.
fn config_watch_paths(settings_chain: &[PathBuf]) -> Vec<PathBuf> {
let mut paths = vec![
crate::keymap::keybindings_path(),
crate::snippets::snippets_path(),
crate::triggers::triggers_path(),
crate::problem_matchers::matchers_path(),
crate::macros::macros_path(),
// The settings layer config sync brings from the connecting
// machine (#262): applied on arrival like the files above.
crate::config_layers::synced_config_path(),
];
for path in settings_chain {
if !paths.contains(path) {
paths.push(path.clone());
}
}
paths
}
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));
// The active profile (#618) decides which settings, keybindings and
// snippets files are read below, so it is chosen first. Never under
// test: a developer's own profile choice must not leak into the suite.
if !cfg!(test) {
crate::profiles::activate_for_workspace(&root);
}
// 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();
let (review_tx, review_rx) = std::sync::mpsc::channel();
let data_dir =
(!cfg!(test)).then(|| user_data_dir(&croft_cache_dir(), &crate::prefs::state_dir()));
let notes_path = data_dir
.as_deref()
.map(|dir| crate::sticky_notes::Notes::store_path(dir, &root));
if !cfg!(test) {
crate::i18n::init(loaded_prefs.locale.as_deref());
}
// 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 (codeql_size_tx, codeql_size_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();
// A second croft on the same workspace finds the socket live and
// leaves it to the first: one editor answers a workspace's agents.
let (hook_listener, hook_bind_error) = if cfg!(test) {
(None, None)
} else {
match crate::agent_approval::bind(&root) {
Ok(listener) => (Some(listener), None),
Err(e) => (None, hook_bind_status(&e)),
}
};
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(),
codeql: crate::widgets::codeql::CodeqlPanel::new(),
test_worker: crate::testing::worker::TestWorker::spawn(root.clone()),
test_run_status: None,
last_test_run: None,
pane_run_statuses: Vec::new(),
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,
tab_click_target: 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(),
config_watch: crate::config_sync::ConfigWatch::new(config_watch_paths(
&merged_settings.chain,
)),
snippets: load_snippets(&crate::snippets::snippets_path()),
format_on_save: loaded_prefs.format_on_save,
default_formatter: loaded_prefs.default_formatter.clone(),
language_formatters: loaded_prefs.language_formatters.clone(),
foreign_formatters_noted: std::collections::BTreeSet::new(),
language_prefs: loaded_prefs.languages.clone(),
copy_on_select: loaded_prefs.copy_on_select,
files_exclude: Vec::new(),
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,
prettier_job: None,
format_save_deadline: None,
outline,
open_editors,
timeline,
agent_lane_panel: crate::widgets::agent_lane::AgentLanePanel::new(),
lane_change_counts: std::collections::HashMap::new(),
dependencies,
dep_ecosystems,
explorer_views,
settings_chain: merged_settings.chain,
settings_provenance: merged_settings.provenance,
timeline_rx,
timeline_tx,
codeql_size_rx,
codeql_size_tx,
codeql_size_pending: std::collections::HashSet::new(),
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,
nested_repo_scan: None,
blame_rx,
blame_tx,
blame_fetched: None,
git_net_job: None,
git_view_job: None,
vim_mode_pref: false,
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,
save_before_debug: !loaded_prefs.disable_save_before_debug,
auto_close_pairs: !loaded_prefs.disable_auto_close_pairs,
paste_reindent: !loaded_prefs.disable_paste_reindent,
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,
centered_layout: layout_prefs.centered_layout,
zen_center_layout: layout_prefs.zen_center_layout,
zen_centered: false,
centered_layout_width: layout_prefs.centered_layout_width,
zen_esc_at: None,
zen_hint_until: None,
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: match hook_bind_error {
Some(hook) if view_bind_error.is_none() => hook,
_ => 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,
breakpoint_lane_press: 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,
codeql_program: PathBuf::from("codeql"),
codeql_run: None,
codeql_cancel: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
codeql_run_name: String::new(),
codeql_run_queue: std::collections::VecDeque::new(),
codeql_batch: (0, 0),
codeql_multi_db: None,
codeql_upgrade: None,
codeql_version: None,
codeql_log_summary: None,
codeql_log_viewer: None,
codeql_model_job: None,
codeql_perf_compare: None,
codeql_query_help: None,
codeql_pack_job: None,
codeql_db_job: None,
codeql_ast_job: None,
codeql_doc_job: None,
codeql_results_walk: None,
codeql_cli_setting: loaded_prefs.codeql_cli_path.clone(),
codeql_cli_source: crate::codeql_cli::Source::Fallback,
codeql_cli_latest: None,
codeql_cli_download: None,
codeql_cli_check: None,
codeql_cli_net: crate::codeql_cli::Net::default(),
codeql_code_search: None,
codeql_variant_submit: None,
codeql_variant_poll: None,
codeql_variant_polled: None,
codeql_variant_results: None,
codeql_variant_export: None,
codeql_queries_job: None,
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_baked_at: None,
minimap_edit_pending: false,
minimap_text: false,
minimap_text_cache: None,
minimap_room: true,
drawn_buffer: None,
chrome_sent: std::collections::HashMap::new(),
chrome_seen: std::collections::HashSet::new(),
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(),
code_scanning: loaded_prefs.code_scanning,
code_scan_seen: None,
code_scan_list: None,
code_scan_fetch: None,
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(),
color_depth: loaded_prefs
.color_depth
.as_deref()
.and_then(crate::color_depth::ColorDepth::from_setting)
.unwrap_or_else(|| {
crate::color_depth::ColorDepth::detect(|name| std::env::var(name).ok())
}),
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,
hook_listener,
hook_root: root.clone(),
approvals: std::collections::VecDeque::new(),
approval_check: None,
approval_ui: None,
approval_edit: None,
approval_merge_into: None,
notebook_kernels: std::collections::HashMap::new(),
kernel_listing: None,
kernel_choice: None,
coverage_at: None,
coverage_lens_path: None,
coverage_install: None,
view_drain_budget: std::time::Duration::from_millis(20),
pending_local_open: None,
pending_discard: None,
pending_unsaved_scm: None,
remote_tag_root: None,
scm_unsaved_cleared: false,
scm_after_format_save: None,
pending_revert_hunk: None,
pending_unsaved: None,
remote_handoff_ok: None,
hot_exit_dir: data_dir.as_deref().map(|dir| dir.join("hot-exit")),
hot_exit_written: None,
hot_exit_retry_at: None,
hot_exit_consumed: Vec::new(),
hot_exit_unremoved: Vec::new(),
exit_notes: Vec::new(),
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,
editor_tab_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,
fleet_command: String::new(),
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(),
markdown_lint_last_seen: std::collections::HashMap::new(),
live_run_files: std::collections::HashSet::new(),
live_run_sent: std::collections::HashMap::new(),
live_run_runner: None,
md_scroll_synced: None,
code_lens_enabled: true,
function_breakpoints: Vec::new(),
screen_reader: loaded_prefs.screen_reader,
screen_reader_command: loaded_prefs.screen_reader_command.clone(),
announcer: crate::a11y::Announcer::default(),
announce_pos: None,
term_suggest_enabled: true,
term_suggestion: None,
recording_shortcut: None,
confirming_shortcut: None,
inline_enabled: false,
inline_worker: None,
inline_config: None,
inline_job: None,
inline_asked: None,
inline_next_id: 0,
keybindings_file: if cfg!(test) {
std::env::temp_dir().join(format!(
"croft-test-keybindings-{}-{}.json",
std::process::id(),
TEST_KEYBINDINGS_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
))
} else {
crate::keymap::keybindings_path()
},
search_editor_job: None,
code_lens_requested: std::collections::HashMap::new(),
sarif_diag_signature: Vec::new(),
sarif_added_polled: None,
sarif_step_signature: None,
sarif_published: Vec::new(),
lsp_progress: std::collections::HashMap::new(),
completion_popup: None,
editor_vim_chord: EditorVimChord::default(),
cmd_k_leader: None,
kitty_keys: false,
vim: crate::vim::VimState::new(),
vim_last_find: None,
vim_visual_line: false,
shortcuts_modal: None,
settings_editor: None,
shortcuts_hit_rect: None,
status_diag_rect: Rect::default(),
status_message_rect: Rect::default(),
status_logged: String::new(),
status_wide: false,
status_codeql_rect: Rect::default(),
status_update_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,
lsp_paused_for_build: false,
build_marker_checked: None,
drift_probe: None,
local_drift: None,
self_install: None,
update_check: None,
manual_update_check: None,
update_fetch: if cfg!(test) {
|| Err(String::from("tests never ask the network"))
} else {
crate::update_check::fetch_latest_checked
},
update_toast: None,
install_source: crate::update_check::current_install_source(),
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_restore_respawns: crate::remote::running_over_ssh(),
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,
debug_sessions: Default::default(),
debug_configs: Vec::new(),
debug_config_draft: None,
debug_compounds: Vec::new(),
selected_debug_config: None,
selected_debug_compound: None,
debug_stop_all: false,
debug_post_tasks: Vec::new(),
debug_compound: None,
pending_debug_launch: None,
pending_attach: None,
pending_test_debug: None,
pending_cargo_launches: Vec::new(),
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_stale_notice: None,
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,
#[cfg(test)]
kernel_start_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(),
undo_pushed_commit_armed: None,
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,
completion_origin: None,
completion_incomplete: false,
completion_reask_due: false,
completion_words: false,
local_completion_seq: u64::MAX,
word_suggestions: crate::word_suggest::WordSuggestions::from_pref(
&loaded_prefs.word_based_suggestions,
),
signature_help_popup: None,
signature_help_request_id: None,
signature_help_anchor: None,
rename_request_id: None,
rename_baseline: Vec::new(),
pending_file_move: None,
prepare_rename_request: None,
format_request_id: None,
format_request_seq: 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,
code_action_baseline: Vec::new(),
pending_code_actions: Vec::new(),
review_boxes: None,
review_pending: Vec::new(),
review_pending_pr: None,
review_submitting: false,
notes: notes_path
.as_deref()
.map(crate::sticky_notes::Notes::load)
.unwrap_or_default(),
notes_path,
note_box_ids: std::collections::HashMap::new(),
notes_shown_gen: 0,
review_export: None,
review_export_sticky: Vec::new(),
review_export_pr: None,
review_ai_prefix: loaded_prefs
.review_ai_prefix
.clone()
.unwrap_or_else(|| String::from(crate::review_threads::DEFAULT_AI_PREFIX)),
review_pr: None,
review_pr_branch: None,
review_nodes: std::collections::HashMap::new(),
review_verdict: None,
review_gh: String::from("gh"),
pr_gh: None,
pr_checks_polled: None,
pr_viewed_fetch: None,
pr_viewed_queue: std::collections::VecDeque::new(),
pr_viewed_write: None,
pr_viewed_seq: 0,
pr_viewed_touched: std::collections::HashMap::new(),
pr_checkout: None,
pr_checkout_rx: None,
review_tx,
review_rx,
recording: None,
recorded_size: (0, 0),
scrubber: None,
scrub_view: None,
scrub_for: None,
outline_scrub_key: None,
auto_approve: None,
scrub_slider: Rect::default(),
scrub_dragging: false,
scrub_cache: std::collections::HashMap::new(),
scrub_trees: std::collections::HashMap::new(),
scrub_builder: None,
scrub_views: std::collections::VecDeque::new(),
scrub_plain: std::collections::VecDeque::new(),
scrub_outlines: std::collections::HashMap::new(),
scrub_view_key: None,
tour: None,
tour_done: loaded_prefs.tour_done,
welcome_tour_button: Rect::default(),
gh_program: PathBuf::from("gh"),
dismiss_target: None,
sarif_locate_pending: None,
sarif_download: None,
sarif_fetch: fetch_sarif_source,
debug_temp_breakpoint: None,
debug_temp_note: None,
agent_ledger: crate::agent_lane::AgentLedger::new(),
agent_ledger_store: (!cfg!(test)).then(agent_ledger_store_path),
agent_ledger_saved: (0, std::time::Instant::now()),
pending_lane_picks: Vec::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,
peek_refs: None,
references_want_peek: false,
outline_synced: None,
outline_parse: None,
outline_parsed_for: None,
outline_lsp_landed: 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(),
linked_asked: false,
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.
// #1286: start in Vim mode when it was saved as the default.
app.follow_vim_mode_pref(loaded_prefs.vim_mode);
// #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);
// #578: the Testing view runs CodeQL tests with the same `codeql`
// as the side bar, from the first tree click on. Tests keep plain
// `codeql` rather than whatever the machine has installed.
if cfg!(test) {
app.test_worker
.set_codeql_program(app.codeql_program.clone());
} else {
app.resolve_codeql_cli();
}
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();
}
// The agent review queue as this workspace last left it (#345).
let root = app.workspace_root().to_path_buf();
app.apply_project_excludes(&loaded_prefs);
app.agent_ledger = app.load_agent_ledger(&root);
app.sync_agent_lane_decorations();
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) =
cell_pixel_of(ws.columns, ws.rows, ws.width, ws.height).unwrap_or(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((cqa, cqi, cqh)),
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::CODEQL_SRC_SVG, 0, ki::KITTY_ID_CODEQL),
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,
codeql_active: cqa,
codeql_inactive: cqi,
codeql_hovered: cqh,
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().map(str::to_owned) else {
return;
};
let at = Rect {
x: cx,
y: cy,
width: crate::widgets::run_debug::RUN_DEBUG_ICON_CELLS_W,
height: crate::widgets::run_debug::RUN_DEBUG_ICON_CELLS_H,
};
if !self.chrome_image_due("run_debug", &osc, at) {
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().map(str::to_owned) else {
return;
};
let at = Rect {
x: cx,
y: cy,
width: crate::iterm2_inline::count_badge_cells_w(self.problems_badge_count),
height: 1,
};
if !self.chrome_image_due("problems_badge", &osc, at) {
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().map(str::to_owned) else {
return;
};
if !self.chrome_image_due("hero", &osc, hero) {
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().map(str::to_owned) else {
return;
};
let at = Rect {
x: cx,
y: cy,
width: crate::widgets::remote::SSH_EMPTY_STATE_CELLS_W,
height: crate::widgets::remote::SSH_EMPTY_STATE_CELLS_H,
};
if !self.chrome_image_due("ssh", &osc, at) {
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;
// A font zoom resizes the cells, not only the grid. Every inline
// image was baked for the old cell size, and a sixel image is sized
// in pixels, so it would outgrow its cells and paint over its
// neighbours: the welcome logo over the version badge (#1843).
if let Some(cell) = self.cell_pixel
&& let Ok(ws) = crossterm::terminal::window_size()
&& cell_pixel_of(ws.columns, ws.rows, ws.width, ws.height)
.is_some_and(|now| now != cell)
{
self.rebake_inline_images();
}
}
/// 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;
// Optional: absent while CodeQL is disabled, so not part of the
// all-or-nothing readiness below.
let cql_block = self.sidebar_areas.codeql_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
};
let cql_state = if self.sidebar_view == SidebarView::CodeQL {
&images.codeql_active
} else if hov == Some(ActivityIcon::CodeQL) {
&images.codeql_hovered
} else {
&images.codeql_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 cql_block.width > 0 {
blocks.push((cql_block, cql_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(_))
)
})
})
}
/// Only iTerm2 evicts cached images, so only there do the activity
/// icons need re-sending while nothing changed.
fn activity_keepalive_allowed(&self) -> bool {
self.inline_protocol == crate::iterm2_inline::InlineImageProtocol::ITerm2
}
/// 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, around: &[u64]) {
use std::io::Write;
// The keepalive re-emit fights iTerm2's image-cache eviction. Neither
// the sixel cell buffer nor Kitty's image layer evicts, so there the
// icons re-emit only when dirty: on Kitty the keepalive cost about
// 13 KB every two seconds, idle, over SSH (#682).
let dirty = self.overlays.activity.dirty();
let allow_keepalive = self.activity_keepalive_allowed()
&& (0..around.len()).any(|i| self.overlays.activity.neighbourhood_changed(i, around));
if !self.overlays.activity.should_refresh(allow_keepalive) {
return;
}
let mut 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();
self.overlays.activity.forget_sent();
return;
}
let hashes: Vec<u64> = overlays
.iter()
.map(|(_, seq)| {
use std::hash::{Hash, Hasher};
let mut h = std::collections::hash_map::DefaultHasher::new();
seq.hash(&mut h);
h.finish()
})
.collect();
let sent: Vec<((u16, u16), u64)> = positions.iter().copied().zip(hashes).collect();
// Everything goes out after a wipe or on the first frame. Otherwise
// a dirty flush sends only the slots whose cell or image changed,
// and a keepalive only the icons whose surroundings changed (`around`
// is in the order of the unchanged positions).
if !self.overlays.activity.nothing_sent() {
let same = positions.as_slice() == self.overlays.activity.last_positions();
let mut i = 0;
overlays.retain(|_| {
let keep = if dirty {
!self.overlays.activity.was_sent(sent[i].0, sent[i].1)
} else {
same && self.overlays.activity.neighbourhood_changed(i, around)
};
i += 1;
keep
});
}
if overlays.is_empty() {
self.overlays.activity.mark_emitted();
self.overlays.activity.store_positions(positions);
self.overlays.activity.set_neighbourhood(around.to_vec());
self.overlays.activity.set_sent(sent);
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);
self.overlays.activity.set_neighbourhood(around.to_vec());
self.overlays.activity.set_sent(sent);
}
/// 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 {
// A screen reader follows the cursor; one that vanishes half the
// time is lost half the time.
self.screen_reader || 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);
}
/// 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;
}
// The active file changed on disk under a clean buffer: its coverage
// marks describe the old text now, so they dim like an edit's (#263).
if let Some(active) = self.editor.path.as_ref()
&& report.reloaded.contains(active)
&& let Some(lens) = self.editor.coverage.as_mut()
{
lens.stale = true;
}
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};
// It opens mid-typing and takes the keys, so nothing a stray Enter
// or a typed line can confirm discards the edits: only the word
// `reload` does, and the box says so (#910).
let title = match paths.as_slice() {
[one] => format!(
"{} changed on disk and you have unsaved edits.",
self.status_path(one)
),
many => format!(
"{} open files changed on disk with unsaved edits.",
many.len()
),
};
if self.input_prompt.is_some() {
self.status = title;
return;
}
self.open_input_prompt(
InputPrompt::new(
InputPurpose::ReloadConflict { paths },
title,
"type reload to discard your unsaved edits",
)
.with_hint("reload + Enter discards your edits · anything else keeps them"),
);
}
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();
self.tree.git_decorations = self.git.status().decorations.clone();
} else {
let mut union: std::collections::HashSet<PathBuf> =
self.git.status().ignored.as_ref().clone();
let mut decorations = self.git.status().decorations.as_ref().clone();
for (_, w) in &self.git_extra {
union.extend(w.status().ignored.iter().cloned());
// Roots can nest (a repo folder inside another root's
// tree), so a shared path keeps its strongest status.
for (path, &dec) in w.status().decorations.iter() {
let slot = decorations.entry(path.clone()).or_insert(dec);
*slot = (*slot).max(dec);
}
}
self.tree.ignored = std::sync::Arc::new(union);
self.tree.git_decorations = std::sync::Arc::new(decorations);
}
}
// 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, and Save All's "Saved N editors"
/// (#852).
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 {
// Clear the screen only if a badge was actually drawn: at start-up
// and on every graphics re-init the count goes from unknown to 0,
// and on iTerm2 a needless clear is a whole-screen repaint.
self.overlays.problems_badge.clear_image();
self.clear_problems_badge_if_emitted();
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.effective_exclude(),
));
let _ = self.search_query_tx.send(SearchRequest::Query(
self.search.query.clone(),
self.search.opts,
));
let term = if crate::widgets::search::as_typed(&self.search.query).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;
// Every batch waiting is merged in one pass (#1340).
let mut arrived = Vec::new();
while let Ok(event) = self.search_results_rx.try_recv() {
match event {
SearchEvent::Hits(q, opts, batch) => {
if q == self.search.query && opts.same_matching(&self.search.opts) {
arrived.extend(batch);
applied = true;
}
}
SearchEvent::Done(q, opts) => {
if q == self.search.query && opts.same_matching(&self.search.opts) {
self.search.complete = true;
applied = true;
}
}
}
}
self.search.add_hits(arrived);
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) {
let Some(lsp) = self.lsp.as_ref() else {
return;
};
// A language server that exited was restarted (#694). It knows no
// documents, so forget which ones were sent: every open tab goes out
// again as a fresh open below, as it does for a new manager.
if lsp.take_servers_restarted() {
self.lsp_last_seen.clear();
self.lsp_progress.clear();
}
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();
// A file and its symbol tabs (#369) share one group, each tab with
// its own `edit_seq`. One tab speaks for the path: the active tab
// when it holds that file (replies are applied where the seq
// matches), else the first. Judging each against the one
// `lsp_last_seen` entry made them take turns resending the whole
// text on every tick.
let active = self.editor.active_index();
let active_path = self
.editor
.path
.clone()
.filter(|_| !self.editor.has_non_text_view());
for (i, tab) in self.editor.iter_tabs().enumerate() {
if tab.has_non_text_view() {
continue;
}
let Some(path) = tab.path.as_ref() else {
continue;
};
if crate::lsp::Language::from_path(path).is_none() {
continue;
}
if i != active && active_path.as_ref() == Some(path) {
continue;
}
if !current.insert(path.clone()) {
continue;
}
// The server holds a proposal's text for this file while it is
// checked (#347); the buffer goes back when the check ends.
if self
.approval_check
.as_ref()
.is_some_and(|c| &c.path == path)
{
continue;
}
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) 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 doc_end = crate::lsp::manager::document_end(&text);
let viewport =
viewport.map(|(start, end)| (start, crate::lsp::manager::rows_end(&text, end)));
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_for(path_scope_id(&path)) {
lsp.request_inlay_hints(path.clone(), doc_end, 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();
// Reopening asks for its lenses again anyway.
self.code_lens_requested.remove(&p);
}
// 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);
}
}
}
}
/// Lints every open `.md` tab and folds the results into the same
/// diagnostics store a real language server writes to (`lsp_diagnostics`,
/// keyed by path then by "producer"), under the synthetic server name
/// `"Markdown Lint"`. It needs no language server, so it works the moment
/// a file opens and on a box where none could be installed. For a file
/// rumdl (#851) reports on, which covers these same rules among its own,
/// it stands down instead, so no violation is listed twice; a file rumdl
/// does not see (one shown only in a split's other group, which is not
/// sent to the language servers, or one rumdl stopped answering for)
/// keeps the built-in lint. Gated by its own
/// edit-seq cursor (`markdown_lint_last_seen`) so an unchanged buffer
/// isn't re-linted every tick. Returns whether any editor's overlay or
/// the PROBLEMS panel changed, for the caller's redraw decision.
pub fn sync_markdown_lint(&mut self) -> bool {
let mut current: std::collections::HashSet<PathBuf> = std::collections::HashSet::new();
let mut to_lint: Vec<(PathBuf, Vec<String>, u64)> = Vec::new();
let mut superseded: Vec<PathBuf> = Vec::new();
// Both collections: `self.editor` is the ACTIVE group's tabs, and a
// split's other panes live in `editor_layout`. Walking only the
// active one left a `.md` open in an inactive pane unlinted, and the
// `closed` sweep below then dropped its diagnostics as though the tab
// had gone - squiggles vanishing from a pane in plain sight.
let inactive_tabs: Vec<&crate::widgets::editor::Editor> = self
.editor_layout
.inactive_groups()
.into_iter()
.flat_map(|g| g.editors.iter())
.collect();
for tab in self.editor.iter_tabs().chain(inactive_tabs) {
if tab.has_non_text_view() {
continue;
}
let Some(path) = tab.path.as_ref() else {
continue;
};
if path.extension().and_then(|e| e.to_str()) != Some("md") {
continue;
}
// The same file can be open in several panes, each its own
// buffer with its own `edit_seq`. Only the FIRST tab seen for a
// path (the active group comes first) is compared: judging each
// pane against one shared cursor made two panes with different
// seqs take turns, re-linting and redrawing on every tick.
if !current.insert(path.clone()) {
continue;
}
if self.lsp.as_ref().is_some_and(|lsp| {
lsp.document_reported_by(path, crate::markdown_lint::SUPERSEDED_BY)
}) {
superseded.push(path.clone());
continue;
}
// The seq alone cannot tell two panes apart: each counts its own
// edits, so they can agree while holding different text. The
// lines last linted are kept too and compared when the seqs
// match (one comparison, no allocation), so switching to the
// other pane re-lints exactly when its text differs.
let seq = tab.edit_seq;
let seen = self
.markdown_lint_last_seen
.get(path)
.is_some_and(|(s, lines)| *s == seq && *lines == tab.lines);
if !seen {
to_lint.push((path.clone(), tab.lines.clone(), seq));
}
}
let mut changed = false;
for path in superseded {
changed |= self.withdraw_markdown_lint(&path);
}
for (path, lines, seq) in to_lint {
let diags = crate::markdown_lint::lint(&lines.join("\n"));
let by_server = self.lsp_diagnostics.entry(path.clone()).or_default();
if diags.is_empty() {
changed |= by_server.remove("Markdown Lint").is_some();
if by_server.is_empty() {
self.lsp_diagnostics.remove(&path);
}
} else if by_server.get("Markdown Lint") != Some(&diags) {
// Only a different set is a change: storing the same
// diagnostics again must not ask for a redraw.
by_server.insert("Markdown Lint".to_string(), diags);
changed = true;
}
self.markdown_lint_last_seen
.insert(path.clone(), (seq, lines));
let merged = self.merged_diagnostics(&path);
if self.editor.path.as_deref() == Some(path.as_path()) {
self.editor.apply_diagnostics(path.clone(), merged.clone());
}
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());
}
}
}
let closed: Vec<PathBuf> = self
.markdown_lint_last_seen
.keys()
.filter(|p| !current.contains(*p))
.cloned()
.collect();
for p in closed {
self.markdown_lint_last_seen.remove(&p);
if let Some(by_server) = self.lsp_diagnostics.get_mut(&p) {
changed |= by_server.remove("Markdown Lint").is_some();
if by_server.is_empty() {
self.lsp_diagnostics.remove(&p);
}
}
}
if changed {
self.rebuild_problems();
self.refresh_problems_badge();
}
changed
}
/// Withdraws what the built-in Markdown lint published for `path`, a
/// file rumdl reports on (#851), and repaints the tabs showing it. The
/// caller rebuilds PROBLEMS when this returns true. Forgetting the seen
/// cursor makes the lint run afresh on the file once rumdl stops
/// reporting on it.
fn withdraw_markdown_lint(&mut self, path: &Path) -> bool {
if self.markdown_lint_last_seen.remove(path).is_none() {
return false;
}
let Some(by_server) = self.lsp_diagnostics.get_mut(path) else {
return false;
};
if by_server.remove("Markdown Lint").is_none() {
return false;
}
if by_server.is_empty() {
self.lsp_diagnostics.remove(path);
}
let merged = self.merged_diagnostics(path);
if self.editor.path.as_deref() == Some(path) {
self.editor
.apply_diagnostics(path.to_path_buf(), merged.clone());
}
for group in self.editor_layout.inactive_groups_mut() {
if group.path.as_deref() == Some(path) {
group.apply_diagnostics(path.to_path_buf(), merged.clone());
}
}
true
}
/// Publish every open SARIF log's results as diagnostics (#577), and
/// withdraw what a closed log published. Recomputed only when the set of
/// open logs, or one of them on disk, changes; returns whether anything
/// did.
pub fn sync_sarif_diagnostics(&mut self) -> bool {
// Logs added to a viewer with `o` are read again when they change
// on disk (#577), at most once a second.
if self
.sarif_added_polled
.is_none_or(|t| t.elapsed() >= std::time::Duration::from_secs(1))
{
self.sarif_added_polled = Some(std::time::Instant::now());
let mut refreshed = 0;
for tab in self.editor.editors.iter_mut() {
if let Some(view) = tab.sarif.as_mut() {
refreshed += view.refresh_added_logs().len();
}
}
if refreshed > 0 {
// Their results are published again below.
self.sarif_diag_signature.clear();
self.status = format!(
"Reloaded {refreshed} changed SARIF log{}",
if refreshed == 1 { "" } else { "s" }
);
}
}
let inactive: Vec<&crate::widgets::editor::Editor> = self
.editor_layout
.inactive_groups()
.into_iter()
.flat_map(|g| g.editors.iter())
.collect();
let mut signature: Vec<(PathBuf, Option<(std::time::SystemTime, u64)>)> = self
.editor
.iter_tabs()
.chain(inactive)
.filter(|t| t.sarif.is_some())
.filter_map(|t| Some((t.path.clone()?, t.disk_stamp())))
.collect();
signature.sort();
signature.dedup_by(|a, b| a.0 == b.0);
if signature == self.sarif_diag_signature {
return false;
}
self.sarif_diag_signature = signature.clone();
// Withdraw everything published before, then publish afresh.
let mut touched: std::collections::HashSet<PathBuf> = std::collections::HashSet::new();
for (target, key) in std::mem::take(&mut self.sarif_published) {
if let Some(by_source) = self.lsp_diagnostics.get_mut(&target) {
by_source.remove(&key);
if by_source.is_empty() {
self.lsp_diagnostics.remove(&target);
}
}
touched.insert(target);
}
let root = self.workspace_root().to_path_buf();
let mut file_lines: std::collections::HashMap<PathBuf, Vec<String>> =
std::collections::HashMap::new();
let mut line_of = |p: &std::path::Path, n: usize| -> Option<String> {
file_lines
.entry(p.to_path_buf())
.or_insert_with(|| {
std::fs::read_to_string(p)
.map(|t| t.lines().map(str::to_string).collect())
.unwrap_or_default()
})
.get(n)
.cloned()
};
let mut published: std::collections::HashMap<
(PathBuf, String),
Vec<crate::lsp::manager::Diagnostic>,
> = std::collections::HashMap::new();
let views: Vec<&crate::sarif::view::SarifView> = self
.editor
.iter_tabs()
.chain(
self.editor_layout
.inactive_groups()
.into_iter()
.flat_map(|g| g.editors.iter()),
)
.filter_map(|t| t.sarif.as_ref())
.collect();
let mut seen_logs = std::collections::HashSet::new();
for view in views {
for (index, loaded) in view.logs.iter().enumerate() {
// What the baseline reported is history, not today's code.
if view.baseline == Some(index) || !seen_logs.insert(loaded.path.clone()) {
continue;
}
let mut roots = vec![root.clone()];
if let Some(dir) = loaded.path.parent() {
roots.push(dir.to_path_buf());
}
let resolver = crate::sarif::resolve::Resolver {
roots,
learned: crate::sarif::resolve::saved_prefixes(self.workspace_root()),
open: self.open_file_paths(),
..Default::default()
};
let log_index = view.logs.iter().position(|l| l.path == loaded.path);
for (run_i, run) in loaded.log.runs.iter().enumerate() {
let key = crate::sarif::diagnostics::source_key(run);
for (result_i, result) in run.results.iter().flatten().enumerate() {
// A fixed result no longer squiggles.
if view.entries.iter().any(|e| {
Some(e.log) == log_index
&& e.run == run_i
&& e.result == result_i
&& e.fixed
}) {
continue;
}
if let Some((target, d)) = crate::sarif::diagnostics::diagnostic_for(
run,
result,
&resolver,
&mut line_of,
) {
published.entry((target, key.clone())).or_default().push(d);
}
}
}
}
}
for ((target, key), diags) in published {
self.lsp_diagnostics
.entry(target.clone())
.or_default()
.insert(key.clone(), diags);
self.sarif_published.push((target.clone(), key));
touched.insert(target);
}
for path in touched {
let merged = self.merged_diagnostics(&path);
if self.editor.path.as_deref() == Some(path.as_path()) {
self.editor.apply_diagnostics(path.clone(), merged.clone());
}
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());
}
}
}
self.rebuild_problems();
self.refresh_problems_badge();
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()
}
/// Every workspace folder as `(name, root)`, for a compound member's
/// `"folder"` and `${workspaceFolder:name}` (#1425).
fn workspace_folders(&self) -> Vec<(String, PathBuf)> {
crate::dap::configs::workspace_folders(self.roots.iter())
}
/// Feed the Source Control empty state the repos one folder below the
/// active root when that root is in none (#1227), so it offers to open
/// them rather than `git init` around them. A depth-1 `read_dir`,
/// rerun at most every two seconds while the card shows.
fn sync_nested_repos(&mut self) {
if self.source_control.status.in_repo {
self.source_control.nested_repos.clear();
self.nested_repo_scan = None;
return;
}
let root = self.active_scm_root.clone();
let fresh = self
.nested_repo_scan
.as_ref()
.is_some_and(|(r, at)| *r == root && at.elapsed() < Duration::from_secs(2));
if fresh {
return;
}
self.source_control.nested_repos = crate::git::child_repos(&root)
.into_iter()
.filter_map(|p| {
let name = p.file_name()?.to_string_lossy().into_owned();
Some((format!("{name}/"), p))
})
.collect();
self.nested_repo_scan = Some((root, std::time::Instant::now()));
}
/// 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.
// A root in no repo (or with no status reply yet) maps to `None`,
// and the file's own repo is asked instead: a workspace opened
// above its repo still gets gutters (#1227).
let repo_bases: Vec<(PathBuf, Option<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();
(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())
.and_then(|(_, repo)| repo.clone())
.or_else(|| path.parent().and_then(crate::git::repo_toplevel))
};
// Keyed by encoding too: the same file open in two tabs under two
// encodings needs HEAD decoded each tab's way (#1242).
let mut fetched: std::collections::HashMap<
(PathBuf, &str),
Option<crate::packed_lines::PackedLines>,
> = 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 enc = ed.encoding;
let head = fetched
.entry((path.clone(), enc.name()))
.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_bytes_at_head(&root, rel).ok())
.and_then(|bytes| crate::widgets::editor::decode_blob(&bytes, enc))
.map(|text| text.lines().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_for(editor_scope_id(&self.editor));
self.editor.whitespace_mode = whitespace_mode_in(
&self.language_prefs,
self.whitespace_mode,
editor_scope_id(&self.editor),
);
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 mut changed = false;
while let Some(result) = self.lsp.as_ref().and_then(|lsp| lsp.drain_completion()) {
changed |= self.apply_completion_result(result);
}
changed
}
/// Open the popup for one completion reply; the drain loop delegates here
/// because the reply channel's sender lives inside the LSP worker. Returns
/// true when the popup state changed.
fn apply_completion_result(&mut self, result: crate::lsp::manager::CompletionResult) -> bool {
if Some(result.request_id) != self.completion_request_id {
return false;
}
// A matching id is not enough: nothing but the open popup clears the
// id, so a reply that lands after an Enter moved the caret would open
// on the next line with an empty prefix, and the next Enter accepted
// its first item instead of breaking the line (#842).
if !self.completion_origin_covers_caret(&result.path) {
self.completion_request_id = None;
return false;
}
self.completion_incomplete = result.is_incomplete;
let Some((cx, cy)) = self.editor.cursor_screen_pos() else {
return false;
};
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;
// A server with nothing to offer, or none at all, leaves the words
// of the open documents, as VS Code's word-based suggestions do
// (#1566). A server's own list is never mixed with them.
let words = self.completion_words && items.is_empty();
if words {
// An empty reply to an ask already showing its words (the
// manager answering for a file no server took) changes nothing:
// rebuilding would only drop the user's place in the list.
if self
.completion_popup
.as_ref()
.is_some_and(|p| p.request_id == result.request_id)
{
return false;
}
items = self.word_completion_items(&prefix);
}
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 words {
self.status = String::from("No suggestions");
}
return self.completion_popup.take().is_some();
}
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);
}
true
}
/// Whether the caret is still in the word the pending completion was
/// requested for: the same buffer and row, not left of the request point,
/// and only word characters typed since. VS Code likewise cancels its
/// suggest session the moment the caret leaves the word.
fn completion_origin_covers_caret(&self, path: &Path) -> bool {
let Some((row, col)) = self.completion_origin else {
return false;
};
let caret = self.editor.cursor_col;
// An untitled buffer's words are asked for with an empty path.
let here = self.editor.path.as_deref().unwrap_or(Path::new(""));
if here != path || self.editor.cursor_row != row || caret < col {
return false;
}
self.editor.lines.get(row).is_some_and(|line| {
line.chars()
.skip(col)
.take(caret - col)
.all(is_word_continuation)
})
}
/// 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) {
self.request_completion_at_caret(true);
}
/// Ask for completions at the caret. The server is asked when the file
/// has a path and a manager runs. When no server reports on the file
/// (a Makefile, a `.env`, a plain-text note), an explicit ask (`words`)
/// opens at once on the words of the open documents (#1566); a server
/// that answers later still replaces them with its own list.
fn request_completion_at_caret(&mut self, words: bool) {
if self.editor.has_non_text_view() {
return;
}
let path = self.editor.path.clone();
let (line, character) = self
.editor
.pos_to_utf16(self.editor.cursor_row, self.editor.cursor_col);
let asked = match (path.clone(), self.lsp.as_mut()) {
(Some(path), Some(lsp)) => Some(lsp.request_completion(path, line, character)),
_ => None,
};
let served = path
.as_deref()
.is_some_and(|p| self.lsp.as_ref().is_some_and(|l| l.document_has_server(p)));
let words = words && self.word_suggestions != crate::word_suggest::WordSuggestions::Off;
if asked.is_none() && !words {
return;
}
let id = asked.unwrap_or_else(|| {
self.local_completion_seq -= 1;
self.local_completion_seq
});
self.completion_request_id = Some(id);
self.completion_origin = Some((self.editor.cursor_row, self.editor.cursor_col));
self.completion_incomplete = false;
self.completion_reask_due = false;
self.completion_words = words;
if words && !served {
self.apply_completion_result(crate::lsp::manager::CompletionResult {
request_id: id,
path: path.unwrap_or_default(),
items: Vec::new(),
is_incomplete: false,
});
}
}
/// The words of the open documents for a completion at the caret, as
/// `word_suggestions` picks them (#1566).
fn word_completion_items(&self, prefix: &str) -> Vec<crate::lsp::CompletionItem> {
use crate::word_suggest::WordSuggestions;
let mode = self.word_suggestions;
if mode == WordSuggestions::Off {
return Vec::new();
}
let active = self.editor.active_index();
let lang = self.editor.scope_id();
let current_path = self.editor.path.as_deref();
// Every open document, the other split groups' too, but not the one
// being edited, nor a copy of it open in another group, whose words
// would include the one being typed.
let others: Vec<&[String]> = match mode {
WordSuggestions::Off | WordSuggestions::CurrentDocument => Vec::new(),
WordSuggestions::MatchingDocuments | WordSuggestions::AllDocuments => self
.editor
.editors
.iter()
.enumerate()
.filter(|&(i, _)| i != active)
.map(|(_, e)| e)
.chain(
self.editor_layout
.inactive_groups()
.into_iter()
.flat_map(|g| g.editors.iter()),
)
.filter(|e| current_path.is_none() || e.path.as_deref() != current_path)
.filter(|e| mode == WordSuggestions::AllDocuments || e.scope_id() == lang)
.map(|e| e.lines.as_slice())
.collect(),
};
crate::word_suggest::collect(
&self.editor.lines,
(self.editor.cursor_row, self.editor.cursor_col),
&others,
prefix,
)
.into_iter()
.map(crate::word_suggest::item)
.collect()
}
/// 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.codeql_icon, col, row) {
Some(ActivityIcon::CodeQL)
} 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::CodeQL => "CodeQL",
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");
}
if self.open_editors.hit_save_all(col, row) {
return Some("Save All");
}
}
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 | SidebarView::CodeQL => {}
}
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) {
// Crossing onto the hover keeps it, so the wheel can reach it.
if self
.hover_popup
.as_ref()
.is_some_and(|p| rect_contains(p.last_area, col, row))
{
self.hover.clear();
return;
}
// 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 {
changed |= self.fan_out_batch(&u.path, u.seq, |e| {
e.apply_inlay_hints(u.path.clone(), u.hints.clone())
});
}
changed
}
/// Hand a seq-stamped batch for `path` to every editor showing the file,
/// the active one and each inactive group, through `apply`. A batch 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. Returns whether any editor
/// took it.
fn fan_out_batch(
&mut self,
path: &Path,
seq: u64,
mut apply: impl FnMut(&mut EditorTabs),
) -> bool {
if self.lsp_last_seen.get(path) != Some(&seq) {
return false;
}
let mut applied = false;
if self.editor.path.as_deref() == Some(path) {
apply(&mut self.editor);
applied = true;
}
for group in self.editor_layout.inactive_groups_mut() {
if group.path.as_deref() == Some(path) {
apply(group);
applied = true;
}
}
applied
}
/// 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 {
self.fan_out_batch(&u.path, u.seq, |e| {
e.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 {
changed |= self.fan_out_batch(&u.path, u.seq, |e| {
e.apply_document_colors(u.path.clone(), u.colors.clone())
});
}
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| {
diagnostics_by_source(by_server)
.map(|(_, d)| d.clone())
.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.
///
/// A solution-style root tsconfig (`"files": []` plus `references`, the
/// layout Vite's TypeScript templates and most monorepos use) compiles
/// nothing on its own: plain `tsc --noEmit` exits 0 having checked no
/// file, which read as a clean project (#1291). Each referenced project
/// is checked instead, `tsc -p <ref> --noEmit`, which writes nothing (no
/// `.tsbuildinfo`, unlike `tsc -b`); nested solution configs are followed
/// to their leaves, and a root that also owns files is checked too. A
/// root that names no files and no references is `ProjectCheck::Empty`,
/// never run and never "clean". Because nothing is emitted, a project
/// importing another referenced project whose declarations were never
/// built gets tsc's TS6305 error: reported as a problem, not hidden.
fn project_check_command(root: &Path) -> Option<ProjectCheck> {
let text = std::fs::read_to_string(root.join("tsconfig.json")).ok()?;
let mut runs: Vec<Vec<String>> = Vec::new();
let mut seen = std::collections::HashSet::new();
let root_config = root.join("tsconfig.json");
seen.insert(std::fs::canonicalize(&root_config).unwrap_or(root_config));
Self::collect_tsc_runs(root, None, &text, &mut seen, &mut runs);
if runs.is_empty() {
return Some(ProjectCheck::Empty);
}
let local = root.join("node_modules").join(".bin").join("tsc");
let (program, prefix): (std::ffi::OsString, &[&str]) = if local.is_file() {
(local.into_os_string(), &[])
} else {
(std::ffi::OsString::from("npx"), &["--no-install", "tsc"])
};
Some(ProjectCheck::Run(
runs.into_iter()
.map(|args| {
let mut all: Vec<String> = prefix.iter().map(|a| a.to_string()).collect();
all.extend(args);
(program.clone(), all)
})
.collect(),
))
}
/// The `tsc` runs that check the tsconfig at `rel` (`None` = the root
/// `tsconfig.json`), whose contents are `text` (#1291).
///
/// A config that owns files gets its own `--noEmit` run, even when it
/// also has `references`: tsc does not check references during a plain
/// project check, and skipping the root would hide its own files'
/// errors. Each reference is then followed, so a referenced
/// solution-style config is checked through its leaves rather than run
/// on its own and compiling nothing. A reference that can't be read
/// is still run, so tsc reports it. `seen` stops a reference cycle.
fn collect_tsc_runs(
root: &Path,
rel: Option<&str>,
text: &str,
seen: &mut std::collections::HashSet<PathBuf>,
runs: &mut Vec<Vec<String>>,
) {
let config: serde_json::Value =
serde_json::from_str(&crate::tasks::strip_jsonc(text)).unwrap_or_default();
let names_no_files = config
.get("files")
.and_then(|f| f.as_array())
.is_some_and(|f| f.is_empty())
&& config.get("include").is_none()
// An `extends` base may supply the files.
&& config.get("extends").is_none();
if !names_no_files {
runs.push(match rel {
None => vec![String::from("--noEmit")],
Some(rel) => vec![
String::from("-p"),
rel.to_string(),
String::from("--noEmit"),
],
});
}
// References resolve against the directory of the config naming them.
let base = rel.map(|rel| {
let p = Path::new(rel);
if root.join(p).is_dir() {
p.to_path_buf()
} else {
p.parent().map(Path::to_path_buf).unwrap_or_default()
}
});
let references = config
.get("references")
.and_then(|r| r.as_array())
.into_iter()
.flatten()
.filter_map(|r| r.get("path")?.as_str());
for reference in references {
let child = match &base {
None => reference.to_string(),
Some(base) => base.join(reference).to_string_lossy().into_owned(),
};
let on_disk = root.join(&child);
let file = if on_disk.is_dir() {
on_disk.join("tsconfig.json")
} else {
on_disk
};
let key = std::fs::canonicalize(&file).unwrap_or(file.clone());
if !seen.insert(key) {
continue;
}
match std::fs::read_to_string(&file) {
Ok(text) => Self::collect_tsc_runs(root, Some(&child), &text, seen, runs),
Err(_) => runs.push(vec![String::from("-p"), child, String::from("--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. The
/// exception is the loose go and lint rows (#1594), kept only for a
/// file that exists, so other `name:1:2: text` output is not a problem.
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)
}
};
if d.needs_file && !path.is_file() {
continue;
}
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(),
code: None,
},
));
}
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) {
// Hints (unused names, unreachable code) stay in the editor
// and its hover, out of the list and its count, as in VS
// Code (#1522).
let shown = diagnostics_by_source(by_server)
.filter(|(_, d)| d.severity != crate::lsp::manager::DiagnosticSeverity::Hint);
for (source, d) in shown {
items.push(ProblemItem {
line: d.start_line,
col: d.start_char,
col_utf16: true,
severity: d.severity,
message: d.message.clone(),
source: source.to_string(),
code: d.code.clone(),
});
}
}
if let Some(build) = self.build_diagnostics.get(path) {
// A task matcher can emit `hint` too; same rule (#1522).
items.extend(
build
.iter()
.map(|(_, item)| item)
.filter(|i| i.severity != crate::lsp::manager::DiagnosticSeverity::Hint)
.cloned(),
);
}
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);
}
}
self.apply_diagnostics_updates(updates)
}
/// Store a batch of servers' diagnostics and repaint what they touch:
/// the body of [`Self::drain_lsp_diagnostics`], apart from the drain.
fn apply_diagnostics_updates(
&mut self,
updates: Vec<crate::lsp::manager::DiagnosticsUpdate>,
) -> bool {
let mut touched: std::collections::HashSet<PathBuf> = std::collections::HashSet::new();
let mut changed = false;
for u in updates {
// While a proposal is being checked (#347), what the servers say
// about its file is about the proposal, not the buffer.
if let Some(check) = self.approval_check.as_mut()
&& check.path == u.path
{
check
.by_server
.insert(diagnostics_store_key(&u), u.diagnostics);
changed = true;
continue;
}
touched.insert(u.path.clone());
store_diagnostics_update(&mut self.lsp_diagnostics, u);
}
// 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;
}
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;
};
for (p, end) in self.inlay_hint_targets() {
if !self.inlay_hints_enabled_for(path_scope_id(&p)) {
continue;
}
if let Some(&seq) = self.lsp_last_seen.get(&p) {
lsp.request_inlay_hints(p, end, seq);
}
}
}
/// Every visible editor's file with where its buffer ends: the range an
/// inlay-hint request covers (#1490).
fn inlay_hint_targets(&self) -> Vec<(PathBuf, lsp_types::Position)> {
let mut targets = Vec::new();
if let Some(p) = self.editor.path.clone() {
targets.push((p, self.editor.document_end()));
}
for group in self.editor_layout.inactive_groups() {
if let Some(p) = group.path.clone() {
targets.push((p, group.document_end()));
}
}
targets
}
/// 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) {
let pinned = self.keep_preview_open_for_navigation_to(&path);
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.restore_preview_after_failed_navigation(pinned);
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) {
// While scrubbing (#371) the outline is the commit's, so the
// chain follows the historical view's caret.
let line = self
.scrub_view
.as_ref()
.map_or(self.editor.cursor_row, |v| v.cursor_row) as u32;
let symbols = self.outline.symbols();
let col = self
.scrub_view
.as_ref()
.map_or(self.editor.cursor_col, |v| v.cursor_col) as u32;
for i in breadcrumb_symbol_chain(symbols, line, col) {
let s = &symbols[i];
crumbs.push(Crumb {
label: s.name.clone(),
target: Some((s.line, s.character)),
});
}
}
crumbs
}
/// What each crumb [`build_breadcrumbs`](Self::build_breadcrumbs) makes
/// stands for, in the same order (#1608).
fn breadcrumb_targets(&self) -> Vec<CrumbTarget> {
let Some(path) = self.editor.path.as_deref() else {
return Vec::new();
};
if self.editor.has_non_text_view() {
return Vec::new();
}
let root = self.roots.owning_root(path);
let rel = root.and_then(|r| path.strip_prefix(r).ok()).unwrap_or(path);
let mut at = root.map(Path::to_path_buf).unwrap_or_default();
let names: Vec<_> = rel
.components()
.filter_map(|c| match c {
std::path::Component::Normal(os) => Some(os.to_os_string()),
_ => None,
})
.collect();
if root.is_none() {
// An absolute path outside every root: its crumbs start at `/`.
at = path
.ancestors()
.last()
.map(Path::to_path_buf)
.unwrap_or_default();
}
let mut targets = Vec::new();
for (k, name) in names.iter().enumerate() {
at.push(name);
targets.push(if k + 1 == names.len() {
CrumbTarget::File(at.clone())
} else {
CrumbTarget::Folder(at.clone())
});
}
if self.outline.path() == Some(path) {
let line = self
.scrub_view
.as_ref()
.map_or(self.editor.cursor_row, |v| v.cursor_row) as u32;
let col = self
.scrub_view
.as_ref()
.map_or(self.editor.cursor_col, |v| v.cursor_col) as u32;
targets.extend(
breadcrumb_symbol_chain(self.outline.symbols(), line, col)
.into_iter()
.map(CrumbTarget::Symbol),
);
}
targets
}
/// Open crumb `i`'s picker under it (#1608): a folder crumb lists the
/// folder, the file crumb lists its folder with the file selected, and a
/// symbol crumb lists the symbols beside it with it selected.
fn open_breadcrumb_picker(&mut self, i: usize) {
let Some(target) = self.breadcrumb_targets().into_iter().nth(i) else {
return;
};
match target {
CrumbTarget::Folder(dir) => self.open_crumb_folder_picker(&dir, i, None),
CrumbTarget::File(path) => {
let dir = path.parent().map(Path::to_path_buf).unwrap_or_default();
self.open_crumb_folder_picker(&dir, i, Some(&path));
}
CrumbTarget::Symbol(s) => {
let Some(path) = self.editor.path.clone() else {
return;
};
let symbols = self.outline.symbols();
let siblings = sibling_symbols(symbols, s);
let selected = siblings.iter().position(|&k| k == s).unwrap_or(0);
let items = siblings
.into_iter()
.map(|k| {
let sym = &symbols[k];
(
sym.name.clone(),
MenuAction::GoToLocation {
path: path.clone(),
line: sym.line,
col: sym.character,
},
)
})
.collect();
self.show_crumb_picker(i, items, selected);
}
}
}
/// The picker of crumb `i` listing `dir`: folders first, then files,
/// each by name; `select` is the row to start on.
fn open_crumb_folder_picker(&mut self, dir: &Path, i: usize, select: Option<&Path>) {
let mut entries: Vec<(bool, String, PathBuf)> = std::fs::read_dir(dir)
.map(|rd| {
rd.filter_map(Result::ok)
.filter(|e| e.file_name() != ".git")
.map(|e| {
let path = e.path();
(
path.is_dir(),
e.file_name().to_string_lossy().into_owned(),
path,
)
})
.collect()
})
.unwrap_or_default();
entries.sort_by(|a, b| {
b.0.cmp(&a.0)
.then_with(|| a.1.to_lowercase().cmp(&b.1.to_lowercase()))
});
if entries.is_empty() {
self.status = format!("{} is empty", dir.display());
return;
}
let selected = select
.and_then(|p| entries.iter().position(|e| e.2 == p))
.unwrap_or(0);
let items = entries
.into_iter()
.map(|(is_dir, name, path)| {
if is_dir {
(
format!("{name}/"),
MenuAction::BrowseCrumbFolder {
dir: path,
crumb: i,
},
)
} else {
(name, MenuAction::OpenCrumbFile(path))
}
})
.collect();
self.show_crumb_picker(i, items, selected);
}
fn show_crumb_picker(&mut self, i: usize, items: Vec<(String, MenuAction)>, selected: usize) {
let Some(origin) = self.editor.breadcrumb_anchor(i) else {
return;
};
let mut menu = ContextMenu::flat(origin, items, self.tree.root.clone());
menu.selected = selected;
menu.crumb = Some(i);
self.context_menu = Some(menu);
}
/// A file picked from a breadcrumb picker opens as a Quick Open pick does.
fn open_crumb_file(&mut self, path: &Path) {
match self.editor.open_preview(path) {
Ok(()) => {
self.sync_open_file_poll_mtime();
self.tree.reveal_path(path);
self.focus_pane(Pane::Editor);
self.status = format!("Opened {}", self.status_path(path));
}
Err(e) => self.status = format!("Error: {e}"),
}
}
/// View: Focus and Select Breadcrumbs (#1608): the last crumb's picker,
/// from which Left / Right walk the bar.
fn focus_breadcrumbs(&mut self) {
// A row too narrow for the whole chain focuses the last crumb that
// fit on it.
let n = self.editor.breadcrumbs.len();
let Some(last) = (0..n)
.rev()
.find(|&i| self.editor.breadcrumb_anchor(i).is_some())
else {
self.status = String::from("No breadcrumbs to focus");
return;
};
self.focus_pane(Pane::Editor);
self.open_breadcrumb_picker(last);
}
/// 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, 0)
.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;
};
// A tab switch while scrubbing is noticed by render, which runs
// after this: rebuild here first, or the new file's key would be
// paired with the previous file's historical text.
if self.scrubber.is_some() && self.scrub_for.as_ref() != Some(&path) {
self.rebuild_scrub_view();
}
// Scrubbing (#371): the outline is the file as it was at the commit
// on screen, from its own syntax tree; no language server knows that
// text. Parsing a big file takes far longer than a frame, so the
// scrubber's builder parses it off the UI thread with the finished
// view, and until that lands the previous outline stays. Leaving
// drops the key, so the live outline is recomputed.
let commit = self
.scrubber
.as_ref()
.and_then(|s| s.commit())
.map(|c| c.hash.clone());
if let (Some(row), Some(commit)) = (self.scrub_view.as_ref().map(|v| v.cursor_row), commit)
{
let key = (path.clone(), commit.clone());
if self.outline_scrub_key.as_ref() != Some(&key) {
let rel = path
.strip_prefix(self.workspace_root())
.map(|p| p.to_string_lossy().into_owned());
let symbols = rel.ok().and_then(|rel| {
self.scrub_outlines
.get(&crate::scrubber::ViewKey { hash: commit, rel })
.cloned()
});
if let Some(symbols) = symbols {
self.outline.set_syntax_symbols(path, symbols, false);
self.outline_scrub_key = Some(key);
self.outline_synced = None;
} else if self.outline.path.as_ref() != Some(&path) {
// Another file's outline must never stand in for this
// one's: empty until its own lands.
self.outline.set_syntax_symbols(path, Vec::new(), false);
self.outline_scrub_key = None;
self.outline_synced = None;
}
}
return self.outline.follow_caret(row as u32);
}
if self.outline_scrub_key.take().is_some() {
self.outline_synced = None;
}
// `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 lsp_pending = seq.is_some();
if outline_parses_inline(&self.editor.lines) {
let syntax = self.compute_syntax_outline(&path);
self.outline
.set_syntax_symbols(path.clone(), syntax, lsp_pending);
} else if self.outline.path.as_ref() != Some(&path) {
// A large buffer is parsed off the UI thread (#1150); until
// that lands, another file's outline must never stand in.
self.outline
.set_syntax_symbols(path.clone(), Vec::new(), true);
}
if lsp_pending && let (Some(lsp), Some(seq)) = (self.lsp.as_ref(), seq) {
lsp.request_document_symbols(path, seq);
}
}
let landed = self.drain_outline_parse();
self.start_outline_parse();
// 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) | landed
}
/// Parse a large buffer's syntax outline on a worker (#1150): inline, a
/// multi-megabyte file re-parsed from scratch on every keystroke and each
/// character took seconds to appear. Starts only when no parse is
/// running and the buffer moved past the last one started, so a burst of
/// typing costs one parse when it ends, not one per key.
fn start_outline_parse(&mut self) {
if self.outline_parse.is_some() || self.outline_parsed_for == self.outline_synced {
return;
}
let Some(key) = self.outline_synced.clone() else {
return;
};
if self.editor.path.as_ref() != Some(&key.0) || outline_parses_inline(&self.editor.lines) {
return;
}
let (path, lines) = (key.0.clone(), self.editor.lines.clone());
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let _ = tx.send(syntax_outline_for(&path, &lines));
});
self.outline_parsed_for = Some(key.clone());
self.outline_parse = Some((key, rx));
}
/// Apply a finished off-thread outline parse, if the buffer is still the
/// one it parsed and the language server's outline of that same buffer
/// has not landed first. True when the outline changed.
fn drain_outline_parse(&mut self) -> bool {
let Some((key, rx)) = &self.outline_parse else {
return false;
};
let symbols = match rx.try_recv() {
Ok(symbols) => symbols,
Err(std::sync::mpsc::TryRecvError::Empty) => return false,
Err(std::sync::mpsc::TryRecvError::Disconnected) => {
self.outline_parse = None;
return false;
}
};
let key = key.clone();
self.outline_parse = None;
if self.outline_synced.as_ref() != Some(&key) {
return false;
}
let (path, seq) = key;
if seq.is_some_and(|seq| self.outline_lsp_landed == Some((path.clone(), seq))) {
return false;
}
self.outline
.set_syntax_symbols(path, symbols, seq.is_some());
true
}
/// 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;
}
// A CodeQL database's folder size landed; drop one for a database
// removed while it was being summed.
while let Ok((path, size)) = self.codeql_size_rx.try_recv() {
self.codeql_size_pending.remove(&path);
if let Some(size) = size
&& self.codeql.databases.iter().any(|db| db.path == path)
{
self.codeql.db_sizes.insert(path, size);
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_pinned(&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)"));
let unsaved = self.unsaved_text_in_any_group(&path);
if let Err(e) = self
.editor
.open_head_diff_with_text_resolved(label, &text, &path, false, unsaved)
{
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();
self.status = format!("Loading {rel} at {hash}\u{2026}");
self.spawn_git_view(move || {
let result = crate::git::show_commit_file_diff(&timeline_root, &hash, &rel);
Box::new(move |app: &mut App| match result {
Ok(raw) => {
let label = std::path::PathBuf::from(format!("{rel} @ {hash}"));
if let Err(e) = app.editor.open_git_diff_side_by_side(&label, &raw) {
app.status = format!("Could not open diff: {e}");
return;
}
app.focus_pane(Pane::Editor);
app.status = format!("Showing {rel} at {hash}");
}
Err(e) => app.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;
};
// What is on disk now is kept first: it may never have been
// snapshotted (an agent's write, a checkout), and the restore
// overwrites it. Refused if it cannot be kept.
if let Ok(current) = std::fs::read(&file)
&& let Err(e) =
crate::history::record_kept_in(&self.history_root, &file, ¤t, now_millis())
{
self.status = format!("Restore cancelled: could not keep the current version ({e})");
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, kept like the
// version it replaced.
self.record_history_snapshot_of_kept(&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;
}
if !symbols.is_empty() {
self.outline_lsp_landed = Some((path.clone(), seq));
}
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> {
syntax_outline_for(path, &self.editor.lines)
}
/// 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 mut empty_reply = false;
{
let Some(lsp) = self.lsp.as_ref() else {
return false;
};
let mut peek_replied = false;
let mut 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;
}
replied = true;
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");
}
if replied {
self.definition_request_id = None;
// An empty F12 reply said nothing (#1302): a slow server, a
// missing one and "nothing here" all looked alike.
if target.is_none() {
self.status = String::from("No definition found");
empty_reply = true;
}
}
}
let mut changed = empty_reply;
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) {
self.open_peek_popup_titled(path, line, col, None);
}
/// [`open_peek_popup`](Self::open_peek_popup) with an optional first
/// line above the location, e.g. "Reference 2 of 7" (#616).
fn open_peek_popup_titled(
&mut self,
path: PathBuf,
line: u32,
col: u32,
title: Option<String>,
) {
// 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<String> = title.into_iter().collect();
body.push(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;
self.peek_refs = None;
}
/// Show the reference `peek_refs` points at in the peek popup (#616),
/// titled with its place in the list.
fn show_peeked_reference(&mut self) {
let Some((targets, idx)) = self.peek_refs.clone() else {
return;
};
let Some((path, line, col)) = targets.get(idx).cloned() else {
return;
};
let title = format!(
"Reference {} of {} \u{2191}\u{2193} steps",
idx + 1,
targets.len()
);
self.open_peek_popup_titled(path, line, col, Some(title));
// Re-opening goes through the same path as a fresh peek, which
// leaves the reference list alone; restore it in case it was reset.
self.peek_refs = Some((targets, idx));
}
/// Step Peek References by `delta`, wrapping at either end.
fn step_peeked_reference(&mut self, delta: isize) {
if let Some((targets, idx)) = self.peek_refs.as_mut() {
let n = targets.len() as isize;
*idx = (*idx as isize + delta).rem_euclid(n) as usize;
}
self.show_peeked_reference();
}
/// Peek References (Alt+Shift+F12, #616): the references of the symbol
/// at the caret in the peek popup rather than a picker.
fn peek_references_at_cursor(&mut self) {
self.request_references_at_cursor();
self.references_want_peek = self.references_request_id.is_some();
}
pub fn drain_lsp_declaration(&mut self) -> bool {
let Some(lsp) = self.lsp.as_ref() else {
return false;
};
let mut reply = None;
while let Some(result) = lsp.drain_declaration() {
if Some(result.request_id) == self.declaration_request_id {
reply = Some((result.target, result.unsupported));
}
}
let Some((target, unsupported)) = reply else {
return false;
};
self.declaration_request_id = None;
self.finish_jump(target, unsupported, "Go to Declaration", "declaration");
true
}
pub fn drain_lsp_type_definition(&mut self) -> bool {
let Some(lsp) = self.lsp.as_ref() else {
return false;
};
let mut reply = None;
while let Some(result) = lsp.drain_type_definition() {
if Some(result.request_id) == self.type_definition_request_id {
reply = Some((result.target, result.unsupported));
}
}
let Some((target, unsupported)) = reply else {
return false;
};
self.type_definition_request_id = None;
self.finish_jump(
target,
unsupported,
"Go to Type Definition",
"type definition",
);
true
}
/// Act on the reply to a go-to request: jump to its target the way Go to
/// Definition does (open the file, move the caret, record nav history),
/// or say so rather than silently doing nothing, both when the language
/// server has no `feature` provider (`unsupported`, e.g. TypeScript's
/// vtsls has no declarations) and when it found no `noun` at this
/// position.
fn finish_jump(
&mut self,
target: Option<(PathBuf, u32, u32)>,
unsupported: bool,
feature: &str,
noun: &str,
) {
match target {
Some((path, line, col)) => self.go_to_definition(path, line, col),
None if unsupported => {
self.status = format!("{feature}: not supported by this file's language server");
}
None => self.status = format!("No {noun} found"),
}
}
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;
}
let peek = std::mem::take(&mut self.references_want_peek);
if unsupported {
self.status =
String::from("Go to References: not supported by this file's language server");
return true;
}
if peek && !targets.is_empty() {
self.peek_refs = Some((targets, 0));
self.show_peeked_reference();
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 = result.kind.noun();
if result.unsupported {
let what = match result.kind {
crate::lsp::manager::HierarchyKind::Supertypes
| crate::lsp::manager::HierarchyKind::Subtypes => "Type hierarchy",
_ => "Call hierarchy",
};
self.status = format!("{what}: 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);
}
/// Request the supertypes or subtypes of the type at the cursor (#613).
/// Cmd+K Shift+U / Cmd+K Shift+D and the right-click menu rows.
fn request_type_hierarchy_at_cursor(&mut self, supertypes: 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("Type hierarchy: no language server for this file");
return;
};
let id = lsp.request_type_hierarchy(path, line, character, supertypes);
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 {
self.editor_language_supports(crate::lsp::LspManager::language_supports_call_hierarchy)
}
/// The language the current editor file's name or extension maps to, if
/// any.
fn editor_language(&self) -> Option<crate::lsp::Language> {
self.editor
.path
.as_deref()
.and_then(crate::lsp::Language::from_path)
}
/// Whether the current editor file's language server reports support
/// through `supports`, one of the `language_supports_*` getters on
/// [`crate::lsp::LspManager`]. Unknown (server not yet spawned) or no
/// server counts as unsupported, so a gated row only appears once support
/// is confirmed.
fn editor_language_supports(
&self,
supports: fn(&crate::lsp::LspManager, crate::lsp::Language) -> Option<bool>,
) -> bool {
let Some(lang) = self.editor_language() else {
return false;
};
self.lsp
.as_ref()
.and_then(|lsp| supports(lsp, 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_for(editor_scope_id(&self.editor)) || !self.editor_is_text() {
return;
}
if seq != self.editor.edit_seq {
return;
}
let Some(path) = self.editor.path.clone() else {
return;
};
let Some(lang) = crate::lsp::Language::from_path(&path) 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.apply_on_type_edits(&result.path, &edits)
{
changed = true;
}
}
changed
}
/// Apply an on-type formatting reply for `path`, the active tab's file
/// (the reply's disposition checked that), keeping the caret beside the
/// text that was just typed.
pub(crate) fn apply_on_type_edits(
&mut self,
path: &std::path::Path,
edits: &[crate::widgets::editor::TextSpanEdit],
) -> bool {
if self.editor.path.as_deref() == Some(path) {
return self.editor.apply_span_edits_moving_caret(edits) > 0;
}
let applied = self.editor.apply_rename_to_open_tab(path, edits).is_some();
self.editor.clamp_cursor();
applied
}
/// 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.linked_asked = false;
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;
self.linked_asked = false;
return mirrored;
}
if self.linked_asked || 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));
self.linked_asked = true;
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_language().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,
),
MenuEntry::item(
format!("{}Centered Layout", check(self.centered_layout_active())),
MenuAction::ToggleCenteredLayout,
),
]
}
/// 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 {
crumb: None,
scroll: Default::default(),
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,
centered_layout: self.centered_layout,
zen_center_layout: self.zen_center_layout,
centered_layout_width: self.centered_layout_width,
});
}
/// Show or hide the activity bar. The Customize Layout row and the
/// palette's View: Toggle Activity Bar Visibility (#852) both land here.
fn toggle_activity_bar(&mut self) {
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();
}
/// Show or hide the status bar: the Customize Layout row and View:
/// Toggle Status Bar Visibility (#852).
fn toggle_status_bar(&mut self) {
self.status_bar_visible = !self.status_bar_visible;
self.persist_layout();
self.after_chrome_visibility_change();
}
/// Dock the primary side bar (and the activity bar with it) to `pos`:
/// the Customize Layout radio rows and View: Toggle Primary Side Bar
/// Position (#852).
fn set_side_bar_position(&mut self, pos: SideBarPosition) {
self.side_bar_position = pos;
self.persist_layout();
self.after_chrome_visibility_change();
}
/// The bottom panel's alignment: the Customize Layout radio rows and
/// View: Set Panel Alignment… (#852).
fn set_panel_alignment(&mut self, al: PanelAlignment) {
self.panel_alignment = al;
self.persist_layout();
}
/// Where the quick input anchors: the Customize Layout radio rows and
/// View: Set Quick Input Position… (#852).
fn set_quick_input_position(&mut self, pos: QuickInputPosition) {
self.quick_input_position = pos;
self.persist_layout();
}
/// View: Set Panel Alignment… (#852): the popup's Panel Alignment radio
/// group as a keyboard picker, opened on the current alignment.
fn open_panel_alignment_picker(&mut self) {
use crate::widgets::list_picker::{ListPicker, ListPurpose, ListRow};
let rows = PanelAlignment::OPTIONS
.iter()
.map(|(_, id, label)| ListRow {
id: (*id).to_string(),
label: (*label).to_string(),
})
.collect();
let mut picker = ListPicker::new(ListPurpose::PanelAlignment, "Panel Alignment", rows);
picker.selected = PanelAlignment::OPTIONS
.iter()
.position(|(al, ..)| *al == self.panel_alignment)
.unwrap_or(0);
self.open_list_picker(picker, "No panel alignments");
}
/// View: Set Quick Input Position… (#852): the popup's Quick Input
/// Position radio group as a keyboard picker, opened on the current one.
fn open_quick_input_position_picker(&mut self) {
use crate::widgets::list_picker::{ListPicker, ListPurpose, ListRow};
let rows = QuickInputPosition::OPTIONS
.iter()
.map(|(_, id, label)| ListRow {
id: (*id).to_string(),
label: (*label).to_string(),
})
.collect();
let mut picker = ListPicker::new(
ListPurpose::QuickInputPosition,
"Quick Input Position",
rows,
);
picker.selected = QuickInputPosition::OPTIONS
.iter()
.position(|(pos, ..)| *pos == self.quick_input_position)
.unwrap_or(0);
self.open_list_picker(picker, "No quick input positions");
}
/// 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.zen_esc_at = None;
self.zen_hint_until = None;
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.zen_centered = self.zen_center_layout;
self.zen_esc_at = None;
self.zen_hint_until = Some(std::time::Instant::now() + ZEN_HINT_FOR);
self.status = String::from("Zen Mode on");
}
self.after_chrome_visibility_change();
}
/// Whether the editor is centred this frame (#1585): Toggle Centered
/// Layout, or a Zen session that started centred.
fn centered_layout_active(&self) -> bool {
self.centered_layout || (self.zen_mode && self.zen_centered)
}
/// View: Toggle Centered Layout (#1585). Off turns off both the setting
/// and a centred Zen session, so the toggle always flips what is on
/// screen; the setting persists, Zen's own centring does not.
fn toggle_centered_layout(&mut self) {
if self.centered_layout_active() {
self.centered_layout = false;
self.zen_centered = false;
} else {
self.centered_layout = true;
}
self.status = String::from(if self.centered_layout_active() {
"Centered Layout on"
} else {
"Centered Layout off"
});
self.persist_layout();
}
/// One Esc reached Zen Mode's editor and closed or cleared nothing
/// (#1585): the second inside [`ZEN_ESC_WINDOW`] leaves Zen, as VS
/// Code's Esc Esc does.
fn note_idle_zen_esc(&mut self, now: std::time::Instant) {
match self.zen_esc_at.take() {
Some(at) if now.saturating_duration_since(at) <= ZEN_ESC_WINDOW => {
self.toggle_zen_mode();
}
_ => self.zen_esc_at = Some(now),
}
}
/// What an Esc in the editor can close or clear (#1585), compared
/// across one Esc to tell an Esc that did something from one that did
/// nothing. Only an Esc that did nothing counts toward Esc Esc.
fn esc_fingerprint(&self) -> impl PartialEq + use<> {
(
(
self.focus,
self.zen_mode,
self.modal_overlay_open(),
self.context_menu.is_some(),
self.prompt.is_some(),
self.peek_popup.is_some(),
self.hover_popup.is_some(),
self.completion_popup.is_some(),
self.signature_help_popup.is_some(),
),
(
self.editor.selection,
self.editor.has_multi_cursor(),
self.editor.snippet_active(),
self.editor
.markdown_preview
.as_ref()
.map(|md| md.has_selection()),
self.status.clone(),
),
(
self.editor.comment_focus.is_some(),
self.vim.enabled,
self.vim.mode(),
self.vim.has_pending(),
),
)
}
/// Drop the Zen hint once its time is up; true when it just went, so
/// the frame without it is drawn (#1585).
fn expire_zen_hint(&mut self, now: std::time::Instant) -> bool {
if self.zen_hint_until.is_some_and(|until| now >= until) {
self.zen_hint_until = None;
return true;
}
false
}
/// 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 {
crumb: None,
scroll: Default::default(),
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)
);
}
/// The AGENT LANE rows (#345): each agent that changed files, then those
/// files as the ledger orders them (unreviewed first), labelled relative
/// to their workspace root.
fn agent_lane_panel_rows(&mut self) -> Vec<crate::widgets::agent_lane::LaneRow> {
use crate::widgets::agent_lane::LaneRow;
let mut rows = Vec::new();
let agents: Vec<String> = self
.agent_ledger
.agents()
.into_iter()
.map(str::to_string)
.collect();
for agent in agents {
rows.push(LaneRow::Agent {
name: agent.clone(),
unreviewed: self.agent_ledger.unreviewed_count(&agent),
});
let files: Vec<_> = self
.agent_ledger
.lane(&agent)
.into_iter()
.map(|f| {
(
f.path.clone(),
f.reviewed_millis,
f.current_hash,
f.unreviewed(),
)
})
.collect();
for (path, reviewed_millis, current_hash, unreviewed) in files {
let changes = reviewed_millis
.and_then(|millis| self.lane_changes(&path, millis, current_hash));
let label = self
.roots
.owning_root(&path)
.and_then(|root| path.strip_prefix(root).ok())
.unwrap_or(&path)
.display()
.to_string();
rows.push(LaneRow::File {
agent: agent.clone(),
path,
label,
unreviewed,
changes,
});
}
}
rows
}
/// Lines added and removed in `path` since the snapshot it was reviewed
/// against (#345), for its lane row. Rows render every frame, so the
/// count is kept until the snapshot, the agent's last write or the file
/// on disk changes. `None` when the snapshot or the file can't be read.
fn lane_changes(
&mut self,
path: &Path,
millis: u64,
current_hash: u64,
) -> Option<(usize, usize)> {
let mtime = std::fs::metadata(path).and_then(|m| m.modified()).ok();
let key = (millis, current_hash, mtime);
if let Some((k, counts)) = self.lane_change_counts.get(path)
&& *k == key
{
return *counts;
}
let counts = (|| {
let snap = crate::history::snapshot_file_in(&self.history_root, path, millis)?;
let decode = |bytes: Vec<u8>| {
let enc = encoding_rs::Encoding::for_bom(&bytes)
.map(|(e, _)| e)
.unwrap_or(encoding_rs::UTF_8);
enc.decode(&bytes).0.into_owned()
};
let before = decode(std::fs::read(snap).ok()?);
let after = decode(std::fs::read(path).ok()?);
let diff = similar::TextDiff::from_lines(&before, &after);
let (mut added, mut removed) = (0, 0);
for change in diff.iter_all_changes() {
match change.tag() {
similar::ChangeTag::Insert => added += 1,
similar::ChangeTag::Delete => removed += 1,
similar::ChangeTag::Equal => {}
}
}
Some((added, removed))
})();
self.lane_change_counts
.insert(path.to_path_buf(), (key, counts));
counts
}
/// Cmd+K V (#345): make the AGENT LANE section visible and open, on the
/// Explorer, or say there is nothing in it yet.
fn show_agent_lane_section(&mut self) {
if self.agent_ledger.agents().is_empty() {
self.status = String::from("Agent Lane: no agent has changed a file yet");
return;
}
if !self.explorer_views.is_visible(ExplorerView::AgentLane) {
self.toggle_explorer_view(ExplorerView::AgentLane);
}
self.agent_lane_panel.collapsed = false;
self.show_tree = true;
self.set_sidebar_view(SidebarView::Explorer);
self.focus_pane(Pane::Tree);
}
/// 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.open_editors.save_all_btn = Rect::default();
self.outline.last_area = Rect::default();
self.timeline.last_area = Rect::default();
self.dependencies.last_area = Rect::default();
self.agent_lane_panel.last_area = Rect::default();
let lane_rows = self.agent_lane_panel_rows();
self.agent_lane_panel.set_rows(lane_rows);
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;
}
// Offered in the ⋯ menu always, but drawn only once an agent has
// changed something: an empty lane would cost rows for nothing.
if v == ExplorerView::AgentLane && self.agent_lane_panel.rows().is_empty() {
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),
ExplorerView::AgentLane => self.agent_lane_panel.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),
ExplorerView::AgentLane => frame.render_widget(&mut self.agent_lane_panel, 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();
let _ = out.write_all(theme_host_colors_seq(theme).as_bytes());
let _ = out.flush();
}
self.rebake_inline_images();
self.status = format!("Color Theme: {}", theme.label());
}
/// Bake every inline image again, for a new background or a new cell
/// size.
fn rebake_inline_images(&mut self) {
// 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::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();
self.place_caret_at(row, col);
Ok(())
}
/// Put the active editor's caret at the 0-based `row` and `col`, clamped
/// to the text, scroll it to mid-screen and focus the editor.
pub fn place_caret_at(&mut self, row: usize, col: usize) {
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();
}
/// 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,
})
}
/// Run one key or mouse gesture, and when it moved the editor to
/// another file without going through the navigation history itself
/// (Quick Open, a Search result, the Explorer, a tab), record where the
/// user left (#1635): Go Back knew only the jumps that recorded
/// themselves, so the usual way of changing file left nothing to go
/// back to. A gesture that recorded or walked the history (Go to
/// Definition, Go Back itself) is left as it did it, and so is one that
/// moved focus to another editor group: a history entry holds no group,
/// so Go Back would reopen that group's file in the focused one.
fn recording_file_switches<R>(&mut self, gesture: impl FnOnce(&mut Self) -> R) -> R {
let left = self.current_nav_loc();
let changes = self.nav.changes();
let group = self.editor_group_identity();
let result = gesture(self);
if let Some(left) = left
&& self.nav.changes() == changes
&& self.editor_group_identity() == group
&& self.editor.path.as_ref() != Some(&left.path)
{
self.nav.record(left);
}
result
}
/// Which editor group has focus, as the split's leaf count and the
/// focused leaf's position: a change in either is a group change.
fn editor_group_identity(&self) -> (usize, usize) {
(
self.editor_layout.leaf_count(),
self.editor_layout.active_dfs_index(),
)
}
/// A code navigation that leaves the active tab for another file keeps
/// that tab open (#1561), as VS Code does by default
/// (`enablePreviewFromCodeNavigation` off): were it the preview, the
/// target would take its slot and close the file being read, and Go
/// Back would swap them again. A jump within the same file replaces
/// nothing, so the tab stays a preview.
///
/// The target counts as the same file under the editor's own path
/// matching (canonicalized), so a symlinked tab and the canonical path
/// a language server answers with are one file. Returns whether the tab
/// was promoted, for [`Self::restore_preview_after_failed_navigation`].
fn keep_preview_open_for_navigation_to(&mut self, target: &Path) -> bool {
let same_file = self.editor.path.as_deref().is_some_and(|p| {
p == target
|| matches!(
(p.canonicalize(), target.canonicalize()),
(Ok(a), Ok(b)) if a == b
)
});
if !same_file && self.editor.is_preview(self.editor.active_index()) {
self.editor.pin_active();
return true;
}
false
}
/// A navigation whose target failed to open (a stale language-server
/// answer, a file deleted since it entered the history) left the user
/// on the tab it started from, so that tab goes back to being the
/// preview it was before [`Self::keep_preview_open_for_navigation_to`].
fn restore_preview_after_failed_navigation(&mut self, pinned: bool) {
if pinned {
self.editor.preview = true;
}
}
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 pinned = self.keep_preview_open_for_navigation_to(&loc.path);
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.restore_preview_after_failed_navigation(pinned);
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 pinned = self.keep_preview_open_for_navigation_to(&loc.path);
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.restore_preview_after_failed_navigation(pinned);
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) {
if let Some(id) = self.request_at_cursor(crate::lsp::LspManager::request_definition) {
self.definition_request_id = Some(id);
}
}
/// Send `request` for the symbol at the editor caret, as the UTF-16
/// position LSP speaks, and return the id its reply will echo; `None`
/// when the buffer has no file or no language server runs.
fn request_at_cursor(
&mut self,
request: fn(&mut crate::lsp::LspManager, PathBuf, u32, u32) -> u64,
) -> Option<u64> {
let (line, character) = self
.editor
.pos_to_utf16(self.editor.cursor_row, self.editor.cursor_col);
let path = self.editor.path.clone()?;
let lsp = self.lsp.as_mut()?;
Some(request(lsp, path, line, character))
}
/// 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) {
if let Some(id) = self.request_at_cursor(crate::lsp::LspManager::request_declaration) {
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) {
if let Some(id) = self.request_at_cursor(crate::lsp::LspManager::request_type_definition) {
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) {
if let Some(id) = self.request_at_cursor(crate::lsp::LspManager::request_implementation) {
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) {
// A request not sent (no path, no server) must not leave the last
// one's id, or Peek would arm itself on it and a later plain Go to
// References would open in the peek popup.
self.references_request_id = None;
self.references_want_peek = false;
if let Some(id) = self.request_at_cursor(crate::lsp::LspManager::request_references) {
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 {
self.editor_language_supports(crate::lsp::LspManager::language_supports_declaration)
}
/// 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 {
self.editor_language_supports(crate::lsp::LspManager::language_supports_type_definition)
}
/// 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 {
self.editor_language_supports(crate::lsp::LspManager::language_supports_implementation)
}
/// 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 {
self.editor_language_supports(crate::lsp::LspManager::language_supports_references)
}
fn editor_language_supports_code_action(&self) -> bool {
self.editor_language_supports(crate::lsp::LspManager::language_supports_code_action)
}
/// 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 "Select All Occurrences of Find Match" (`Cmd+Shift+L`,
/// #1558): a selection on every match of the selection, or of the word
/// at the caret.
fn select_all_occurrences(&mut self) {
if self.editor.has_non_text_view() {
return;
}
let n = self.editor.select_all_occurrences();
self.status = if n == 0 {
String::from("Nothing to select: select text on one line, or put the caret on a word")
} else {
format!("Selected {n} occurrences (type to replace, Esc to cancel)")
};
}
/// VS Code "Add Cursors to Line Ends" (`Shift+Alt+I`, #1558): a caret at
/// the end of each selected line.
fn add_cursors_to_line_ends(&mut self) {
if self.editor.has_non_text_view() {
return;
}
let n = self.editor.add_cursors_to_line_ends();
self.status = if n == 0 {
String::from("Select the lines to put cursors at the ends of")
} else {
format!("{n} cursors at line ends")
};
}
/// 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" });
}
/// Kill from the caret to the end of its line, yanking the text to the
/// clipboard (emacs `kill-line`). `Ctrl+K` in the editor on macOS and in
/// vim mode; elsewhere `Ctrl+K` leads the `Cmd+K` chords (#843), and the
/// palette's "Kill to End of Line" is the way here.
fn kill_to_end_of_line(&mut self) {
if self.editor.has_non_text_view() {
return;
}
let killed = self.editor.kill_to_eol();
if !killed.is_empty() {
copy_to_clipboard(&killed);
self.status = format!("Killed {} chars", killed.chars().count());
}
}
/// 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;
// The verdict is in, whichever way it went: "Preparing rename…" no
// longer describes anything (it stayed up beside the open prompt).
if self.status == "Preparing rename…" {
self.status.clear();
}
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;
self.land_rename(edits);
true
}
/// Apply a rename reply, unless a buffer it edits was typed into after
/// the request went out (#1151): its positions were computed against
/// the text as it was then, and would land on whatever sits there now.
fn land_rename(
&mut self,
edits: Option<Vec<(PathBuf, Vec<crate::widgets::editor::TextSpanEdit>)>>,
) {
let baseline = std::mem::take(&mut self.rename_baseline);
match edits {
Some(files) => {
if let Some(file) = self.stale_edit_target(&baseline, &files) {
self.status = format!(
"Rename cancelled: {file} changed while the server was working; press F2 again"
);
return;
}
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"),
}
}
/// The first file of a workspace edit whose open buffer changed after
/// `baseline` was taken, named for the status bar (#1151).
fn stale_edit_target(
&self,
baseline: &[(PathBuf, u64)],
files: &[(PathBuf, Vec<crate::widgets::editor::TextSpanEdit>)],
) -> Option<String> {
files
.iter()
.filter(|(_, edits)| !edits.is_empty())
.find(|(path, _)| {
self.buffer_group(path)
.is_some_and(|group| group.edited_since(baseline, path))
})
.map(|(path, _)| self.status_path(path))
}
/// Every open tab's file and `edit_seq`, in every split group: the
/// baseline a workspace edit is checked against when it lands (#1151).
fn edit_seqs_in_every_group(&self) -> Vec<(PathBuf, u64)> {
std::iter::once(&self.editor)
.chain(self.editor_layout.inactive_groups())
.flat_map(|group| group.edit_seqs())
.collect()
}
/// The editor group whose tab holds `path`'s text, the active group
/// first: the one [`Self::apply_edits_to_open_buffer`] edits. A split
/// may show only a diff of the file while another holds the file
/// itself (#1113).
fn buffer_group(&self, path: &Path) -> Option<&EditorTabs> {
std::iter::once(&self.editor)
.chain(self.editor_layout.inactive_groups())
.find(|group| group.find_buffer_tab(path).is_some())
}
/// Apply workspace `edits` to the tab holding `path`'s text in any
/// split group, the active group first. `None` when no group holds it,
/// so the caller edits the file on disk.
fn apply_edits_to_open_buffer(
&mut self,
path: &Path,
edits: &[crate::widgets::editor::TextSpanEdit],
) -> Option<usize> {
if let Some(n) = self.editor.apply_rename_to_open_tab(path, edits) {
return Some(n);
}
self.editor_layout
.inactive_groups_mut()
.into_iter()
.find_map(|group| group.apply_rename_to_open_tab(path, edits))
}
/// Apply an LSP rename `WorkspaceEdit` (already normalised to per-file
/// char-indexed spans). Open tabs, in any split group, 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.apply_edits_to_open_buffer(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;
};
// A Prettier project formats with its own Prettier and config, as
// VS Code's Prettier extension does; tsserver's formatter knows
// neither (#1255).
if let Some(bin) = crate::prettier::for_file(&path) {
let sent = self.editor.text_for_formatter();
self.prettier_job = Some(crate::prettier::Job::spawn(bin, path, sent));
self.status = String::from("Formatting document with Prettier");
return;
}
if self.lsp.is_none() {
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) ignore these but the fields are
// required by the LSP request.
let (tab_size, insert_spaces) = self.editor.indent_preference();
let seq = self.format_target_seq(&path);
let Some(lsp) = self.lsp.as_mut() else {
return;
};
let id = lsp.request_formatting(path, tab_size, insert_spaces);
self.format_request_id = Some(id);
self.format_request_seq = seq;
self.format_request_selection = false;
self.status = String::from("Formatting document");
}
/// The `edit_seq` of the tab a format reply for `path` lands in (the
/// one `apply_rename_to_open_tab` picks), or `None` when no tab holds it.
fn format_target_seq(&self, path: &std::path::Path) -> Option<u64> {
let idx = self.editor.find_buffer_tab(path)?;
Some(self.editor.editors[idx].edit_seq)
}
/// "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 seq = self.format_target_seq(&path);
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_seq = seq;
self.format_request_selection = true;
self.status = String::from("Formatting selection");
}
/// Apply a finished Prettier run to the tab it formatted, then let the
/// save it held go ahead. A buffer edited while Prettier ran keeps the
/// edit: the result only fits the text that was sent.
pub fn drain_prettier_format(&mut self) -> bool {
let Some(reply) = self
.prettier_job
.as_ref()
.and_then(|job| job.poll(std::time::Instant::now()))
else {
return false;
};
let Some(job) = self.prettier_job.take() else {
return false;
};
let formatted = match reply {
Ok(formatted) => formatted,
Err(e) => {
// Said after the save, which would otherwise cover it with
// "Saved".
let saving = self.save_after_format.is_some();
self.complete_pending_save();
self.status = match saving {
true => format!("Prettier failed: {e}; saved without formatting"),
false => format!("Prettier failed: {e}"),
};
return true;
}
};
let tab = self.editor.find_buffer_tab(&job.path);
let buffer = tab.map(|i| &self.editor.editors[i]).map(|e| {
(
e.text_for_formatter(),
e.lines.clone(),
e.has_final_newline(),
)
});
self.status = match buffer {
Some((text, lines, final_newline)) if text == job.sent => {
if formatted == job.sent {
String::from("Document already formatted")
} else {
// The buffer keeps no line for a final newline it already
// has; one Prettier adds becomes the empty last line that
// writes it.
let body = match final_newline {
true => formatted.strip_suffix('\n').unwrap_or(&formatted),
false => &formatted,
};
let edits = crate::prettier::edits_for(&lines, body);
self.editor.apply_rename_to_open_tab(&job.path, &edits);
self.editor.clamp_cursor();
String::from("Formatted document with Prettier")
}
}
Some(_) => String::from("Prettier result dropped: the file changed while it ran"),
None => String::from("Format failed: document not open"),
};
self.complete_pending_save();
true
}
pub fn drain_lsp_format(&mut self) -> bool {
self.drain_lsp_format_at(std::time::Instant::now())
}
/// Apply a formatter reply that has arrived, or, once a format-on-save
/// has waited `FORMAT_ON_SAVE_TIMEOUT` with none, write its file
/// unformatted: a busy, hung or unreachable server left it unsaved for
/// good (#1491). Returns true when the next frame should redraw.
fn drain_lsp_format_at(&mut self, now: std::time::Instant) -> 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;
if let Some(lsp) = self.lsp.as_ref() {
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 {
let overdue = self.save_after_format.is_some()
&& self
.format_save_deadline
.is_some_and(|deadline| now >= deadline);
if overdue {
let secs = FORMAT_ON_SAVE_TIMEOUT.as_secs();
self.save_without_formatting(&format!("the formatter did not answer in {secs} s"));
}
return overdue;
}
self.format_request_id = None;
self.land_format(edits, unsupported, path);
true
}
/// Write a format-on-save's file now, unformatted, and drop the reply
/// it was waiting on, which would otherwise land on the saved text.
fn save_without_formatting(&mut self, reason: &str) {
let Some(path) = self.save_after_format.clone() else {
return;
};
self.format_request_id = None;
self.format_request_seq = None;
self.format_request_selection = false;
self.complete_pending_save();
// A refused write (a disk conflict, a lossy encoding) or a skipped
// one (the tab was closed meanwhile) keeps the status it set.
if self.path_is_saved(&path) {
self.status = format!(
"Saved {} without formatting: {reason}",
self.status_path(&path)
);
}
}
/// Whether `path` is open in some tab, in any split, and none of its
/// tabs has unsaved edits. A closed file was not written, so it is not
/// saved either.
fn path_is_saved(&self, path: &Path) -> bool {
let mut tabs = std::iter::once(&self.editor)
.chain(self.editor_layout.inactive_groups())
.flat_map(|g| g.editors.iter())
.filter(|e| e.path.as_deref() == Some(path))
.peekable();
tabs.peek().is_some() && tabs.all(|e| !e.dirty)
}
/// Apply a formatter's reply to the request in flight, then finish a
/// format-on-save. Split from [`Self::drain_lsp_format`] so tests can
/// deliver a reply without a server.
fn land_format(
&mut self,
edits: Option<Vec<crate::widgets::editor::TextSpanEdit>>,
unsupported: bool,
path: Option<PathBuf>,
) {
let selection = std::mem::take(&mut self.format_request_selection);
let requested_at = self.format_request_seq.take();
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;
}
match (edits, path) {
// The edits are positions in the text the server was sent; typed
// into since, they land on the wrong lines (#1127). Drop them, as
// VS Code does, and let a format-on-save write what is there.
(Some(edits), Some(path))
if !edits.is_empty() && self.format_target_seq(&path) != requested_at =>
{
let file = self.status_path(&path);
let saving = self.save_after_format.is_some();
self.complete_pending_save();
self.status = if saving {
format!(
"Saved {file} without formatting: it changed while the formatter was running"
)
} else {
format!(
"Format skipped: {file} changed while the formatter was running; format again"
)
};
return;
}
(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();
}
/// 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;
};
// A modify/delete conflict resolved to the deleting side leaves an
// empty Result: the resolution is "no file", so remove it from the
// index and the disk, as `git rm` would (#1244).
if self
.editor
.merge
.as_ref()
.is_some_and(|mv| mv.deleted.is_some())
&& self.editor.lines.iter().all(|l| l.is_empty())
{
let rel = self.repo_rel(&path);
let root = self.scm_root();
match crate::git::remove_path(&root, &rel) {
Ok(()) => {
self.close_tabs_with_path_everywhere(&path);
self.refresh_source_control();
self.status = format!("Merge complete: removed {rel}");
}
Err(e) => self.status = format!("Remove failed: {e}"),
}
return;
}
// The merge of an agent's proposal with unsaved edits (#1353): the
// save is the approval, and the file is croft's scratch copy, which
// no repository should stage.
if self
.approval_edit
.as_ref()
.is_some_and(|(_, scratch)| *scratch == path)
{
if self.editor.dirty {
self.save();
} else {
self.approve_saved_edit(&path);
}
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) => {
let why = self.git_error_line("add", &e);
self.status = format!("Stage failed: {why}");
}
}
}
/// 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 mut deleted = None;
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 read as an
// empty side; a deleted one is also remembered, so taking it
// removes the file rather than staging an empty one (#1244).
(o, t) => {
let base = crate::git::read_file_at_stage(&canon_root, &rel, 1).map(&to_lines);
if base.is_ok() {
deleted = match (&o, &t) {
(Err(_), Ok(_)) => Some(crate::merge_editor::CheckSide::Current),
(Ok(_), Err(_)) => Some(crate::merge_editor::CheckSide::Incoming),
_ => None,
};
}
Some((
base.unwrap_or_default(),
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;
};
mv.deleted = deleted;
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);
}
/// The range a Quick Fix asks the server about, as UTF-16 `(line, col)`
/// start and end, with the diagnostics on its lines as context: the
/// selection when there is one (VS Code sends it, so selection-scoped
/// refactors like Extract Function are offered), else the caret point.
#[allow(clippy::type_complexity)]
fn code_action_request(
&self,
) -> ((u32, u32), (u32, u32), Vec<crate::lsp::manager::Diagnostic>) {
let ((sr, sc), (er, ec)) = match self.editor.selection.filter(|s| s.has_area()) {
Some(sel) => sel.normalised(),
None => {
let caret = (self.editor.cursor_row, self.editor.cursor_col);
(caret, caret)
}
};
let start = self.editor.pos_to_utf16(sr, sc);
let end = self.editor.pos_to_utf16(er, ec);
// Rows are plain line numbers, unaffected by the UTF-16 columns.
let diagnostics = self.editor.diagnostics_in_line_range(start.0, end.0);
(start, end, diagnostics)
}
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;
};
let ((sr, sc), (er, ec), diagnostics) = self.code_action_request();
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, sr, sc, er, ec, diagnostics);
self.code_action_request_id = Some(id);
self.code_action_pending_resolve = false;
self.code_action_baseline = self.edit_seqs_in_every_group();
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 let Some(file) = self.stale_edit_target(&self.code_action_baseline, &item.edits) {
self.status = format!(
"Quick fix cancelled: {file} changed while the server was working; try it again"
);
return;
}
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.code_action_baseline = self.edit_seqs_in_every_group();
self.status = String::from("Resolving quick fix");
}
/// Accept a completion by the server's own edit and its additional edits
/// (auto-imports), shifted by what was typed or deleted at the caret since
/// the request, as one generated edit and one undo step. A snippet's
/// range is cleared by the same edit and its body then expanded at the
/// caret, tab stops and all: expanded over the typed prefix alone, a
/// range reaching further left the rest in the buffer, and the imports
/// never came. False when the item has no usable edit, for the prefix
/// fallback.
fn accept_completion_edit(&mut self, item: &crate::lsp::CompletionItem) -> bool {
use crate::widgets::editor::TextSpanEdit;
let Some(te) = &item.text_edit else {
return false;
};
let row = self.editor.cursor_row;
if te.start.0 != row || te.end.0 != row || (!item.is_snippet && te.new_text.contains('\n'))
{
return false;
}
let inserted = if item.is_snippet {
String::new()
} else {
te.new_text.clone()
};
let Some(line) = self.editor.lines.get(row) else {
return false;
};
let to_char = |e: &TextSpanEdit, c: usize| {
if e.utf16 {
crate::widgets::editor::utf16_to_char_col(line, c as u32)
} else {
c
}
};
let caret = self.editor.cursor_col;
// The server's ranges describe the line when the completion was asked
// for; the caret has moved since by what was typed (or deleted) at it.
// Everything on this row from the request point on shifts with it,
// both ways: a Backspace after the request made the server's end
// reach past the word and swallow the `)` after it.
let shift: isize = match self.completion_origin {
Some((r, c)) if r == row => caret as isize - c as isize,
_ => 0,
};
let origin_col = self.completion_origin.map_or(caret, |(_, c)| c);
let moved = |c: usize| -> usize {
if c >= origin_col {
(c as isize + shift).max(0) as usize
} else {
c
}
};
let line_len = line.chars().count();
let start = to_char(te, te.start.1);
let end = moved(to_char(te, te.end.1)).max(caret).min(line_len);
if start > caret {
return false;
}
// The main edit and its additional edits (auto-imports) go in as ONE
// edit against the same text, as the spec defines them: applied one
// after the other, an import on this row landed in the edited line,
// and one accept took two undos.
let mut edits = vec![TextSpanEdit {
start: (row, start),
end: (row, end),
new_text: inserted.clone(),
utf16: false,
}];
for e in &item.additional_edits {
let mut e = e.clone();
if e.start.0 == row {
e.start.1 = moved(to_char(&e, e.start.1));
e.end.1 = if e.end.0 == row {
moved(to_char(&e, e.end.1))
} else {
e.end.1
};
e.utf16 = false;
}
edits.push(e);
}
// The caret lands after the inserted text, moved by what the
// additional edits before it added or removed.
let mut caret_row = row as isize;
let mut caret_col = (start + inserted.chars().count()) as isize;
for e in &edits[1..] {
if e.end > (row, start) {
continue;
}
let added_rows = e.new_text.matches('\n').count() as isize;
caret_row += added_rows - (e.end.0 - e.start.0) as isize;
if e.end.0 == row {
let tail = e.new_text.rsplit('\n').next().unwrap_or("").chars().count() as isize;
caret_col += if added_rows == 0 && e.start.0 == row {
tail - (e.end.1 - e.start.1) as isize
} else {
tail + e.start.1 as isize - e.end.1 as isize
};
}
}
// An accepted completion is the server's text, not the user's (#349).
self.editor
.apply_span_edits_as(&edits, crate::provenance::Seat::Generated);
self.editor.cursor_row = caret_row.max(0) as usize;
self.editor.cursor_col = caret_col.max(0) as usize;
self.editor.clamp_cursor();
if item.is_snippet {
self.editor.expand_snippet(&te.new_text, 0);
}
true
}
/// 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());
let item = self
.completion_popup
.as_ref()
.and_then(|p| p.selected_item().cloned());
self.completion_popup = None;
self.completion_request_id = None;
if let Some(item) = item
&& self.accept_completion_edit(&item)
{
return true;
}
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 incomplete = self.note_incomplete_completion_edit();
let Some(popup) = self.completion_popup.as_mut() else {
return;
};
popup.set_prefix(prefix);
if !popup.visible_is_empty() {
return;
}
self.completion_popup = None;
// A capped list (`isIncomplete`) only holds what matched the word
// as it was (#1529): with none of it left, the session still waits
// on the re-ask for the word as it is.
if !incomplete {
self.completion_request_id = None;
}
}
/// A word edit while the pending completion is an incomplete list
/// (#1529): mark a re-ask due, popup shown or not. Returns whether the
/// session is incomplete.
fn note_incomplete_completion_edit(&mut self) -> bool {
let live = self.completion_incomplete && self.completion_request_id.is_some();
if live {
self.completion_reask_due = true;
}
live
}
/// Send the re-ask a word edit left due (#1529). Runs after `sync_lsp`,
/// so the server has the edit's `didChange` before the request; keeps
/// the session's origin so the reply opens while the caret stays in the
/// word, and ends the session once the caret has left it.
fn send_due_completion_reask(&mut self) {
if !std::mem::take(&mut self.completion_reask_due) {
return;
}
if !self.completion_incomplete || self.completion_request_id.is_none() {
return;
}
let Some(path) = self.editor.path.clone() else {
return;
};
if self.editor.has_non_text_view() || !self.completion_origin_covers_caret(&path) {
self.completion_incomplete = false;
self.completion_request_id = None;
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_for_incomplete(path, line, character);
self.completion_request_id = Some(id);
}
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;
}
self.render_welcome_panel(frame, outer_area);
// The first-launch tour (#377), until it has been taken or skipped.
if !self.tour_done && self.tour.is_none() && outer_area.height > 6 {
let label = " Take the Tour ";
let w = label.chars().count() as u16;
if outer_area.width > w + 4 {
let rect = Rect {
x: outer_area.x + (outer_area.width - w) / 2,
y: outer_area.y + outer_area.height - 3,
width: w,
height: 1,
};
frame.render_widget(
ratatui::widgets::Paragraph::new(label).style(
Style::default()
.fg(self.theme.accent_contrast_fg())
.bg(self.theme.accent())
.add_modifier(Modifier::BOLD),
),
rect,
);
self.welcome_tour_button = rect;
}
}
}
fn render_welcome_panel(&mut self, frame: &mut ratatui::Frame, outer_area: Rect) {
// 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.
//
// It never shares a cell with the logo or the tagline at any size
// (#1843): it starts past the logo's cells, which the image fills
// edge to edge, and its three rows end on the logo's last row, so
// the tagline below (whose last column reaches the badge's first)
// can never paint over its corner. Where there is no room beside
// the logo, the version goes in the blank row under it instead.
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).min(logo_h_cells.saturating_sub(3));
let gap_y = logo_y + logo_h_cells;
let badge_fits = badge_x + version_w + 2 <= area.x + area.width && badge_y + 2 < area_max_y;
// Clear of the Take the Tour button, two rows above the border.
if !badge_fits && gap_y + 2 < area_max_y && version_w <= area.width {
frame.buffer_mut().set_string(
area.x + (area.width - version_w) / 2,
gap_y,
&version_label,
Style::default()
.fg(self.theme.ui(rgb_color(GRAD_TL)))
.add_modifier(Modifier::BOLD),
);
}
if badge_fits {
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)", or "> IN THIS BUILD
// (vX.Y.Z+)" for a build carrying changes past that release. 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,
crate::release_notes::heading(
crate::release_notes::unreleased(),
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 codeql_block = if self.is_extension_enabled("codeql") {
activity_codeql_block(area)
} else {
Rect::default()
};
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 codeql_active = self.sidebar_view == SidebarView::CodeQL;
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 codeql_hovered = hov == Some(ActivityIcon::CodeQL);
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 codeql_block.width > 0 {
render_glyph(
frame,
codeql_block,
crate::icons::ACTIVITY_CODEQL,
codeql_active,
codeql_hovered,
);
}
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.codeql_icon = codeql_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),
SidebarView::CodeQL => {
self.codeql.theme = self.theme;
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, wraps, _) = t.grid_lines_wrapped();
let end = lines
.iter()
.rposition(|l| !l.trim().is_empty())
.map_or(0, |i| i + 1);
// Masked before the cut, over wrapped rows joined, so a
// secret straddling a wrap (or the cut) is still masked.
// Persisted to disk and replayed next launch: every
// redact rule applies (#360), as for the dump.
let masked = crate::triggers::mask_rows(&lines[..end], &wraps, &triggers);
let start = end.saturating_sub(crate::terminal_session::TRANSCRIPT_LINES);
masked[start..end].to_vec()
},
host: t.host_socket().map(|s| s.display().to_string()),
})
.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.
/// Called once at startup, replacing the default lone pane.
///
/// What comes back depends on where croft runs (#1458). A local launch
/// brings back only panes with something still in them: a shell still
/// running in its pane host, and an agent lane, whose agent is seated
/// again. A plain pane whose shell has ended would come back as an
/// empty fresh shell, so it is left out, and a launch with nothing to
/// bring back keeps the one default terminal. A remote croft (over
/// SSH, as `croft remote` runs it) restores every pane, so a dropped
/// connection comes back to the panel it had.
pub fn restore_terminal_session(&mut self) {
self.restore_terminal_session_with(self.terminal_restore_respawns);
}
/// [`Self::restore_terminal_session`], with `respawn` saying whether a
/// plain pane whose shell has ended comes back as a fresh shell in its
/// directory (with its name and transcript). A recorded directory that
/// no longer exists falls back to the workspace root; a pane whose
/// shell fails to spawn is skipped. Focus returns to the pane that had
/// it, or the first pane when that one was not brought back.
fn restore_terminal_session_with(&mut self, respawn: bool) {
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();
let mut active = 0;
for (i, p) in rec.panes.iter().enumerate() {
// 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()
}
}
};
// A shell still running in its pane host (croft was killed, not
// quit) is reattached as it is: its screen is redrawn by the
// host, and a lane's agent is still running in it (#694).
let reattached = p
.host
.as_deref()
.map(Path::new)
.filter(|s| crate::session::is_alive(s))
.and_then(|s| PtyTerminal::attach_hosted(s).ok());
if let Some(mut t) = reattached {
t.set_manual_name(p.name.clone());
if let Some(lane) = lane {
lanes.insert(t.uid(), lane.clone());
}
if i == rec.active {
active = terms.len();
}
terms.push(t);
continue;
}
if !respawn && lane.is_none() {
continue;
}
// 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());
}
// Focus follows the saved active pane only when it is
// actually brought back; one left out or failing to spawn
// keeps the first-pane fallback, not a neighbour.
if i == rec.active {
active = terms.len();
}
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 = active.min(self.terminals.len() - 1);
self.sync_focus_flags();
self.status = format!("Restored terminal session ({} panes)", self.terminals.len());
self.save_terminal_session_if_hosted();
}
/// Record the panel now when a pane's shell is in a pane host (#694):
/// the record is how a croft that crashes finds its shells again, so it
/// must not wait for the next split or a clean quit.
pub fn save_terminal_session_if_hosted(&mut self) {
if self.terminals.iter().any(|t| t.host_socket().is_some()) {
self.save_terminal_session();
}
}
/// 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 {
crumb: None,
scroll: Default::default(),
origin,
items,
selected: 0,
open_submenu: None,
submenu_selected: 0,
target_dir: self.tree.root.clone(),
});
}
/// A terminal action run as a command (#1562): from the palette, a
/// `keybindings.json` chord or an imported VS Code one. Each acts on the
/// active pane, showing the panel when it was hidden, as its chord and
/// menu row do; those that take the keyboard (rename, copy mode, quick
/// select, history) also focus the terminal and bring its tab to the
/// front, since another bottom-panel tab would hide the mode and take
/// its keys.
fn run_terminal_command(&mut self, cmd: crate::widgets::command_palette::Command) {
use crate::widgets::command_palette::Command as Cmd;
self.show_terminal = true;
let idx = self.active_terminal;
match cmd {
Cmd::TerminalClear => self.clear_terminal_at(idx),
Cmd::TerminalRename => self.begin_rename_terminal(idx),
Cmd::TerminalKill => {
if self.close_terminal_at(idx) {
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");
}
}
Cmd::TerminalSplit => 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::TerminalNewWithProfile => self.open_terminal_profile_picker(idx),
Cmd::TerminalQuickSelect => {
self.set_bottom_panel_tab(BottomPanelTab::Terminal);
self.open_terminal_quick_select();
}
Cmd::TerminalCopyMode => {
self.set_bottom_panel_tab(BottomPanelTab::Terminal);
self.open_terminal_copy_mode();
}
Cmd::TerminalCommandHistory => {
self.set_bottom_panel_tab(BottomPanelTab::Terminal);
self.open_command_history();
}
Cmd::TerminalOpenScrollback => self.open_scrollback_in_editor(),
_ => {}
}
}
/// 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 = find_texts(self.terminals[idx].find_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) if req.probe => self.probe_view_path(&req.to_path()),
Ok(req) => {
let reply = self.apply_view_request(&req.to_path());
// `croft edit file:line[:col]` (#1606).
if let (crate::view_ipc::ViewReply::Ok, Some((row, col))) = (&reply, req.at) {
self.place_caret_at(row, col);
}
reply
}
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. The shortcut and the pane menu
/// go through [`Self::close_terminal_reporting`]; tests use this.
#[cfg(test)]
pub fn close_active_terminal(&mut self) -> bool {
self.close_terminal_at(self.active_terminal)
}
/// Open another terminal beside the active one and say so: the `Cmd+T`
/// chord and the pane menu's Split Terminal (#1598).
fn split_terminal_reporting(&mut self) {
match self.split_terminal() {
Ok(()) => {
self.terminal_status(format!("Split terminal: {} active", self.terminals.len()));
}
Err(e) => {
self.status = format!("Split terminal failed: {e}");
}
}
}
/// Close the pane at `idx` and say so, or say why not: the `Cmd+W` chord
/// (on the active pane) and the pane menu's Kill Terminal (#1598).
fn close_terminal_reporting(&mut self, idx: usize) {
if self.close_terminal_at(idx) {
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");
}
}
/// 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. A tab with
/// unsaved changes is never one: the bulk closes keep those open (#862).
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)| !ed.dirty && 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")
};
}
/// Terminal: Run Selected Text in Active Terminal (#1292): send the
/// editor's selection, or with none the caret's line, to the active
/// pane, then Enter. A block goes as one paste, bracketed when the
/// program in the pane asked for it, and Enter follows outside the
/// brackets so it runs. Without a selection the caret steps to the next
/// non-blank line, so repeated runs walk through a script. Focus stays
/// in the editor.
fn run_selected_text_in_terminal(&mut self) {
if !self.editor_is_text() {
self.status = String::from("Run Selected Text works on text tabs");
return;
}
let selected = self.editor.selection_text();
let stepping = selected.is_empty();
let text = if stepping {
self.editor
.lines
.get(self.editor.cursor_row)
.cloned()
.unwrap_or_default()
} else {
selected
};
let text = text.trim_end_matches(['\n', '\r']);
if stepping {
let next = (self.editor.cursor_row + 1..self.editor.lines.len())
.find(|&r| !self.editor.lines[r].trim().is_empty());
if let Some(row) = next {
self.editor.cursor_row = row;
self.editor.cursor_col = 0;
}
}
if text.trim().is_empty() {
self.status = String::from("Nothing to run on this line");
return;
}
let lines = text.lines().count();
let text = text.to_string();
self.show_terminal = true;
self.bottom_panel_tab = BottomPanelTab::Terminal;
self.reveal_terminal_pane(self.active_terminal);
self.paste_terminal_input(text.as_bytes());
self.write_terminal_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
self.status = format!(
"Ran {lines} line{} in {}",
if lines == 1 { "" } else { "s" },
self.terminal().label()
);
}
/// 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.
///
/// Each row is written with the colours and attributes its cells
/// showed, re-emitted as SGR per run of equal style, and the frame ends
/// with the cursor where the shell left it (hidden when the program hid
/// it), so a player shows the session rather than its text. A row a
/// redact rule touches is written as its masked plain text and gives up
/// its colour, as the scrollback dump's rows do: a mask spliced between
/// escapes could break them.
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 triggers = self.triggers.clone();
let Some((size, lines, cursor)) = self.terminals.get(self.active_terminal).map(|t| {
// The VISIBLE screen only, never the scrollback above it: writing
// history after a clear scrolls the live screen straight off the
// top, so the cast would show the tail of the history rather
// than what the user was looking at, at ~400 KB per frame.
let (rows, cursor) = t.screen_ansi_wrapped();
let plains: Vec<String> = rows.iter().map(|r| r.0.clone()).collect();
let wraps: Vec<bool> = rows.iter().map(|r| r.2).collect();
// Masked like a scrollback dump (#360): a cast is a file made to
// be shared, so every redact rule applies, and a reveal on
// screen never reaches it.
let masked = crate::triggers::mask_rows(&plains, &wraps, &triggers);
let lines: Vec<String> = rows
.into_iter()
.zip(masked)
.map(|((plain, ansi, _), masked)| if masked == plain { ansi } else { masked })
.collect();
((t.last_inner.width, t.last_inner.height), lines, cursor)
}) 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"));
frame.push_str(&cursor_suffix(cursor));
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
}
/// Keep the language server's check in step with the proposal at the
/// head of the queue (#347): send a new head's text as its file's
/// content, and when a proposal leaves the head, give the file back:
/// an open buffer's text is resent, a file no tab has is closed.
pub fn sync_approval_check(&mut self) {
let head = self
.approvals
.front()
.map(|p| (p.arrived, p.proposal.path.clone(), p.proposal.after.clone()));
if let Some(check) = self.approval_check.as_ref()
&& head.as_ref().map(|(arrived, ..)| *arrived) != Some(check.arrived)
{
self.end_approval_check();
}
let Some((arrived, path, after)) = head else {
return;
};
if self.approval_check.is_some() {
return;
}
let Some(lsp) = self.lsp.as_ref() else {
return;
};
if crate::lsp::Language::from_path(&path).is_none() {
return;
}
let opened = !self.lsp_last_seen.contains_key(&path);
if opened {
lsp.open_doc(path.clone(), after);
} else {
lsp.change_doc(path.clone(), after);
}
self.approval_check = Some(crate::agent_approval::ProposalCheck {
arrived,
started: std::time::Instant::now(),
path,
opened,
by_server: std::collections::HashMap::new(),
});
}
fn end_approval_check(&mut self) {
let Some(check) = self.approval_check.take() else {
return;
};
let tab_has_it = self
.editor
.iter_tabs()
.any(|t| t.path.as_deref() == Some(check.path.as_path()));
if tab_has_it && (!check.opened || !self.lsp_last_seen.contains_key(&check.path)) {
// A seq no tab has makes `sync_lsp` send the buffer's text next
// tick, over the proposal's. (A tab opened during a check of a
// file the check had opened needs the same: the server has it
// open already, with the proposal.)
self.lsp_last_seen.insert(check.path, u64::MAX);
} else if check.opened {
if let Some(lsp) = self.lsp.as_ref() {
lsp.close_doc(check.path.clone());
}
self.lsp_last_seen.remove(&check.path);
}
}
/// Take agent edit proposals off the hook socket and drop the ones
/// whose hook has already given up, keeping the popup on the head of
/// the queue.
fn drain_hook_requests(&mut self) -> bool {
let head = self.approvals.front().map(|p| p.arrived);
let mut changed = match self.hook_listener.as_ref() {
Some(listener) => crate::agent_approval::accept_into(listener, &mut self.approvals),
None => false,
};
// Auto-approved edits are answered before anyone is notified.
changed |= self.apply_auto_approve();
self.notify_new_approvals();
let now = std::time::Instant::now();
let before = self.approvals.len();
self.approvals.retain(|p| !p.expired(now));
changed |= self.approvals.len() != before;
if self.approvals.front().map(|p| p.arrived) != head {
self.approval_ui = None;
}
changed |= self.check_approval_edit();
if self.approvals.is_empty() {
self.approval_ui = None;
} else if self.approval_ui.is_none() && self.approval_edit.is_none() {
self.approval_ui = Some(crate::agent_approval::ApprovalUi::new(now));
changed = true;
}
self.refresh_approval_target_dirty();
changed
}
/// The unsaved text of `path`'s tab, if croft has it open and dirty in
/// any editor group. An agent's proposal is computed from disk, so it
/// knows nothing of these edits (#347).
fn dirty_tab_lines(&self, path: &Path) -> Option<Vec<String>> {
let canon = |p: &Path| std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf());
let want = canon(path);
let groups = std::iter::once(&self.editor).chain(self.editor_layout.inactive_groups());
groups
.flat_map(|g| g.editors.iter())
.find(|e| e.dirty && e.path.as_deref().is_some_and(|p| canon(p) == want))
.map(|e| e.lines.clone())
}
/// Keep the popup's dirty-target flag current: the tab may be saved or
/// edited while the proposal waits.
fn refresh_approval_target_dirty(&mut self) {
let dirty = self
.approvals
.front()
.is_some_and(|p| self.dirty_tab_lines(&p.proposal.path).is_some());
if let Some(ui) = self.approval_ui.as_mut() {
ui.target_dirty = dirty;
}
}
/// Tell the notification sinks about each proposal that arrived since
/// the last pass, once, with its Approve and Deny links (#359).
fn notify_new_approvals(&mut self) {
for i in 0..self.approvals.len() {
if self.approvals[i].notified {
continue;
}
self.approvals[i].notified = true;
let pending = &self.approvals[i];
let path = &pending.proposal.path;
let file = path
.strip_prefix(&self.hook_root)
.unwrap_or(path)
.display()
.to_string();
let event = crate::notifications::Event::ApprovalPending {
agent: pending.request.agent.clone(),
file,
token: pending.token.clone(),
};
self.notifier
.emit(event, &self.hook_root, &remote_host_label());
}
}
/// Answer "allow" to every queued proposal from the auto-approved agent
/// while its window lasts (#347), and drop the window once it ends.
/// Returns true when anything was approved or the window closed.
fn apply_auto_approve(&mut self) -> bool {
let Some((agent, until)) = self.auto_approve.clone() else {
return false;
};
let now = std::time::Instant::now();
if now >= until {
self.auto_approve = None;
self.status = format!("Stopped auto-approving {agent}: its 10 minutes are up");
return true;
}
let mut approved = Vec::new();
let mut kept = std::collections::VecDeque::new();
// A file with unsaved edits in croft is never approved unseen: the
// agent's edit would land under them. It waits for the popup, which
// offers the merge (#347).
let dirty: Vec<bool> = self
.approvals
.iter()
.map(|p| self.dirty_tab_lines(&p.proposal.path).is_some())
.collect();
for (p, dirty) in std::mem::take(&mut self.approvals).into_iter().zip(dirty) {
if p.request.agent == agent && !dirty {
approved.push(p.proposal.path.display().to_string());
p.answer(&crate::agent_hook::Decision::Allow);
} else {
kept.push_back(p);
}
}
self.approvals = kept;
if approved.is_empty() {
return false;
}
if self.approvals.is_empty() {
self.approval_ui = None;
}
self.status = format!("Auto-approved {agent}'s edit to {}", approved.join(", "));
true
}
/// Agents: Stop Auto-Approving (#347).
fn stop_auto_approve(&mut self) {
self.status = match self.auto_approve.take() {
Some((agent, _)) => format!("Stopped auto-approving {agent}"),
None => String::from("No agent is being auto-approved"),
};
}
fn handle_approval_key(&mut self, key: KeyEvent) {
let rows = self
.approvals
.front()
.map(|p| crate::agent_approval::diff_rows(&p.proposal).len())
.unwrap_or(0);
let Some(ui) = self.approval_ui.as_mut() else {
return;
};
let Some(decision) = ui.key(key, std::time::Instant::now(), rows) else {
if std::mem::take(&mut ui.edit_requested) {
self.start_approval_edit();
}
return;
};
// Approving over unsaved edits would have the agent's write land
// under them: merge instead, and approve what the merge saves.
if matches!(decision, crate::agent_hook::Decision::Allow) && ui.target_dirty {
ui.approve_all = false;
self.start_approval_edit();
return;
}
let approve_all = ui.approve_all;
if let Some(head) = self.approvals.pop_front() {
if approve_all {
let agent = head.request.agent.clone();
self.auto_approve = Some((
agent.clone(),
std::time::Instant::now() + crate::agent_approval::AUTO_APPROVE_FOR,
));
self.status = format!(
"Approving every edit from {agent} for 10 minutes (Agents: Stop Auto-Approving ends it)"
);
}
head.answer(&decision);
}
// What was already queued from that agent goes through too.
if approve_all {
self.apply_auto_approve();
}
self.approval_ui = (!self.approvals.is_empty())
.then(|| crate::agent_approval::ApprovalUi::new(std::time::Instant::now()));
}
/// `e` in the approval popup (#347): open the head proposal's text as a
/// scratch file named like the real one (so it gets its language's
/// highlighting and server), with the popup put away. Saving it
/// approves the saved text; closing it unsaved brings the popup back.
fn start_approval_edit(&mut self) {
let Some(head) = self.approvals.front() else {
return;
};
// Refused up front rather than after the user has done the editing.
if let Err(why) = crate::agent_approval::edited_input(
&head.request.tool,
&head.request.input,
head.proposal.before.as_deref(),
&head.proposal.after,
) {
self.status = why;
return;
}
let name = head
.proposal
.path
.file_name()
.map(|n| n.to_os_string())
.unwrap_or_else(|| std::ffi::OsString::from("proposal.txt"));
let dir = croft_cache_dir().join("approval-edits").join(&head.token);
let file = dir.join(name);
let token = head.token.clone();
let agent = head.request.agent.clone();
let written = std::fs::create_dir_all(&dir)
.and_then(|()| std::fs::write(&file, &head.proposal.after));
if let Err(e) = written {
self.status = format!("Could not open the proposal to edit: {e}");
return;
}
let target = head.proposal.path.clone();
let base: Vec<String> = head
.proposal
.before
.as_deref()
.unwrap_or_default()
.lines()
.map(str::to_string)
.collect();
let theirs: Vec<String> = head.proposal.after.lines().map(str::to_string).collect();
let yours = self.dirty_tab_lines(&target);
// A tab of its own: `open` on the strip's deref would load the
// scratch file INTO the current tab, over whatever it held.
if let Err(e) = self.editor.open_pinned(&file) {
self.status = format!("Could not open the proposal to edit: {e}");
return;
}
self.approval_ui = None;
self.approval_edit = Some((token, file));
self.approval_merge_into = None;
self.focus_pane(Pane::Editor);
let Some(yours) = yours else {
self.status = format!(
"Editing {agent}'s proposal: save to approve it as edited, close the tab unsaved to go back"
);
return;
};
// Three-way: the disk text both started from, your unsaved edits
// as Current, the agent's proposal as Incoming. What is saved is
// what the agent writes, and your tab takes it too.
let (mut mv, result) = crate::merge_editor::MergeView::new(base, yours, theirs, false);
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;
mv.anchor_panes_on(0);
let n = mv.conflicts.len();
if let Some(row) = mv.conflicts.first().map(|c| c.result_start) {
self.editor.cursor_row = row.min(self.editor.lines.len().saturating_sub(1));
self.editor.cursor_col = 0;
}
mv.proposal_from = Some(agent.clone());
self.editor.merge = Some(mv);
self.approval_merge_into = Some(target);
self.status = format!(
"Merging {agent}'s proposal with your unsaved edits ({n} conflict{}): save to approve the result, close the tab unsaved to go back",
if n == 1 { "" } else { "s" }
);
}
/// Keep an in-progress proposal edit honest (#347): the proposal gone
/// (answered elsewhere, or the agent stopped waiting) ends it with a
/// note; its tab closed unsaved ends it quietly, and the popup returns.
fn check_approval_edit(&mut self) -> bool {
let Some((token, file)) = self.approval_edit.clone() else {
return false;
};
if !self.approvals.iter().any(|p| p.token == token) {
self.approval_edit = None;
self.status = String::from(
"The agent stopped waiting for that edit, so saving it approves nothing",
);
return true;
}
let groups = std::iter::once(&self.editor).chain(self.editor_layout.inactive_groups());
let open = groups
.flat_map(|g| g.editors.iter())
.any(|e| e.path.as_deref() == Some(file.as_path()));
if !open {
self.approval_edit = None;
let _ = std::fs::remove_file(&file);
return true;
}
false
}
/// A save of the proposal being edited approves it with the saved text
/// as the tool's new input (#347), and closes the scratch tab.
fn approve_saved_edit(&mut self, saved: &std::path::Path) {
let Some((token, file)) = self.approval_edit.clone() else {
return;
};
if saved != file {
return;
}
let Some(idx) = self.approvals.iter().position(|p| p.token == token) else {
self.approval_edit = None;
self.status = String::from(
"The agent stopped waiting for that edit, so saving it approves nothing",
);
return;
};
let unresolved = self
.editor
.merge
.as_ref()
.filter(|_| self.editor.path.as_deref() == Some(file.as_path()))
.map_or(0, |mv| mv.unresolved_count());
if unresolved > 0 {
self.status = format!(
"{unresolved} conflict{} left: resolve {} and save again; nothing approved yet",
if unresolved == 1 { "" } else { "s" },
if unresolved == 1 { "it" } else { "them" }
);
return;
}
let text = match std::fs::read_to_string(&file) {
Ok(t) => t,
Err(e) => {
self.status = format!("Could not read the edited proposal: {e}");
return;
}
};
let pending = &self.approvals[idx];
let input = match crate::agent_approval::edited_input(
&pending.request.tool,
&pending.request.input,
pending.proposal.before.as_deref(),
&text,
) {
Ok(input) => input,
Err(why) => {
self.status = why;
return;
}
};
let Some(pending) = self.approvals.remove(idx) else {
return;
};
let agent = pending.request.agent.clone();
pending.answer(&crate::agent_hook::Decision::AllowEdited { input });
self.approval_edit = None;
if self.editor.path.as_deref() == Some(file.as_path()) {
self.editor.close_active();
}
let _ = std::fs::remove_file(&file);
self.status = format!("Approved {agent}'s edit as you changed it");
if let Some(target) = self.approval_merge_into.take() {
// Your tab takes the merged text, one Undo from your edits, so
// the agent's write lands on what the buffer already holds.
let canon = |p: &Path| std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf());
let want = canon(&target);
let lines: Vec<String> = text.lines().map(str::to_string).collect();
let mut groups = self.editor_layout.inactive_groups_mut();
groups.push(&mut self.editor);
for tab in groups
.into_iter()
.flat_map(|g| g.editors.iter_mut())
.filter(|e| e.path.as_deref().is_some_and(|p| canon(p) == want))
{
let end = tab.lines.len();
tab.splice_result_rows(0, end, lines.clone());
}
self.status = format!(
"Approved the merge of your edits and {agent}'s; your tab holds the same text"
);
}
if !self.approvals.is_empty() {
self.approval_ui = Some(crate::agent_approval::ApprovalUi::new(
std::time::Instant::now(),
));
}
}
fn render_approval_popup(&self, frame: &mut ratatui::Frame) {
let (Some(ui), Some(head)) = (self.approval_ui.as_ref(), self.approvals.front()) else {
return;
};
let area = frame.area();
crate::widgets::approval_popup::render(
area,
frame.buffer_mut(),
self.theme,
head,
ui,
self.approvals.len(),
self.workspace_root(),
self.approval_check
.as_ref()
.filter(|c| c.arrived == head.arrived),
);
}
/// 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.approval_ui.is_some()
|| 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();
}
}
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");
let (langs, ws_global) = (&self.language_prefs, self.whitespace_mode);
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 = whitespace_mode_in(langs, ws_global, editor_scope_id(ed));
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 = whitespace_mode_in(langs, ws_global, editor_scope_id(ed));
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;
self.codeql.focus_gradient = gradient;
self.codeql.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.agent_lane_panel.theme = self.theme;
self.agent_lane_panel.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;
// The labels go through `set_stringn`, which indexes the buffer
// directly, so a strip with no row inside the frame paints nothing.
let strip = strip.intersection(frame.area());
if strip.is_empty() {
return;
}
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::ALL.map(|tab| (tab, tab.label()));
// 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);
}
/// The OUTPUT tab on the Messages channel (#1609): every status message
/// croft has shown, in full, newest last.
fn show_status_messages(&mut self) {
self.output.sync();
self.output.select_by_name(crate::output::CHANNEL_MESSAGES);
self.set_bottom_panel_tab(BottomPanelTab::Output);
}
/// Output: Select Channel… (#852): the OUTPUT toolbar's channel dropdown
/// as a keyboard picker, opened on the channel shown now. Choosing one
/// shows it in the OUTPUT tab.
fn open_output_channel_picker(&mut self) {
use crate::widgets::list_picker::{ListPicker, ListPurpose, ListRow};
// The panel only syncs while painted; a tab never shown yet would
// otherwise open the picker on the wrong channel.
self.output.sync();
let current = self.output.selected_name();
let rows: Vec<ListRow> = crate::output::channel_names()
.into_iter()
.map(|name| ListRow {
id: name.clone(),
label: name,
})
.collect();
let selected = rows
.iter()
.position(|r| Some(&r.id) == current.as_ref())
.unwrap_or(0);
let mut picker = ListPicker::new(ListPurpose::OutputChannel, "Output Channels", rows);
picker.selected = selected;
self.open_list_picker(picker, "No output channels yet");
}
/// 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);
let target = self.editor_layout.neighbor_leaf_in_dir(synth, 1, dir);
self.move_active_editor_to_group(target, dir);
}
/// Move the active tab into the group at depth-first index `target`, or,
/// with none, into a new group created in direction `dir`.
fn move_active_editor_to_group(&mut self, target: Option<usize>, dir: editor_layout::Dir) {
match target {
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 "Move Editor into Next / Previous Group" (#1565): the active
/// tab moves to the group after (or before) this one in reading order;
/// past the last (or first) group, a new group opens to the right (or
/// left) to hold it, as VS Code does.
fn move_active_editor_to_adjacent_group(&mut self, next: bool) {
let here = self.editor_layout.active_dfs_index();
let (target, dir) = if next {
let target = here + 1;
(
(target < self.editor_layout.leaf_count()).then_some(target),
editor_layout::Dir::Right,
)
} else {
(here.checked_sub(1), editor_layout::Dir::Left)
};
self.move_active_editor_to_group(target, dir);
}
/// View: Move Editor Left / Right (#1565): the active tab one place
/// along its tab bar. At the end of the bar (or of the pinned block)
/// nothing moves and the status line says so.
fn move_active_tab(&mut self, right: bool) {
if !self.editor.move_active_tab(right) {
self.status = String::from(if right {
"Move: the editor is already the last tab"
} else {
"Move: the editor is already the first tab"
});
}
self.poke_cursor();
}
/// 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) {
// The new window reads the file from disk, so unsaved edits would
// stay behind in the tab this closes (#862).
if self.editor.editors.get(idx).is_some_and(|e| e.dirty) {
self.status = String::from("New Window: save the file first");
return;
}
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
}
}
}
/// Render the frame the terminal is sent: [`Self::render`], with every
/// colour fitted to the terminal's depth (#1433).
fn render_for_terminal(&mut self, frame: &mut ratatui::Frame) {
self.render(frame);
self.color_depth.fit_buffer(frame.buffer_mut());
}
fn render(&mut self, frame: &mut ratatui::Frame) {
// Set again by the welcome panel when it paints the button.
self.welcome_tour_button = Rect::default();
let size = frame.area();
self.last_frame_area = size;
if let Some(menu) = self.context_menu.as_mut() {
menu.localize();
}
self.update_announcer();
if self.notes.generation != self.notes_shown_gen {
self.notes_shown_gen = self.notes.generation;
let mut counts: std::collections::HashMap<PathBuf, usize> =
std::collections::HashMap::new();
for n in self.notes.live().filter(|n| !n.resolved) {
*counts.entry(self.tree.root.join(&n.file)).or_default() += 1;
}
self.tree.note_counts = std::sync::Arc::new(counts);
}
// 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)
};
// Centered Layout (#1585): the editor keeps its width in the middle
// of the column and the margins stay plain background.
let editor_area = if self.centered_layout_active() {
centered_editor_rect(editor_area, self.centered_layout_width)
} else {
editor_area
};
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.agent_lane_panel.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
};
self.sync_nested_repos();
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 => {
// Breakpoints change from many places (F9, the gutter,
// the condition and logpoint editors); syncing here keeps
// the list current without a refresh at each of them.
self.sync_breakpoint_list();
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),
SidebarView::CodeQL => {
self.codeql.focused = self.focus == Pane::Tree;
let running = self.codeql_run.as_ref().map(|(_, since)| {
(self.codeql_run_name.clone(), since.elapsed().as_secs())
});
self.codeql.set_running(running);
frame.render_widget(&mut self.codeql, 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;
// Without an inline-image protocol an image tab draws itself in
// half blocks (#1591).
let cell_images = !self.inline_images_enabled();
self.editor.cell_images = cell_images;
for group in self.editor_layout.inactive_groups_mut() {
group.cell_images = cell_images;
}
// 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(),
}
}));
}
// Sticky notes (#367) on this file, at their re-found lines.
self.note_box_ids.clear();
if let Some(file) = self.note_file_key() {
let lines = &self.editor.lines;
let boxes: Vec<(u64, String, crate::widgets::editor::CommentBox)> = self
.notes
.on_file(&file)
.map(|n| {
let id = Self::note_box_id(&n.id);
(
id,
n.id.clone(),
crate::widgets::editor::CommentBox {
id,
line: n.place(lines),
author: n.title(),
body: n.text(),
},
)
})
.collect();
for (id, note_id, b) in boxes {
self.note_box_ids.insert(id, note_id);
self.editor.comment_boxes.push(b);
}
}
// Pending review comments (#366) on this file, until submitted.
if !self.review_pending.is_empty()
&& let Some((root, _)) = &self.review_pr
&& let Some(rel) = self.editor.path.as_deref().and_then(|p| {
let top = self.git_worker_for_root(root).status().repo_root.clone()?;
p.strip_prefix(&top).ok().map(|r| {
r.components()
.map(|c| c.as_os_str().to_string_lossy())
.collect::<Vec<_>>()
.join("/")
})
})
{
let lines = self.editor.lines.len();
for (i, c) in self.review_pending.iter().enumerate() {
if c.path == rel {
self.editor
.comment_boxes
.push(crate::widgets::editor::CommentBox {
id: Self::PENDING_REVIEW_ID + i as u64,
line: c.line.min(lines.saturating_sub(1)),
author: String::from("you \u{b7} pending"),
body: c.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);
if self.scrubber.is_some() && self.scrub_for != self.editor.path {
self.rebuild_scrub_view();
}
let paint_history = self.scrub_view.is_some();
let active_idx = self.editor_layout.active_dfs_index();
let focused_area = if self.editor_layout.is_split() {
let mut rects = rects;
// The active group carries the minimap (#1231).
let minimap = self.carve_minimap(rects[active_idx]);
if let Some((ed_rect, full_strip, _)) = minimap {
frame.render_widget(
ratatui::widgets::Block::default()
.style(Style::default().bg(self.theme.editor_bg())),
full_strip,
);
rects[active_idx] = ed_rect;
}
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);
}
match minimap {
Some((_, _, img_rect)) => self.paint_minimap(frame, img_rect),
None => 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.paint_minimap(frame, 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
};
// The history scrubber's view stands in for the live editor's
// text (#371); the tab strip stays the live one, while the breadcrumbs
// and Outline follow the commit (see `sync_outline`).
if paint_history
&& let Some(view) = self.scrub_view.as_mut()
&& self.editor.last_body.width > 0
{
view.theme = self.theme;
// The editor paints only the rows it has text for, so a
// shorter historical file would leave the live buffer's
// lower lines showing through: blank the body first.
let body = self.editor.last_body;
frame.render_widget(ratatui::widgets::Clear, body);
frame.render_widget(
ratatui::widgets::Block::default()
.style(Style::default().bg(self.theme.editor_bg())),
body,
);
frame.render_widget(view, body);
}
self.render_scrub_slider(frame);
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);
// The selected item's signature and documentation (#1527).
if let Some(details) = popup_ref.details_area_for(area, focused_area) {
frame.render_widget(popup_ref.details(), details);
}
}
}
// 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.
// `min(1)`: at a one-row window the band is zero rows high just
// below the frame, and a one-row strip there writes outside the
// buffer (#1133).
let strip = Rect {
x: area.x,
y: area.y,
width: area.width,
height: area.height.min(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);
}
// Both update pills are one click target, doing what the updater
// chord does (#865); recorded as (start column, width).
let update_chip_x: u16 = spans.iter().map(|s| s.content.chars().count() as u16).sum();
if self.any_update_ready() {
spans.push(Span::styled(
format!(" ⟳ Update ready - {UPDATE_CROFT_CHORD} 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 `update_armed`: while the staged release
// builds, the chord 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} - {UPDATE_CROFT_CHORD} to rebuild ",
env!("CROFT_GIT_HASH")
),
Style::default()
.bg(self.theme.ui(Color::Rgb(0x8a, 0x60, 0x00)))
.fg(Color::White)
.add_modifier(Modifier::BOLD),
));
}
let update_chip_end: u16 = spans.iter().map(|s| s.content.chars().count() as u16).sum();
let update_chip = (update_chip_end > update_chip_x)
.then(|| (update_chip_x, update_chip_end - update_chip_x));
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((agent, until)) = &self.auto_approve {
let left = until
.saturating_duration_since(std::time::Instant::now())
.as_secs();
spans.push(Span::styled(
format!(
" \u{2713} auto-approving {agent} {}:{:02} ",
left / 60,
left % 60
),
Style::default()
.bg(self.theme.ui(Color::Rgb(0x8a, 0x60, 0x00)))
.fg(Color::White)
.add_modifier(Modifier::BOLD),
));
spans.push(Span::raw(" "));
}
if let Some(chip) = self.notebook_kernel_chip() {
spans.push(Span::styled(
chip,
Style::default()
.fg(self.theme.ui(Color::Rgb(0xf3, 0x9c, 0x12)))
.add_modifier(Modifier::BOLD),
));
}
// A running CodeQL query (#578): what runs and for how long, and a
// click on it cancels the run.
let mut codeql_chip: Option<(u16, u16)> = None;
if let Some((_, since)) = &self.codeql_run {
let secs = since.elapsed().as_secs();
let text = format!(
" \u{27f3} CodeQL {} {}:{:02} \u{2715} ",
self.codeql_run_name,
secs / 60,
secs % 60
);
let x: u16 = spans.iter().map(|s| s.content.chars().count() as u16).sum();
codeql_chip = Some((x, text.chars().count() as u16));
spans.push(Span::styled(
text,
Style::default()
.bg(self.theme.ui(Color::Rgb(0x2b, 0x5d, 0x8a)))
.fg(Color::White)
.add_modifier(Modifier::BOLD),
));
spans.push(Span::raw(" "));
}
if let Some((_, _, started)) = &self.recording {
// A terminal recording (#356) is the other state a user can
// leave on; it is not the macro recorder, so it has its own
// badge and says how long it has run.
let secs = started.elapsed().as_secs();
spans.push(Span::styled(
format!(" \u{25cf} CAST {}:{:02} ", secs / 60, secs % 60),
Style::default()
.bg(self.theme.ui(Color::Rgb(0x8a, 0x1c, 0x5a)))
.fg(Color::White)
.add_modifier(Modifier::BOLD),
));
spans.push(Span::raw(" "));
}
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.
// Screen reader mode shows the announcement in the status slot, and
// every status passes through the UI catalog (#621).
let status_text = if self.screen_reader && !self.announcer.line.is_empty() {
self.announcer.line.clone()
} else {
crate::i18n::tr(&self.status).into_owned()
};
// A message seen for the first time is kept, in full, in the Messages
// output channel, and may take the whole bar until the next key or
// click (#1609): elided to fit, its middle was gone for good.
if self.status != self.status_logged {
self.status_logged = self.status.clone();
// The idle "Ready" says nothing worth the cluster's room.
self.status_wide = !self.status.is_empty() && self.status != "Ready";
if !self.status.is_empty() {
crate::output::push(
crate::output::CHANNEL_MESSAGES,
crate::output::OutputLevel::Info,
&crate::i18n::tr(&self.status),
);
}
}
self.announce_pos = None;
self.status_message_rect = Rect::default();
let mut status_x: u16 = 0;
if !status_text.is_empty() {
spans.push(Span::styled("\u{2502} ", zone_div));
let x: u16 = spans.iter().map(|s| s.content.chars().count() as u16).sum();
status_x = x;
if status_h > 0 && x < outer[2].width {
self.announce_pos = Some((outer[2].x + x, outer[2].y));
}
spans.push(Span::styled(
status_text.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;
self.status_codeql_rect = match codeql_chip {
Some((x, w)) if status_h > 0 && x < status_rect.width => Rect {
x: status_rect.x + x,
y: status_rect.y,
width: w.min(status_rect.width - x),
height: 1,
},
_ => Rect::default(),
};
self.status_update_rect = match update_chip {
Some((x, w)) if status_h > 0 && x < status_rect.width => Rect {
x: status_rect.x + x,
y: status_rect.y,
width: w.min(status_rect.width - x),
height: 1,
},
_ => Rect::default(),
};
// 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).
// The active file's coverage rides the Ln/Col readout (#263): that
// segment is not a click target, so the clickable ones keep their
// indices.
let coverage = self
.editor
.coverage
.as_ref()
.and_then(|l| l.percent)
.map(|p| format!(" \u{b7} {p:.0}% covered"))
.unwrap_or_default();
let mut seg_texts: Vec<String> = vec![
format!(
" Ln {}, Col {}{coverage} ",
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 mut 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 !status_text.is_empty() {
let left_fixed: u16 = spans
.iter()
.take(spans.len().saturating_sub(1))
.map(|s| s.content.chars().count() as u16)
.sum();
let fits_beside = |right: u16| {
status_rect
.width
.saturating_sub(right)
.saturating_sub(left_fixed)
.saturating_sub(1)
};
// A fresh message that does not fit beside the cluster takes the
// cluster's room until the next key or click (#1609).
let text_cells = |t: &str| unicode_width::UnicodeWidthStr::width(t) as u16;
if self.status_wide && text_cells(&status_text) > fits_beside(right_total) {
right_total = 0;
}
let avail = fits_beside(right_total);
if let Some(last) = spans.last_mut()
&& text_cells(&last.content) > avail
{
// Keep the message's dim style through the elision so a
// truncated transient doesn't suddenly brighten.
*last = Span::styled(elide_middle(&status_text, avail as usize), last.style);
}
if status_h > 0 && status_x < status_rect.width {
let shown = spans.last().map_or(0, |l| text_cells(&l.content));
self.status_message_rect = Rect {
x: status_rect.x + status_x,
y: status_rect.y,
width: shown.min(status_rect.width - status_x),
height: 1,
};
}
}
// 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;
if self.status_message_rect.right() > rx {
self.status_message_rect.width = rx.saturating_sub(self.status_message_rect.x);
}
// 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_codeql_rect.x >= rx {
self.status_codeql_rect = Rect::default();
} else if self.status_codeql_rect.right() > rx {
self.status_codeql_rect.width = rx - self.status_codeql_rect.x;
}
if self.status_update_rect.x >= rx {
self.status_update_rect = Rect::default();
} else if self.status_update_rect.right() > rx {
self.status_update_rect.width = rx - self.status_update_rect.x;
}
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());
popup.last_area = 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_zen_hint(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_unsaved_scm_confirm(frame);
self.render_replace_all_confirm(frame);
self.render_broadcast_confirm(frame);
self.render_run_block_confirm(frame);
self.render_unsaved_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);
// Above the pickers a tour step opens (#863), so they never hide
// the caption explaining them.
self.render_tour_caption(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);
// Below the input prompt: Enter on a number or text setting opens
// the prompt over the editor, and drawn after it the editor hid it.
self.render_settings_editor(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_approval_popup(frame);
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;
self.paint_terminal_suggestion(frame);
// 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));
}
self.park_screen_reader_cursor(frame);
}
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.
let top = menu.scroll_for(clipped.height.saturating_sub(2) as usize);
self.render_menu_panel(frame, clipped, &menu.items, menu.selected, top, 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, 0, grad);
}
}
/// Paint one bordered menu panel of `entries` into `rect`, from entry
/// `top` on, 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,
top: 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));
// Clipped to the frame (a submenu flipped at a narrow edge can still
// reach past it).
let rect = rect.intersection(frame.area());
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().skip(top) {
if (i - top) as u16 >= inner.height {
break;
}
let row = Rect {
x: inner.x,
y: inner.y + (i - top) 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(), menu_hint(action, &self.keymap))
}
// 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).min(area.width);
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,
};
// Clipped to the frame: a terminal narrower or shorter than the
// dialog's minimum made a rect outside the buffer, which panics.
let rect = rect.intersection(area);
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).min(area.width);
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 rect = rect.intersection(area);
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 unsaved-changes prompt (#862): what would be lost and the three
/// ways out. Amber like Replace All's rather than red, since its default
/// (S / Enter) keeps the edits and only D throws anything away.
fn render_unsaved_confirm(&self, frame: &mut ratatui::Frame) {
let Some(exit) = self.pending_unsaved.as_ref() else {
return;
};
let (headline, names, save, discard) = match exit {
UnsavedExit::CloseTab { idx, .. } => (
String::from("This tab has unsaved changes:"),
self.editor.tab_display_label(*idx),
String::from("ave and close"),
String::from("on't save"),
),
other => {
let files = self.unsaved_files();
let verb = other.verb();
(
if files.len() == 1 {
String::from("1 file has unsaved changes:")
} else {
format!("{} files have unsaved changes:", files.len())
},
files.join(", "),
format!("ave all and {verb}"),
format!("iscard and {verb}"),
)
}
};
let area = frame.area();
let width = area.width.saturating_sub(8).clamp(50, 96).min(area.width);
let height: u16 = 8;
let rect = Rect {
x: (area.width.saturating_sub(width)) / 2 + area.x,
y: (area.height.saturating_sub(height)) / 2 + area.y,
width,
height,
};
let rect = rect.intersection(area);
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(
" UNSAVED CHANGES ",
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 key = |k: &'static str, color: Color| {
Span::styled(k, Style::default().fg(color).add_modifier(Modifier::BOLD))
};
let body = ratatui::text::Text::from(vec![
Line::from(Span::styled(
headline,
Style::default().fg(self.theme.ui(Color::White)),
)),
Line::from(""),
Line::from(Span::styled(
truncate_for_display(&names, inner.width as usize),
Style::default().fg(self.theme.ui(Color::Rgb(0xeb, 0xcb, 0x8b))),
)),
Line::from(""),
Line::from(vec![
key("[S]", Color::Green),
Span::raw(format!("{save} ")),
key("[D]", Color::Red),
Span::raw(format!("{discard} ")),
key("[Esc]", self.theme.ui(Color::White)),
Span::raw(" cancel"),
]),
]);
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).min(area.width);
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 rect = rect.intersection(area);
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,
);
}
/// The unsaved-changes prompt in front of a commit or stash (#1438):
/// names the unsaved files and offers Save All & Commit, Commit Anyway
/// or Cancel, as VS Code does.
fn render_unsaved_scm_confirm(&self, frame: &mut ratatui::Frame) {
let Some(pending) = self.pending_unsaved_scm.as_ref() else {
return;
};
let area = frame.area();
let width = area.width.saturating_sub(8).clamp(50, 96).min(area.width);
let height: u16 = 8;
let rect = Rect {
x: (area.width.saturating_sub(width)) / 2 + area.x,
y: (area.height.saturating_sub(height)) / 2 + area.y,
width,
height,
};
let rect = rect.intersection(area);
let accent = self.theme.ui(Color::Rgb(0xe5, 0xc0, 0x7b));
let verb = pending.op.verb();
let block = 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(
" UNSAVED CHANGES ",
Style::default()
.fg(Color::Black)
.bg(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 n = pending.files.len();
let names: Vec<String> = pending
.files
.iter()
.map(|p| {
p.strip_prefix(&pending.root)
.unwrap_or(p)
.display()
.to_string()
})
.collect();
let white = Style::default().fg(self.theme.ui(Color::White));
let dim = Style::default().fg(self.theme.ui(Color::Rgb(0x9a, 0xa4, 0xb8)));
let key = Style::default().fg(accent).add_modifier(Modifier::BOLD);
let body = ratatui::text::Text::from(vec![
ratatui::text::Line::from(ratatui::text::Span::styled(
format!(
"{n} file{} {} unsaved changes: {}",
if n == 1 { "" } else { "s" },
if n == 1 { "has" } else { "have" },
names.join(", ")
),
white,
)),
ratatui::text::Line::from(ratatui::text::Span::styled(
format!("{verb} records the files on disk, without these edits."),
dim,
)),
ratatui::text::Line::from(""),
ratatui::text::Line::from(vec![
ratatui::text::Span::styled("[S]", key),
ratatui::text::Span::raw(format!(" Save All & {verb} ")),
ratatui::text::Span::styled("[C]", key),
ratatui::text::Span::raw(format!(" {verb} Anyway ")),
ratatui::text::Span::styled("[Esc]", key),
ratatui::text::Span::raw(" Cancel"),
]),
]);
frame.render_widget(
ratatui::widgets::Paragraph::new(body).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).min(area.width);
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 rect = rect.intersection(area);
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).min(area.width);
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 rect = rect.intersection(area);
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).min(area.width);
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 rect = rect.intersection(area);
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 rect = rect.intersection(area);
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).min(area.width);
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 rect = rect.intersection(area);
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);
}
/// Zen Mode hides the status bar, so for a few seconds after entering
/// it a box at the bottom says how to leave (#1585).
fn render_zen_hint(&self, frame: &mut ratatui::Frame) {
if !self.zen_mode
|| !self
.zen_hint_until
.is_some_and(|until| std::time::Instant::now() < until)
{
return;
}
let text = zen_hint_text();
let area = frame.area();
let width = text.chars().count() as u16 + 4;
let height: u16 = 3;
if area.width < width || area.height < height + 1 {
return;
}
let rect = Rect {
x: area.x + (area.width - width) / 2,
y: area.y + area.height - height - 1,
width,
height,
};
let accent = self.theme.accent();
let block = ratatui::widgets::Block::default()
.borders(ratatui::widgets::Borders::ALL)
.border_type(ratatui::widgets::BorderType::Rounded)
.border_style(Style::default().fg(accent))
.style(Style::default().bg(self.theme.editor_bg()));
frame.render_widget(ratatui::widgets::Clear, rect);
frame.render_widget(
ratatui::widgets::Paragraph::new(ratatui::text::Span::styled(
text,
Style::default().fg(accent),
))
.alignment(ratatui::layout::Alignment::Center)
.block(block),
rect,
);
}
/// 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 failed = toast.failed;
let staging = self.staged_status == UpdateStatus::InProgress && !ready;
let accent = self.theme.accent();
let btn_bg = self.theme.button();
let brew = self.install_source == crate::update_check::InstallSource::Homebrew;
let actions: Vec<(String, UpdateToastAction)> = if ready {
vec![(" Relaunch ".to_string(), UpdateToastAction::Relaunch)]
} else if staging {
Vec::new()
} else if brew {
// Homebrew upgrades it (#375); the popup can only name the
// command and be dismissed.
vec![(" Later ".to_string(), UpdateToastAction::Later)]
} else {
let update = if failed.is_some() {
" Retry "
} else {
" Update "
};
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 let (Some(reason), false) = (failed, staging) {
format!("\u{2717} croft v{version} was not installed: {reason}")
} else if staging {
format!(
"{} building croft v{version} in the background",
self.update_spinner_glyph()
)
} else if brew {
format!(
"\u{27f3} croft v{version} is available - run `{}`",
crate::update_check::BREW_UPGRADE
)
} 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).min(area.width);
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 rect = rect.intersection(area);
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::SaveAs => (
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 save, Esc to cancel (missing folders are created)",
),
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",
),
PromptKind::HitCondition { .. } => (
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 hit count, e.g. 5 (blank for a plain breakpoint), Esc to cancel",
),
PromptKind::FunctionBreakpoint => (
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 break on entry to this function, Esc to cancel",
),
PromptKind::DataBreakpoint => (
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 pause when this variable is written, Esc to cancel",
),
PromptKind::NewProfile => (
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 it from your current settings, keybindings and snippets, Esc to cancel",
),
PromptKind::ReviewComment => (
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 add it to your pending review, Esc to cancel",
),
PromptKind::ReviewSummary => (
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 submit the review (the summary may be empty), Esc to cancel",
),
PromptKind::StickyNote => (
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 leave the note on this line (shared with everyone in the session), 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,
},
);
}
}
/// [`ctrl_k_leads`] for the pane that has the keyboard now.
fn ctrl_k_leads_here(&self) -> bool {
let shell_focused = self.focus == Pane::Terminal
&& matches!(self.bottom_panel_tab, BottomPanelTab::Terminal);
ctrl_k_leads(
cfg!(target_os = "macos"),
shell_focused,
self.vim.enabled && self.focus == Pane::Editor,
)
}
/// 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);
// `Cmd` held on the second key, for the chords that ask for it. Off
// macOS `Ctrl` counts, as it does for the leader (#843): VS Code's
// Linux `Ctrl+K Ctrl+S` is the Keyboard Shortcuts editor.
let cmd_held = has_cmd_or_linux_ctrl(key.modifiers);
match key.code {
// Cmd+K N in the editor: leave a sticky note on this line (#367).
// In a terminal the same chord keeps its meaning (below).
KeyCode::Char(c)
if plain
&& !shifted
&& c.eq_ignore_ascii_case(&'n')
&& self.focus == Pane::Editor =>
{
self.open_sticky_note_prompt();
true
}
// 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).
// Cmd+K Cmd+S (Cmd held on the second key): the Keyboard Shortcuts
// editor, VS Code's binding (#612). Before the plain S arm, which
// keeps Select for Compare.
KeyCode::Char(c) if c.eq_ignore_ascii_case(&'s') && cmd_held && !shifted => {
self.open_keyboard_shortcuts();
true
}
// Cmd+K Shift+F / Shift+R: open the search results as a Search
// Editor, and re-run the active one (#615). Before the plain F
// and R arms; Shift+R in the terminal keeps its own meaning.
KeyCode::Char(c) if shifted && plain && c.eq_ignore_ascii_case(&'f') => {
self.open_search_editor();
true
}
KeyCode::Char(c)
if shifted
&& plain
&& c.eq_ignore_ascii_case(&'r')
&& self.focus != Pane::Terminal =>
{
self.rerun_search_editor();
true
}
// Cmd+K Shift+G: inline AI suggestions on / off (#607).
KeyCode::Char(c) if shifted && plain && c.eq_ignore_ascii_case(&'g') => {
self.toggle_inline_suggestions();
true
}
// Cmd+K Shift+E: run the caret line's code lens (#608). Must
// precede the plain E (reveal in Explorer) arm below.
KeyCode::Char(c) if shifted && plain && c.eq_ignore_ascii_case(&'e') => {
self.run_code_lens_at_cursor();
true
}
// Cmd+K Shift+U / Shift+D: supertypes ("up") and subtypes
// ("down") of the type at the caret (#613). Case-insensitive for
// CSI-u hosts; must precede the plain U and D arms below.
KeyCode::Char(c) if shifted && plain && c.eq_ignore_ascii_case(&'u') => {
self.request_type_hierarchy_at_cursor(true);
true
}
KeyCode::Char(c) if shifted && plain && c.eq_ignore_ascii_case(&'d') => {
self.request_type_hierarchy_at_cursor(false);
true
}
// 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') && cmd_held => {
self.goto_last_edit_location();
true
}
// Cmd+K Shift+Q: Session: Detach (#679). Normally the attach
// client takes this chord before it reaches croft; this arm
// serves a leader the client released after its pause.
KeyCode::Char(c) if shifted && plain && c.eq_ignore_ascii_case(&'q') => {
self.detach_session_client();
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 => {
self.close_tabs_to_right(self.editor.active_index());
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.open_diff_across_groups(&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, path)) => self.request_remote_launch(host, path),
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 Shift+V: view the symbol at the caret in a tab of its
// own (#369; croft binding, VS Code has no such command). Must
// precede Live Run's case-insensitive Cmd+K V arm.
KeyCode::Char(c) if shifted && plain && c.eq_ignore_ascii_case(&'v') => {
self.open_symbol_tab();
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 => {
self.keep_tab_open(self.editor.active_index());
true
}
KeyCode::Char(c) if plain && c.eq_ignore_ascii_case(&'p') => {
self.toggle_tab_pin(self.editor.active_index());
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 V: Live Run, "values" for the active Python file.
KeyCode::Char(c) if plain && c.eq_ignore_ascii_case(&'v') => {
self.toggle_live_run();
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<()> {
self.editor.sync_occurrence_word_sel();
// A key press means the status message has been seen: the right-hand
// cluster takes its room back (#1609).
if matches!(key.kind, KeyEventKind::Press | KeyEventKind::Repeat) {
self.status_wide = false;
}
// 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;
// Esc Esc leaves Zen Mode (#1585), counting only Escapes in the
// editor that closed or cleared nothing: one that dismisses a popup
// or a selection is that, not half of the pair.
let zen_esc = self.zen_mode
&& self.focus == Pane::Editor
&& key.code == KeyCode::Esc
&& key.modifiers.is_empty()
&& key.kind == KeyEventKind::Press;
let before = zen_esc.then(|| self.esc_fingerprint());
let result = self.recording_file_switches(|app| app.handle_key_inner(key));
match before {
Some(before) if before == self.esc_fingerprint() => {
self.note_idle_zen_esc(std::time::Instant::now());
}
_ if key.kind != KeyEventKind::Release => self.zen_esc_at = None,
_ => {}
}
// 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(());
}
KeyCode::Up | KeyCode::Down if self.peek_refs.is_some() => {
self.step_peeked_reference(if key.code == KeyCode::Up { -1 } else { 1 });
return Ok(());
}
_ => self.close_peek_popup(),
}
}
if key.kind != KeyEventKind::Press && key.kind != KeyEventKind::Repeat {
return Ok(());
}
// Keyboard Shortcuts editor (#612): the next key is the new chord.
// Only the key that answers the prompt: once the user has clicked
// away or let it sit, a later Cmd+S must save, not become a binding.
if let Some((cmd, at)) = self.recording_shortcut.take()
&& at.elapsed() < SHORTCUT_RECORD_WINDOW
{
self.record_shortcut(cmd, key);
return Ok(());
}
// A chord that was taken (#1482): Enter reassigns it, any other key
// keeps both shortcuts as they were. The recorded chord's own key
// repeat, from holding it a moment too long, is not an answer.
if let Some((cmd, chord, owners)) = self.confirming_shortcut.take() {
if key.kind == KeyEventKind::Repeat
&& crate::keymap::Chord::from_event(key) == crate::keymap::Chord::from_event(chord)
{
self.confirming_shortcut = Some((cmd, chord, owners));
return Ok(());
}
if key.code == KeyCode::Enter && key.modifiers.is_empty() {
self.write_shortcut(cmd, chord, &owners);
} else {
self.status = String::from("Shortcut unchanged");
}
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.approval_ui.is_some() {
self.handle_approval_key(key);
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.settings_editor.is_some() && self.input_prompt.is_none() {
self.handle_settings_editor_key(key);
return Ok(());
}
// The tour (#377): Esc leaves it at any time, as its first caption
// and its keys row say, from a palette, Quick Open or picker its step
// opened too (#863). Esc there closed only that, so at the theme
// picker a user taking the caption at its word stayed in the tour.
// A modal the user opens mid-tour is theirs: its Esc just closes it.
if key.code == KeyCode::Esc
&& key.modifiers.is_empty()
&& key.kind == KeyEventKind::Press
&& self.tour.as_ref().is_some_and(|run| run.step_opened_modal)
&& (self.command_palette.is_some()
|| self.file_finder.is_some()
|| self.context_menu.is_some())
{
if self.command_palette.is_some() {
self.close_command_palette();
}
if self.file_finder.is_some() {
self.close_file_finder();
}
if self.context_menu.take().is_some() {
self.overlays.activity.mark_dirty();
}
self.finish_tour();
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(());
}
// The unsaved-changes prompt (#862): S or Enter saves, D goes on
// without saving, N or Esc cancels. N is a cancel, not "don't save":
// every other croft confirm reads N as "stop", and a reflex N must
// not throw edits away. Letters count only unmodified, so a stray
// Ctrl+D (add next match) cannot discard either.
if self.pending_unsaved.is_some() {
let plain = key.modifiers.difference(KeyModifiers::SHIFT).is_empty();
match key.code {
KeyCode::Char('s' | 'S') if plain => self.answer_unsaved(true),
KeyCode::Enter => self.answer_unsaved(true),
KeyCode::Char('d' | 'D') if plain => self.answer_unsaved(false),
KeyCode::Char('n' | 'N') if plain => self.cancel_unsaved(),
KeyCode::Esc => self.cancel_unsaved(),
_ => {}
}
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_unsaved_scm.is_some() {
match key.code {
KeyCode::Char('s') | KeyCode::Char('S') | KeyCode::Enter => {
self.save_all_then_pending_scm();
}
KeyCode::Char('c') | KeyCode::Char('C') => {
self.continue_pending_scm_without_saving();
}
KeyCode::Char('n') | KeyCode::Char('N') | KeyCode::Esc => {
self.cancel_pending_unsaved_scm();
}
_ => {}
}
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(());
}
// While a commit is on screen, keys that would edit the hidden live
// buffer are refused rather than typed blind into it (#371).
if self.scrub_view.is_some()
&& self.focus == Pane::Editor
&& matches!(key.kind, KeyEventKind::Press | KeyEventKind::Repeat)
&& !key
.modifiers
.intersects(KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SUPER)
&& matches!(
key.code,
KeyCode::Char(_)
| KeyCode::Enter
| KeyCode::Backspace
| KeyCode::Delete
| KeyCode::Tab
)
{
self.status = String::from(
"Looking at history - Esc returns to your working tree before editing",
);
return Ok(());
}
// The tour (#377): with no picker or palette open, Enter moves on and
// Esc leaves. Below the modal guards, so a picker a step opened keeps
// its own Enter and Esc; the context menu is checked here because its
// guard comes later, and the theme picker is one.
if self.tour.is_some()
&& self.context_menu.is_none()
&& key.kind == KeyEventKind::Press
&& key.modifiers.is_empty()
&& matches!(key.code, KeyCode::Enter | KeyCode::Esc)
{
if key.code == KeyCode::Enter {
self.advance_tour();
} else {
self.finish_tour();
}
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(());
}
// Ctrl+Shift+PageUp / PageDown: View: Move Editor Left / Right
// (#1565), VS Code's Linux and Windows chords. Ahead of the editor's
// Shift+PageUp / PageDown page selection, which would otherwise read
// them as a select with the Ctrl ignored.
if self.focus == Pane::Editor
&& matches!(key.code, KeyCode::PageUp | KeyCode::PageDown)
&& key.modifiers == KeyModifiers::CONTROL | KeyModifiers::SHIFT
{
self.move_active_tab(key.code == KeyCode::PageDown);
return Ok(());
}
// A user's chord for a terminal command is meant for the terminal
// (#1562), so it is taken before the shell sees the key; every other
// chord still passes through to the shell. Only the Terminal tab has
// a shell: on Output, Problems, Ports or Captures the key is the
// panel's own.
if self.focus == Pane::Terminal
&& self.bottom_panel_tab == BottomPanelTab::Terminal
&& !self.keymap.is_empty()
&& is_rebindable_chord(key)
&& let Some(cmd) = self.keymap.command_for(key).filter(|c| c.skips_the_shell())
{
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, the
// updater's Ctrl+Shift+F9 among them, keep their croft meaning
// everywhere.
let terminal_owns_fkeys = self.focus == Pane::Terminal
&& matches!(self.bottom_panel_tab, BottomPanelTab::Terminal)
&& self.debug_sessions.is_empty()
&& 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_by_user();
} 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.debug_sessions.is_empty() {
self.debug_pause();
return Ok(());
}
// Debug: Switch Session (#567), only while debugging: with no session
// the chord is not claimed at all.
if is_switch_debug_session_key(key) && !self.debug_sessions.is_empty() {
self.switch_debug_session();
return Ok(());
}
// Checked before the F9 family below, whose Shift arm would take it.
if is_update_croft_key(key) {
self.update_croft();
return Ok(());
}
if matches!(key.code, KeyCode::F(9)) && !terminal_owns_fkeys {
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 {
// Bare F9 is Toggle Breakpoint whatever the updater is
// doing (#865): it used to start a rebuild of croft when
// one was on offer, and was swallowed while it ran.
self.debug_toggle_breakpoint();
}
return Ok(());
}
if is_run_to_cursor_key(key) && !terminal_owns_fkeys {
self.debug_run_to_cursor();
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; off macOS Ctrl+K arms it too,
// except in a focused shell and the vim-mode editor (`ctrl_k_leads`).
if is_cmd_k_leader_key(key, self.ctrl_k_leads_here()) {
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, self.kitty_keys) && !sc_focused {
self.save();
return Ok(());
}
// File: New Untitled Text File (#1580). Only from the editor or the
// side bar: a terminal's `Ctrl`+`N` is the shell's next-history, and
// in a vim-mode editor it is vim's own.
if is_new_untitled_file_key(key)
&& matches!(self.focus, Pane::Editor | Pane::Tree)
&& !(self.vim.enabled
&& self.focus == Pane::Editor
&& key.modifiers.contains(KeyModifiers::CONTROL))
{
self.new_untitled_file();
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) {
// The TERMINAL tab, not whichever panel tab was last up (#852).
self.set_bottom_panel_tab(BottomPanelTab::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(());
}
// The bottom panel's tabs (#852), claimed from any pane like the
// side bar jumps above.
if is_show_problems_key(key) {
self.set_bottom_panel_tab(BottomPanelTab::Problems);
return Ok(());
}
if is_show_output_key(key) {
self.set_bottom_panel_tab(BottomPanelTab::Output);
return Ok(());
}
if is_save_all_key(key) {
self.save_all();
return Ok(());
}
// VS Code "Focus and Select Breadcrumbs" (Cmd/Ctrl+Shift+., #1608),
// claimed from any pane; the live shell keeps its Ctrl form.
let terminal_owns_ctrl_shift_dot = self.focus == Pane::Terminal
&& self.bottom_panel_tab == BottomPanelTab::Terminal
&& key.modifiers.contains(KeyModifiers::CONTROL);
if is_focus_breadcrumbs_key(key) && !terminal_owns_ctrl_shift_dot {
self.focus_breadcrumbs();
return Ok(());
}
// Ctrl+Shift+H in the live shell stays its command history; Cmd+Shift+H
// and every other pane's Ctrl+Shift+H are Replace in Files (#860).
let terminal_owns_ctrl_shift_h = self.focus == Pane::Terminal
&& self.bottom_panel_tab == BottomPanelTab::Terminal
&& key.modifiers.contains(KeyModifiers::CONTROL);
if is_replace_in_files_key(key) && !terminal_owns_ctrl_shift_h {
self.open_replace_in_files();
return Ok(());
}
if self.is_remote && is_drop_to_local_key(key) {
self.guard_unsaved(UnsavedExit::DropToLocal);
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.
//
// Ctrl+Q follows the same rule (#1290): it is vim's visual block,
// nano's search backwards and the shell's XON, and quitting from
// inside one of them killed the app, the shell and every unsaved
// tab. Quit keeps Ctrl+Q from every other pane.
let terminal_owns_ctrl = self.focus == Pane::Terminal
&& matches!(self.bottom_panel_tab, BottomPanelTab::Terminal)
&& key.modifiers == KeyModifiers::CONTROL;
if is_sidebar_toggle_key(key) && !terminal_owns_ctrl {
self.toggle_side_bar();
return Ok(());
}
match (key.code, key.modifiers) {
(KeyCode::Char('q'), KeyModifiers::CONTROL) if !terminal_owns_ctrl => {
self.guard_unsaved(UnsavedExit::Quit);
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),
SidebarView::CodeQL => self.handle_codeql_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(());
}
}
// Settle edits that landed since the last pass first (an
// LSP rename or quick fix applied to the file's tab): with
// two tabs changed at once, the keystroke's tab would be
// copied over the other and erase that edit.
self.sync_symbol_views();
self.handle_editor_key(key);
// Settle the clip on this edit before clamping the caret to
// it: a line opened at the symbol's end grows the clip, so
// the caret on it is inside, not past it (#369).
self.sync_symbol_views();
// A symbol tab's caret never leaves its symbol (#369).
self.editor.clamp_to_symbol_view();
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;
}
// VS Code's Alt+C / Alt+W / Alt+R flip the Aa / ab / .* toggles from
// any Search input, and Alt+D opens or closes the include / exclude
// rows (#860).
if let Some(toggle) = search_toggle_for_key(key) {
self.toggle_search_opt(toggle);
return;
}
if is_search_details_key(key) {
self.search.toggle_details();
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}");
}
}
_ => {}
}
}
/// Flip one of the Search side bar's mode toggles, from a click or a key,
/// and re-run the query under it. The status line names the new state:
/// the toggle's glyph is two cells in a panel that may be off-screen.
fn toggle_search_opt(&mut self, toggle: crate::widgets::search::SearchToggle) {
use crate::widgets::search::SearchToggle;
let on = self.search.toggle_opt(toggle);
let name = match toggle {
SearchToggle::CaseSensitive => "Match Case",
SearchToggle::WholeWord => "Match Whole Word",
SearchToggle::UseRegex => "Use Regular Expression",
SearchToggle::PreserveCase => "Preserve Case",
};
self.status = format!("Search: {name} {}", if on { "on" } else { "off" });
// Preserve Case shapes replacements only: the hits stay as they are.
if toggle != SearchToggle::PreserveCase {
self.submit_search_query();
}
}
/// Search: Replace in Files (#860, `Cmd+Shift+H`): the Search side bar
/// with its Replace row expanded and focused, the way the chevron opens
/// it.
fn open_replace_in_files(&mut self) {
// As for the Search jump: a live find bar would keep painting over
// the editor and shadow the side bar's input.
self.close_editor_find();
self.set_sidebar_view(SidebarView::Search);
self.search.open_replace();
}
/// 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 crate::widgets::search::as_typed(&self.search.query).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, failed) = self.search.replace_all_skipping(&dirty);
let list = |paths: &[PathBuf]| {
let names: Vec<String> = paths.iter().take(2).map(|p| self.status_path(p)).collect();
let more = paths.len().saturating_sub(names.len());
if more > 0 {
format!("{} and {more} more", names.join(", "))
} else {
names.join(", ")
}
};
let mut status = format!("Replace All: replaced {n} occurrence(s)");
if !skipped.is_empty() {
status.push_str(&format!(
"; skipped {} (unsaved changes — save first)",
list(&skipped)
));
}
if !failed.is_empty() {
status.push_str(&format!(
"; could not rewrite {} (not UTF-8, or unwritable)",
list(&failed)
));
}
self.status = status;
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();
}
// Home/End stay on the caret's line; with Ctrl they take the
// whole message (#1334).
KeyCode::Home if key.modifiers.contains(KeyModifiers::CONTROL) => {
self.source_control.message_start();
self.poke_cursor();
}
KeyCode::End if key.modifiers.contains(KeyModifiers::CONTROL) => {
self.source_control.message_end();
self.poke_cursor();
}
KeyCode::Home => {
self.source_control.home();
self.poke_cursor();
}
KeyCode::End => {
self.source_control.end();
self.poke_cursor();
}
// In a multi-line message Up/Down move between its lines; on
// its first/last line they scroll the change list as before.
KeyCode::Up => {
if self.source_control.move_cursor_up() {
self.poke_cursor();
} else {
self.source_control.scroll_up(1);
}
}
KeyCode::Down => {
if self.source_control.move_cursor_down() {
self.poke_cursor();
} else {
self.source_control.scroll_down(1);
}
}
// Shift/Alt+Enter start a new message line (the commit body),
// VS Code's multi-line SCM input; plain Enter commits.
KeyCode::Enter
if key
.modifiers
.intersects(KeyModifiers::SHIFT | KeyModifiers::ALT) =>
{
self.source_control.insert_char('\n');
self.poke_cursor();
}
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));
});
}
/// View Stash (#1581): stash `index`'s changes against the commit it
/// was made on, untracked files included, in a read-only scratch tab
/// like a commit's patch.
fn open_stash_patch(&mut self, index: usize) {
let root = self.scm_root();
let label = format!("stash@{{{index}}}");
self.status = format!("Loading {label}\u{2026}");
self.spawn_git_view(move || {
let result = crate::git::show_stash(&root, index);
Box::new(move |app: &mut App| match result {
Ok(text) => match app.editor.open_text_buffer(Path::new(&label), &text) {
Ok(()) => {
app.focus_pane(Pane::Editor);
app.sync_open_file_poll_mtime();
app.status = format!("Opened {label}");
}
Err(e) => app.status = format!("Open stash failed: {e}"),
},
Err(e) => app.status = format!("Show stash failed: {e}"),
})
});
}
/// 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) {
let root = self.scm_root();
let hash = hash.to_string();
let short_hash = short_hash.to_string();
self.status = format!("Loading commit {short_hash}\u{2026}");
self.spawn_git_view(move || {
let result = crate::git::show_commit(&root, &hash);
Box::new(move |app: &mut App| match result {
Ok(text) => {
let label = format!("commit {short_hash}");
match app.editor.open_text_buffer(Path::new(&label), &text) {
Ok(()) => {
app.focus_pane(Pane::Editor);
app.sync_open_file_poll_mtime();
app.status = format!("Opened commit {short_hash}");
}
Err(e) => app.status = format!("Open commit failed: {e}"),
}
}
Err(e) => app.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);
self.set_extension_enabled(&id, now_enabled);
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) {
// Read before the manifest goes: a re-add of a newer version must
// approve its tools afresh, like its consent below.
let command_ids = crate::mcp::registry::command_ids_of_in_dir(&self.config_dir, id);
match crate::mcp::catalog::uninstall_in(&self.config_dir.join("extensions"), id) {
Ok(()) => {
let _ =
crate::prefs::forget_mcp_tool_fingerprints_in(&self.config_dir, &command_ids);
// 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, `o` shows the
/// runner's output, 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('s' | 'S') if self.testing.is_busy() => self.cancel_test_run(),
KeyCode::Char('r' | 'R') => self.rediscover_tests(),
KeyCode::Char('w' | 'W') => {
self.toggle_test_watch(crate::testing::watch::WatchScope::All)
}
KeyCode::Char('o' | 'O') => self.show_test_runner_output(),
KeyCode::Up => self.testing.scroll_up(1),
KeyCode::Down => self.testing.scroll_down(1),
_ => {}
}
}
/// Open the bottom panel on OUTPUT with the Test Runner channel selected
/// (#845): where a failed discovery's or run's reason (the traceback,
/// the compile error) actually is. `o` in the Testing view, or a click
/// on its "see OUTPUT › Test Runner" pointer.
fn show_test_runner_output(&mut self) {
// The panel mirrors the bus's channels only when it syncs, and the
// runner may have written its first line since the last frame.
self.output.sync();
if !self.output.select_by_name(crate::output::CHANNEL_TESTS) {
self.status = String::from("The test runner has not written any output yet");
}
self.set_bottom_panel_tab(BottomPanelTab::Output);
}
/// A new run while one is in flight is refused with the way out
/// (#1534): it used to be dropped without a word, and a hung test left
/// the view refusing every run until croft quit.
fn refuse_test_run_while_busy(&mut self) -> bool {
if !self.testing.is_busy() {
return false;
}
self.status = String::from(TEST_RUN_IN_PROGRESS);
// The run in flight still reports its outcome over this (#856).
if let Some(run) = self.test_run_status.as_mut() {
run.shown = self.status.clone();
}
true
}
/// Testing: Cancel Test Run, `s` in the Testing view, or its Stop
/// control (#1534): kill the run or discovery in flight. The panel
/// settles when the worker reports the run's end.
fn cancel_test_run(&mut self) {
if !self.testing.is_busy() {
self.status = String::from("No test run in progress");
return;
}
self.test_worker.cancel();
self.status = String::from("Cancelling test run");
}
/// 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 old root's run will never report its end (#856).
self.test_run_status = None;
// The build this armed for is being dropped (#373).
self.disarm_failure_breakpoint();
self.pending_test_debug = None;
// Its names belong to the old project (#1535).
self.last_test_run = None;
if self.sidebar_view == SidebarView::Testing {
self.discover_tests();
}
}
/// Run everything with the runner's coverage tool (#263). Results
/// stream into the tree as usual; the report lands in the editor's
/// gutter, the status bar and the Testing summary.
fn run_all_tests_with_coverage(&mut self) {
if self.refuse_test_run_while_busy() || !self.testing_runner_available() {
return;
}
self.test_run_with_unsaved_saved(|app| {
app.test_worker.run_coverage();
app.set_sidebar_view(SidebarView::Testing);
app.status = String::from("Running tests with coverage");
});
}
/// Fold a finished coverage run into the editor, and keep the active
/// file's lens current: rebuilt when the report or the file changes,
/// dimmed once the file is edited or rewritten after the run.
fn sync_coverage(&mut self) -> bool {
use crate::testing::worker::CoverageError;
let mut changed = false;
match self.testing.take_coverage_error() {
Some(CoverageError::Missing { tool, install }) => {
self.status = format!(
"Coverage needs {tool}: run \"Testing: Install Coverage Tool\" ({install})"
);
self.coverage_install = Some(install);
changed = true;
}
Some(CoverageError::NoReport) => {
self.status = String::from("The coverage run wrote no report");
changed = true;
}
Some(CoverageError::Unsupported { runner }) => {
self.status = format!("Coverage is not available for {runner}");
changed = true;
}
None => {}
}
let fresh = self.testing.take_coverage_fresh();
if fresh {
self.coverage_at = Some(std::time::SystemTime::now());
if let Some(pct) = self.testing.coverage.as_ref().and_then(|c| c.percent()) {
self.status = format!("Coverage: {pct:.0}% of lines");
}
}
let path = self.editor.path.clone();
if fresh || path != self.coverage_lens_path {
self.coverage_lens_path = path.clone();
let stale = path
.as_ref()
.is_some_and(|p| self.file_changed_since_coverage(p));
self.editor.coverage = match (self.testing.coverage.as_ref(), path.as_ref()) {
(Some(c), Some(p)) => c.lens(p, stale),
_ => None,
};
changed = true;
}
if self.editor.dirty
&& let Some(lens) = self.editor.coverage.as_mut()
&& !lens.stale
{
lens.stale = true;
changed = true;
}
changed
}
/// The file on disk is newer than the coverage run.
fn file_changed_since_coverage(&self, path: &Path) -> bool {
let Some(at) = self.coverage_at else {
return false;
};
std::fs::metadata(path)
.and_then(|m| m.modified())
.is_ok_and(|m| m > at)
}
/// Drop the coverage report and give the gutter lane back to git.
fn clear_coverage(&mut self) {
self.testing.coverage = None;
self.editor.coverage = None;
self.coverage_at = None;
self.status = String::from("Coverage cleared");
}
/// Testing: Show Coverage Report (#263): the last coverage run as a
/// tab, one file per line with its percentage, least covered first.
fn show_coverage_report(&mut self) {
let Some(coverage) = self.testing.coverage.as_ref() else {
self.status = String::from("No coverage yet: run Testing: Run All Tests with Coverage");
return;
};
let report = coverage.report(&self.active_test_root);
match self
.editor
.open_text_buffer(Path::new("Coverage Report"), &report)
{
Ok(()) => self.focus_pane(Pane::Editor),
Err(e) => self.status = format!("Could not open the report: {e}"),
}
}
/// Developer: Show Memory Usage (#694): what each subsystem holds, as a
/// tab. Running it again refreshes the same tab.
fn show_memory_usage(&mut self) {
use memory_report::{BufferMem, ChannelMem, MemoryReport, ServerMem, TerminalMem};
let live = self.terminals.iter().map(|t| (t, false));
let closed = self.closed_terminals.iter().map(|c| (&c.term, true));
let terminals = live
.chain(closed)
.map(|(t, closed)| {
let (scrollback_lines, screen_lines, columns) = t.grid_extent();
let rewind_bytes = t.rewind().lock().map(|r| r.bytes()).unwrap_or(0);
TerminalMem {
name: t.label().to_string(),
closed,
rewind_bytes,
scrollback_lines,
screen_lines,
columns,
}
})
.collect();
let root = self.roots.primary().to_path_buf();
let buffers = std::iter::once(&self.editor)
.chain(self.editor_layout.inactive_groups())
.flat_map(|g| g.editors.iter())
.map(|e| {
let (steps, bytes) = e.undo_history_size();
let name = e.path.as_deref().map_or_else(
|| String::from("untitled"),
|p| p.strip_prefix(&root).unwrap_or(p).display().to_string(),
);
BufferMem { name, steps, bytes }
})
.collect();
let channels = crate::output::channel_sizes()
.into_iter()
.map(|(name, lines, bytes)| ChannelMem { name, lines, bytes })
.collect();
let mut servers: std::collections::BTreeMap<&str, ServerMem> = Default::default();
for by_server in self.lsp_diagnostics.values() {
// A server's pushed and pulled entries are one file (#1102).
let mut counted = std::collections::HashSet::new();
for (key, diags) in by_server {
let server = diagnostics_source(key);
let entry = servers.entry(server).or_insert_with(|| ServerMem {
name: server.to_string(),
files: 0,
diagnostics: 0,
});
if counted.insert(server) {
entry.files += 1;
}
entry.diagnostics += diags.len();
}
}
let report = MemoryReport {
rss_kb: perf_hud::read_rss_kb(),
rewind_budget: crate::rewind::budget().total(),
cell_bytes: std::mem::size_of::<alacritty_terminal::term::cell::Cell>(),
terminals,
buffers,
channels,
servers: servers.into_values().collect(),
}
.format();
match self
.editor
.open_text_buffer(Path::new("Memory Usage"), &report)
{
Ok(()) => self.focus_pane(Pane::Editor),
Err(e) => self.status = format!("Could not open the report: {e}"),
}
}
/// Install the runner's coverage tool in a terminal pane, where its
/// output and any prompt are visible.
fn install_coverage_tool(&mut self) {
let Some(command) = self.coverage_install.clone() else {
self.status = String::from("No coverage tool is missing");
return;
};
match crate::widgets::terminal::PtyTerminal::new(&self.active_test_root) {
Ok(mut term) => {
term.set_manual_name(Some(String::from("coverage install")));
term.write_input(format!("{command}\r").as_bytes());
self.insert_terminal(term);
self.show_terminal = true;
self.focus_pane(Pane::Terminal);
self.status = format!("Installing: {command}");
}
Err(e) => self.status = format!("Could not open a terminal: {e}"),
}
}
/// Debug: Install Go Debugger (delve) (#264). Runs `go install` in a
/// terminal pane, where the user sees the command and its output: that
/// visible run is the consent, as for a coverage tool. Without Go there
/// is nothing to run it with, so it says that instead.
fn install_delve(&mut self) {
if !crate::dap::install::go_on_path() {
self.status = crate::dap::install::dlv_missing_message(false);
return;
}
match crate::widgets::terminal::PtyTerminal::new(self.roots.primary()) {
Ok(mut term) => {
term.set_manual_name(Some(String::from("delve install")));
term.write_input(format!("{}\r", crate::dap::install::DLV_INSTALL).as_bytes());
self.insert_terminal(term);
self.show_terminal = true;
self.focus_pane(Pane::Terminal);
self.status = String::from(
"Installing delve into ~/.croft/servers/go; start debugging again once it finishes",
);
}
Err(e) => self.status = format!("Could not open a terminal: {e}"),
}
}
/// Remote: Sync Config Now (#262): run `croft sync-config <host>` in a
/// terminal pane, where ssh can ask for a password and the report of
/// what was pushed, kept or left for the user to settle stays readable.
fn sync_config_to(&mut self, host: &str) {
let host = host.trim();
// Typed into a shell below: an alias is plain, so anything else is
// refused rather than quoted.
let plain = !host.is_empty()
&& !host.starts_with('-')
&& host
.chars()
.all(|c| c.is_ascii_alphanumeric() || "._@-".contains(c));
if !plain {
self.status = format!("{host:?} is not an ssh host alias");
return;
}
let exe = std::env::current_exe()
.map(|p| p.display().to_string())
.unwrap_or_else(|_| String::from("croft"));
match crate::widgets::terminal::PtyTerminal::new(self.roots.primary()) {
Ok(mut term) => {
term.set_manual_name(Some(format!("config sync: {host}")));
term.write_input(
format!(
"{} sync-config {host}\r",
crate::remote::shell_quote_for_e_arg(std::path::Path::new(&exe))
)
.as_bytes(),
);
self.insert_terminal(term);
self.show_terminal = true;
self.focus_pane(Pane::Terminal);
self.status = format!("Syncing config to {host}");
}
Err(e) => self.status = format!("Could not open a terminal: {e}"),
}
}
/// Watch `scope`, or stop watching it (#263).
fn toggle_test_watch(&mut self, scope: crate::testing::watch::WatchScope) {
use crate::testing::watch::WatchScope;
let label = match &scope {
WatchScope::All => String::from("all tests"),
WatchScope::Suite(s) => format!("suite {s}"),
WatchScope::Test(t) => t.clone(),
};
self.status = if self.testing.watch.toggle(scope) {
format!("Watching {label}: it reruns when a file is saved")
} else {
format!("Stopped watching {label}")
};
}
/// Rerun what is watched, if a save made it due, and report a watched
/// run that has just turned red. A rerun leaves the sidebar where the
/// user has it: a save should not pull them away from what they were
/// doing. A red run already raises the activity-bar badge; the status
/// line adds which test and how to get to it.
fn tick_test_watch(&mut self) -> bool {
use crate::testing::watch::{WatchNotice, WatchScope};
// The one reader of the run-ended latch also settles a run's
// "Running …" status (#856).
let finished = self.testing.take_finished();
let mut changed = self.announce_test_run_end(finished);
if let Some(ok) = finished
&& self.testing.watch.finished(ok) == WatchNotice::NewlyRed
{
self.status = match self.testing.first_failed() {
Some(name) => {
format!("Watched tests failed: {name} (Testing: Go to First Failure)")
}
None => String::from("Watched tests failed"),
};
changed = true;
}
if self.testing.watch.scope().is_none() {
return changed;
}
// Only a due rerun needs the runner looked up: that lookup reads the
// runner manifests, and this runs on every pass of the main loop
// while a watch is on (#1841).
let now = std::time::Instant::now();
if self.testing.watch.due_at().is_none_or(|due| now < due) {
return changed;
}
let busy = self.testing.is_busy()
|| crate::testing::worker::runner_for(&self.active_test_root).is_none();
let Some(scope) = self.testing.watch.take_due(now, busy) else {
return changed;
};
match scope {
WatchScope::All => self.test_worker.run_all(),
WatchScope::Suite(suite) => {
self.testing
.start_filter(&crate::testing::suite_pattern(&suite));
self.test_worker.run_suite(suite);
}
WatchScope::Test(name) => {
self.testing.start_single(&name);
self.test_worker.run_one(name);
}
}
true
}
/// Jump to the first failing test's source.
fn go_to_first_failed_test(&mut self) {
match self.testing.first_failed() {
Some(name) => self.jump_to_test_source(name),
None => self.status = String::from("No failing tests"),
}
}
/// CodeQL: Run Tests (#578): every CodeQL test, through the Testing
/// view's run-all, with the same `codeql` the side bar runs. Refused,
/// with the reason, when the workspace's runner is not the CodeQL one.
fn run_codeql_tests(&mut self) {
use crate::testing::worker::{Runner, runner_for};
if runner_for(&self.active_test_root) != Some(Runner::Codeql) {
self.status = String::from(
"No CodeQL tests here: a test pack's qlpack.yml declares tests: or extractor:",
);
return;
}
if self.refuse_test_run_while_busy() {
return;
}
self.run_all_tests();
self.status = String::from("Running CodeQL tests");
self.await_test_run_outcome(String::from("CodeQL tests"));
}
/// CodeQL: Accept Test Output (#578): make a failing CodeQL test's
/// actual results its expected ones, through `codeql test accept`. The
/// test is the one the open file belongs to (its `.ql`, `.qlref`,
/// `.expected` or `.actual`), else every CodeQL test the last run
/// failed. Only tests a run left `.actual` output for are accepted.
fn accept_codeql_test_output(&mut self) {
use crate::testing::codeqltest as ct;
let tests: Vec<PathBuf> = match self.editor.path.as_deref().and_then(ct::test_for_file) {
Some(test) => vec![test],
None => self
.testing
.failed_names()
.into_iter()
.map(|id| self.active_test_root.join(ct::id_path(&id)))
.filter(|t| t.is_file())
.collect(),
};
if tests.is_empty() {
self.status = String::from(
"No CodeQL test to accept: open one of its files, or run the tests first",
);
return;
}
let ready: Vec<PathBuf> = tests
.into_iter()
.filter(|t| ct::actual_output(t).is_file())
.collect();
if ready.is_empty() {
self.status = String::from(
"No actual output to accept: run the test first, and accept it once it fails",
);
return;
}
let what = match ready.as_slice() {
[one] => one
.file_name()
.map_or_else(String::new, |n| n.to_string_lossy().into_owned()),
many => format!("{} tests", many.len()),
};
self.start_codeql_pack_job(
ct::accept_args(&ready),
format!("Accepting the output of {what}\u{2026}"),
format!("Accepted the output of {what} as expected"),
format!("Could not accept the output of {what}"),
);
}
/// Point every CodeQL run at `program`: the side bar's queries and,
/// through the test worker, the Testing view's CodeQL tests (#578).
/// The one place the configured `codeql` changes, so the two never
/// disagree.
fn set_codeql_program(&mut self, program: PathBuf) {
self.test_worker.set_codeql_program(program.clone());
self.codeql_program = program;
}
/// Pick the `codeql` to run from settings, `PATH` and croft's managed
/// copies (#578), at startup and when the setting changes.
fn resolve_codeql_cli(&mut self) {
let home = std::env::var_os("HOME").map(PathBuf::from);
let resolved = crate::codeql_cli::resolve(
self.codeql_cli_setting.as_deref(),
home.as_deref(),
std::env::var_os("PATH").as_deref(),
&croft_cache_dir(),
);
self.codeql_cli_source = resolved.source;
self.set_codeql_program(resolved.program);
}
/// 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.refuse_test_run_while_busy() || !self.testing_runner_available() {
return;
}
self.last_test_run = Some(LastTestRun::All);
self.test_run_with_unsaved_saved(|app| {
app.test_worker.run_all();
app.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.refuse_test_run_while_busy() || !self.testing_runner_available() {
return;
}
self.last_test_run = Some(LastTestRun::One(name.clone()));
self.test_run_with_unsaved_saved(|app| {
app.testing.start_single(&name);
app.test_worker.run_one(name);
app.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.refuse_test_run_while_busy() || !self.testing_runner_available() {
return;
}
self.last_test_run = Some(LastTestRun::Suite(suite.clone()));
self.test_run_with_unsaved_saved(|app| {
app.testing
.start_filter(&crate::testing::suite_pattern(&suite));
app.test_worker.run_suite(suite);
app.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.refuse_test_run_while_busy() || !self.testing_runner_available() {
return;
}
self.test_run_with_unsaved_saved(|app| app.run_named_test_now(name));
}
fn run_named_test_now(&mut self, name: String) {
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.last_test_run = Some(LastTestRun::One(run.clone()));
self.test_worker.run_one(run.clone());
} else {
self.testing.start_filter(&run);
self.last_test_run = Some(LastTestRun::Filter(run.clone()));
self.test_worker.run_filter(run.clone());
}
self.set_sidebar_view(SidebarView::Testing);
self.status = format!("Running test {run}");
self.await_test_run_outcome(crate::testing::leaf_name(&run).to_string());
}
/// When a test run is already going, say so (#1535) rather than let a
/// palette command do nothing; true when it was.
fn testing_busy_says_so(&mut self) -> bool {
if self.testing.is_busy() {
self.status = String::from("Tests are already running");
return true;
}
false
}
/// Testing: Run Tests in Current File (#1535): the suite the active
/// file is, in the runner's own naming (see [`file_test_suite`]). A file
/// the runner cannot select by itself says so.
fn run_tests_in_current_file(&mut self) {
if self.testing_busy_says_so() || !self.testing_runner_available() {
return;
}
let Some(path) = self.editor.path.clone() else {
self.status = String::from("Run Tests in Current File: open a test file first");
return;
};
let root = self.active_test_root.clone();
let suite = crate::testing::worker::runner_for(&root)
.and_then(|runner| file_test_suite(runner, &root, &path));
let Some(suite) = suite else {
self.status = String::from(
"Run Tests in Current File: the runner cannot pick out this file's tests; use Run All Tests",
);
return;
};
self.run_suite(suite.clone());
self.status = format!("Running tests in {suite}");
self.await_test_run_outcome(suite);
}
/// Testing: Rerun Failed Tests (#1535): each test the tree shows failed,
/// by its exact name.
fn rerun_failed_tests(&mut self) {
if self.testing_busy_says_so() || !self.testing_runner_available() {
return;
}
let failed = self.testing.failed_names();
if failed.is_empty() {
self.status = String::from("Rerun Failed Tests: no test has failed");
return;
}
self.start_many_tests(failed);
}
/// Run `names` exactly, one after another, as one run.
fn start_many_tests(&mut self, names: Vec<String>) {
self.testing.start_many(&names);
self.last_test_run = Some(LastTestRun::Many(names.clone()));
let label = format!("{} tests", names.len());
self.test_worker.run_many(names);
self.set_sidebar_view(SidebarView::Testing);
self.status = format!("Running {label}");
self.await_test_run_outcome(label);
}
/// Testing: Rerun Last Run (#1535): the last run started, as it was
/// asked (everything, one test, a filter, a suite or a set).
fn rerun_last_test_run(&mut self) {
if self.testing_busy_says_so() {
return;
}
let Some(last) = self.last_test_run.clone() else {
self.status = String::from("Rerun Last Run: no test has run yet");
return;
};
if !self.testing_runner_available() {
return;
}
match last {
LastTestRun::All => self.run_all_tests(),
LastTestRun::One(name) => self.run_test(name),
LastTestRun::Suite(suite) => self.run_suite(suite),
LastTestRun::Filter(pattern) => {
self.testing.start_filter(&pattern);
self.last_test_run = Some(LastTestRun::Filter(pattern.clone()));
self.test_worker.run_filter(pattern);
self.set_sidebar_view(SidebarView::Testing);
}
LastTestRun::Many(names) => self.start_many_tests(names),
}
}
/// Keep the "Running …" status a test run just set until the run ends,
/// when [`Self::announce_test_run_end`] replaces it with the outcome
/// (#856).
fn await_test_run_outcome(&mut self, label: String) {
self.test_run_status = Some(RunningStatus::new(&self.status, label));
}
/// Once the test run that set a "Running …" status is over, say how it
/// went there (#856): the panel's tree updates, but nothing else touched
/// the status bar, which went on claiming a run long finished. Only
/// while the bar still shows what the run set, so a newer message is
/// never clobbered. Nothing has ended until the run-ended latch fires: a
/// run-all is idle until the worker's start lands. A run that ended with
/// no verdict (the coverage tool missing) just lets go. `finished` is
/// the panel's run-ended latch, which the caller has consumed.
fn announce_test_run_end(&mut self, finished: Option<Option<bool>>) -> bool {
let Some(verdict) = finished else {
return false;
};
// Another run already started in the same drain: the status that
// waits is its, and its own end settles it.
if self.testing.is_busy() {
return false;
}
let Some(run) = self.test_run_status.take() else {
return false;
};
let Some(ok) = verdict else {
return false;
};
let testing = &self.testing;
run.settle(&mut self.status, |label, took| {
testing.run_outcome(label, ok, took.as_secs_f64())
})
}
/// Keep the "Running …" status a task or fenced block just set until
/// pane `pane` reports the command finished (#856). A newer run in the
/// same pane takes over the wait.
fn await_pane_outcome(&mut self, pane: u64, label: String) {
self.pane_run_statuses.retain(|(uid, _)| *uid != pane);
self.pane_run_statuses
.push((pane, RunningStatus::new(&self.status, label)));
}
/// Testing: Run Test at Cursor with Coverage (#263): the caret's test
/// alone, resolved as run-at-cursor resolves it, under the coverage
/// tool. The report replaces the last one, and so describes only the
/// code that test reached.
fn run_test_at_cursor_with_coverage(&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 with Coverage: no function at the caret");
return;
};
if self.refuse_test_run_while_busy() || !self.testing_runner_available() {
return;
}
self.test_run_with_unsaved_saved(|app| app.run_test_at_cursor_with_coverage_now(name));
}
fn run_test_at_cursor_with_coverage_now(&mut self, name: String) {
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);
} else {
self.testing.start_filter(&run);
}
self.test_worker
.run_coverage_scoped(crate::testing::worker::CoverageScope {
name: run.clone(),
exact,
suite: false,
});
self.set_sidebar_view(SidebarView::Testing);
self.status = format!("Running test {run} with coverage");
self.await_test_run_outcome(crate::testing::leaf_name(&run).to_string());
}
/// A Testing-tree row's coverage glyph (#263): that test, or that whole
/// suite, under the coverage tool, marked in the tree as a plain run of
/// it would be. The report replaces the last one.
fn run_scope_with_coverage(&mut self, name: String, suite: bool) {
if self.refuse_test_run_while_busy() || !self.testing_runner_available() {
return;
}
self.test_run_with_unsaved_saved(|app| app.run_scope_with_coverage_now(name, suite));
}
fn run_scope_with_coverage_now(&mut self, name: String, suite: bool) {
if suite {
self.testing
.start_filter(&crate::testing::suite_pattern(&name));
} else {
self.testing.start_single(&name);
}
self.test_worker
.run_coverage_scoped(crate::testing::worker::CoverageScope {
name: name.clone(),
exact: !suite,
suite,
});
self.status = if suite {
format!("Running suite {name} with coverage")
} else {
format!("Running test {name} with coverage")
};
let label = if suite {
format!("suite {name}")
} else {
crate::testing::leaf_name(&name).to_string()
};
self.await_test_run_outcome(label);
}
/// 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) {
if !self.debug_sessions.is_empty() {
self.status = String::from("A debug session is already running (Shift+F5 stops it)");
return;
}
self.launch_with_unsaved_saved(|app| app.debug_named_test_now(name));
}
fn debug_named_test_now(&mut self, name: String) {
use std::collections::BTreeMap;
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) => {
// The interpreter F5 and Live Run pick, from the test file's
// folder up (#864), not only a root `.venv`; refused before
// any setup when debugpy cannot run under it.
let test_dir = self
.editor
.path
.as_deref()
.and_then(Path::parent)
.filter(|dir| dir.starts_with(&root))
.unwrap_or(&root)
.to_path_buf();
let project_py =
debuggee_python(&test_dir, &root, std::env::var_os("PATH").as_deref());
let project_found = project_py.is_some();
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_py.unwrap_or_else(|| adapter_py.clone());
let mut request =
crate::dap::session::pytest_debug_launch_request(&project_py, &root, &name);
// A launch.json config for debugging tests (#1398) brings
// its env, cwd, args and debugpy settings, as in VS Code.
let configs = crate::dap::configs::discover_configs(&root);
let test_config = crate::dap::configs::debug_test_config(&configs);
if let Some(cfg) = test_config {
let ctx = crate::dap::configs::SubstCtx {
workspace_folder: root.clone(),
file: self.editor.path.clone(),
folders: self.workspace_folders(),
};
match crate::dap::configs::resolve(cfg, &ctx) {
Ok(rc) => {
request = crate::dap::configs::with_debug_test_config(request, &rc);
}
Err(e) => {
self.disarm_failure_breakpoint();
self.debug_error(e);
return;
}
}
}
// Checked once the config has had its say, so a `python`
// it names is the one validated (#1398).
let note = match debug_test_python(&request, &root, &adapter_py, project_found)
.as_deref()
.map_or(Ok(None), debuggee_python_note)
{
Ok(note) => note,
Err(refusal) => {
self.disarm_failure_breakpoint();
self.debug_error(refusal);
return;
}
};
let using = test_config
.map(|c| format!(" with \"{}\"", c.name))
.unwrap_or_default();
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.debug_sessions.replace_with(name.clone(), session);
self.run_debug.feedback = Some(format!("Debugging test {name}{using}"));
self.run_debug.feedback_is_error = false;
let lead = with_python_note(
format!("Debugging test {name}{using}"),
note.as_deref(),
);
self.status = self.with_failure_note(format!(
"{lead} — F5 continue · F10 step over · Shift+F5 stop"
));
self.reveal_debug_view();
if note.is_some() {
self.debug_console_push(lead);
}
}
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::Go) => {
self.start_delve_test_session(&root, &name, breakpoints);
}
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");
}
Some(crate::testing::worker::Runner::Codeql) => {
// No session starts here either (#373).
self.disarm_failure_breakpoint();
self.status = String::from(
"Debugging is not available for CodeQL tests — 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));
}
/// Run a launch's `cargo` build on a background thread (#1392); the
/// drain launches the config once cargo names the executable.
fn start_cargo_program_build(
&mut self,
rc: crate::dap::configs::ResolvedConfig,
slot: LaunchSlot,
spec: crate::dap::configs::CargoSpec,
) {
let cwd = rc
.cwd
.clone()
.unwrap_or_else(|| self.active_workspace_root());
let line = format!("cargo {}", spec.args.join(" "));
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let _ = tx.send(crate::dap::configs::build_cargo_program(&spec, &cwd));
});
self.run_debug.feedback = Some(format!("Building with {line}\u{2026}"));
self.run_debug.feedback_is_error = false;
self.status = format!(
"config \"{}\": building with {line} \u{2014} debug starts when it succeeds",
rc.name
);
let root = self.tree.root.clone();
self.pending_cargo_launches
.push((rx, Box::new(rc), slot, root));
}
/// Launch every `cargo` config whose build finished, or report why it
/// did not. True when anything landed.
fn drain_pending_cargo_launch(&mut self) -> bool {
use std::sync::mpsc::TryRecvError;
let mut landed = false;
let mut i = 0;
while i < self.pending_cargo_launches.len() {
let result = match self.pending_cargo_launches[i].0.try_recv() {
Ok(r) => r,
Err(TryRecvError::Empty) => {
i += 1;
continue;
}
Err(TryRecvError::Disconnected) => Err(String::from("the build thread died")),
};
let (_, mut rc, slot, build_root) = self.pending_cargo_launches.remove(i);
landed = true;
// Re-rooting mid-build would otherwise launch the old
// workspace's binary in the new one.
if build_root != self.tree.root {
self.status = format!(
"config \"{}\": cargo finished, but the workspace changed — launch it again from its workspace",
rc.name
);
continue;
}
match result {
Ok(program) => {
rc.program = Some(program.to_string_lossy().into_owned());
self.launch_resolved_in(*rc, slot);
}
Err(e) => self.debug_error(format!("config \"{}\": {e}", rc.name)),
}
}
landed
}
/// 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.debug_sessions.is_empty() {
// 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.debug_sessions.replace_with(name, 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
/// while one is already queued. Outside a recognised test project the
/// worker finds no runner and says nothing — the tool would error with no
/// manifest, and `cargo test -- --list` compiles the test binary so we
/// never auto-fire it per-keystroke. Finding the runner is the worker's
/// job, not this thread's (#1841): it reads every runner manifest and
/// can walk the whole tree for CodeQL test packs, which stalled the
/// switch to the Testing view.
fn discover_tests(&mut self) {
if self.testing.is_busy() || self.test_worker.discover_queued() {
return;
}
self.test_worker.discover_quietly();
}
/// `r` in the Testing view: discover again, saying so when no runner
/// claims the workspace rather than doing nothing. Like the view's own
/// discover, the worker is the one that looks for the runner (#1841).
fn rediscover_tests(&mut self) {
if !self.testing.is_busy() {
self.test_worker.discover();
}
}
/// Reveal the CodeQL view (#578): the QL icon and the palette. Refused,
/// with the reason, while the built-in CodeQL extension is disabled.
/// The saved lists it shows are small files read here; the workspace's
/// queries take a walk of the tree, which runs off the UI thread so the
/// view opens at once (#840).
fn open_codeql_view(&mut self) {
if !self.is_extension_enabled("codeql") {
self.status = String::from(
"CodeQL is disabled - enable it in the Extensions view to show its side bar",
);
return;
}
self.show_tree = true;
self.refresh_codeql_databases();
self.refresh_codeql_history();
self.discover_codeql_queries();
self.refresh_codeql_variant();
self.set_sidebar_view(SidebarView::CodeQL);
}
/// CodeQL view keys: arrows move between headers and actions, Enter or
/// Space folds a section or runs an action, Esc returns to the Explorer.
/// On the database card, Enter picks the current database, and Delete
/// removes it, F2 renames it, `e` shows its folder in the Explorer, `u`
/// upgrades it and `w` adds its source to the workspace; in the
/// Databases section `r` runs the open query, `q` opens Quick Query and
/// `a` views the AST, as the card's chips do. On a query history row,
/// Space or Right expands its details and Left folds them, Delete
/// removes it, F2 renames it, `v` opens its query, `t` the query's text
/// as it ran, `o` its results directory, `c` compares its results, `x`
/// exports them and `l` shows its query log. `s`
/// steps the query history's sort order within that section and the
/// databases' anywhere else. `n` creates a query, in the selected pack
/// when there is one. `r` on a pack or one of its queries runs every
/// query in the pack; Esc then first cancels the ones still queued, and
/// once none are, the running query.
/// In the Variant Analysis Repositories section `a` adds a repository
/// (into the selected list), `l` a list, `o` an owner, `s` adds the
/// repositories a GitHub Code Search finds to the selected list and `g`
/// opens the selected repository or owner on GitHub; on a submitted run,
/// Enter opens its report, `v` its results, `x` exports them, `c` copies
/// its repository list and `l` opens its logs on GitHub Actions; Enter selects what a run
/// targets, Space folds a list, F2 renames a list and Delete removes an
/// entry, asking first for a list.
fn handle_codeql_key(&mut self, key: KeyEvent) {
use crate::codeql_variant::Item;
use crate::widgets::codeql::{Action, Hit, Section};
let db = self.codeql.selected_database();
let run = self.codeql.selected_history();
let va_item = self.codeql.selected_variant_item();
let in_va = self.codeql.selected_section() == Some(Section::VariantAnalysis);
let in_db = self.codeql.selected_section() == Some(Section::Databases);
match key.code {
KeyCode::Esc if !self.codeql_run_queue.is_empty() => self.cancel_codeql_queue(),
KeyCode::Esc if self.codeql_run.is_some() => self.cancel_codeql_run(),
KeyCode::Esc => self.set_sidebar_view(SidebarView::Explorer),
KeyCode::Up => self.codeql.move_selection(false),
KeyCode::Down => self.codeql.move_selection(true),
KeyCode::Char(' ') | KeyCode::Right if run.is_some() => {
if let Some(i) = run {
self.codeql.toggle_history(i);
}
}
KeyCode::Left if run.is_some_and(|i| self.codeql.is_expanded(i)) => {
if let Some(i) = run {
self.codeql.toggle_history(i);
}
}
KeyCode::Char(c @ ('r' | 'q' | 'a')) if in_db => {
let chip = crate::widgets::codeql::DB_CHIPS
.iter()
.find(|chip| chip.key == Some(c));
if let Some(chip) = chip {
self.activate_codeql(Hit::Action(chip.action));
}
}
KeyCode::Char('c') if run.is_some() => {
if let Some(i) = run {
self.compare_codeql_results(i);
}
}
KeyCode::Char('x') if run.is_some() => self.prompt_export_codeql_results(),
KeyCode::Char('l') if run.is_some() => {
if let Some(i) = run {
self.show_codeql_query_log(i);
}
}
KeyCode::Char(' ') if matches!(va_item, Some(Item::List(_))) => {
if let Some(Item::List(i)) = va_item {
self.codeql.toggle_variant_list(i);
}
}
KeyCode::Enter | KeyCode::Char(' ') => {
if let Some(hit) = self.codeql.selected_hit() {
self.activate_codeql(hit);
}
}
KeyCode::Delete => {
if let Some(i) = db {
self.confirm_remove_codeql_database(i);
} else if let Some(i) = run {
self.confirm_remove_codeql_history(i);
} else if let Some(item) = va_item {
self.remove_codeql_variant_item(item);
}
}
KeyCode::F(2) => {
if let Some(i) = db {
self.prompt_rename_codeql_database(i);
} else if let Some(i) = run {
self.prompt_rename_codeql_history(i);
} else if let Some(Item::List(i)) = va_item {
self.prompt_rename_codeql_variant_list(i);
}
}
KeyCode::Char('m') if self.codeql.selected_model_endpoint().is_some() => {
self.model_codeql_endpoint(self.codeql.selected_model_endpoint());
}
KeyCode::Char('c') if self.codeql.selected_variant_run().is_some() => {
self.copy_codeql_variant_repo_list(self.codeql.selected_variant_run());
}
KeyCode::Char('l') if self.codeql.selected_variant_run().is_some() => {
self.view_codeql_variant_logs(self.codeql.selected_variant_run());
}
KeyCode::Char('a') if in_va => self.prompt_add_codeql_variant_repo(),
KeyCode::Char('l') if in_va => self.prompt_add_codeql_variant_list(),
KeyCode::Char('o') if in_va => self.prompt_add_codeql_variant_owner(),
KeyCode::Char('s') if in_va => self.prompt_codeql_variant_code_search(),
KeyCode::Char('g') if in_va => self.open_codeql_variant_on_github(),
KeyCode::Char('e') => {
if let Some(i) = db {
self.reveal_codeql_database(i);
}
}
KeyCode::Char('u') => {
if let Some(i) = db {
self.upgrade_codeql_database(i);
}
}
KeyCode::Char('w') => {
if let Some(i) = db {
self.add_codeql_database_source(i);
}
}
KeyCode::Char('x') if self.codeql.selected_variant_run().is_some() => {
self.prompt_export_codeql_variant_results(self.codeql.selected_variant_run());
}
KeyCode::Char('v') if self.codeql.selected_variant_run().is_some() => {
self.open_codeql_variant_results(self.codeql.selected_variant_run());
}
KeyCode::Char('v') => {
if let Some(i) = run {
self.view_codeql_history_query(i);
}
}
KeyCode::Char('o') => {
if let Some(i) = run {
self.open_codeql_history_results_dir(i);
}
}
KeyCode::Char('t') => {
if let Some(i) = run {
self.view_codeql_history_query_text(i);
}
}
KeyCode::Char('s')
if run.is_some()
|| self.codeql.selected_hit() == Some(Hit::Action(Action::SortHistory)) =>
{
self.sort_codeql_history();
}
KeyCode::Char('s') => self.sort_codeql_databases(),
KeyCode::Char('n') => self.prompt_create_codeql_query(),
KeyCode::Char('r') => {
if let Some(p) = self.codeql.selected_pack() {
self.run_codeql_pack(p);
}
}
_ => {}
}
}
/// The four places a CodeQL database comes from, in a picker whose rows
/// run the matching side-bar action.
fn open_codeql_database_sources(&mut self) {
use crate::widgets::list_picker::{ListPicker, ListPurpose, ListRow};
let rows = CODEQL_DB_SOURCES
.iter()
.enumerate()
.map(|(i, (_, label))| ListRow {
id: i.to_string(),
label: String::from(*label),
})
.collect();
self.open_list_picker(
ListPicker::new(ListPurpose::CodeqlDbSource, "Add CodeQL Database", rows),
"",
);
}
/// The databases, under the side bar's language, in a picker whose
/// choice becomes the current one (#578): the database card's switch.
fn open_codeql_database_picker(&mut self) {
use crate::widgets::list_picker::{ListPicker, ListPurpose, ListRow};
let rows: Vec<ListRow> = self
.codeql
.database_choices()
.into_iter()
.map(|(i, label)| ListRow {
id: i.to_string(),
label,
})
.collect();
if rows.is_empty() {
self.status = String::from("No CodeQL databases in this language");
return;
}
self.open_list_picker(
ListPicker::new(ListPurpose::CodeqlDatabase, "Select CodeQL Database", rows),
"",
);
}
/// Run what a CodeQL side-bar row offers. Sections and query packs fold;
/// the language and database lists select; a query row runs; "Create
/// one" asks for a query name; a variant analysis entry becomes what a
/// run targets (a list already selected folds instead); the actions
/// still to come in #578 say so rather than do nothing.
fn activate_codeql(&mut self, hit: crate::widgets::codeql::Hit) {
use crate::widgets::codeql::{Action, Hit, LANGUAGES};
match hit {
Hit::Header(section) => self.codeql.toggle(section),
Hit::Action(Action::SelectLanguage(i)) => {
self.codeql.language = if self.codeql.language == Some(i) {
None
} else {
Some(i)
};
self.status = match self.codeql.language {
Some(i) => format!("CodeQL language: {}", LANGUAGES[i]),
None => String::from("CodeQL language: all"),
};
}
Hit::Action(Action::SelectDatabase(i)) => {
let path = Self::codeql_db_store_path();
let mut store = crate::codeql_db::DatabaseStore::load(&path);
if i < store.databases.len() {
store.current = Some(i);
let _ = store.save(&path);
self.status = format!("Current CodeQL database: {}", store.databases[i].name);
}
self.refresh_codeql_databases();
}
Hit::Action(Action::SortDatabases) => self.sort_codeql_databases(),
Hit::Action(Action::SortHistory) => self.sort_codeql_history(),
Hit::Action(
action @ (Action::AddDatabaseFromFolder
| Action::AddDatabaseFromArchive
| Action::AddDatabaseFromUrl
| Action::AddDatabaseFromGithub),
) => {
use crate::widgets::input_prompt::{CodeqlDbSource, InputPrompt, InputPurpose};
let (source, title, hint) = match action {
Action::AddDatabaseFromFolder => (
CodeqlDbSource::Folder,
"Add CodeQL Database from Folder",
"path to the database folder",
),
Action::AddDatabaseFromArchive => (
CodeqlDbSource::Archive,
"Add CodeQL Database from Archive",
"path to a .zip",
),
Action::AddDatabaseFromUrl => (
CodeqlDbSource::Url,
"Add CodeQL Database from URL",
"https://… .zip",
),
_ => (
CodeqlDbSource::Github,
"Add CodeQL Database from GitHub",
"owner/repo [language]",
),
};
self.open_input_prompt(InputPrompt::new(
InputPurpose::CodeqlDatabase { source },
String::from(title),
String::from(hint),
));
}
Hit::Action(Action::OpenHistory(i)) => {
let history = crate::codeql_query::History::load(&Self::codeql_history_path());
let Some(entry) = history.entries.get(i) else {
return;
};
match &entry.status {
crate::codeql_query::RunStatus::Succeeded => {
let output = entry.output.clone();
match self.editor.open(&output) {
Ok(()) => self.sync_open_file_poll_mtime(),
Err(e) => self.status = format!("{}: {e}", output.display()),
}
}
crate::codeql_query::RunStatus::Failed(why) => {
self.status = format!("That run failed: {why}");
}
crate::codeql_query::RunStatus::Running => {
self.status = String::from("That query is still running");
}
crate::codeql_query::RunStatus::Cancelled => {
self.status = String::from("That run was cancelled");
}
}
}
Hit::Action(Action::TogglePack(i)) => self.codeql.toggle_pack(i),
Hit::Action(Action::RunQuery(pack, query)) => {
let Some(path) = self
.codeql
.queries
.get(pack)
.and_then(|p| p.queries.get(query))
.cloned()
else {
return;
};
// A side-bar row runs the file as saved, as VS Code's
// Queries view does.
match std::fs::read_to_string(&path) {
Ok(source) => self.run_codeql_file(path, &source),
Err(e) => self.status = format!("{}: {e}", path.display()),
}
}
Hit::Action(Action::AddDatabase) => self.open_codeql_database_sources(),
Hit::Action(Action::PickDatabase) => self.open_codeql_database_picker(),
Hit::Action(Action::RunOpenQuery) => {
self.run_command(crate::widgets::command_palette::Command::CodeqlRunQuery)
}
Hit::Action(Action::CompareHistory(i)) => self.compare_codeql_results(i),
Hit::Action(Action::ExportHistory(i)) => {
// The export prompt takes the selected entry.
self.codeql.select_history(i);
self.prompt_export_codeql_results();
}
Hit::Action(Action::HistoryLog(i)) => self.show_codeql_query_log(i),
Hit::Action(Action::QuickQuery) => {
self.run_command(crate::widgets::command_palette::Command::CodeqlQuickQuery)
}
Hit::Action(Action::ShowEvaluatorLog) => self.run_command(
crate::widgets::command_palette::Command::CodeqlShowEvaluatorLogViewer,
),
Hit::Action(Action::CreateQuery) => self.prompt_create_codeql_query(),
Hit::Action(Action::SetUpControllerRepository) => self.prompt_codeql_controller(),
Hit::Action(Action::VariantList(i))
if self
.codeql
.variant
.is_selected(crate::codeql_variant::Item::List(i)) =>
{
self.codeql.toggle_variant_list(i);
}
Hit::Action(Action::VariantList(i)) => {
self.select_codeql_variant_item(crate::codeql_variant::Item::List(i));
}
Hit::Action(Action::VariantRepo(list, j)) => {
self.select_codeql_variant_item(crate::codeql_variant::Item::Repo(list, j));
}
Hit::Action(Action::VariantOwner(i)) => {
self.select_codeql_variant_item(crate::codeql_variant::Item::Owner(i));
}
Hit::Action(Action::AddVariantRepo) => self.prompt_add_codeql_variant_repo(),
Hit::Action(Action::AddVariantList) => self.prompt_add_codeql_variant_list(),
Hit::Action(Action::AddVariantOwner) => self.prompt_add_codeql_variant_owner(),
Hit::Action(Action::OpenVariantConfig) => self.open_codeql_variant_config(),
Hit::Action(Action::VariantRun(i)) => self.open_codeql_variant_run(i),
Hit::Action(Action::ViewAst) => self.view_codeql_ast(),
Hit::Action(Action::OpenModelEditor) => self.open_codeql_model_editor(),
Hit::Action(Action::ModelGroup(i)) => {
if let Some(view) = self.codeql.model.as_mut()
&& let Some(group) = view.endpoints.get(i).map(|e| e.group())
{
view.toggle(&group);
}
}
Hit::Action(Action::ModelEndpoint(i)) => {
let Some(e) = self
.codeql
.model
.as_ref()
.and_then(|v| v.endpoints.get(i))
.cloned()
else {
return;
};
let modeled = if e.supported {
"modeled by CodeQL"
} else {
"not modeled"
};
let Some(loc) = e.location.clone() else {
self.status = format!("{}: {modeled}; no location", e.label());
return;
};
let Some(path) = self.codeql_source_file(&loc.path) else {
self.status = format!("{} is not on this machine", loc.path.display());
return;
};
let (line, column) = (loc.line.max(1) - 1, loc.column.max(1) - 1);
self.status = match self.open_at(&path, line as usize, column as usize) {
Ok(()) => format!("{} ({}): {modeled}", e.label(), e.kind),
Err(err) => format!("{}: {err}", path.display()),
};
}
Hit::Action(Action::ClearEvalLog) => {
self.codeql.evallog = None;
self.status = String::from("Cleared the evaluator log");
}
Hit::Action(Action::EvalPredicate(i)) => {
if let Some(view) = self.codeql.evallog.as_mut() {
view.toggle(i);
}
}
Hit::Action(Action::EvalDependency(target)) => match target {
Some(i) => {
if let Some(view) = self.codeql.evallog.as_mut() {
view.open.insert(i);
}
self.codeql.select_evallog_predicate(i);
}
None => {
self.status =
String::from("That predicate is not in this log (it was cached or inlined)")
}
},
Hit::Action(Action::ClearAst) => {
self.codeql.ast = None;
self.status = String::from("Cleared the AST");
}
Hit::Action(Action::AstNode(i)) => {
let Some(view) = self.codeql.ast.as_mut() else {
return;
};
view.toggle(i);
match view.target(i) {
Some((path, line, column)) if path.is_file() => {
let (line, column) = (line.max(1) - 1, column.max(1) - 1);
if let Err(e) = self.open_at(&path, line as usize, column as usize) {
self.status = format!("{}: {e}", path.display());
}
}
Some((path, ..)) => {
self.status = format!("{} is not on this machine", path.display());
}
None => {}
}
}
}
}
fn codeql_variant_path() -> PathBuf {
croft_cache_dir().join("codeql-variant-analysis.json")
}
/// Reload the variant analysis config into the side bar. One that
/// cannot be read is reported, and the section says so rather than
/// showing it empty.
fn refresh_codeql_variant(&mut self) {
self.refresh_codeql_variant_runs();
match crate::codeql_variant::VariantConfig::load(&Self::codeql_variant_path()) {
Ok(config) => {
self.codeql.variant = config;
self.codeql.variant_error = false;
}
Err(e) => {
self.codeql.variant = crate::codeql_variant::VariantConfig::default();
self.codeql.variant_error = true;
self.status = format!("Could not read the variant analysis config: {e}");
}
}
}
/// Change the variant analysis config with `edit` and save it, showing
/// `edit`'s message. A config that cannot be read is left as it is,
/// never saved over with an empty one. Returns whether it saved.
fn edit_codeql_variant(
&mut self,
edit: impl FnOnce(&mut crate::codeql_variant::VariantConfig) -> Result<String, String>,
) -> bool {
let path = Self::codeql_variant_path();
let mut config = match crate::codeql_variant::VariantConfig::load(&path) {
Ok(config) => config,
Err(e) => {
self.codeql.variant_error = true;
self.status =
format!("Could not read the variant analysis config, so it is unchanged: {e}");
return false;
}
};
let message = match edit(&mut config) {
Ok(m) => m,
Err(e) => {
self.status = e;
return false;
}
};
if let Err(e) = config.save(&path) {
self.status = format!("Could not save the variant analysis config: {e}");
return false;
}
self.status = message;
self.codeql.variant = config;
self.codeql.variant_error = false;
true
}
/// Ask for the controller repository variant analysis runs from (#578,
/// VS Code's "Set up controller repository"), starting from the current
/// one.
fn prompt_codeql_controller(&mut self) {
use crate::widgets::input_prompt::{InputPrompt, InputPurpose};
// From the file: the palette can ask before the side bar loaded it.
let current = crate::codeql_variant::VariantConfig::load(&Self::codeql_variant_path())
.ok()
.and_then(|c| c.controller_repo);
self.open_input_prompt(
InputPrompt::new(
InputPurpose::CodeqlControllerRepository,
String::from("Set Up Controller Repository"),
"owner/repo or its GitHub URL",
)
.with_value(current.unwrap_or_default()),
);
}
fn submit_codeql_controller(&mut self, value: &str) {
let saved = self.edit_codeql_variant(|c| {
c.set_controller(value)
.map(|nwo| format!("Variant analysis controller repository: {nwo}"))
});
if saved {
self.codeql
.select_action(crate::widgets::codeql::Action::SetUpControllerRepository);
}
}
/// Ask for a repository to add for variant analysis, into the list whose
/// line (or one of whose repositories) is selected in the side bar.
fn prompt_add_codeql_variant_repo(&mut self) {
use crate::widgets::input_prompt::{InputPrompt, InputPurpose};
let list = self
.codeql
.selected_variant_list()
.and_then(|i| self.codeql.variant.lists.get(i))
.map(|l| l.name.clone());
let title = match &list {
Some(name) => format!("Add Repository to {name}"),
None => String::from("Add Variant Analysis Repository"),
};
self.open_input_prompt(InputPrompt::new(
InputPurpose::CodeqlAddVariantRepo { list },
title,
"owner/repo or its GitHub URL",
));
}
fn submit_add_codeql_variant_repo(&mut self, list: Option<&str>, value: &str) {
use crate::codeql_variant::Item;
let mut added = None;
let saved = self.edit_codeql_variant(|c| {
let index = match list {
Some(name) => Some(
c.list_index(name)
.ok_or_else(|| format!("The list {name} is no longer there"))?,
),
None => None,
};
let nwo = c.add_repo(index, value)?;
let len = match index {
Some(i) => c.lists[i].repos.len(),
None => c.repos.len(),
};
added = Some(Item::Repo(index, len - 1));
Ok(match list {
Some(name) => format!("Added {nwo} to {name}"),
None => format!("Added {nwo} for variant analysis"),
})
});
if let (true, Some(item)) = (saved, added) {
if let Some(name) = list {
self.codeql.folded_lists.remove(name);
}
self.codeql.select_variant_item(item);
}
}
/// Ask for a GitHub Code Search query whose repositories go into the
/// selected list (#578, VS Code's "Add repositories with GitHub Code
/// Search"). The side bar's language scopes the search.
fn prompt_codeql_variant_code_search(&mut self) {
use crate::widgets::input_prompt::{InputPrompt, InputPurpose};
if self.codeql_code_search.is_some() {
self.status = String::from("A GitHub Code Search is already running");
return;
}
let Some(list) = self
.codeql
.selected_variant_list()
.and_then(|i| self.codeql.variant.lists.get(i))
.map(|l| l.name.clone())
else {
self.status =
String::from("Select a repository list for the Code Search results (l adds one)");
return;
};
let hint = match self.codeql_search_language() {
Some(lang) if lang != "actions" => format!("a GitHub Code Search query ({lang} only)"),
_ => String::from("a GitHub Code Search query"),
};
self.open_input_prompt(InputPrompt::new(
InputPurpose::CodeqlVariantCodeSearch { list: list.clone() },
format!("Add Repositories to {list} with GitHub Code Search"),
&hint,
));
}
/// The CodeQL id of the side bar's language, when one is picked.
fn codeql_search_language(&self) -> Option<&'static str> {
self.codeql
.language
.and_then(|i| crate::widgets::codeql::LANGUAGE_IDS.get(i).copied())
}
/// Run the Code Search off the UI thread; [`Self::drain_codeql_code_search`]
/// adds what it finds to `list`.
fn start_codeql_variant_code_search(&mut self, list: String, value: &str) {
if value.trim().is_empty() {
self.status = String::from("A Code Search query cannot be empty");
return;
}
let query = crate::codeql_variant::code_search_query(value, self.codeql_search_language());
let gh = self.gh_program.to_string_lossy().into_owned();
let root = self.active_workspace_root().to_path_buf();
let (tx, rx) = std::sync::mpsc::channel();
let search = query.clone();
std::thread::spawn(move || {
use crate::codeql_variant::{CODE_SEARCH_LIMIT, CODE_SEARCH_PAGE, code_search_args};
let mut out = String::new();
let mut cut = None;
// Page by page up to the API's last, stopping at a short page.
// A later page's failure (Code Search allows ten requests a
// minute) keeps what the earlier ones found and says so.
for page in 1..=CODE_SEARCH_LIMIT / CODE_SEARCH_PAGE {
let text = match crate::pr_review::run_gh(
&gh,
&code_search_args(&search, page),
&root,
crate::pr_review::GH_TIMEOUT,
) {
Ok(text) => text,
Err(why) if page == 1 => {
let _ = tx.send(Err(why));
return;
}
Err(why) => {
cut = Some(format!("page {page} failed: {why}"));
break;
}
};
out.push_str(&text);
if !out.ends_with('\n') {
out.push('\n');
}
if text.lines().count() < CODE_SEARCH_PAGE {
break;
}
}
let _ = tx.send(Ok((crate::codeql_variant::parse_code_search(&out), cut)));
});
self.status = format!("Searching GitHub code for {query}…");
self.codeql_code_search = Some((list, rx));
}
/// Add a finished Code Search's repositories to its list. Returns true
/// when one finished.
pub fn drain_codeql_code_search(&mut self) -> bool {
let Some((_, rx)) = self.codeql_code_search.as_ref() else {
return false;
};
let outcome = match rx.try_recv() {
Ok(outcome) => outcome,
Err(std::sync::mpsc::TryRecvError::Empty) => return false,
Err(std::sync::mpsc::TryRecvError::Disconnected) => {
Err(String::from("the search stopped without answering"))
}
};
let Some((list, _)) = self.codeql_code_search.take() else {
return false;
};
let (found, cut) = match outcome {
Ok((found, _)) if found.is_empty() => {
self.status = String::from("GitHub Code Search found no repositories");
return true;
}
Ok(outcome) => outcome,
Err(why) => {
self.status = format!("GitHub Code Search failed: {why}");
return true;
}
};
let mut index = None;
let saved = self.edit_codeql_variant(|c| {
let i = c
.list_index(&list)
.ok_or_else(|| format!("The list {list} is no longer there"))?;
let (added, had) = c.add_repos(i, &found)?;
index = Some(i);
let plural = |n: usize| if n == 1 { "repository" } else { "repositories" };
let mut message = format!("Added {added} {} to {list}", plural(added));
if had > 0 {
message.push_str(&format!(" ({had} already there)"));
}
if let Some(why) = &cut {
message.push_str(&format!("; the search stopped early, {why}"));
}
Ok(message)
});
if let (true, Some(i)) = (saved, index) {
self.codeql.folded_lists.remove(&list);
self.codeql
.select_variant_item(crate::codeql_variant::Item::List(i));
}
true
}
fn prompt_add_codeql_variant_list(&mut self) {
use crate::widgets::input_prompt::{InputPrompt, InputPurpose};
self.open_input_prompt(InputPrompt::new(
InputPurpose::CodeqlAddVariantList,
String::from("Add Repository List"),
"the list's name",
));
}
fn submit_add_codeql_variant_list(&mut self, value: &str) {
let mut added = None;
let saved = self.edit_codeql_variant(|c| {
let i = c.add_list(value)?;
added = Some(i);
Ok(format!("Added repository list {}", c.lists[i].name))
});
if let (true, Some(i)) = (saved, added) {
self.codeql
.select_variant_item(crate::codeql_variant::Item::List(i));
}
}
fn prompt_add_codeql_variant_owner(&mut self) {
use crate::widgets::input_prompt::{InputPrompt, InputPurpose};
self.open_input_prompt(InputPrompt::new(
InputPurpose::CodeqlAddVariantOwner,
String::from("Add Variant Analysis Owner"),
"a user or organisation, or its GitHub URL",
));
}
/// VS Code's "CodeQL: Install Pack Dependencies" for pack `pack` of the
/// Queries section (#578): `codeql pack install` on its folder.
fn install_codeql_pack_dependencies(&mut self, pack: usize) {
let Some(p) = self.codeql.queries.get(pack) else {
return;
};
if p.name == crate::codeql_query::NO_PACK {
self.status =
String::from("These queries are in no pack, so they have no dependencies");
return;
}
let (name, args) = (
p.name.clone(),
crate::codeql_query::pack_install_args(&p.dir),
);
self.start_codeql_pack_job(
args,
format!("Installing the dependencies of {name}\u{2026}"),
format!("Installed the dependencies of {name}"),
format!("Could not install the dependencies of {name}"),
);
}
/// VS Code's "CodeQL: Quick Query" (#578): open a scratch query for the
/// selected database's language, kept in croft's cache so it outlives
/// the session. The first time, its pack is written; until `codeql pack
/// install` has left a lock file, its library dependency is installed.
fn open_codeql_quick_query(&mut self) {
let store = crate::codeql_db::DatabaseStore::load(&Self::codeql_db_store_path());
let Some(db) = store.current.and_then(|i| store.databases.get(i)) else {
self.status = String::from("Add a CodeQL database and select it first");
return;
};
let Some(module) = db
.language
.as_deref()
.and_then(crate::codeql_query::language_module)
else {
self.status = format!("CodeQL database {} has no language croft knows", db.name);
return;
};
let dir = croft_cache_dir()
.join("codeql")
.join("quick-query")
.join(module);
let query = dir.join("quick-query.ql");
let fresh = !query.is_file();
if fresh {
let (pack, source) = crate::codeql_query::quick_query(module);
let written = std::fs::create_dir_all(&dir)
.and_then(|()| std::fs::write(dir.join("qlpack.yml"), pack))
.and_then(|()| std::fs::write(&query, source));
if let Err(e) = written {
self.status = format!("Could not create the quick query: {e}");
return;
}
}
match self.editor.open(&query) {
Ok(()) => {
self.sync_open_file_poll_mtime();
self.focus_pane(Pane::Editor);
}
Err(e) => {
self.status = format!("{}: {e}", query.display());
return;
}
}
if !dir.join("codeql-pack.lock.yml").is_file() {
self.start_codeql_pack_job(
crate::codeql_query::pack_install_args(&dir),
format!("Installing codeql/{module}-all for the quick query\u{2026}"),
format!("Quick query ready: codeql/{module}-all is installed"),
format!("Could not install codeql/{module}-all for the quick query"),
);
} else {
self.status = format!("Opened the {module} quick query");
}
}
/// Ask which packs "CodeQL: Download Packs" fetches (#578).
fn prompt_download_codeql_packs(&mut self) {
use crate::widgets::input_prompt::{InputPrompt, InputPurpose};
self.open_input_prompt(InputPrompt::new(
InputPurpose::CodeqlDownloadPacks,
String::from("Download Packs"),
"packs to download, e.g. codeql/java-queries codeql/python-all@1.0.0",
));
}
fn submit_download_codeql_packs(&mut self, value: &str) {
let packs = crate::codeql_query::parse_pack_list(value);
if packs.is_empty() {
self.status = String::from("Name at least one pack to download");
return;
}
let what = packs.join(", ");
self.start_codeql_pack_job(
crate::codeql_query::pack_download_args(&packs),
format!("Downloading {what}\u{2026}"),
format!("Downloaded {what}"),
format!("Could not download {what}"),
);
}
/// Run a `codeql pack` command on a worker thread (#578); one at a
/// time, since installs and downloads write the same package cache.
fn start_codeql_pack_job(
&mut self,
args: Vec<String>,
running: String,
done: String,
failed: String,
) {
if self.codeql_pack_job.is_some() {
self.status = String::from("A CodeQL pack install or download is already running");
return;
}
let program = self.codeql_program.clone();
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let _ = tx.send(Self::codeql_command(&program, &args));
});
self.status = running;
self.codeql_pack_job = Some((rx, done, failed));
}
/// Collect a finished pack install or download (#578) onto the status
/// line.
pub fn drain_codeql_pack_job(&mut self) -> bool {
let Some((rx, _, _)) = self.codeql_pack_job.as_ref() else {
return false;
};
let outcome = match rx.try_recv() {
Ok(outcome) => outcome,
Err(std::sync::mpsc::TryRecvError::Empty) => return false,
Err(std::sync::mpsc::TryRecvError::Disconnected) => {
Err(String::from("the pack command stopped unexpectedly"))
}
};
let Some((_, done, failed)) = self.codeql_pack_job.take() else {
return false;
};
self.status = match outcome {
Ok(()) => done,
Err(why) => format!("{failed}: {why}"),
};
true
}
fn submit_add_codeql_variant_owner(&mut self, value: &str) {
let saved = self.edit_codeql_variant(|c| {
c.add_owner(value)
.map(|o| format!("Added every repository of {o} for variant analysis"))
});
if saved {
let last = self.codeql.variant.owners.len().saturating_sub(1);
self.codeql
.select_variant_item(crate::codeql_variant::Item::Owner(last));
}
}
fn prompt_rename_codeql_variant_list(&mut self, index: usize) {
use crate::widgets::input_prompt::{InputPrompt, InputPurpose};
let Some(name) = self.codeql.variant.lists.get(index).map(|l| l.name.clone()) else {
return;
};
self.open_input_prompt(
InputPrompt::new(
InputPurpose::CodeqlRenameVariantList { name: name.clone() },
String::from("Rename Repository List"),
"the list's name",
)
.with_value(name),
);
}
fn submit_rename_codeql_variant_list(&mut self, name: &str, value: &str) {
let mut renamed = None;
let saved = self.edit_codeql_variant(|c| {
let i = c
.list_index(name)
.ok_or_else(|| format!("The list {name} is no longer there"))?;
c.rename_list(i, value)?;
renamed = Some(i);
Ok(format!("Renamed repository list to {}", c.lists[i].name))
});
if let (true, Some(i)) = (saved, renamed) {
// A fold is kept by name; it follows the list.
if self.codeql.folded_lists.remove(name) {
self.codeql.folded_lists.insert(value.trim().to_string());
}
self.codeql
.select_variant_item(crate::codeql_variant::Item::List(i));
}
}
/// Remove a variant analysis entry: a repository or owner at once, a
/// list (with its repositories) after asking.
fn remove_codeql_variant_item(&mut self, item: crate::codeql_variant::Item) {
use crate::codeql_variant::Item;
use crate::widgets::input_prompt::{InputPrompt, InputPurpose};
let Some(name) = self.codeql.variant.name_of(item).map(str::to_string) else {
return;
};
if let Item::List(i) = item {
let n = self.codeql.variant.lists[i].repos.len();
let what = match n {
0 => String::new(),
1 => String::from(" and its 1 repository"),
n => format!(" and its {n} repositories"),
};
self.open_input_prompt(
InputPrompt::new(
InputPurpose::CodeqlRemoveVariantList { name: name.clone() },
format!("Remove repository list '{name}'{what}?"),
"Enter to remove · Esc to keep",
)
.with_value("remove"),
);
return;
}
let saved = self.edit_codeql_variant(|c| {
// The side bar names the entry by position; make sure the file
// still has it there before removing anything.
if c.name_of(item) != Some(name.as_str()) {
return Err(String::from(
"The variant analysis config changed on disk; look again",
));
}
c.remove(item)?;
Ok(format!("Removed {name}"))
});
if saved {
self.keep_codeql_selection_on_a_row();
}
}
fn perform_remove_codeql_variant_list(&mut self, name: &str) {
let saved = self.edit_codeql_variant(|c| {
let i = c
.list_index(name)
.ok_or_else(|| format!("The list {name} is no longer there"))?;
c.remove(crate::codeql_variant::Item::List(i))?;
Ok(format!("Removed repository list {name}"))
});
if saved {
self.codeql.folded_lists.remove(name);
self.keep_codeql_selection_on_a_row();
}
}
/// After a row went away, keep the selection on a row rather than on
/// the welcome text that moved up under it.
fn keep_codeql_selection_on_a_row(&mut self) {
let last = self.codeql.lines().len().saturating_sub(1);
self.codeql.selected = self.codeql.selected.min(last);
if self.codeql.selected_hit().is_none() {
self.codeql.move_selection(false);
}
}
/// Make `item` what a variant analysis runs against (VS Code's "Select").
fn select_codeql_variant_item(&mut self, item: crate::codeql_variant::Item) {
let Some(name) = self.codeql.variant.name_of(item).map(str::to_string) else {
return;
};
let saved = self.edit_codeql_variant(|c| {
if c.name_of(item) != Some(name.as_str()) {
return Err(String::from(
"The variant analysis config changed on disk; look again",
));
}
c.select(item)?;
Ok(format!("Variant analysis runs against {name}"))
});
if saved {
self.codeql.select_variant_item(item);
}
}
/// Open the variant analysis config in an editor tab, writing an empty
/// one first when there is none. One that cannot be parsed opens as it
/// is, to be fixed.
fn open_codeql_variant_config(&mut self) {
let path = Self::codeql_variant_path();
if !path.exists()
&& let Err(e) = crate::codeql_variant::VariantConfig::default().save(&path)
{
self.status = format!("Could not create {}: {e}", path.display());
return;
}
match self.editor.open(&path) {
Ok(()) => {
self.sync_open_file_poll_mtime();
self.focus_pane(Pane::Editor);
}
Err(e) => self.status = format!("{}: {e}", path.display()),
}
}
/// The GitHub page of the variant analysis repository or owner selected
/// in the side bar (the controller on its row), else of the one a run
/// targets.
fn codeql_variant_github_url(&self) -> Option<String> {
use crate::codeql_variant::{Item, Selection};
use crate::widgets::codeql::{Action, Hit};
let v = &self.codeql.variant;
let name = match self.codeql.selected_variant_item() {
Some(item @ (Item::Repo(..) | Item::Owner(_))) => v.name_of(item)?.to_string(),
Some(Item::List(_)) => return None,
None if self.codeql.selected_hit()
== Some(Hit::Action(Action::SetUpControllerRepository)) =>
{
v.controller_repo.clone()?
}
None => match v.selected.as_ref()? {
Selection::Repo { nwo, .. } => nwo.clone(),
Selection::Owner { owner } => owner.clone(),
Selection::List { .. } => return None,
},
};
Some(format!("https://github.com/{name}"))
}
/// Open the selected variant analysis repository or owner on GitHub
/// (VS Code's "Open on GitHub"). Where no browser can be reached the
/// status line shows the address instead.
fn open_codeql_variant_on_github(&mut self) {
let Some(url) = self.codeql_variant_github_url() else {
self.status = String::from(
"Select a variant analysis repository or owner in the CodeQL side bar first",
);
return;
};
self.open_url_for_user(&url);
}
/// Open `url` in the user's browser: through the relay or a detected
/// URL on a remote session, and never from a test.
fn open_url_for_user(&mut self, url: &str) {
if cfg!(test) {
// Tests never start a browser.
self.status = format!("Open {url}");
return;
}
if self.drop_relay_active() || is_remote_session() {
self.open_detected_url(url);
return;
}
self.status = match open_url(url) {
Ok(()) => format!("Opened {url}"),
Err(e) => format!("Could not open a browser ({e}): {url}"),
};
}
/// The store index of the current database, for the palette commands
/// that act on it; says what to do when there is none.
fn current_codeql_database(&mut self) -> Option<usize> {
let store = crate::codeql_db::DatabaseStore::load(&Self::codeql_db_store_path());
let current = store.current.filter(|&i| i < store.databases.len());
if current.is_none() {
self.status = String::from("Select a CodeQL database first");
}
current
}
/// Ask before removing database `index` (#578), saying whether its
/// files go too: only a copy croft made in its own cache is deleted.
fn confirm_remove_codeql_database(&mut self, index: usize) {
use crate::widgets::input_prompt::{InputPrompt, InputPurpose};
let store = crate::codeql_db::DatabaseStore::load(&Self::codeql_db_store_path());
let Some(db) = store.databases.get(index) else {
return;
};
let what = if Self::codeql_cached_copy(&db.path).is_some() {
"Its downloaded files are deleted."
} else {
"Its folder stays on disk."
};
self.open_input_prompt(
InputPrompt::new(
InputPurpose::CodeqlRemoveDatabase {
path: db.path.clone(),
},
format!("Remove CodeQL database '{}'? {what}", db.name),
"Enter to remove · Esc to keep",
)
.with_value("remove"),
);
}
/// The folder to delete with the database at `path`: the entry under
/// croft's database cache that holds it (an extracted archive keeps the
/// database one level down). `None` for a database the user pointed at
/// elsewhere, which croft only forgets. Both sides are canonicalised so
/// a `..` in a hand-edited list cannot walk out of the cache.
fn codeql_cached_copy(path: &Path) -> Option<PathBuf> {
Self::cache_entry_holding(&Self::codeql_db_cache_dir(), path)
}
/// The entry directly under `cache` that holds `path`, both
/// canonicalised; `None` when `path` is elsewhere, is `cache` itself, or
/// either does not exist.
fn cache_entry_holding(cache: &Path, path: &Path) -> Option<PathBuf> {
let cache = cache.canonicalize().ok()?;
let path = path.canonicalize().ok()?;
let first = path.strip_prefix(&cache).ok()?.components().next()?;
Some(cache.join(first))
}
/// Remove the database at `path` from the list, deleting its files when
/// croft made them, and save.
fn perform_remove_codeql_database(&mut self, path: &Path) {
let store_path = Self::codeql_db_store_path();
let mut store = crate::codeql_db::DatabaseStore::load(&store_path);
let Some(i) = store.position(path) else {
self.status = String::from("That CodeQL database is no longer listed");
return;
};
let name = store.databases[i].name.clone();
let cached = Self::codeql_cached_copy(path);
store.remove(i);
if let Err(e) = store.save(&store_path) {
self.status = format!("Could not save the CodeQL database list: {e}");
return;
}
self.status = match cached.map(std::fs::remove_dir_all) {
Some(Err(e)) => format!("Removed CodeQL database {name}, but not its files: {e}"),
_ => format!("Removed CodeQL database {name}"),
};
self.refresh_codeql_databases();
// Stay on the database card while there is one, never on the
// welcome text below it.
if !self.codeql.databases.is_empty() {
self.codeql.select_database_card();
}
if self.codeql.selected_hit().is_none() {
self.codeql.move_selection(false);
}
}
fn prompt_rename_codeql_database(&mut self, index: usize) {
use crate::widgets::input_prompt::{InputPrompt, InputPurpose};
let store = crate::codeql_db::DatabaseStore::load(&Self::codeql_db_store_path());
let Some(db) = store.databases.get(index) else {
return;
};
self.open_input_prompt(
InputPrompt::new(
InputPurpose::CodeqlRenameDatabase {
path: db.path.clone(),
},
String::from("Rename CodeQL Database"),
"the name shown in the side bar",
)
.with_value(db.name.clone()),
);
}
fn submit_rename_codeql_database(&mut self, path: &Path, value: &str) {
let store_path = Self::codeql_db_store_path();
let mut store = crate::codeql_db::DatabaseStore::load(&store_path);
let Some(i) = store.position(path) else {
self.status = String::from("That CodeQL database is no longer listed");
return;
};
let old = store.databases[i].name.clone();
if let Err(e) = store.rename(i, value) {
self.status = e;
return;
}
// History from before runs recorded their database's path names it
// only by its old name. The rename keeps that name among its former
// names, so such runs still count for it; with no other database
// ever called that, they are also pinned to its path. Otherwise the
// runs could be either's, and both stay protected by name.
let same_name = store
.databases
.iter()
.enumerate()
.filter(|&(j, d)| j != i && d.has_had_name(&old))
.count();
if same_name == 0 {
let history_path = Self::codeql_history_path();
let mut history = crate::codeql_query::History::load(&history_path);
if history.adopt_legacy(&old, path)
&& let Err(e) = history.save(&history_path)
{
self.status = format!("Could not save the CodeQL query history: {e}");
return;
}
}
// Renaming can move it in a name-sorted list.
if let Some(by) = store.sort_by {
store.sort(by);
}
self.status = match store.save(&store_path) {
Ok(()) => format!("Renamed CodeQL database to {}", value.trim()),
Err(e) => format!("Could not save the CodeQL database list: {e}"),
};
self.refresh_codeql_databases();
if store.position(path).is_some() {
self.codeql.select_database_card();
}
}
/// Step the databases to the next sort order (name, language, date
/// added), keeping the selection on the database card.
fn sort_codeql_databases(&mut self) {
let store_path = Self::codeql_db_store_path();
let mut store = crate::codeql_db::DatabaseStore::load(&store_path);
let on_card = self.codeql.selected_database().is_some();
let by = store
.sort_by
.map_or(crate::codeql_db::DbSort::Name, |b| b.next());
store.sort(by);
self.status = match store.save(&store_path) {
Ok(()) => format!("CodeQL databases sorted by {}", by.label()),
Err(e) => format!("Could not save the CodeQL database list: {e}"),
};
self.refresh_codeql_databases();
if on_card {
self.codeql.select_database_card();
}
}
/// Show database `index`'s folder in the Explorer (VS Code's "Show
/// Database Directory").
fn reveal_codeql_database(&mut self, index: usize) {
let store = crate::codeql_db::DatabaseStore::load(&Self::codeql_db_store_path());
let Some(path) = store.databases.get(index).map(|d| d.path.clone()) else {
return;
};
self.reveal_in_explorer(path.clone());
if !self.tree.nodes.iter().any(|n| n.path == path) {
self.status = format!(
"{} is outside the workspace; add its folder to the workspace to browse it",
path.display()
);
}
}
/// Upgrade database `index` to the CLI's current schema (#578, VS
/// Code's "CodeQL: Upgrade Database") on a worker thread;
/// [`Self::drain_codeql_upgrade`] collects it. Refused while a query or
/// another upgrade runs: either would read a database being rewritten.
fn upgrade_codeql_database(&mut self, index: usize) {
self.start_codeql_db_job(index, crate::codeql_query::DbJob::Upgrade);
}
/// Run `job` on database `index` on a worker thread (#578): an upgrade,
/// or VS Code's "CodeQL: Clear Cache", "Trim Cache" and "Trim Cache to
/// Overlay Base". One at a time, never beside a query run, since each
/// rewrites the database a query would read.
fn start_codeql_db_job(&mut self, index: usize, job: crate::codeql_query::DbJob) {
if let Some((_, running, _, _)) = self.codeql_upgrade.as_ref() {
self.status = format!("A CodeQL database {} is already running", running.noun());
return;
}
if self.codeql_run.is_some() {
self.status = format!(
"Wait for the CodeQL query run to finish before {}",
job.gerund()
);
return;
}
let store = crate::codeql_db::DatabaseStore::load(&Self::codeql_db_store_path());
let Some(db) = store.databases.get(index).cloned() else {
return;
};
let program = self.codeql_program.clone();
let path = db.path.clone();
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let _ = tx.send(Self::codeql_command(&program, &job.args(&path)));
});
self.status = job.running(&db.name);
self.codeql_upgrade = Some((rx, job, db.name, db.path));
}
/// Collect a finished database upgrade or cache cleanup (#578) onto the
/// status line.
pub fn drain_codeql_upgrade(&mut self) -> bool {
let Some((rx, _, _, _)) = self.codeql_upgrade.as_ref() else {
return false;
};
let outcome = match rx.try_recv() {
Ok(outcome) => outcome,
Err(std::sync::mpsc::TryRecvError::Empty) => return false,
Err(std::sync::mpsc::TryRecvError::Disconnected) => {
Err(String::from("the job stopped unexpectedly"))
}
};
let Some((_, job, name, _)) = self.codeql_upgrade.take() else {
return false;
};
self.status = job.finished(&name, outcome);
true
}
/// Ask the CodeQL CLI for its version on a worker thread (#578, VS
/// Code's "CodeQL: Copy Version Information");
/// [`Self::drain_codeql_version`] copies the report.
fn copy_codeql_version(&mut self) {
if self.codeql_version.is_some() {
return;
}
let program = self.codeql_program.clone();
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let _ = tx.send(Self::read_codeql_version(&program));
});
self.status = String::from("Reading the CodeQL CLI version\u{2026}");
self.codeql_version = Some(rx);
}
/// Copy the version report once the CLI has answered (#578). A missing
/// CLI still copies croft's version and the platform, saying why the
/// CLI's could not be read.
pub fn drain_codeql_version(&mut self) -> bool {
let Some(rx) = self.codeql_version.as_ref() else {
return false;
};
let cli = match rx.try_recv() {
Ok(cli) => cli,
Err(std::sync::mpsc::TryRecvError::Empty) => return false,
Err(std::sync::mpsc::TryRecvError::Disconnected) => {
Err(String::from("the version check stopped unexpectedly"))
}
};
self.codeql_version = None;
let text = crate::codeql_query::version_information(env!("CARGO_PKG_VERSION"), &cli);
copy_to_clipboard(&text);
self.status = match cli {
Ok(_) => String::from("Copied CodeQL version information"),
Err(why) => format!("Copied version information; the CodeQL CLI is unavailable: {why}"),
};
true
}
/// `program`'s bare version number, or why it could not be read.
fn read_codeql_version(program: &std::path::Path) -> Result<String, String> {
let out = crate::review_ops::output_retrying_busy(
std::process::Command::new(program).args(crate::codeql_query::version_args()),
);
match out {
Ok(o) if o.status.success() => {
Ok(String::from_utf8_lossy(&o.stdout).trim().to_string())
}
Ok(o) => Err(String::from_utf8_lossy(&o.stderr)
.lines()
.map(str::trim)
.find(|l| !l.is_empty())
.unwrap_or("codeql failed")
.to_string()),
Err(e) => Err(format!("could not run codeql: {e}")),
}
}
/// Download the newest known CodeQL CLI release into croft's cache on a
/// worker thread (#578, the VS Code extension's managed CLI);
/// [`Self::drain_codeql_cli_download`] switches to it.
fn download_codeql_cli(&mut self) {
let (os, arch) = (std::env::consts::OS, std::env::consts::ARCH);
let Some(asset) = crate::codeql_cli::asset_name(os, arch) else {
self.status = format!(
"GitHub publishes no CodeQL CLI for {os} on {arch}; install one and set codeql_cli_path"
);
return;
};
self.start_codeql_cli_download(asset);
}
fn start_codeql_cli_download(&mut self, asset: &'static str) {
use crate::codeql_cli::JobUpdate;
if self.codeql_cli_download.is_some() {
self.status = String::from("The CodeQL CLI is already downloading");
return;
}
let version =
crate::codeql_cli::install_version(self.codeql_cli_latest.as_deref()).to_string();
let root = crate::codeql_cli::cli_root(&croft_cache_dir());
let net = self.codeql_cli_net.clone();
let (tx, rx) = std::sync::mpsc::channel();
self.status = format!("Downloading CodeQL CLI v{version}\u{2026}");
std::thread::spawn(move || {
let send = |update| {
let _ = tx.send(update);
};
let out = crate::codeql_cli::download_and_install(&net, &root, &version, asset, &send);
send(JobUpdate::Done(out.map(|program| (version, program))));
});
self.codeql_cli_download = Some(rx);
}
/// Show the CLI download's progress, and switch to the CLI once it is
/// installed (#578), unless settings name another: that one always wins.
pub fn drain_codeql_cli_download(&mut self) -> bool {
use crate::codeql_cli::JobUpdate;
use std::sync::mpsc::TryRecvError;
let Some(rx) = self.codeql_cli_download.take() else {
return false;
};
let mut changed = false;
let outcome = loop {
match rx.try_recv() {
Ok(JobUpdate::Progress(line)) => {
self.status = line;
changed = true;
}
Ok(JobUpdate::Done(outcome)) => break outcome,
Err(TryRecvError::Empty) => {
self.codeql_cli_download = Some(rx);
return changed;
}
Err(TryRecvError::Disconnected) => {
break Err(String::from("the download stopped unexpectedly"));
}
}
};
self.status = match outcome {
Ok((version, _)) if self.codeql_cli_source == crate::codeql_cli::Source::Settings => {
format!(
"Installed CodeQL CLI v{version}; codeql_cli_path in settings still takes precedence"
)
}
Ok((version, program)) => {
self.set_codeql_program(program);
let status = format!("Installed CodeQL CLI v{version} and switched to it");
self.codeql_cli_source = crate::codeql_cli::Source::Managed(version);
status
}
Err(why) => format!("Could not install the CodeQL CLI: {why}"),
};
true
}
/// Look up the newest CodeQL CLI release and the version in use on a
/// worker thread (#578, VS Code's "CodeQL: Check for CLI Updates");
/// [`Self::drain_codeql_cli_check`] compares them.
fn check_codeql_cli_updates(&mut self) {
if self.codeql_cli_check.is_some() {
return;
}
// A managed copy's folder names its version; any other CLI is asked.
let known = match &self.codeql_cli_source {
crate::codeql_cli::Source::Managed(v) => Some(v.clone()),
_ => None,
};
let program = self.codeql_program.clone();
let latest = self.codeql_cli_net.latest.clone();
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let current = known.or_else(|| Self::read_codeql_version(&program).ok());
let _ = tx.send((latest(), current));
});
self.status = String::from("Checking for CodeQL CLI updates\u{2026}");
self.codeql_cli_check = Some(rx);
}
/// Report the update check (#578), remembering the latest release for
/// "CodeQL: Download CLI".
pub fn drain_codeql_cli_check(&mut self) -> bool {
let Some(rx) = self.codeql_cli_check.as_ref() else {
return false;
};
let (latest, current) = match rx.try_recv() {
Ok(answer) => answer,
Err(std::sync::mpsc::TryRecvError::Empty) => return false,
Err(std::sync::mpsc::TryRecvError::Disconnected) => {
(Err(String::from("the check stopped unexpectedly")), None)
}
};
self.codeql_cli_check = None;
self.status = match latest {
Ok(latest) => {
let status = crate::codeql_cli::update_status(&latest, current.as_deref());
self.codeql_cli_latest = Some(latest);
status
}
Err(why) => format!("Could not check for CodeQL CLI updates: {why}"),
};
true
}
/// Add database `index`'s source to the workspace (#578, VS Code's
/// "CodeQL: Add Database Source to Workspace"): its `src` folder, else
/// its `src.zip`, extracted once into croft's cache.
fn add_codeql_database_source(&mut self, index: usize) {
use crate::codeql_db::DbSource;
let store = crate::codeql_db::DatabaseStore::load(&Self::codeql_db_store_path());
let Some(db) = store.databases.get(index) else {
return;
};
let folder = match crate::codeql_db::database_source(&db.path) {
None => {
self.status = format!("CodeQL database {} has no src folder or src.zip", db.name);
return;
}
Some(DbSource::Folder(folder)) => folder,
Some(DbSource::Zip(zip)) => {
let cache = Self::codeql_source_cache_dir();
let dest = cache.join(crate::codeql_db::source_cache_name(&db.path, &zip));
if !dest.is_dir() {
// An older extraction of this database's source is out
// of date: its archive changed, which is why the name
// no longer matches. Drop it, unless it is open as a
// workspace root.
let prefix = crate::codeql_db::source_cache_prefix(&db.path);
for old in std::fs::read_dir(&cache).into_iter().flatten().flatten() {
let path = old.path();
let stale = old.file_name().to_string_lossy().starts_with(&prefix);
let open = path
.canonicalize()
.is_ok_and(|p| self.roots.iter().any(|r| r == p));
if stale && !open {
let _ = std::fs::remove_dir_all(&path);
}
}
// Extract beside it and rename, so an interrupted
// extraction never passes for a finished one.
let partial = PathBuf::from(format!("{}.partial", dest.display()));
let _ = std::fs::remove_dir_all(&partial);
let done = crate::codeql_db::extract_zip(
&zip,
&partial,
Some(crate::codeql_db::SOURCE_ZIP_LIMIT),
)
.and_then(|_| std::fs::rename(&partial, &dest).map_err(|e| e.to_string()));
if let Err(e) = done {
let _ = std::fs::remove_dir_all(&partial);
self.status = format!("Could not extract {}: {e}", zip.display());
return;
}
}
dest
}
};
let folder = folder.canonicalize().unwrap_or(folder);
let name = db.name.clone();
if self.roots.iter().any(|r| r == folder) {
self.status =
format!("The source of CodeQL database {name} is already in the workspace");
return;
}
self.add_workspace_folder(folder.clone());
if self.roots.iter().any(|r| r == folder) {
self.status = format!("Added the source of CodeQL database {name} to the workspace");
}
}
/// The databases "Delete Unused Databases" removes: copies in croft's
/// cache that no query history entry ran on, never the current one or
/// one being upgraded. A database the user pointed at elsewhere is
/// theirs and never listed.
fn unused_codeql_databases(&self) -> Vec<PathBuf> {
let store = crate::codeql_db::DatabaseStore::load(&Self::codeql_db_store_path());
let history = crate::codeql_query::History::load(&Self::codeql_history_path());
let upgrading = self.codeql_upgrade.as_ref().map(|(_, _, _, p)| p);
store
.databases
.iter()
.enumerate()
.filter(|&(i, d)| store.current != Some(i) && Some(&d.path) != upgrading)
.filter(|(_, d)| Self::codeql_cached_copy(&d.path).is_some())
.filter(|(_, d)| {
let mut names = vec![d.name.as_str()];
names.extend(d.former_names.iter().map(String::as_str));
!history.entries.iter().any(|e| e.refers_to(&d.path, &names))
})
.map(|(_, d)| d.path.clone())
.collect()
}
/// Ask before deleting the unused databases (#578); says so when there
/// are none.
fn confirm_delete_unused_codeql_databases(&mut self) {
use crate::widgets::input_prompt::{InputPrompt, InputPurpose};
let paths = self.unused_codeql_databases();
let title = match paths.len() {
0 => {
self.status = String::from("There are no unused CodeQL databases to delete");
return;
}
1 => String::from("Delete 1 unused CodeQL database?"),
n => format!("Delete {n} unused CodeQL databases?"),
};
self.open_input_prompt(
InputPrompt::new(
InputPurpose::CodeqlDeleteUnusedDatabases { paths },
title,
"Enter to delete · Esc to keep",
)
.with_value("delete"),
);
}
/// Remove the databases at `paths` from the list, delete their cached
/// folders, and save. Each is checked again first: one that became
/// current or was run on while the prompt was open is kept.
fn perform_delete_unused_codeql_databases(&mut self, paths: &[PathBuf]) {
let unused = self.unused_codeql_databases();
let store_path = Self::codeql_db_store_path();
let mut store = crate::codeql_db::DatabaseStore::load(&store_path);
let mut deleted = 0;
let mut file_error = None;
for path in paths.iter().filter(|p| unused.contains(p)) {
let Some(i) = store.position(path) else {
continue;
};
let cached = Self::codeql_cached_copy(path);
store.remove(i);
deleted += 1;
if let Some(Err(e)) = cached.map(std::fs::remove_dir_all) {
file_error.get_or_insert(e);
}
}
if let Err(e) = store.save(&store_path) {
self.status = format!("Could not save the CodeQL database list: {e}");
return;
}
let what = match deleted {
0 => String::from("There are no unused CodeQL databases to delete"),
1 => String::from("Deleted 1 unused CodeQL database"),
n => format!("Deleted {n} unused CodeQL databases"),
};
self.status = match file_error {
Some(e) => format!("{what}, but not all their files: {e}"),
None => what,
};
self.refresh_codeql_databases();
if self.codeql.selected_hit().is_none() {
self.codeql.move_selection(false);
}
}
fn codeql_db_store_path() -> PathBuf {
croft_cache_dir().join("codeql-databases.json")
}
/// Where fetched or extracted databases live: croft's cache, never
/// beside the archive the user pointed at.
fn codeql_db_cache_dir() -> PathBuf {
croft_cache_dir().join("codeql").join("databases")
}
/// Where a database's `src.zip` is extracted to be browsed, one folder
/// per database, beside the database cache.
fn codeql_source_cache_dir() -> PathBuf {
croft_cache_dir().join("codeql").join("sources")
}
fn codeql_history_path() -> PathBuf {
croft_cache_dir().join("codeql-history.json")
}
/// Where query runs write their results, one folder per run.
fn codeql_results_dir() -> PathBuf {
croft_cache_dir().join("codeql").join("results")
}
/// Mirror the saved query history into the side bar.
fn refresh_codeql_history(&mut self) {
let history = crate::codeql_query::History::load(&Self::codeql_history_path());
self.codeql.history = history
.entries
.iter()
.map(crate::widgets::codeql::HistoryRow::new)
.collect();
self.codeql.history_sort = history.sort_by;
// An expanded entry that went folds away with it.
if let Some(out) = &self.codeql.expanded
&& !self.codeql.history.iter().any(|r| &r.output == out)
{
self.codeql.expanded = None;
}
}
/// The query history entry the palette commands act on: the selected
/// row, else the most recent run; says so when there is none.
fn current_codeql_history(&mut self) -> Option<usize> {
let history = crate::codeql_query::History::load(&Self::codeql_history_path());
let current = self
.codeql
.selected_history()
.filter(|&i| i < history.entries.len())
.or_else(|| history.newest());
if current.is_none() {
self.status = String::from("There is no CodeQL query history yet");
}
current
}
/// The results folder of a history entry that croft may delete: its
/// run's own folder under the results cache. `None` when the output
/// points anywhere else (a hand-edited history), which croft only
/// forgets.
fn codeql_cached_results(output: &Path) -> Option<PathBuf> {
Self::cache_entry_holding(&Self::codeql_results_dir(), output.parent()?)
}
/// Ask before removing history entry `index` (#578), saying whether its
/// results go too. A run still in flight is refused: its worker would
/// write the results back.
fn confirm_remove_codeql_history(&mut self, index: usize) {
use crate::widgets::input_prompt::{InputPrompt, InputPurpose};
let history = crate::codeql_query::History::load(&Self::codeql_history_path());
let Some(entry) = history.entries.get(index) else {
return;
};
if entry.status == crate::codeql_query::RunStatus::Running {
self.status = String::from("That query is still running");
return;
}
let what = if Self::codeql_cached_results(&entry.output).is_some() {
"Its results are deleted."
} else {
"Its results stay on disk."
};
self.open_input_prompt(
InputPrompt::new(
InputPurpose::CodeqlRemoveHistory {
output: entry.output.clone(),
},
format!(
"Remove query history entry '{}'? {what}",
entry.display_name()
),
"Enter to remove · Esc to keep",
)
.with_value("remove"),
);
}
/// Remove the history entry whose run wrote `output`, deleting its
/// results folder when it is croft's own, and save.
fn perform_remove_codeql_history(&mut self, output: &Path) {
let path = Self::codeql_history_path();
let mut history = crate::codeql_query::History::load(&path);
let Some(i) = history.position(output) else {
self.status = String::from("That query history entry is no longer listed");
return;
};
let name = history.entries[i].display_name();
let cached = Self::codeql_cached_results(output);
history.remove(i);
if let Err(e) = history.save(&path) {
self.status = format!("Could not save the CodeQL query history: {e}");
return;
}
self.status = match cached.map(std::fs::remove_dir_all) {
Some(Err(e)) => {
format!("Removed {name} from the query history, but not its results: {e}")
}
_ => format!("Removed {name} from the query history"),
};
self.refresh_codeql_history();
// Stay in the list: on the row that took its place, else the one
// above, never on the welcome text.
let n = self.codeql.history.len();
if n > 0 {
self.codeql.select_history(i.min(n - 1));
}
if self.codeql.selected_hit().is_none() {
self.codeql.move_selection(false);
}
}
fn prompt_rename_codeql_history(&mut self, index: usize) {
use crate::widgets::input_prompt::{InputPrompt, InputPurpose};
let history = crate::codeql_query::History::load(&Self::codeql_history_path());
let Some(entry) = history.entries.get(index) else {
return;
};
self.open_input_prompt(
InputPrompt::new(
InputPurpose::CodeqlRenameHistory {
output: entry.output.clone(),
},
String::from("Rename Query History Entry"),
"the label shown in the side bar",
)
.with_value(entry.display_name()),
);
}
fn submit_rename_codeql_history(&mut self, output: &Path, value: &str) {
let path = Self::codeql_history_path();
let mut history = crate::codeql_query::History::load(&path);
let Some(i) = history.position(output) else {
self.status = String::from("That query history entry is no longer listed");
return;
};
if let Err(e) = history.rename(i, value) {
self.status = e;
return;
}
// Renaming can move it in a name-sorted list.
history.sort(history.sort_by);
self.status = match history.save(&path) {
Ok(()) => format!("Renamed query history entry to {}", value.trim()),
Err(e) => format!("Could not save the CodeQL query history: {e}"),
};
self.refresh_codeql_history();
if let Some(i) = history.position(output) {
self.codeql.select_history(i);
}
}
/// Step the query history to the next sort order (date, name, status),
/// keeping the selection on the same entry.
fn sort_codeql_history(&mut self) {
let path = Self::codeql_history_path();
let mut history = crate::codeql_query::History::load(&path);
let selected = self
.codeql
.selected_history()
.and_then(|i| history.entries.get(i))
.map(|e| e.output.clone());
let by = history.sort_by.next();
history.sort(by);
self.status = match history.save(&path) {
Ok(()) => format!("CodeQL query history sorted by {}", by.label()),
Err(e) => format!("Could not save the CodeQL query history: {e}"),
};
self.refresh_codeql_history();
if let Some(i) = selected.and_then(|o| history.position(&o)) {
self.codeql.select_history(i);
}
}
/// Open the query file history entry `index` ran (VS Code's "View
/// Query"): the file as it is now, which may have changed since.
fn view_codeql_history_query(&mut self, index: usize) {
let history = crate::codeql_query::History::load(&Self::codeql_history_path());
let Some(query) = history.entries.get(index).map(|e| e.query.clone()) else {
return;
};
match self.editor.open(&query) {
Ok(()) => self.sync_open_file_poll_mtime(),
Err(e) => self.status = format!("{}: {e}", query.display()),
}
}
/// "View Query Text" (#578): the query of history entry `index` as it
/// was when it ran, which the file itself may no longer be.
fn view_codeql_history_query_text(&mut self, index: usize) {
let history = crate::codeql_query::History::load(&Self::codeql_history_path());
let Some(entry) = history.entries.get(index) else {
return;
};
let text = crate::codeql_query::query_text_path(&entry.output, &entry.query);
if !text.is_file() {
self.status = format!(
"{} ran before croft kept query text; v opens the query file",
entry.query_name()
);
return;
}
match self.editor.open(&text) {
Ok(()) => {
self.sync_open_file_poll_mtime();
self.status = format!("{} as it was when it ran", entry.query_name());
}
Err(e) => self.status = format!("{}: {e}", text.display()),
}
}
/// The evaluator log of history entry `index`, or why there is none: a
/// run croft made before it kept logs, or one still going.
fn codeql_history_log(&mut self, index: usize) -> Option<PathBuf> {
let history = crate::codeql_query::History::load(&Self::codeql_history_path());
let entry = history.entries.get(index)?;
if entry.status == crate::codeql_query::RunStatus::Running {
self.status = format!("{} is still running", entry.query_name());
return None;
}
let log = crate::codeql_query::evaluator_log(&entry.output);
if log.is_file() {
return Some(log);
}
self.status = format!("{} has no evaluator log", entry.query_name());
None
}
/// VS Code's "Show Evaluator Log (Raw JSON)" for history entry `index`.
fn show_codeql_evaluator_log(&mut self, index: usize) {
let Some(log) = self.codeql_history_log(index) else {
return;
};
match self.editor.open(&log) {
Ok(()) => self.sync_open_file_poll_mtime(),
Err(e) => self.status = format!("{}: {e}", log.display()),
}
}
/// VS Code's "Show Query Log" for history entry `index`: the newest
/// log `codeql` wrote into the run's `logs` folder. Runs croft made
/// before it passed `--logdir` have none.
fn show_codeql_query_log(&mut self, index: usize) {
let history = crate::codeql_query::History::load(&Self::codeql_history_path());
let Some(entry) = history.entries.get(index) else {
return;
};
if entry.status == crate::codeql_query::RunStatus::Running {
self.status = format!("{} is still running", entry.query_name());
return;
}
let logs = std::fs::read_dir(crate::codeql_query::query_log_dir(&entry.output))
.map(|dir| {
dir.flatten()
.filter_map(|e| {
let meta = e.metadata().ok().filter(|m| m.is_file())?;
Some((e.path(), meta.modified().ok()?))
})
.collect()
})
.unwrap_or_default();
let Some(log) = crate::codeql_query::newest_query_log(logs) else {
self.status = format!("{} has no query log", entry.query_name());
return;
};
match self.editor.open(&log) {
Ok(()) => self.sync_open_file_poll_mtime(),
Err(e) => self.status = format!("{}: {e}", log.display()),
}
}
/// VS Code's "Show Evaluator Log (Summary Text)" for history entry
/// `index`: `codeql generate log-summary` on a worker thread the first
/// time, then the summary it wrote beside the log.
fn show_codeql_evaluator_log_summary(&mut self, index: usize) {
let Some(log) = self.codeql_history_log(index) else {
return;
};
let summary = crate::codeql_query::evaluator_log_summary(&log);
if summary.is_file() {
match self.editor.open(&summary) {
Ok(()) => self.sync_open_file_poll_mtime(),
Err(e) => self.status = format!("{}: {e}", summary.display()),
}
return;
}
if self.codeql_log_summary.is_some() {
self.status = String::from("An evaluator log summary is already being made");
return;
}
let program = self.codeql_program.clone();
let args = crate::codeql_query::log_summary_args(&log, &summary);
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let _ = tx.send(Self::codeql_command(&program, &args));
});
self.status = String::from("Summarising the evaluator log\u{2026}");
self.codeql_log_summary = Some((rx, summary));
}
/// Open a finished evaluator log summary (#578), or say why the CLI
/// could not make it.
pub fn drain_codeql_log_summary(&mut self) -> bool {
let Some((rx, _)) = self.codeql_log_summary.as_ref() else {
return false;
};
let outcome = match rx.try_recv() {
Ok(outcome) => outcome,
Err(std::sync::mpsc::TryRecvError::Empty) => return false,
Err(std::sync::mpsc::TryRecvError::Disconnected) => {
Err(String::from("the summary stopped unexpectedly"))
}
};
let Some((_, summary)) = self.codeql_log_summary.take() else {
return false;
};
match outcome.and_then(|()| {
self.editor
.open(&summary)
.map_err(|e| format!("{}: {e}", summary.display()))
}) {
Ok(()) => {
self.sync_open_file_poll_mtime();
self.status = String::from("Opened the evaluator log summary");
}
Err(why) => self.status = format!("Could not summarise the evaluator log: {why}"),
}
true
}
/// The predicates the evaluator log `log` records, for a worker thread:
/// `codeql generate log-summary --format=predicates` the first time
/// (kept beside the log), then that summary parsed.
fn codeql_log_predicates(
program: &Path,
log: &Path,
) -> Result<Vec<crate::codeql_evallog::Predicate>, String> {
let predicates = crate::codeql_query::evaluator_log_predicates(log);
if !predicates.is_file() {
let args = crate::codeql_query::log_predicates_args(log, &predicates);
Self::codeql_command(program, &args)?;
}
let text = std::fs::read_to_string(&predicates)
.map_err(|e| format!("{}: {e}", predicates.display()))?;
Ok(crate::codeql_evallog::parse(&text))
}
/// VS Code's "Show Evaluator Log (Viewer)" for history entry `index`:
/// on a worker thread, `codeql generate log-summary --format=predicates`
/// the first time (kept beside the log), then that summary parsed and
/// rendered as a tree of predicates, slowest first.
fn show_codeql_evaluator_log_viewer(&mut self, index: usize) {
let Some(log) = self.codeql_history_log(index) else {
return;
};
if self.codeql_log_viewer.is_some() {
self.status = String::from("The evaluator log viewer is already being prepared");
return;
}
let history = crate::codeql_query::History::load(&Self::codeql_history_path());
let query = history
.entries
.get(index)
.map(|e| e.query_name())
.unwrap_or_default();
let program = self.codeql_program.clone();
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let _ = tx.send(Self::codeql_log_predicates(&program, &log));
});
self.status = String::from("Reading the evaluator log\u{2026}");
self.codeql_log_viewer = Some((rx, query));
}
/// Show a prepared evaluator log tree (#578) in a tab with every
/// predicate folded, or say why it could not be made.
pub fn drain_codeql_log_viewer(&mut self) -> bool {
let Some((rx, _)) = self.codeql_log_viewer.as_ref() else {
return false;
};
let outcome = match rx.try_recv() {
Ok(outcome) => outcome,
Err(std::sync::mpsc::TryRecvError::Empty) => return false,
Err(std::sync::mpsc::TryRecvError::Disconnected) => {
Err(String::from("the viewer stopped unexpectedly"))
}
};
let Some((_, query)) = self.codeql_log_viewer.take() else {
return false;
};
let label = format!("Evaluator Log ({query})");
match outcome.and_then(|predicates| {
let text = crate::codeql_evallog::render(&query, &predicates);
// The side bar's Evaluator Log Viewer shows the same tree.
self.codeql.evallog = Some(crate::codeql_evallog::LogView {
query: query.clone(),
predicates,
..Default::default()
});
self.codeql
.collapsed
.remove(&crate::widgets::codeql::Section::EvaluatorLog);
self.editor
.open_text_buffer(Path::new(&label), &text)
.map_err(|e| e.to_string())
}) {
Ok(()) => {
self.editor.fold_all();
self.focus_pane(Pane::Editor);
self.status = String::from("Opened the evaluator log viewer");
}
Err(why) => self.status = format!("Could not read the evaluator log: {why}"),
}
true
}
/// VS Code's "Compare Performance" for history entry `index` (#578):
/// the predicate timings of its evaluator log against those of the
/// latest earlier successful run of the same query, biggest change
/// first. Predicate summaries either run lacks are made on a worker
/// thread, as the evaluator log viewer makes them.
fn compare_codeql_performance(&mut self, index: usize) {
let history = crate::codeql_query::History::load(&Self::codeql_history_path());
let Some(entry) = history.entries.get(index) else {
return;
};
let Some(new_log) = self.codeql_history_log(index) else {
return;
};
let Some(partner) = history.perf_partner(index) else {
self.status = format!(
"There is no earlier successful run of {} to compare with",
entry.query_name()
);
return;
};
let Some(old_log) = self.codeql_history_log(partner) else {
return;
};
if self.codeql_perf_compare.is_some() {
self.status = String::from("A performance comparison is already being prepared");
return;
}
let query = entry.query_name();
let old_label = format!("earlier ({})", history.entries[partner].database);
let new_label = format!("later ({})", entry.database);
let program = self.codeql_program.clone();
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let table = Self::codeql_log_predicates(&program, &old_log).and_then(|old| {
let new = Self::codeql_log_predicates(&program, &new_log)?;
let rows = crate::codeql_evallog::compare(&old, &new);
Ok(crate::codeql_evallog::render_comparison(
&old_label, &new_label, &rows,
))
});
let _ = tx.send(table);
});
self.status = String::from("Comparing the evaluator logs\u{2026}");
self.codeql_perf_compare = Some((rx, format!("Performance ({query})")));
}
/// Show a prepared performance comparison (#578) in a tab, or say why
/// it could not be made.
pub fn drain_codeql_perf_compare(&mut self) -> bool {
let Some((rx, _)) = self.codeql_perf_compare.as_ref() else {
return false;
};
let outcome = match rx.try_recv() {
Ok(outcome) => outcome,
Err(std::sync::mpsc::TryRecvError::Empty) => return false,
Err(std::sync::mpsc::TryRecvError::Disconnected) => {
Err(String::from("the comparison stopped unexpectedly"))
}
};
let Some((_, label)) = self.codeql_perf_compare.take() else {
return false;
};
match outcome.and_then(|text| {
self.editor
.open_text_buffer(Path::new(&label), &text)
.map_err(|e| e.to_string())
}) {
Ok(()) => {
self.focus_pane(Pane::Editor);
self.status = String::from("Opened the performance comparison");
}
Err(why) => self.status = format!("Could not compare performance: {why}"),
}
true
}
/// VS Code's "Export Results" (#578): ask where to copy the results of
/// the selected history entry, else of the newest successful run,
/// suggesting `<query-stem>-results.<csv|sarif>` in the workspace.
fn prompt_export_codeql_results(&mut self) {
use crate::codeql_query::{History, RunStatus};
use crate::widgets::input_prompt::{InputPrompt, InputPurpose};
let history = History::load(&Self::codeql_history_path());
let Some(entry) = self
.codeql
.selected_history()
.filter(|&i| i < history.entries.len())
.or_else(|| history.newest_success())
.and_then(|i| history.entries.get(i))
else {
self.status = String::from("There is no successful CodeQL query run to export");
return;
};
if entry.status != RunStatus::Succeeded {
self.status = format!(
"{} did not succeed, so it has no results to export",
entry.query_name()
);
return;
}
if !entry.output.is_file() {
self.status = format!("The results of {} are gone", entry.query_name());
return;
}
let dest = self
.workspace_root()
.join(crate::codeql_query::export_file_name(
&entry.query,
&entry.output,
));
self.open_input_prompt(
InputPrompt::new(
InputPurpose::CodeqlExportResults {
output: entry.output.clone(),
},
format!("Export the results of {}", entry.query_name()),
"the file to copy the results to",
)
.with_value(dest.display().to_string()),
);
}
/// Copy the results at `output` to the typed path; an existing file is
/// never overwritten.
fn submit_export_codeql_results(&mut self, output: &Path, value: &str) {
if value.trim().is_empty() {
self.status = String::from("Name a file to export the results to");
return;
}
let dest = self.typed_path(value);
// Open the results first: a missing or unreadable run then fails
// before anything is created at the destination.
let mut src = match std::fs::File::open(output) {
Ok(src) => src,
Err(e) => {
self.status = format!("Could not read the results at {}: {e}", output.display());
return;
}
};
// `create_new` refuses an existing file (or a dangling symlink) in
// the same step that creates it, so nothing can slip in between a
// check and the copy.
let created = std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&dest);
let mut file = match created {
Ok(file) => file,
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
self.status = format!(
"{} already exists; export the results to a new file",
dest.display()
);
return;
}
Err(e) => {
self.status = format!("Could not export the results to {}: {e}", dest.display());
return;
}
};
// A copy failing midway leaves the partial file in place: removing
// it by name could delete a file another process put there since.
self.status = match std::io::copy(&mut src, &mut file) {
Ok(_) => format!("Exported results to {}", dest.display()),
Err(e) => format!(
"Could not finish exporting to {} ({e}); the file there is incomplete",
dest.display()
),
};
}
/// VS Code's "CodeQL: Preview Query Help" (#578): the help of the open
/// `.ql` query, else of the query the selected or newest history entry
/// ran, rendered to Markdown by `codeql generate query-help` on a worker
/// thread and shown in the Markdown preview.
fn preview_codeql_query_help(&mut self) {
let query = match self.editor.path.clone() {
Some(p) if p.extension().is_some_and(|e| e == "ql") => p,
_ => {
let Some(i) = self.current_codeql_history() else {
self.status = String::from("Open a .ql query to preview its help");
return;
};
let history = crate::codeql_query::History::load(&Self::codeql_history_path());
let Some(query) = history.entries.get(i).map(|e| e.query.clone()) else {
return;
};
query
}
};
if self.codeql_query_help.is_some() {
self.status = String::from("Query help is already being rendered");
return;
}
let stem = query
.file_stem()
.map(|s| s.to_string_lossy().into_owned())
.unwrap_or_default();
let name = query
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
let help = croft_cache_dir()
.join("codeql")
.join("help")
.join(format!("{stem}.md"));
let program = self.codeql_program.clone();
let args = crate::codeql_query::query_help_args(&query, &help);
let out = help.clone();
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
// An earlier preview's file must not stand in for help the CLI
// did not write this time.
let _ = std::fs::remove_file(&out);
let outcome = out
.parent()
.map_or(Ok(()), std::fs::create_dir_all)
.map_err(|e| format!("{}: {e}", out.display()))
.and_then(|()| Self::codeql_command(&program, &args));
let _ = tx.send(outcome);
});
self.status = format!("Rendering the help of {name}\u{2026}");
self.codeql_query_help = Some((rx, help, name));
}
/// Preview rendered query help (#578), or say the query has none: the
/// CLI fails, or writes nothing, when there is no `.qhelp` or `.md`
/// beside the query.
pub fn drain_codeql_query_help(&mut self) -> bool {
let Some((rx, _, _)) = self.codeql_query_help.as_ref() else {
return false;
};
let outcome = match rx.try_recv() {
Ok(outcome) => outcome,
Err(std::sync::mpsc::TryRecvError::Empty) => return false,
Err(std::sync::mpsc::TryRecvError::Disconnected) => {
Err(String::from("the help rendering stopped unexpectedly"))
}
};
let Some((_, help, name)) = self.codeql_query_help.take() else {
return false;
};
let written = std::fs::metadata(&help).is_ok_and(|m| m.len() > 0);
match outcome {
Err(why) => self.status = format!("{name} has no query help: {why}"),
Ok(()) if !written => {
self.status = format!("{name} has no query help (no .qhelp or .md beside it)");
}
Ok(()) => match self.editor.open(&help) {
Ok(()) => {
self.sync_open_file_poll_mtime();
if self.editor.markdown_preview.is_none() {
self.editor.toggle_markdown_preview();
}
self.focus_pane(Pane::Editor);
self.status = format!("Query help for {name}");
}
Err(e) => self.status = format!("{}: {e}", help.display()),
},
}
true
}
/// VS Code's "Compare Results" for history entry `index` (#578): its
/// table against the latest earlier run of the same query, written
/// beside its results as a CSV of the rows only one run has, and opened.
fn compare_codeql_results(&mut self, index: usize) {
use crate::codeql_query::RunStatus;
let history = crate::codeql_query::History::load(&Self::codeql_history_path());
let Some(entry) = history.entries.get(index) else {
return;
};
if entry.status != RunStatus::Succeeded {
self.status = format!(
"{} did not finish, so it has no results",
entry.display_name()
);
return;
}
if entry.output.extension().is_none_or(|e| e != "csv") {
self.status =
String::from("Only table results can be compared; alerts open in the SARIF viewer");
return;
}
let Some(partner) = history.compare_partner(index).map(|i| &history.entries[i]) else {
self.status = format!(
"There is no earlier successful run of {} to compare with",
entry.query_name()
);
return;
};
let read =
|p: &Path| std::fs::read_to_string(p).map_err(|e| format!("{}: {e}", p.display()));
let compared = read(&partner.output).and_then(|old| {
let new = read(&entry.output)?;
crate::codeql_query::compare_tables(
&old,
&new,
&format!("earlier ({})", partner.database),
&format!("later ({})", entry.database),
)
});
let text = match compared {
Ok(text) => text,
Err(why) => {
self.status = format!("Could not compare the results: {why}");
return;
}
};
let out = entry
.output
.with_file_name(format!("compare-{}.csv", partner.started));
if let Err(e) = std::fs::write(&out, &text) {
self.status = format!("{}: {e}", out.display());
return;
}
let differing = text.lines().count().saturating_sub(1);
match self.editor.open(&out) {
Ok(()) => {
self.sync_open_file_poll_mtime();
self.status = match differing {
0 => String::from("Both runs have the same results"),
1 => String::from("1 row differs between the runs"),
n => format!("{n} rows differ between the runs"),
};
}
Err(e) => self.status = format!("{}: {e}", out.display()),
}
}
/// "CodeQL: Open Query Results Directory" (#578): the folder of the
/// Query History run selected in the side bar, else of the newest run.
fn open_codeql_results_directory(&mut self) {
let index = self
.codeql
.selected_history()
.or_else(|| crate::codeql_query::History::load(&Self::codeql_history_path()).newest());
match index {
Some(i) => self.open_codeql_history_results_dir(i),
None => self.status = String::from("No CodeQL query has run yet"),
}
}
/// VS Code's "Open Results Directory" for history entry `index`. The
/// folder lives in croft's cache, outside the workspace, so the
/// Explorer can show it only when the user has it open; otherwise its
/// results file opens and the status line names the folder.
fn open_codeql_history_results_dir(&mut self, index: usize) {
let history = crate::codeql_query::History::load(&Self::codeql_history_path());
let Some(output) = history.entries.get(index).map(|e| e.output.clone()) else {
return;
};
let Some(dir) = output.parent().map(Path::to_path_buf) else {
return;
};
if !dir.is_dir() {
self.status = format!("{} does not exist (yet)", dir.display());
} else if self.tree.nodes.iter().any(|n| n.path == dir) {
self.reveal_in_explorer(dir);
} else if output.is_file() {
match self.editor.open(&output) {
Ok(()) => {
self.sync_open_file_poll_mtime();
self.status = format!("Results directory: {}", dir.display());
}
Err(e) => self.status = format!("{}: {e}", output.display()),
}
} else {
self.status = format!("Results directory: {}", dir.display());
}
}
/// Find the workspace's queries for the side bar's Queries section now,
/// for a caller that needs the list at once (a query just created, Run
/// All Queries). It walks the tree, so opening the view does this off
/// the UI thread instead. A walk still in flight is dropped: it may
/// predate what this one finds.
fn refresh_codeql_queries(&mut self) {
self.codeql_queries_job = None;
self.codeql.discovering_queries = false;
self.codeql.queries = crate::codeql_query::discover(self.workspace_root());
}
/// Find the workspace's queries on a worker thread (#840): the walk can
/// take seconds on a large tree, and switching to the CodeQL view must
/// not wait for it. [`Self::drain_codeql_queries`] lists what it finds;
/// until then the section keeps its last list, or says it is looking.
/// A walk of this root already in flight is left to finish rather than
/// doubled; one of a root the workspace has since left is replaced.
fn discover_codeql_queries(&mut self) {
let root = self.workspace_root().to_path_buf();
if self
.codeql_queries_job
.as_ref()
.is_some_and(|(walked, _)| *walked == root)
{
return;
}
let (tx, rx) = std::sync::mpsc::channel();
let walk = root.clone();
std::thread::spawn(move || {
let _ = tx.send(crate::codeql_query::discover(&walk));
});
self.codeql_queries_job = Some((root, rx));
self.codeql.discovering_queries = true;
}
/// List the queries a discovery found, once it lands (#840). True when
/// the side bar changed. A walk of a root the workspace has left since
/// is dropped unread, landed or not, and the view, if showing, walks
/// the root it shows now.
pub fn drain_codeql_queries(&mut self) -> bool {
let Some((walked, rx)) = self.codeql_queries_job.as_ref() else {
return false;
};
if walked.as_path() != self.workspace_root() {
self.codeql_queries_job = None;
self.codeql.discovering_queries = false;
if self.sidebar_view == SidebarView::CodeQL {
self.discover_codeql_queries();
}
return true;
}
match rx.try_recv() {
Ok(queries) => self.codeql.set_queries(queries),
Err(std::sync::mpsc::TryRecvError::Empty) => return false,
// The walk died: stop saying it is looking.
Err(std::sync::mpsc::TryRecvError::Disconnected) => {
self.codeql.discovering_queries = false;
}
}
self.codeql_queries_job = None;
true
}
/// Ask for the name of a new query (#578, VS Code's "CodeQL: Create
/// Query"). It goes into the pack whose line or query row is selected in
/// the Queries section, else the workspace root, and is written in the
/// pack's language, else the Language section's, else none.
fn prompt_create_codeql_query(&mut self) {
use crate::widgets::codeql::LANGUAGE_IDS;
use crate::widgets::input_prompt::{InputPrompt, InputPurpose};
let pack = self
.codeql
.selected_pack()
.and_then(|p| self.codeql.queries.get(p));
let root = self.workspace_root().to_path_buf();
let dir = pack.map_or_else(|| root.clone(), |p| p.dir.clone());
let language = pack
.and_then(|p| p.language.clone())
.or_else(|| self.codeql.language.map(|i| LANGUAGE_IDS[i].to_string()));
let place = match pack {
Some(p) if p.name != crate::codeql_query::NO_PACK => p.name.clone(),
_ => String::from("the workspace root"),
};
let lang = language
.as_deref()
.map(|l| format!(" ({l})"))
.unwrap_or_default();
self.open_input_prompt(InputPrompt::new(
InputPurpose::CodeqlCreateQuery { dir, language },
format!("Create CodeQL Query in {place}{lang}"),
"query name, e.g. find-unsafe-calls",
));
}
/// Write the new query, open it and list it in the Queries section;
/// a refused name or an existing file is said on the status line.
fn submit_create_codeql_query(&mut self, dir: &Path, language: Option<&str>, name: &str) {
let root = self.workspace_root().to_path_buf();
let path = match crate::codeql_query::scaffold_query(&root, dir, name, language) {
Ok(path) => path,
Err(e) => {
self.status = format!("Could not create the query: {e}");
return;
}
};
self.refresh_codeql_queries();
match self.editor.open(&path) {
Ok(()) => {
self.sync_open_file_poll_mtime();
self.focus_pane(Pane::Editor);
let shown = path.strip_prefix(&root).unwrap_or(&path);
self.status = format!("Created CodeQL query {}", shown.display());
}
Err(e) => self.status = format!("{}: {e}", path.display()),
}
}
/// Mirror the remembered variant analyses into the side bar.
fn refresh_codeql_variant_runs(&mut self) {
self.codeql.variant_runs =
crate::codeql_submit::load_submitted(&Self::codeql_variant_runs_path())
.iter()
.map(crate::codeql_submit::run_label)
.collect();
}
/// Open the report of remembered variant analysis `index`: its status
/// and a row per repository. It is written from the last progress read;
/// an unfinished run is read again at once.
fn open_codeql_variant_run(&mut self, index: usize) {
let runs = crate::codeql_submit::load_submitted(&Self::codeql_variant_runs_path());
let Some(run) = runs.get(index) else {
return;
};
if !run.progress.as_ref().is_some_and(|p| p.is_done()) {
self.codeql_variant_polled = None;
}
let path = croft_cache_dir()
.join("codeql")
.join("variant-reports")
.join(format!(
"{}-{}.md",
run.controller.replace('/', "-"),
run.id
));
let written = path
.parent()
.map_or(Ok(()), std::fs::create_dir_all)
.and_then(|()| std::fs::write(&path, crate::codeql_submit::run_report(run)));
if let Err(e) = written {
self.status = format!("{}: {e}", path.display());
return;
}
match self.editor.open(&path) {
Ok(()) => {
self.sync_open_file_poll_mtime();
self.focus_pane(Pane::Editor);
}
Err(e) => self.status = format!("{}: {e}", path.display()),
}
}
/// Follow submitted variant analyses (#578): every
/// [`CODEQL_VARIANT_POLL`], read the progress of those GitHub has not
/// finished, off the UI thread, and record what comes back. A run
/// finishing says so on the status line. Runs older than
/// [`CODEQL_VARIANT_FOLLOW`] are left alone: GitHub keeps their results
/// only so long, and one that never finishes would be read forever.
/// Nothing is read until the side bar has loaded the runs (opening the
/// CodeQL view, or a submission), so a session that never touches
/// CodeQL never calls GitHub for it. Returns true when progress landed.
pub fn poll_codeql_variant_runs(&mut self) -> bool {
use crate::codeql_submit as cs;
if let Some(rx) = self.codeql_variant_poll.as_ref() {
let polled = match rx.try_recv() {
Ok(p) => p,
Err(std::sync::mpsc::TryRecvError::Empty) => return false,
Err(std::sync::mpsc::TryRecvError::Disconnected) => Vec::new(),
};
self.codeql_variant_poll = None;
let path = Self::codeql_variant_runs_path();
for (mut run, outcome) in polled {
let Ok(progress) = outcome else { continue };
let was_done = run.progress.as_ref().is_some_and(|p| p.is_done());
if progress.is_done() && !was_done {
let (done, total) = progress.counts();
self.status = format!(
"Variant analysis {} of {} {}: {done}/{total} repositories, {} results",
run.id,
run.query.file_name().unwrap_or_default().to_string_lossy(),
progress.status,
progress.results()
);
}
run.progress = Some(progress);
let _ = cs::update_submitted(&path, &run);
}
self.refresh_codeql_variant_runs();
return true;
}
if self.codeql.variant_runs.is_empty()
|| self.disabled_extensions.contains("codeql")
|| self
.codeql_variant_polled
.is_some_and(|t| t.elapsed() < CODEQL_VARIANT_POLL)
{
return false;
}
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
let unfinished: Vec<cs::Submitted> = cs::load_submitted(&Self::codeql_variant_runs_path())
.into_iter()
.filter(|r| !r.progress.as_ref().is_some_and(|p| p.is_done()))
.filter(|r| now.saturating_sub(r.submitted_at) < CODEQL_VARIANT_FOLLOW.as_secs())
.collect();
self.codeql_variant_polled = Some(std::time::Instant::now());
if unfinished.is_empty() {
return false;
}
let gh = self.gh_program.to_string_lossy().into_owned();
let root = self.active_workspace_root().to_path_buf();
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let polled = unfinished
.into_iter()
.map(|run| {
let outcome = crate::pr_review::run_gh(
&gh,
&cs::progress_args(&run.controller, run.id),
&root,
crate::pr_review::GH_TIMEOUT,
)
.and_then(|answer| cs::parse_progress(&answer));
(run, outcome)
})
.collect();
let _ = tx.send(polled);
});
self.codeql_variant_poll = Some(rx);
false
}
/// The submitted variant analysis run `index`, else the newest; says
/// so when none has been submitted.
fn codeql_variant_run(
&mut self,
index: Option<usize>,
) -> Option<crate::codeql_submit::Submitted> {
let runs = crate::codeql_submit::load_submitted(&Self::codeql_variant_runs_path());
let run = index.map_or(runs.last(), |i| runs.get(i)).cloned();
if run.is_none() {
self.status = String::from("No variant analysis has been submitted yet");
}
run
}
/// Copy the repositories variant analysis run `index` (else the newest)
/// covers, one per line (#578).
fn copy_codeql_variant_repo_list(&mut self, index: Option<usize>) {
let Some(run) = self.codeql_variant_run(index) else {
return;
};
self.status = match crate::codeql_submit::repository_list(&run) {
Some(list) => {
copy_to_clipboard(&list);
format!(
"Copied the {} repositories of variant analysis {}",
list.lines().count(),
run.id
)
}
None => format!(
"Variant analysis {} has not reported its repositories yet",
run.id
),
};
}
/// Open the GitHub Actions run of variant analysis run `index` (else
/// the newest), where its logs are (#578).
fn view_codeql_variant_logs(&mut self, index: Option<usize>) {
let Some(run) = self.codeql_variant_run(index) else {
return;
};
match crate::codeql_submit::workflow_run_url(&run) {
Some(url) => self.open_url_for_user(&url),
None => {
self.status = format!(
"Variant analysis {} has no Actions run yet; GitHub starts one shortly",
run.id
)
}
}
}
/// Fetch the results of remembered variant analysis `index` (the newest
/// when `None`) and open them (#578): each repository that succeeded
/// with results has its artifact downloaded (once; later opens use the
/// copy), its alerts gathered into one SARIF log, one run per
/// repository, and its tables into one CSV with a repository column.
/// The fetching happens on a worker thread;
/// [`Self::drain_codeql_variant_results`] opens what it made.
fn open_codeql_variant_results(&mut self, index: Option<usize>) {
use crate::codeql_submit as cs;
if self.codeql_variant_results.is_some() {
self.status = String::from("Variant analysis results are already being fetched");
return;
}
let runs = cs::load_submitted(&Self::codeql_variant_runs_path());
let Some(run) = index.map_or(runs.last(), |i| runs.get(i)).cloned() else {
self.status = String::from("No variant analysis has been submitted yet");
return;
};
let repos = cs::repos_with_results(&run);
if repos.is_empty() {
self.status = match &run.progress {
None => format!(
"Variant analysis {} has not reported any progress yet",
run.id
),
Some(_) => format!("Variant analysis {} has no results yet", run.id),
};
return;
}
let dir = croft_cache_dir()
.join("codeql")
.join("variant-results")
.join(format!("{}-{}", run.controller.replace('/', "-"), run.id));
let gh = self.gh_program.to_string_lossy().into_owned();
let program = self.codeql_program.clone();
let root = self.active_workspace_root().to_path_buf();
let (tx, rx) = std::sync::mpsc::channel();
let count = repos.len();
std::thread::spawn(move || {
let _ = tx.send(Self::fetch_codeql_variant_results(
&gh, &program, &root, &run, &repos, &dir,
));
});
self.codeql_variant_results = Some(rx);
self.status = format!(
"Fetching the results of {count} repositor{}\u{2026}",
if count == 1 { "y" } else { "ies" }
);
}
/// The worker behind [`Self::open_codeql_variant_results`].
fn fetch_codeql_variant_results(
gh: &str,
program: &Path,
root: &Path,
run: &crate::codeql_submit::Submitted,
repos: &[String],
dir: &Path,
) -> VariantResults {
use crate::codeql_submit::{self as cs, RepoResults};
let mut sarif = Vec::new();
let mut tables = Vec::new();
let mut failed = Vec::new();
for nwo in repos {
let repo_dir = dir.join(nwo.replace('/', "-"));
let fetched = (|| -> Result<(Option<String>, RepoResults), String> {
let sha_file = repo_dir.join("commit");
if !repo_dir.join("done").is_file() {
let answer = crate::pr_review::run_gh(
gh,
&cs::repo_task_args(&run.controller, run.id, nwo),
root,
crate::pr_review::GH_TIMEOUT,
)?;
let (url, sha) = cs::parse_artifact(&answer)?;
if !cs::artifact_url_allowed(&url) {
return Err(String::from(
"GitHub gave a results link croft will not fetch",
));
}
let _ = std::fs::remove_dir_all(&repo_dir);
std::fs::create_dir_all(&repo_dir)
.map_err(|e| format!("{}: {e}", repo_dir.display()))?;
let resp = ureq::AgentBuilder::new()
.timeout(std::time::Duration::from_secs(300))
.build()
.get(&url)
.call()
.map_err(|e| format!("download failed: {e}"))?;
let zip = repo_dir.join("results.zip");
let mut f = std::fs::File::create(&zip).map_err(|e| e.to_string())?;
std::io::copy(&mut resp.into_reader(), &mut f)
.map_err(|e| format!("download failed: {e}"))?;
crate::codeql_db::extract_zip(&zip, &repo_dir, Some(cs::ARTIFACT_LIMIT))?;
let _ = std::fs::remove_file(&zip);
std::fs::write(&sha_file, sha.unwrap_or_default())
.map_err(|e| e.to_string())?;
std::fs::write(repo_dir.join("done"), "").map_err(|e| e.to_string())?;
}
let sha = std::fs::read_to_string(&sha_file)
.ok()
.filter(|s| !s.is_empty());
let found = |name: &str| cs::find_named(&repo_dir, name);
if let Some(path) = found("results.sarif") {
let text = std::fs::read_to_string(&path).map_err(|e| e.to_string())?;
return Ok((sha, RepoResults::Sarif(text)));
}
let bqrs = found("results.bqrs")
.ok_or_else(|| String::from("its results hold neither SARIF nor BQRS"))?;
let csv = repo_dir.join("results.csv");
if !csv.is_file() {
Self::codeql_decode_sets(program, &bqrs, &csv, &|args| {
Self::codeql_command(program, &args)
})?;
}
let text = std::fs::read_to_string(&csv).map_err(|e| e.to_string())?;
Ok((sha, RepoResults::Table(text)))
})();
match fetched {
Ok((sha, RepoResults::Sarif(text))) => sarif.push((nwo.clone(), sha, text)),
Ok((_, RepoResults::Table(text))) => tables.push((nwo.clone(), text)),
Err(why) => failed.push((nwo.clone(), why)),
}
}
let write = |name: &str, text: String| -> Result<PathBuf, String> {
let path = dir.join(name);
std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
std::fs::write(&path, text).map_err(|e| format!("{}: {e}", path.display()))?;
Ok(path)
};
let sarif_path = match sarif.is_empty() {
true => None,
false => Some(write("results.sarif", cs::combine_sarif(&sarif)?)?),
};
let csv_path = match tables.is_empty() {
true => None,
false => Some(write("results.csv", cs::combine_csv(&tables))?),
};
Ok(VariantResultFiles {
sarif: sarif_path,
csv: csv_path,
repos: sarif.len() + tables.len(),
failed,
})
}
/// Open the results a finished fetch made: the SARIF log in the viewer
/// (else the CSV), saying what else there is and what failed.
pub fn drain_codeql_variant_results(&mut self) -> bool {
let Some(rx) = self.codeql_variant_results.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) => {
Err(String::from("the fetch stopped without answering"))
}
};
self.codeql_variant_results = None;
let files = match outcome {
Ok(files) => files,
Err(why) => {
self.status = format!("Could not open the variant analysis results: {why}");
return true;
}
};
let failed = match files.failed.as_slice() {
[] => String::new(),
[(nwo, why)] => format!("; {nwo} failed: {why}"),
[(nwo, why), rest @ ..] => {
format!("; {nwo} failed: {why} (and {} more)", rest.len())
}
};
let Some(open) = files.sarif.clone().or_else(|| files.csv.clone()) else {
self.status = format!("No repository's results could be fetched{failed}");
return true;
};
if let Err(e) = self.editor.open(&open) {
self.status = format!("{}: {e}", open.display());
return true;
}
self.sync_open_file_poll_mtime();
self.focus_pane(Pane::Editor);
let tables = match (&files.sarif, &files.csv) {
(Some(_), Some(csv)) => format!("; tables in {}", csv.display()),
_ => String::new(),
};
self.status = format!(
"Results of {} repositor{}{tables}{failed}",
files.repos,
if files.repos == 1 { "y" } else { "ies" }
);
true
}
/// Ask where to export the results of remembered variant analysis
/// `index` (the newest when `None`): a folder, offered as one in the
/// workspace, or `gist` (#578, VS Code's "Export results").
fn prompt_export_codeql_variant_results(&mut self, index: Option<usize>) {
use crate::widgets::input_prompt::{InputPrompt, InputPurpose};
let runs = crate::codeql_submit::load_submitted(&Self::codeql_variant_runs_path());
let Some(i) = index.or(runs.len().checked_sub(1)) else {
self.status = String::from("No variant analysis has been submitted yet");
return;
};
let Some(run) = runs.get(i) else {
return;
};
if crate::codeql_submit::repos_with_results(run).is_empty() {
self.status = format!("Variant analysis {} has no results to export", run.id);
return;
}
let folder = self
.workspace_root()
.join(format!("codeql-variant-analysis-{}", run.id));
self.open_input_prompt(
InputPrompt::new(
InputPurpose::CodeqlExportVariantResults { index: i },
format!("Export Variant Analysis {} Results", run.id),
"a folder for the Markdown files, or gist for a secret gist",
)
.with_value(folder.display().to_string()),
);
}
/// Export on a worker thread: fetch the results as
/// [`Self::open_codeql_variant_results`] does (downloaded copies are
/// reused), write them as Markdown, and for `gist` post the files with
/// `gh gist create`.
fn start_export_codeql_variant_results(&mut self, index: usize, value: &str) {
use crate::codeql_submit as cs;
if self.codeql_variant_export.is_some() {
self.status = String::from("Variant analysis results are already being exported");
return;
}
let value = value.trim();
if value.is_empty() {
self.status = String::from("Give a folder, or gist");
return;
}
let runs = cs::load_submitted(&Self::codeql_variant_runs_path());
let Some(run) = runs.get(index).cloned() else {
self.status = String::from("That variant analysis is no longer remembered");
return;
};
let gist = value.eq_ignore_ascii_case("gist");
let base = croft_cache_dir()
.join("codeql")
.join("variant-results")
.join(format!("{}-{}", run.controller.replace('/', "-"), run.id));
let target = if gist {
base.join("export")
} else {
self.typed_path(value)
};
let repos = cs::repos_with_results(&run);
let gh = self.gh_program.to_string_lossy().into_owned();
let program = self.codeql_program.clone();
let root = self.active_workspace_root().to_path_buf();
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let outcome = (|| {
let files =
Self::fetch_codeql_variant_results(&gh, &program, &root, &run, &repos, &base)?;
if files.repos == 0 {
let why = files.failed.first().map_or("", |(_, w)| w.as_str());
return Err(format!("no repository's results could be fetched: {why}"));
}
let read = |p: &Option<PathBuf>| -> Result<Option<String>, String> {
p.as_ref()
.map(|p| {
std::fs::read_to_string(p).map_err(|e| format!("{}: {e}", p.display()))
})
.transpose()
};
let markdown = cs::export_markdown(
&run,
read(&files.sarif)?.as_deref(),
read(&files.csv)?.as_deref(),
)?;
if gist {
let _ = std::fs::remove_dir_all(&target);
}
std::fs::create_dir_all(&target)
.map_err(|e| format!("{}: {e}", target.display()))?;
let mut written = Vec::new();
for (name, text) in &markdown {
let path = target.join(name);
std::fs::write(&path, text).map_err(|e| format!("{}: {e}", path.display()))?;
written.push(path);
}
let url = match gist {
false => None,
true => {
let name = run
.query
.file_name()
.unwrap_or_default()
.to_string_lossy()
.into_owned();
let desc = format!(
"{name} (variant analysis {} of {} repositories)",
run.id, files.repos
);
let out = crate::pr_review::run_gh(
&gh,
&cs::gist_args(&desc, &written),
&root,
crate::pr_review::GH_TIMEOUT,
)?;
Some(
out.lines()
.rev()
.find(|l| l.starts_with("https://"))
.ok_or_else(|| String::from("gh made no gist"))?
.trim()
.to_string(),
)
}
};
Ok(VariantExport {
summary: (!gist).then(|| target.join("_summary.md")),
gist: url,
repos: files.repos,
failed: files.failed,
})
})();
let _ = tx.send(outcome);
});
self.codeql_variant_export = Some(rx);
self.status = String::from("Exporting the variant analysis results\u{2026}");
}
/// Report a finished export: open a folder export's summary, or name
/// the gist.
pub fn drain_codeql_variant_export(&mut self) -> bool {
let Some(rx) = self.codeql_variant_export.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) => {
Err(String::from("the export stopped without answering"))
}
};
self.codeql_variant_export = None;
let done = match outcome {
Ok(done) => done,
Err(why) => {
self.status = format!("Could not export the variant analysis results: {why}");
return true;
}
};
let failed = match done.failed.as_slice() {
[] => String::new(),
[(nwo, why)] => format!("; {nwo} left out: {why}"),
[(nwo, why), rest @ ..] => format!("; {nwo} left out: {why} (and {} more)", rest.len()),
};
let plural = if done.repos == 1 { "y" } else { "ies" };
self.status = match (done.gist, done.summary) {
(Some(url), _) => format!("Exported {} repositor{plural} to {url}{failed}", done.repos),
(None, Some(summary)) => {
if self.editor.open(&summary).is_ok() {
self.sync_open_file_poll_mtime();
self.focus_pane(Pane::Editor);
}
let dir = summary.parent().unwrap_or(&summary).display().to_string();
format!("Exported {} repositor{plural} to {dir}{failed}", done.repos)
}
(None, None) => String::from("Exported nothing"),
};
true
}
/// Where submitted variant analyses are remembered (#578).
fn codeql_variant_runs_path() -> PathBuf {
croft_cache_dir().join("codeql-variant-analyses.json")
}
/// Submit the open query as a variant analysis (#578, VS Code's "CodeQL:
/// Run Variant Analysis"): bundle it into a query pack and post it to
/// the controller repository, which runs it on GitHub Actions against
/// the selected list, repository or owner. The bundling and the post
/// happen on a worker thread; [`Self::drain_codeql_variant_submit`]
/// reports the run.
fn run_codeql_variant_analysis(&mut self) {
use crate::codeql_submit as cs;
if self.codeql_variant_submit.is_some() {
self.status = String::from("A variant analysis is already being submitted");
return;
}
let query = match self.editor.path.clone() {
Some(p) if p.extension().is_some_and(|e| e == "ql") => p,
_ => {
self.status = String::from("Open a .ql query to run a variant analysis");
return;
}
};
// The bundle is built from the file on disk.
if self.editor.dirty {
self.status = String::from("Save the query before running a variant analysis");
return;
}
let config = match crate::codeql_variant::VariantConfig::load(&Self::codeql_variant_path())
{
Ok(c) => c,
Err(why) => {
self.status = format!("Could not read the variant analysis config: {why}");
return;
}
};
let Some(controller) = config.controller_repo.clone() else {
self.status = String::from(
"Set up a controller repository under Variant Analysis Repositories first",
);
return;
};
let targets = match cs::targets(&config) {
Ok(t) => t,
Err(why) => {
self.status = why;
return;
}
};
let pack_language = cs::enclosing_pack(&query)
.and_then(|(_, file)| std::fs::read_to_string(file).ok())
.and_then(|text| crate::codeql_query::pack_language(&text));
let Some(language) =
pack_language.or_else(|| self.codeql_search_language().map(str::to_string))
else {
self.status = String::from(
"The query's pack names no language: pick one in the CodeQL side bar's Language section",
);
return;
};
let submitted_at = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
let stem = query
.file_stem()
.map(|s| s.to_string_lossy().into_owned())
.unwrap_or_default();
let work = croft_cache_dir()
.join("codeql")
.join("variant")
.join(format!("{submitted_at}-{stem}"));
let program = self.codeql_program.clone();
let gh = self.gh_program.to_string_lossy().into_owned();
let root = self.active_workspace_root().to_path_buf();
let describe = targets.describe();
let (tx, rx) = std::sync::mpsc::channel();
let query_for_run = query.clone();
std::thread::spawn(move || {
let query = query_for_run;
let outcome = (|| {
let _ = std::fs::remove_dir_all(&work);
let pack = cs::prepare_pack(&query, &language, &work)?;
let run = |args: Vec<String>| Self::codeql_command(&program, &args);
run(crate::codeql_query::pack_install_args(&pack))
.map_err(|e| format!("installing the pack's dependencies failed: {e}"))?;
let bundle = work.join("pack.tgz");
run(cs::pack_bundle_args(&pack, &bundle))
.map_err(|e| format!("bundling the query failed: {e}"))?;
let bytes =
std::fs::read(&bundle).map_err(|e| format!("{}: {e}", bundle.display()))?;
let body = work.join("body.json");
std::fs::write(
&body,
cs::submission_body(&language, &bytes, &targets).to_string(),
)
.map_err(|e| format!("{}: {e}", body.display()))?;
let answer = crate::pr_review::run_gh(
&gh,
&cs::submit_args(&controller, &body),
&root,
crate::pr_review::GH_TIMEOUT,
)?;
cs::parse_submission(&answer, &controller, &query, &language, submitted_at)
})();
let _ = std::fs::remove_dir_all(&work);
let _ = tx.send(outcome);
});
self.codeql_variant_submit = Some(rx);
self.status = format!(
"Submitting {} as a variant analysis against {describe}\u{2026}",
query.file_name().unwrap_or_default().to_string_lossy()
);
}
/// Report a finished variant analysis submission, and remember the run.
/// Returns true when one finished.
pub fn drain_codeql_variant_submit(&mut self) -> bool {
let Some(rx) = self.codeql_variant_submit.as_ref() else {
return false;
};
let outcome = match rx.try_recv() {
Ok(outcome) => outcome,
Err(std::sync::mpsc::TryRecvError::Empty) => return false,
Err(std::sync::mpsc::TryRecvError::Disconnected) => {
Err(String::from("the submission stopped without answering"))
}
};
self.codeql_variant_submit = None;
self.status = match outcome {
Ok(run) => {
let name = run
.query
.file_name()
.unwrap_or_default()
.to_string_lossy()
.into_owned();
let skipped = match run.skipped {
0 => String::new(),
n => format!(
", {n} repositor{} skipped",
if n == 1 { "y" } else { "ies" }
),
};
let url = run.url();
let id = run.id;
match crate::codeql_submit::record_submitted(&Self::codeql_variant_runs_path(), run)
{
Ok(()) => {
// Follow it from now on, starting with the next tick.
self.codeql_variant_polled = None;
self.refresh_codeql_variant_runs();
format!("Variant analysis {id} of {name} submitted{skipped}: {url}")
}
Err(e) => format!(
"Variant analysis {id} of {name} submitted{skipped}: {url} (not remembered: {e})"
),
}
}
Err(why) => format!("Could not submit the variant analysis: {why}"),
};
true
}
/// Run the open `.ql` query or `.qls` suite on the current database
/// (#578). The CLI reads the file from disk, so an unsaved buffer is
/// refused rather than silently running the saved text.
fn run_codeql_query(&mut self) {
let query = match self.editor.path.clone() {
Some(p) if p.extension().is_some_and(|e| e == "ql" || e == "qls") => p,
_ => {
self.status = String::from("Open a .ql query or .qls suite to run it");
return;
}
};
if self.editor.dirty {
let name = query
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
self.status = format!("Save {name} before running it: CodeQL reads it from disk");
return;
}
let source = self.editor.lines.join("\n");
self.run_codeql_file(query, &source);
}
/// VS Code's "CodeQL: Run Query Suite" (#578): the open `.qls` suite on
/// the current database, through `database analyze` into SARIF.
fn run_codeql_query_suite(&mut self) {
if !self
.editor
.path
.as_deref()
.is_some_and(crate::codeql_query::is_suite)
{
self.status = String::from("Open a .qls query suite to run it");
return;
}
self.run_codeql_query();
}
/// Run `query`, whose text is `source`, on the current database (#578):
/// alerts through `database analyze` into SARIF, anything else through
/// `query run` into a table decoded as CSV. The run happens on a worker
/// thread; [`Self::drain_codeql_run`] collects it.
fn run_codeql_file(&mut self, query: PathBuf, source: &str) {
self.run_codeql_file_with(query, source, None);
}
/// [`Self::run_codeql_file`], or with `quick` a quick evaluation of a
/// span of `query` through the CLI's query server (#578), recorded in
/// the history like any run and decoded to a table.
fn run_codeql_file_with(
&mut self,
query: PathBuf,
source: &str,
quick: Option<crate::codeql_qs::QuickEval>,
) {
let mode = match quick {
Some(q) => CodeqlRunMode::Quick(q),
None => CodeqlRunMode::Whole,
};
self.run_codeql_file_on(query, source, mode, None);
}
/// CodeQL: Run Queries in Published Pack (#578): ask which pack.
fn prompt_run_codeql_published_pack(&mut self) {
use crate::widgets::input_prompt::{InputPrompt, InputPurpose};
self.open_input_prompt(InputPrompt::new(
InputPurpose::CodeqlRunPublishedPack,
String::from("Run Queries in Published Pack"),
"e.g. codeql/python-queries, scope/name@1.0.0, scope/name:path/in/pack",
));
}
/// Download the pack `reference` names and run it, or the part of it
/// after `:`, on the current database into SARIF (#578).
fn run_codeql_published_pack(&mut self, reference: &str) {
let reference = reference.trim();
if crate::codeql_query::published_pack(reference).is_none() {
self.status = format!("{reference:?} is not a pack: write scope/name");
return;
}
self.run_codeql_file_on(PathBuf::from(reference), "", CodeqlRunMode::Pack, None);
}
/// [`Self::run_codeql_file_with`] on the database at `database`, or on
/// the current one when that is `None`.
fn run_codeql_file_on(
&mut self,
query: PathBuf,
source: &str,
mode: CodeqlRunMode,
database: Option<&Path>,
) {
use crate::codeql_query::{self as cq, History, HistoryEntry, Output, RunStatus};
if self.codeql_run.is_some() {
self.status = String::from("A CodeQL query is already running");
return;
}
if let Some((_, job, _, _)) = self.codeql_upgrade.as_ref() {
self.status = format!("Wait for the CodeQL database {} to finish", job.noun());
return;
}
let store = crate::codeql_db::DatabaseStore::load(&Self::codeql_db_store_path());
let db = match database {
Some(path) => store.databases.iter().find(|db| db.path == path).cloned(),
None => store.current.and_then(|i| store.databases.get(i)).cloned(),
};
let Some(db) = db else {
self.status = match database {
Some(path) => format!("The CodeQL database {} is gone", path.display()),
None => String::from("Add a CodeQL database and select it first"),
};
return;
};
let started = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
let stem = query
.file_stem()
.map(|s| s.to_string_lossy().into_owned())
.unwrap_or_default();
// Runs of a pack start back to back, so two queries of the same
// name can start within the same second; each keeps its own folder.
let base = Self::codeql_results_dir().join(format!("{started}-{stem}"));
let mut dir = base.clone();
let mut n = 1;
while dir.exists() {
n += 1;
dir = PathBuf::from(format!("{}-{n}", base.display()));
}
let kind = match mode {
CodeqlRunMode::Quick(_) => Output::Table,
CodeqlRunMode::Pack => Output::Sarif,
CodeqlRunMode::Whole => cq::output_of(&query, source),
};
let output = dir.join(match kind {
Output::Sarif => "results.sarif",
Output::Table => "results.csv",
});
// The query as it is run, for "View Query Text": the file may change
// or go before anyone looks back at this run. Read-only, since
// editing it would change nothing.
let text = cq::query_text_path(&output, &query);
if !matches!(mode, CodeqlRunMode::Pack)
&& let Some(parent) = text.parent()
&& std::fs::create_dir_all(parent).is_ok()
&& std::fs::write(&text, source).is_ok()
{
use std::os::unix::fs::PermissionsExt;
let _ = std::fs::set_permissions(&text, std::fs::Permissions::from_mode(0o444));
}
let mut history = History::load(&Self::codeql_history_path());
history.push(HistoryEntry {
query: query.clone(),
database: db.name.clone(),
database_path: Some(db.path.clone()),
started,
seconds: 0,
status: RunStatus::Running,
output: output.clone(),
name: match &mode {
CodeqlRunMode::Quick(q) => Some(q.title()),
_ => None,
},
results: None,
});
let _ = history.save(&Self::codeql_history_path());
self.refresh_codeql_history();
let name = match &mode {
CodeqlRunMode::Quick(q) => q.title(),
CodeqlRunMode::Pack => query.display().to_string(),
CodeqlRunMode::Whole => query
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default(),
};
// Where the query server looks for the workspace's own packs.
let packs: Vec<PathBuf> = self.roots.iter().map(Path::to_path_buf).collect();
// The workspace's model packs (#578), which customize the run.
let models = crate::codeql_model::model_pack_args(self.workspace_root());
let program = self.codeql_program.clone();
let (tx, rx) = std::sync::mpsc::channel();
// A fresh flag per run, so a late cancel never stops the next one.
let cancel = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
self.codeql_cancel = cancel.clone();
std::thread::spawn(move || {
let run = |args: Vec<String>| Self::codeql_command_until(&program, &args, &cancel);
let outcome = std::fs::create_dir_all(&dir)
.map_err(|e| format!("{}: {e}", dir.display()))
.and_then(|()| match (mode, kind) {
(CodeqlRunMode::Quick(q), _) => {
let bqrs = dir.join("results.bqrs");
crate::codeql_qs::run_quick_eval(
&program, &db.path, &query, &bqrs, &packs, q.span, q.count, &cancel,
)
.and_then(|()| Self::codeql_decode_sets(&program, &bqrs, &output, &run))
}
(CodeqlRunMode::Pack, _) => {
let reference = query.to_string_lossy();
let pack = cq::published_pack(&reference).unwrap_or_default();
run(cq::pack_download_args(&[pack.to_string()])).and_then(|()| {
let mut args = cq::analyze_args(&query, &db.path, &output);
args.extend(models.iter().cloned());
run(args)
})
}
(CodeqlRunMode::Whole, Output::Sarif) => {
let mut args = cq::analyze_args(&query, &db.path, &output);
args.extend(models.iter().cloned());
if cq::is_suite(&query) {
Self::check_codeql_suite(&program, &query).and_then(|()| run(args))
} else {
run(args)
}
}
(CodeqlRunMode::Whole, Output::Table) => {
let bqrs = dir.join("results.bqrs");
let mut args = cq::run_args(&query, &db.path, &bqrs);
args.extend(models.iter().cloned());
run(args)
.and_then(|()| Self::codeql_decode_sets(&program, &bqrs, &output, &run))
}
});
let _ = tx.send(match outcome {
Ok(()) => RunStatus::Succeeded,
Err(_) if cancel.load(std::sync::atomic::Ordering::SeqCst) => RunStatus::Cancelled,
Err(e) => RunStatus::Failed(e),
});
});
self.codeql_run = Some((rx, std::time::Instant::now()));
self.codeql_run_name = name.clone();
self.status = format!("Running {name} on {}\u{2026}", db.name);
}
/// Refuse suite `suite` when it selects a query whose results are not
/// alerts (#578): `database analyze` cannot produce those tables.
fn check_codeql_suite(program: &Path, suite: &Path) -> Result<(), String> {
let out = crate::review_ops::output_retrying_busy(
std::process::Command::new(program)
.args(crate::codeql_query::resolve_suite_args(suite)),
)
.map_err(|e| format!("could not run codeql: {e}"))?;
if !out.status.success() {
return Err(crate::codeql_query::failure_reason(
&String::from_utf8_lossy(&out.stderr),
));
}
let tables = crate::codeql_query::table_queries_in_suite(
&String::from_utf8_lossy(&out.stdout),
|p| std::fs::read_to_string(p).ok(),
)?;
if tables.is_empty() {
return Ok(());
}
Err(format!(
"the suite selects queries that are not alert queries ({}); run those on their own",
tables.join(", ")
))
}
/// CodeQL: Quick Evaluation, and its count variant (#578): evaluate the
/// predicate under the cursor, or the selected expression, of the open
/// query on the current database, through the CLI's query server.
fn quick_eval_codeql(&mut self, count: bool) {
let Some(query) = self
.editor
.path
.clone()
.filter(|p| p.extension().is_some_and(|e| e == "ql"))
else {
self.status = String::from("Open a .ql query to quick-evaluate part of it");
return;
};
if self.editor.dirty {
self.status = String::from("Save the query first: the query server reads it from disk");
return;
}
let selection = self.editor.selection.map(|s| s.normalised());
let Some((span, label)) = crate::codeql_qs::span_at(
&self.editor.lines,
self.editor.cursor_row,
self.editor.cursor_col,
selection,
) else {
self.status = String::from("Put the cursor on a predicate, or select an expression");
return;
};
let source = self.editor.lines.join("\n");
self.run_codeql_file_with(
query,
&source,
Some(crate::codeql_qs::QuickEval { span, count, label }),
);
}
/// CodeQL: Debug Query (#578): evaluate the open query up to its first
/// breakpoint, the way VS Code's CodeQL debugger stops at one: the
/// predicate the breakpoint's line defines or calls is quick-evaluated.
/// With no breakpoints the whole query runs.
fn debug_codeql_query(&mut self) {
let Some(query) = self
.editor
.path
.clone()
.filter(|p| p.extension().is_some_and(|e| e == "ql"))
else {
self.status = String::from("Open a .ql query to debug it");
return;
};
let lines: Vec<usize> = self
.editor
.breakpoints
.get(&query)
.map(|b| b.iter().copied().collect())
.unwrap_or_default();
if lines.is_empty() {
self.run_codeql_query();
return;
}
if self.editor.dirty {
self.status = String::from("Save the query first: the query server reads it from disk");
return;
}
let target = lines.iter().find_map(|&line| {
let text = self.editor.lines.get(line.checked_sub(1)?)?;
crate::codeql_qs::breakpoint_target(text, line as u32)
});
let Some((span, name)) = target else {
self.status = format!(
"No predicate at the breakpoint on line {}: put it on a line that defines or calls one",
lines[0]
);
return;
};
let source = self.editor.lines.join("\n");
let label = format!("{name} (breakpoint on line {})", span.line);
self.run_codeql_file_with(
query,
&source,
Some(crate::codeql_qs::QuickEval {
span,
count: false,
label,
}),
);
}
/// [`Self::codeql_command`], killing `codeql` as soon as `cancel` is
/// raised (#578). Its output is drained on threads of its own, so a
/// chatty CLI never blocks on a full pipe while this polls.
fn codeql_command_until(
program: &Path,
args: &[String],
cancel: &std::sync::atomic::AtomicBool,
) -> Result<(), String> {
use std::io::Read as _;
use std::sync::atomic::Ordering;
if cancel.load(Ordering::SeqCst) {
return Err(String::from("cancelled"));
}
let mut child = crate::review_ops::spawn_retrying_busy(
std::process::Command::new(program)
.args(args)
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::piped()),
)
.map_err(|e| format!("could not run codeql: {e}"))?;
let mut stderr = child.stderr.take();
let reader = std::thread::spawn(move || {
let mut text = String::new();
if let Some(s) = stderr.as_mut() {
let _ = s.read_to_string(&mut text);
}
text
});
let status = loop {
if cancel.load(Ordering::SeqCst) {
let _ = child.kill();
let _ = child.wait();
return Err(String::from("cancelled"));
}
match child.try_wait() {
Ok(Some(status)) => break status,
Ok(None) => std::thread::sleep(std::time::Duration::from_millis(25)),
Err(e) => return Err(format!("could not wait for codeql: {e}")),
}
};
let err = reader.join().unwrap_or_default();
if status.success() {
Ok(())
} else {
Err(crate::codeql_query::failure_reason(&err))
}
}
/// CodeQL: Cancel Running Query (#578): stop the query in flight, and
/// the queries a pack or multi-database run has queued after it.
fn cancel_codeql_run(&mut self) {
if self.codeql_run.is_none() {
self.status = String::from("No CodeQL query is running");
return;
}
self.codeql_cancel
.store(true, std::sync::atomic::Ordering::SeqCst);
let queued = self.codeql_run_queue.len();
self.codeql_run_queue.clear();
self.status = match queued {
0 => String::from("Cancelling the running CodeQL query\u{2026}"),
n => format!("Cancelling the running CodeQL query and {n} queued\u{2026}"),
};
}
/// Walk a CodeQL results table (#578, VS Code's `codeQLQueryResults`
/// up/down/left/right): move its cursor by (`rows`, `cols`) and open
/// the code of the cell's entity, else of the first entity in its row.
/// The table is the active results sheet, else the one walked last,
/// so the walk goes on once the code has the focus.
fn walk_codeql_results(&mut self, rows: isize, cols: isize) {
use crate::codeql_query as cq;
let active = self
.editor
.path
.clone()
.filter(|p| self.editor.sheet.is_some() && cq::locations_path(p).is_file());
let on_table = active.is_some();
let Some(table) = active.or_else(|| self.codeql_results_walk.clone()) else {
self.status = String::from("Open a CodeQL results table first");
return;
};
// The active tab when it is the table, else a tab showing it.
let tab = if on_table {
Some(&mut *self.editor)
} else {
self.editor
.editors
.iter_mut()
.find(|t| t.path.as_deref() == Some(table.as_path()) && t.sheet.is_some())
};
let Some(sheet) = tab.and_then(|t| t.sheet.as_mut()) else {
self.codeql_results_walk = None;
self.status = String::from("Open a CodeQL results table first");
return;
};
let current = sheet.current_sheet;
let Some(data) = sheet.sheets.get_mut(current) else {
return;
};
if data.rows.is_empty() {
self.status = String::from("The results table is empty");
return;
}
let step = |at: usize, by: isize, len: usize| -> usize {
(at as isize + by).clamp(0, len.saturating_sub(1) as isize) as usize
};
data.cur_row = step(data.cur_row, rows, data.rows.len());
data.cur_col = step(data.cur_col, cols, data.col_widths.len().max(1));
let (cells, col) = (data.rows[data.cur_row].clone(), data.cur_col);
let row = data.cur_row + 1;
self.codeql_results_walk = Some(table.clone());
let saved: Vec<cq::RowLocs> = std::fs::read_to_string(cq::locations_path(&table))
.ok()
.and_then(|t| serde_json::from_str(&t).ok())
.unwrap_or_default();
let Some(locs) = cq::row_locations(&saved, &cells) else {
self.status = format!("Result {row} has no location");
return;
};
let Some(loc) = locs
.get(col)
.cloned()
.flatten()
.or_else(|| locs.iter().flatten().next().cloned())
else {
self.status = format!("Result {row} has no location");
return;
};
let Some(path) = self.codeql_source_file(&loc.path) else {
self.status = format!("{} is not on this machine", loc.path.display());
return;
};
if self.editor.path.as_deref() == Some(table.as_path()) {
self.editor.pin_active();
}
let (line, column) = (loc.line.max(1) - 1, loc.column.max(1) - 1);
self.status = match self.open_at(&path, line as usize, column as usize) {
Ok(()) => format!("Result {row}: {}:{}", path.display(), loc.line),
Err(e) => format!("{}: {e}", path.display()),
};
}
/// A source file a CodeQL result names, on this machine: the path
/// itself, else its copy in an extracted source archive or in a
/// database's `src` folder, which both mirror the original paths.
fn codeql_source_file(&self, path: &Path) -> Option<PathBuf> {
if path.is_file() {
return Some(path.to_path_buf());
}
let rel = path.strip_prefix("/").unwrap_or(path);
let extracted = std::fs::read_dir(Self::codeql_source_cache_dir())
.into_iter()
.flatten()
.flatten()
.map(|e| e.path());
let src = crate::codeql_db::DatabaseStore::load(&Self::codeql_db_store_path())
.databases
.into_iter()
.map(|d| d.path.join("src"));
extracted
.chain(src)
.map(|root| root.join(rel))
.find(|p| p.is_file())
}
/// Decode `bqrs` to CSV, one file per result set (#578): the main set
/// (`#select`) to `out`, each other beside it as `results-<set>.csv`.
/// `bqrs decode` without a set writes them all into one CSV, header
/// rows and all, so that is only the fallback for a BQRS whose sets
/// cannot be listed. `run` runs each decode.
fn codeql_decode_sets(
program: &Path,
bqrs: &Path,
out: &Path,
run: &dyn Fn(Vec<String>) -> Result<(), String>,
) -> Result<(), String> {
use crate::codeql_query as cq;
let sets = Self::codeql_stdout(program, &cq::info_args(bqrs))
.map(|json| cq::parse_result_sets(&json))
.unwrap_or_default();
let Some(main) = cq::main_result_set(&sets).map(str::to_string) else {
return run(cq::decode_args(bqrs, out));
};
for (name, _) in &sets {
let file = cq::result_set_file(out, name, *name == main);
run(cq::decode_set_args(bqrs, &file, name))?;
// Where each cell's entity is, for walking the results in the
// code. Optional: a table without it still opens.
let raw = file.with_extension("entities.json");
if run(cq::decode_locations_args(bqrs, &raw, name)).is_ok()
&& let Ok(text) = std::fs::read_to_string(&raw)
&& let Ok(json) = serde_json::to_string(&cq::parse_row_locations(&text))
{
let _ = std::fs::write(cq::locations_path(&file), json);
}
let _ = std::fs::remove_file(&raw);
}
Ok(())
}
/// CodeQL: Show Result Set (#578): pick which result set of the Query
/// History run selected (else the newest) to open.
fn show_codeql_result_sets(&mut self) {
use crate::widgets::list_picker::{ListPicker, ListPurpose, ListRow};
let history = crate::codeql_query::History::load(&Self::codeql_history_path());
let Some(entry) = self
.codeql
.selected_history()
.or_else(|| history.newest())
.and_then(|i| history.entries.get(i))
.cloned()
else {
self.status = String::from("No CodeQL query has run yet");
return;
};
let name = entry.query_name();
if entry.output.extension().is_none_or(|e| e != "csv") {
self.status = format!("{name} found alerts, which open in the SARIF viewer");
return;
}
let sets = crate::codeql_query::result_set_files(&entry.output);
if sets.len() < 2 {
self.status = format!("{name} has one result set");
return;
}
let rows = sets
.into_iter()
.map(|(set, path)| ListRow {
id: path.display().to_string(),
label: set,
})
.collect();
self.open_list_picker(
ListPicker::new(
ListPurpose::CodeqlResultSet,
format!("Result sets of {name}"),
rows,
),
"No result sets",
);
}
/// Run `codeql` with `args` and return what it printed on stdout; a
/// failure is read as [`Self::codeql_command`] reads it.
fn codeql_stdout(program: &Path, args: &[String]) -> Result<String, String> {
let out =
crate::review_ops::output_retrying_busy(std::process::Command::new(program).args(args))
.map_err(|e| format!("could not run codeql: {e}"))?;
if out.status.success() {
return Ok(String::from_utf8_lossy(&out.stdout).into_owned());
}
Err(crate::codeql_query::failure_reason(
&String::from_utf8_lossy(&out.stderr),
))
}
/// What a contextual query (AST, CFG) runs on (#578): the open file,
/// the current database, its language, and the file's name in that
/// database's source archive. Says what is missing when something is.
fn codeql_contextual_target(
&mut self,
) -> Option<(PathBuf, crate::codeql_db::DbEntry, String, String)> {
let Some(file) = self.editor.path.clone() else {
self.status = String::from("Open a source file from the CodeQL database first");
return None;
};
let store = crate::codeql_db::DatabaseStore::load(&Self::codeql_db_store_path());
let Some(db) = store.current.and_then(|i| store.databases.get(i)).cloned() else {
self.status = String::from("Select a CodeQL database first");
return None;
};
let Some(lang) = db.language.clone() else {
self.status = format!("CodeQL database {} does not say its language", db.name);
return None;
};
// The places this database's source can be open from: its `src`
// folder and its extracted `src.zip`s, which both mirror the
// absolute paths it was built from.
let prefix = crate::codeql_db::source_cache_prefix(&db.path);
let mut roots: Vec<PathBuf> = std::fs::read_dir(Self::codeql_source_cache_dir())
.into_iter()
.flatten()
.flatten()
.filter(|e| e.file_name().to_string_lossy().starts_with(&prefix))
.map(|e| e.path())
.collect();
roots.push(db.path.join("src"));
let archive = crate::codeql_ast::archive_path(&file, &roots);
Some((file, db, lang, archive))
}
/// A fresh folder for one contextual query run of `kind`.
fn codeql_contextual_dir(kind: &str) -> PathBuf {
let stamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0);
croft_cache_dir()
.join("codeql")
.join(kind)
.join(stamp.to_string())
}
/// Resolve `lang`'s contextual query tagged `tag`, and make sure its
/// pack's dependencies are there (#578).
fn codeql_contextual_query(
program: &Path,
dir: &Path,
lang: &str,
tag: &str,
) -> Result<PathBuf, String> {
use crate::codeql_ast as ast;
let suite = dir.join(format!("{tag}.qls"));
std::fs::write(&suite, ast::contextual_suite(lang, tag))
.map_err(|e| format!("{}: {e}", suite.display()))?;
let listed = Self::codeql_stdout(program, &ast::resolve_args(&suite))?;
let query = ast::first_query(&listed).ok_or_else(|| {
format!(
"no {tag} query for {lang}; download the codeql/{lang}-all pack \
with CodeQL: Download Packs"
)
})?;
// A library pack downloaded on its own may lack what it depends
// on; installing is quick when nothing is missing.
if let Some(pack) = ast::pack_dir(&query) {
Self::codeql_command(program, &crate::codeql_query::pack_install_args(&pack))?;
}
Ok(query)
}
/// CodeQL: View CFG (#578): the control flow graph of the function at
/// the cursor, from the current database, opened as a document.
fn view_codeql_cfg(&mut self) {
use crate::codeql_ast as ast;
if self.codeql_doc_job.is_some() {
self.status = String::from("A CodeQL view is already being made");
return;
}
let Some((file, db, lang, archive)) = self.codeql_contextual_target() else {
return;
};
let (line, column) = (self.editor.cursor_row + 1, self.editor.cursor_col + 1);
let name = file
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
let title = format!("{name}:{line}:{column} in {}", db.name);
let dir = Self::codeql_contextual_dir("cfg");
let program = self.codeql_program.clone();
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let read = || -> Result<PathBuf, String> {
let io = |e: std::io::Error| format!("{}: {e}", dir.display());
std::fs::create_dir_all(&dir).map_err(io)?;
let query = Self::codeql_contextual_query(&program, &dir, &lang, "print-cfg")?;
let (f, l, c) = (
dir.join("file.csv"),
dir.join("line.csv"),
dir.join("column.csv"),
);
std::fs::write(&f, ast::selected_file_csv(&archive)).map_err(io)?;
std::fs::write(&l, format!("{line}\n")).map_err(io)?;
std::fs::write(&c, format!("{column}\n")).map_err(io)?;
let bqrs = dir.join("cfg.bqrs");
Self::codeql_command(
&program,
&crate::codeql_cfg::run_args(&query, &db.path, &f, &l, &c, &bqrs),
)?;
let json = dir.join("cfg.json");
Self::codeql_command(&program, &ast::decode_args(&bqrs, &json))?;
let cfg =
crate::codeql_cfg::parse_cfg(&std::fs::read_to_string(&json).map_err(io)?)?;
let doc = dir.join("cfg.md");
std::fs::write(&doc, crate::codeql_cfg::render_document(&cfg, &title))
.map_err(io)?;
use std::os::unix::fs::PermissionsExt;
let _ = std::fs::set_permissions(&doc, std::fs::Permissions::from_mode(0o444));
Ok(doc)
};
let _ = tx.send(read());
});
self.status = format!("Reading the control flow graph at {name}:{line}\u{2026}");
self.codeql_doc_job = Some((
rx,
String::from("Control flow graph"),
String::from("Could not read the control flow graph"),
));
}
/// Open a finished CodeQL document (#578), or say why there is none.
pub fn drain_codeql_doc(&mut self) -> bool {
let Some((rx, ..)) = self.codeql_doc_job.as_ref() else {
return false;
};
let outcome = match rx.try_recv() {
Ok(outcome) => outcome,
Err(std::sync::mpsc::TryRecvError::Empty) => return false,
Err(std::sync::mpsc::TryRecvError::Disconnected) => {
Err(String::from("it stopped unexpectedly"))
}
};
let Some((_, done, failed)) = self.codeql_doc_job.take() else {
return false;
};
self.status = match outcome {
Ok(doc) => match self.editor.open(&doc) {
Ok(()) => done,
Err(e) => format!("{}: {e}", doc.display()),
},
Err(why) => format!("{failed}: {why}"),
};
true
}
/// CodeQL: Open Referenced File (#578): the query the open `.qlref`
/// test file names, as `codeql resolve qlref` finds it through the
/// test pack's dependencies.
fn open_codeql_referenced_file(&mut self) {
let Some(qlref) = self
.editor
.path
.clone()
.filter(|p| p.extension().is_some_and(|e| e == "qlref"))
else {
self.status = String::from("Open a .qlref file first");
return;
};
if self.codeql_doc_job.is_some() {
self.status = String::from("A CodeQL view is already being made");
return;
}
let name = qlref
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
let program = self.codeql_program.clone();
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let found = Self::codeql_stdout(&program, &crate::codeql_query::qlref_args(&qlref))
.and_then(|json| {
crate::codeql_query::parse_qlref(&json)
.ok_or_else(|| String::from("the CLI named no query"))
});
let _ = tx.send(found);
});
self.status = format!("Resolving {name}\u{2026}");
self.codeql_doc_job = Some((
rx,
format!("The query {name} references"),
format!("Could not resolve {name}"),
));
}
/// The Query History run selected in the side bar, else the newest;
/// says so when nothing has run.
fn codeql_chosen_run(&mut self) -> Option<crate::codeql_query::HistoryEntry> {
let history = crate::codeql_query::History::load(&Self::codeql_history_path());
let entry = self
.codeql
.selected_history()
.or_else(|| history.newest())
.and_then(|i| history.entries.get(i))
.cloned();
if entry.is_none() {
self.status = String::from("No CodeQL query has run yet");
}
entry
}
/// The folder of the database `entry` ran on, by its recorded path,
/// else by its name in the store.
fn codeql_run_database(entry: &crate::codeql_query::HistoryEntry) -> Option<PathBuf> {
entry.database_path.clone().or_else(|| {
crate::codeql_db::DatabaseStore::load(&Self::codeql_db_store_path())
.databases
.into_iter()
.find(|d| d.name == entry.database)
.map(|d| d.path)
})
}
/// The alert views of a run (#578): "View Alerts (SARIF)" opens the
/// SARIF as JSON; "View Alerts (CSV)" has `codeql database
/// interpret-results` write the alerts as CSV from the results the
/// database keeps, without running the query again.
fn view_codeql_alerts(&mut self, csv: bool) {
let Some(entry) = self.codeql_chosen_run() else {
return;
};
let name = entry.query_name();
if entry.status != crate::codeql_query::RunStatus::Succeeded
|| entry.output.extension().is_none_or(|e| e != "sarif")
{
self.status = format!("{name} did not produce alerts; its results are a table");
return;
}
if !csv {
// Opened, then reopened as text: the override holds only for
// the tab's own file, so it is set once the tab is on it.
let opened = self.editor.open(&entry.output).and_then(|()| {
self.editor.force_text = true;
self.editor.open(&entry.output)
});
self.status = match opened {
Ok(()) => format!("Alerts of {name} (SARIF)"),
Err(e) => format!("{}: {e}", entry.output.display()),
};
return;
}
let Some(db) = Self::codeql_run_database(&entry) else {
self.status = format!("The database {name} ran on is gone", name = entry.database);
return;
};
if self.codeql_doc_job.is_some() {
self.status = String::from("A CodeQL view is already being made");
return;
}
let out = entry.output.with_file_name("alerts.csv");
let program = self.codeql_program.clone();
let query = entry.query.clone();
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let made = Self::codeql_command(
&program,
&crate::codeql_query::interpret_csv_args(&db, &query, &out),
)
.map(|()| out);
let _ = tx.send(made);
});
self.status = format!("Writing the alerts of {name} as CSV\u{2026}");
self.codeql_doc_job = Some((
rx,
format!("Alerts of {name} (CSV)"),
format!("Could not write the alerts of {name} as CSV"),
));
}
/// "View Results (CSV)" (#578): a run's raw results as tables. A table
/// run's are its results already; an alert run's are decoded from the
/// BQRS the database keeps for the query.
fn view_codeql_raw_results(&mut self) {
let Some(entry) = self.codeql_chosen_run() else {
return;
};
let name = entry.query_name();
if entry.status != crate::codeql_query::RunStatus::Succeeded {
self.status = format!("{name} has no results");
return;
}
if entry.output.extension().is_some_and(|e| e == "csv") {
self.status = match self.editor.open(&entry.output) {
Ok(()) => format!("Results of {name} (CSV)"),
Err(e) => format!("{}: {e}", entry.output.display()),
};
return;
}
let Some(db) = Self::codeql_run_database(&entry) else {
self.status = format!("The database {name} ran on is gone", name = entry.database);
return;
};
let Some(bqrs) = crate::codeql_query::kept_bqrs(&db, &entry.query) else {
self.status = format!("The database no longer keeps the results of {name}");
return;
};
if self.codeql_doc_job.is_some() {
self.status = String::from("A CodeQL view is already being made");
return;
}
let out = entry.output.with_file_name("raw-results.csv");
let program = self.codeql_program.clone();
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let made = Self::codeql_decode_sets(&program, &bqrs, &out, &|args| {
Self::codeql_command(&program, &args)
})
.map(|()| out);
let _ = tx.send(made);
});
self.status = format!("Decoding the results of {name}\u{2026}");
self.codeql_doc_job = Some((
rx,
format!("Results of {name} (CSV)"),
format!("Could not decode the results of {name}"),
));
}
/// CodeQL: Open Model Editor (#578): read the current database's
/// library endpoints with its language's model-editor query, off the
/// UI thread; [`Self::drain_codeql_model`] lists them under Method
/// Modeling.
fn open_codeql_model_editor(&mut self) {
use crate::codeql_query as cq;
if self.codeql_model_job.is_some() {
self.status = String::from("The model editor is already reading endpoints");
return;
}
let store = crate::codeql_db::DatabaseStore::load(&Self::codeql_db_store_path());
let Some(db) = store.current.and_then(|i| store.databases.get(i)).cloned() else {
self.status = String::from("Select a CodeQL database first");
return;
};
let Some(lang) = db.language.clone() else {
self.status = format!("CodeQL database {} does not say its language", db.name);
return;
};
let dir = Self::codeql_contextual_dir("model");
let program = self.codeql_program.clone();
let (tx, rx) = std::sync::mpsc::channel();
let lang_for = lang.clone();
std::thread::spawn(move || {
let read = || -> Result<Vec<crate::codeql_model::Endpoint>, String> {
let io = |e: std::io::Error| format!("{}: {e}", dir.display());
std::fs::create_dir_all(&dir).map_err(io)?;
let suite = dir.join("endpoints.qls");
std::fs::write(&suite, crate::codeql_model::endpoints_suite(&lang_for))
.map_err(io)?;
let listed =
Self::codeql_stdout(&program, &crate::codeql_ast::resolve_args(&suite))?;
let query = crate::codeql_ast::first_query(&listed).ok_or_else(|| {
format!(
"no model-editor query for {lang_for}; download the \
codeql/{lang_for}-queries pack with CodeQL: Download Packs"
)
})?;
let bqrs = dir.join("endpoints.bqrs");
Self::codeql_command(&program, &cq::run_args(&query, &db.path, &bqrs))?;
let json = dir.join("endpoints.json");
Self::codeql_command(
&program,
&cq::decode_locations_args(&bqrs, &json, "#select"),
)?;
let endpoints = crate::codeql_model::parse_endpoints(
&std::fs::read_to_string(&json).map_err(io)?,
);
if endpoints.is_empty() {
return Err(String::from(
"the database has no library endpoints to model (is it a library?)",
));
}
Ok(endpoints)
};
let _ = tx.send(read());
});
self.status = format!("Reading the endpoints of {}\u{2026}", db.name);
self.codeql_model_job = Some((rx, db.name, lang));
}
/// Model endpoint `endpoint` of the Model Editor (#578): pick what it
/// is, as a source at its return value, a sink at an argument, or a
/// summary, or remove the models made for it.
fn model_codeql_endpoint(&mut self, endpoint: Option<usize>) {
use crate::widgets::list_picker::{ListPicker, ListPurpose, ListRow};
let Some(view) = self.codeql.model.as_ref() else {
self.status = String::from("Open the model editor first");
return;
};
let Some(e) = endpoint.and_then(|i| view.endpoints.get(i)) else {
self.status = String::from("Select an endpoint in Method Modeling first");
return;
};
let choices = e.choices();
if choices.is_empty() {
self.status = format!("{} is a class; model its methods", e.label());
return;
}
let i = endpoint.unwrap_or(0);
let mut rows: Vec<ListRow> = choices
.iter()
.enumerate()
.map(|(j, m)| ListRow {
id: format!("{i}:{j}"),
label: m.describe(),
})
.collect();
let path = e.access_path();
if view
.models
.iter()
.any(|m| m.ty == e.namespace && Some(&m.path) == path.as_ref())
{
rows.push(ListRow {
id: format!("{i}:remove"),
label: String::from("remove the models made for it"),
});
}
let title = format!("Model {}", e.label());
self.open_list_picker(ListPicker::new(ListPurpose::CodeqlModel, title, rows), "");
}
/// A model picked for an endpoint (`<endpoint>:<choice>` or
/// `<endpoint>:remove`): ask for its kind, or remove its models.
fn choose_codeql_model(&mut self, id: &str) {
use crate::widgets::input_prompt::{InputPrompt, InputPurpose};
let Some((endpoint, choice)) = id.split_once(':') else {
return;
};
let Ok(endpoint) = endpoint.parse::<usize>() else {
return;
};
if choice == "remove" {
let Some(view) = self.codeql.model.as_mut() else {
return;
};
let Some(e) = view.endpoints.get(endpoint).cloned() else {
return;
};
let path = e.access_path();
view.models
.retain(|m| !(m.ty == e.namespace && Some(&m.path) == path.as_ref()));
self.status = match self.write_codeql_models() {
Ok(file) => format!(
"Removed the models of {} from {}",
e.label(),
file.display()
),
Err(why) => format!("Could not save the models: {why}"),
};
return;
}
let Ok(choice) = choice.parse::<usize>() else {
return;
};
let Some(model) = self
.codeql
.model
.as_ref()
.and_then(|v| v.endpoints.get(endpoint))
.and_then(|e| e.choices().into_iter().nth(choice))
else {
return;
};
self.open_input_prompt(
InputPrompt::new(
InputPurpose::CodeqlModelKind { endpoint, choice },
format!("Kind of {}", model.describe()),
String::from("remote, command-injection, sql-injection, taint, value, \u{2026}"),
)
.with_value(model.which.default_kind()),
);
}
/// Save choice `choice` of endpoint `endpoint` with kind `kind` in the
/// database's model pack (#578).
fn save_codeql_model(&mut self, endpoint: usize, choice: usize, kind: &str) {
let kind = kind.trim();
if kind.is_empty() {
self.status = String::from("A model needs a kind");
return;
}
let Some(view) = self.codeql.model.as_mut() else {
return;
};
let Some(mut model) = view
.endpoints
.get(endpoint)
.and_then(|e| e.choices().into_iter().nth(choice))
else {
return;
};
model.kind = kind.to_string();
let label = view.endpoints[endpoint].label();
let described = model.describe();
view.models.retain(|m| *m != model);
view.models.push(model);
self.status = match self.write_codeql_models() {
Ok(file) => format!("Modeled {label} as a {described} in {}", file.display()),
Err(why) => format!("Could not save the model: {why}"),
};
}
/// Write the Model Editor's models to the database's model pack: its
/// pack file, the data extension CodeQL reads, and croft's own list.
/// Returns the data extension's path.
fn write_codeql_models(&mut self) -> Result<PathBuf, String> {
use crate::codeql_model as cm;
let view = self
.codeql
.model
.as_ref()
.ok_or("no model editor is open")?;
let (dir, name) = cm::model_pack(self.workspace_root(), &view.database, &view.language);
let io = |e: std::io::Error| format!("{}: {e}", dir.display());
std::fs::create_dir_all(dir.join("models")).map_err(io)?;
std::fs::write(
dir.join("codeql-pack.yml"),
cm::pack_yml(&name, &view.language),
)
.map_err(io)?;
let slug = dir
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
let file = dir.join("models").join(format!("{slug}.model.yml"));
std::fs::write(&file, cm::models_yml(&view.language, &view.models)).map_err(io)?;
let json = serde_json::to_string_pretty(&view.models).map_err(|e| e.to_string())?;
std::fs::write(dir.join("croft-models.json"), json).map_err(io)?;
Ok(file
.strip_prefix(self.workspace_root())
.unwrap_or(&file)
.to_path_buf())
}
/// List a finished endpoints read under Method Modeling (#578), or say
/// why there is none.
pub fn drain_codeql_model(&mut self) -> bool {
let Some((rx, ..)) = self.codeql_model_job.as_ref() else {
return false;
};
let outcome = match rx.try_recv() {
Ok(outcome) => outcome,
Err(std::sync::mpsc::TryRecvError::Empty) => return false,
Err(std::sync::mpsc::TryRecvError::Disconnected) => {
Err(String::from("the endpoints read stopped unexpectedly"))
}
};
let Some((_, database, language)) = self.codeql_model_job.take() else {
return false;
};
match outcome {
Ok(endpoints) => {
let modeled = endpoints.iter().filter(|e| e.supported).count();
self.status = format!(
"{} endpoints of {database}, {modeled} modeled by CodeQL",
endpoints.len()
);
// The models made before, kept beside the pack.
let (dir, _) =
crate::codeql_model::model_pack(self.workspace_root(), &database, &language);
let models = std::fs::read_to_string(dir.join("croft-models.json"))
.ok()
.and_then(|t| serde_json::from_str(&t).ok())
.unwrap_or_default();
self.codeql.model = Some(crate::codeql_model::ModelView {
database,
language,
endpoints,
models,
..Default::default()
});
self.codeql
.collapsed
.remove(&crate::widgets::codeql::Section::MethodModeling);
}
Err(why) => self.status = format!("Could not read the endpoints: {why}"),
}
true
}
/// CodeQL: View AST (#578): the AST of the open file, read from the
/// current database with its language's print-AST query, off the UI
/// thread; [`Self::drain_codeql_ast`] shows it in the AST Viewer.
fn view_codeql_ast(&mut self) {
use crate::codeql_ast as ast;
if self.codeql_ast_job.is_some() {
self.status = String::from("An AST is already being read");
return;
}
let Some((file, db, lang, archive)) = self.codeql_contextual_target() else {
return;
};
let dir = Self::codeql_contextual_dir("ast");
let program = self.codeql_program.clone();
let (tx, rx) = std::sync::mpsc::channel();
let (db_path, csv) = (db.path.clone(), ast::selected_file_csv(&archive));
let shown = archive.clone();
std::thread::spawn(move || {
let read = || -> Result<ast::AstTree, String> {
let io = |e: std::io::Error| format!("{}: {e}", dir.display());
std::fs::create_dir_all(&dir).map_err(io)?;
let query = Self::codeql_contextual_query(&program, &dir, &lang, "print-ast")?;
let selected = dir.join("selected-file.csv");
std::fs::write(&selected, csv).map_err(io)?;
let bqrs = dir.join("ast.bqrs");
Self::codeql_command(&program, &ast::run_args(&query, &db_path, &selected, &bqrs))?;
let json = dir.join("ast.json");
Self::codeql_command(&program, &ast::decode_args(&bqrs, &json))?;
let tree = ast::parse_graph(&std::fs::read_to_string(&json).map_err(io)?)?;
if tree.roots.is_empty() {
return Err(format!("the database has no AST for {shown}"));
}
Ok(tree)
};
let _ = tx.send(read());
});
let name = file
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
self.status = format!("Reading the AST of {name} from {}\u{2026}", db.name);
self.codeql_ast_job = Some((
rx,
ast::AstView {
file,
archive,
database: db.name,
..ast::AstView::default()
},
));
}
/// Show a finished AST read in the AST Viewer (#578), or say why there
/// is none.
pub fn drain_codeql_ast(&mut self) -> bool {
let Some((rx, _)) = self.codeql_ast_job.as_ref() else {
return false;
};
let outcome = match rx.try_recv() {
Ok(outcome) => outcome,
Err(std::sync::mpsc::TryRecvError::Empty) => return false,
Err(std::sync::mpsc::TryRecvError::Disconnected) => {
Err(String::from("the AST read stopped unexpectedly"))
}
};
let Some((_, mut view)) = self.codeql_ast_job.take() else {
return false;
};
match outcome {
Ok(tree) => {
let name = view
.file
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
self.status = format!("AST of {name}: {} nodes", tree.nodes.len());
view.tree = tree;
self.codeql.ast = Some(view);
self.codeql
.collapsed
.remove(&crate::widgets::codeql::Section::AstViewer);
}
Err(why) => self.status = format!("Could not read the AST: {why}"),
}
true
}
/// Run `codeql` with `args` and wait. A failure is the reason and the
/// fix the CLI printed on stderr ([`crate::codeql_query::failure_reason`]).
fn codeql_command(program: &Path, args: &[String]) -> Result<(), String> {
let out =
crate::review_ops::output_retrying_busy(std::process::Command::new(program).args(args))
.map_err(|e| format!("could not run codeql: {e}"))?;
if out.status.success() {
return Ok(());
}
Err(crate::codeql_query::failure_reason(
&String::from_utf8_lossy(&out.stderr),
))
}
/// Collect a finished query run (#578): record how it went in the
/// history, open its results when it succeeded, and start a pack run's
/// next query.
pub fn drain_codeql_run(&mut self) -> bool {
use crate::codeql_query::RunStatus;
let Some((rx, since)) = self.codeql_run.as_ref() else {
return false;
};
let status = match rx.try_recv() {
Ok(s) => s,
Err(std::sync::mpsc::TryRecvError::Empty) => return false,
Err(std::sync::mpsc::TryRecvError::Disconnected) => {
RunStatus::Failed(String::from("the query run stopped unexpectedly"))
}
};
let seconds = since.elapsed().as_secs();
self.codeql_run = None;
let failed = matches!(status, RunStatus::Failed(_));
self.record_codeql_run(status, seconds);
if self.codeql_batch.0 > 0 {
self.codeql_batch.1 += usize::from(failed);
self.start_next_queued_codeql();
}
true
}
/// Write a finished run's outcome into its history entry and open its
/// results when it succeeded.
fn record_codeql_run(&mut self, status: crate::codeql_query::RunStatus, seconds: u64) {
use crate::codeql_query::{History, RunStatus};
let mut history = History::load(&Self::codeql_history_path());
// The newest run still marked running is this one; a sorted history
// need not have it on top, and it may have been removed meanwhile.
let Some(entry) = history
.entries
.iter_mut()
.filter(|e| e.status == RunStatus::Running)
.max_by_key(|e| e.started)
else {
return;
};
entry.status = status.clone();
entry.seconds = seconds;
entry.results = (status == RunStatus::Succeeded)
.then(|| crate::codeql_query::count_results(&entry.output))
.flatten();
let output = entry.output.clone();
// A published pack's run names the pack by its reference.
let name = match entry.query.is_relative() {
true => entry.query.display().to_string(),
false => entry
.query
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default(),
};
let _ = history.save(&Self::codeql_history_path());
self.refresh_codeql_history();
match status {
RunStatus::Failed(why) => self.status = format!("{name} failed: {why}"),
RunStatus::Cancelled => self.status = format!("{name} cancelled"),
_ => match self.editor.open(&output) {
Ok(()) => {
self.sync_open_file_poll_mtime();
self.status = format!("{name} finished in {seconds}s");
let sets = crate::codeql_query::result_set_files(&output).len();
if sets > 1 && output.extension().is_some_and(|e| e == "csv") {
self.status.push_str(&format!(
"; {sets} result sets, see CodeQL: Show Result Set"
));
}
}
Err(e) => self.status = format!("{}: {e}", output.display()),
},
}
}
/// Run every query in pack `pack` on the current database, one after
/// another (#578): the first starts now and [`Self::drain_codeql_run`]
/// starts each next one as the one before finishes, failed or not.
/// Each run keeps its own history entry. Refused while a query is
/// running, so two pack runs never interleave.
fn run_codeql_pack(&mut self, pack: usize) {
if self.codeql_run.is_some() {
self.status = String::from("A CodeQL query is already running");
return;
}
let Some(queries) = self.codeql.queries.get(pack).map(|p| p.queries.clone()) else {
return;
};
self.run_codeql_batch(queries, "That pack has no queries");
}
/// Run `queries` one after another on the current database, through
/// the queue a pack run uses; `none` is what to say when there are none.
fn run_codeql_batch(&mut self, queries: Vec<PathBuf>, none: &str) {
if self.codeql_run.is_some() {
self.status = String::from("A CodeQL query is already running");
return;
}
let store = crate::codeql_db::DatabaseStore::load(&Self::codeql_db_store_path());
if store.current.and_then(|i| store.databases.get(i)).is_none() {
self.status = String::from("Add a CodeQL database and select it first");
return;
}
if queries.is_empty() {
self.status = none.to_string();
return;
}
self.codeql_batch = (queries.len(), 0);
self.codeql_run_queue = queries
.into_iter()
.map(|query| crate::codeql_query::QueuedRun {
query,
source: None,
database: None,
})
.collect();
self.start_next_queued_codeql();
}
/// CodeQL: Run Query on Multiple Databases (#578): check databases in
/// a list, then run the open query on each of them in turn.
fn run_codeql_query_on_databases(&mut self) {
let query = match self.editor.path.clone() {
Some(p) if p.extension().is_some_and(|e| e == "ql") => p,
_ => {
self.status = String::from("Open a .ql query to run it");
return;
}
};
let store = crate::codeql_db::DatabaseStore::load(&Self::codeql_db_store_path());
let checked: Vec<PathBuf> = store
.current
.and_then(|i| store.databases.get(i))
.map(|db| db.path.clone())
.into_iter()
.collect();
self.codeql_multi_db = Some((query, self.editor.lines.join("\n"), checked));
self.open_codeql_multi_db_picker(0);
}
/// The checklist of databases for "Run Query on Multiple Databases",
/// with row `selected` under the cursor: Enter on a database checks or
/// unchecks it, Enter on the first row runs.
fn open_codeql_multi_db_picker(&mut self, selected: usize) {
use crate::widgets::list_picker::{ListPicker, ListPurpose, ListRow};
let Some((query, _, checked)) = self.codeql_multi_db.as_ref() else {
return;
};
let store = crate::codeql_db::DatabaseStore::load(&Self::codeql_db_store_path());
if store.databases.is_empty() {
self.codeql_multi_db = None;
self.status = String::from("Add a CodeQL database first");
return;
}
let name = query
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
let mut rows = vec![ListRow {
id: String::from("run"),
label: match checked.len() {
1 => String::from("\u{25b6} Run on the checked database"),
n => format!("\u{25b6} Run on the {n} checked databases"),
},
}];
rows.extend(store.databases.iter().enumerate().map(|(i, db)| ListRow {
id: i.to_string(),
label: format!(
"{} {}{}",
if checked.contains(&db.path) { "[x]" } else { "[ ]" },
db.name,
db.language.as_deref().map(|l| format!(" ({l})")).unwrap_or_default()
),
}));
let mut picker = ListPicker::new(
ListPurpose::CodeqlMultiDb,
format!("Run {name} on databases"),
rows,
);
picker.selected = selected.min(picker.rows.len() - 1);
self.open_list_picker(picker, "");
}
/// A row picked in the databases checklist (#578): toggle a database,
/// or queue the query on every checked one.
fn choose_codeql_multi_db(&mut self, id: &str, selected: usize) {
let Some((_, _, checked)) = self.codeql_multi_db.as_mut() else {
return;
};
if id != "run" {
let store = crate::codeql_db::DatabaseStore::load(&Self::codeql_db_store_path());
if let Some(db) = id
.parse::<usize>()
.ok()
.and_then(|i| store.databases.get(i))
{
match checked.iter().position(|p| *p == db.path) {
Some(at) => {
checked.remove(at);
}
None => checked.push(db.path.clone()),
}
}
self.open_codeql_multi_db_picker(selected);
return;
}
if checked.is_empty() {
self.status = String::from("Check at least one database to run on");
self.open_codeql_multi_db_picker(selected);
return;
}
let Some((query, source, checked)) = self.codeql_multi_db.take() else {
return;
};
if self.codeql_run.is_some() {
self.status = String::from("A CodeQL query is already running");
return;
}
// In the list's order, not the order they were checked in.
let store = crate::codeql_db::DatabaseStore::load(&Self::codeql_db_store_path());
let databases: Vec<PathBuf> = store
.databases
.iter()
.map(|db| db.path.clone())
.filter(|p| checked.contains(p))
.collect();
self.codeql_batch = (databases.len(), 0);
self.codeql_run_queue = databases
.into_iter()
.map(|database| crate::codeql_query::QueuedRun {
query: query.clone(),
source: Some(source.clone()),
database: Some(database),
})
.collect();
self.start_next_queued_codeql();
}
/// CodeQL: Run All Queries in Workspace (#578): every query the side
/// bar's Queries section lists, pack after pack.
fn run_all_codeql_queries(&mut self) {
self.refresh_codeql_queries();
let queries: Vec<PathBuf> = self
.codeql
.queries
.iter()
.flat_map(|p| p.queries.iter().cloned())
.collect();
self.run_codeql_batch(queries, "No CodeQL queries in the workspace");
}
/// CodeQL: Run Queries in Selected Files (#578): the `.ql` files
/// selected in the Explorer, and every query under a selected folder.
fn run_selected_codeql_queries(&mut self) {
let mut paths: Vec<PathBuf> = self.tree.marked.iter().cloned().collect();
if paths.is_empty()
&& let Some(p) = self.tree.selected_path()
{
paths.push(p.to_path_buf());
}
let queries = crate::codeql_query::queries_in(&paths);
self.run_codeql_batch(
queries,
"Select .ql files, or folders holding them, in the Explorer first",
);
}
/// Start the pack run's next query, read from disk as the side-bar rows
/// are; one that cannot be read counts as failed and the next is tried.
/// With the queue empty, the pack run is over and the status line sums
/// it up.
fn start_next_queued_codeql(&mut self) {
let (total, _) = self.codeql_batch;
while self.codeql_run.is_none() {
let Some(next) = self.codeql_run_queue.pop_front() else {
let failed = self.codeql_batch.1;
self.codeql_batch = (0, 0);
let queries = if total == 1 { "query" } else { "queries" };
self.status = match failed {
0 => format!("Ran {total} CodeQL {queries}"),
n => format!("Ran {total} CodeQL {queries}, {n} failed"),
};
return;
};
let n = total - self.codeql_run_queue.len();
let path = next.query;
let source = match next.source {
Some(source) => source,
None => match std::fs::read_to_string(&path) {
Ok(source) => source,
Err(e) => {
self.codeql_batch.1 += 1;
self.status = format!("{}: {e}", path.display());
continue;
}
},
};
if let Some(database) = next.database {
self.run_codeql_file_on(path, &source, CodeqlRunMode::Whole, Some(&database));
if self.codeql_run.is_none() {
// That database went away meanwhile: the others may
// still be there.
self.codeql_batch.1 += 1;
continue;
}
} else {
self.run_codeql_file(path, &source);
}
if self.codeql_run.is_none() {
// Refused (the database went away meanwhile): the rest
// would be refused too.
self.codeql_run_queue.clear();
self.codeql_batch = (0, 0);
return;
}
if let Some(rest) = self.status.strip_prefix("Running ") {
self.status = format!("Running CodeQL queries {n}/{total}: {rest}");
}
}
}
/// Drop the pack run's queries still waiting (#578); the one running
/// finishes and is recorded as usual.
fn cancel_codeql_queue(&mut self) {
let left = self.codeql_run_queue.len();
self.codeql_run_queue.clear();
self.codeql_batch = (0, 0);
self.status = match left {
0 => String::from("No CodeQL queries are queued"),
1 => String::from("Cancelled 1 queued CodeQL query"),
n => format!("Cancelled {n} queued CodeQL queries"),
};
}
/// Mirror the saved database list into the side bar.
fn refresh_codeql_databases(&mut self) {
let store = crate::codeql_db::DatabaseStore::load(&Self::codeql_db_store_path());
// The card shows each folder's size: summed once per database on a
// worker as the list loads or changes, never while painting or on
// the key that opened the list. Known sizes stay until it reports.
self.codeql
.db_sizes
.retain(|path, _| store.databases.iter().any(|db| &db.path == path));
for db in &store.databases {
if self.codeql.db_sizes.contains_key(&db.path)
|| !self.codeql_size_pending.insert(db.path.clone())
{
continue;
}
let tx = self.codeql_size_tx.clone();
let path = db.path.clone();
std::thread::spawn(move || {
let size = crate::codeql_db::folder_size(&path);
let _ = tx.send((path, size));
});
}
self.codeql.databases = store.databases;
self.codeql.current_db = store.current;
self.codeql.db_sort = store.sort_by;
}
/// A path as typed: `~` expanded, relative to the workspace root.
fn typed_path(&self, value: &str) -> PathBuf {
let v = value.trim();
let p = match v.strip_prefix("~/") {
Some(rest) => std::env::var_os("HOME")
.map(PathBuf::from)
.unwrap_or_default()
.join(rest),
None => PathBuf::from(v),
};
if p.is_absolute() {
p
} else {
self.workspace_root().join(p)
}
}
/// Add a CodeQL database from `value` (#578): a folder, an archive, a
/// URL to a zip, or `owner/repo [language]` on GitHub.
pub fn submit_codeql_database(
&mut self,
source: crate::widgets::input_prompt::CodeqlDbSource,
value: &str,
) {
use crate::widgets::input_prompt::CodeqlDbSource;
if source == CodeqlDbSource::Folder {
let dir = self.typed_path(value);
match crate::codeql_db::find_database_in(&dir) {
Some(found) => self.register_codeql_database(&found),
None => {
self.status = format!(
"{} is not a CodeQL database (no codeql-database.yml)",
dir.display()
);
}
}
return;
}
// Downloads and extraction run on a worker (#1155): a database is
// commonly hundreds of megabytes, and inline the whole UI froze until
// it was on disk.
if let Some((what, _)) = &self.codeql_db_job {
self.status = format!("Still adding the CodeQL database {what}");
return;
}
let cache = Self::codeql_db_cache_dir();
let (what, job): (String, Box<dyn FnOnce() -> Result<PathBuf, String> + Send>) =
match source {
CodeqlDbSource::Archive => {
let zip = self.typed_path(value);
let stem = zip
.file_stem()
.map(|s| s.to_string_lossy().into_owned())
.unwrap_or_else(|| String::from("database"));
(
zip.display().to_string(),
Box::new(move || Self::extract_codeql_zip(&cache, &zip, &stem)),
)
}
CodeqlDbSource::Url => {
let url = value.trim().to_string();
(
url.clone(),
Box::new(move || Self::download_codeql_zip_from_url(&cache, &url)),
)
}
CodeqlDbSource::Github => {
let repo = value.trim().to_string();
let gh = self.gh_program.clone();
(
repo.clone(),
Box::new(move || Self::download_codeql_db_from_github(&gh, &cache, &repo)),
)
}
CodeqlDbSource::Folder => unreachable!("added above"),
};
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let _ = tx.send(job());
});
self.status = format!("Adding the CodeQL database {what}\u{2026}");
self.codeql_db_job = Some((what, rx));
}
/// Register a database that finished downloading or extracting (#1155).
pub fn drain_codeql_db_job(&mut self) -> bool {
let Some((what, rx)) = self.codeql_db_job.as_ref() else {
return false;
};
let outcome = match rx.try_recv() {
Ok(outcome) => outcome,
Err(std::sync::mpsc::TryRecvError::Empty) => return false,
Err(std::sync::mpsc::TryRecvError::Disconnected) => Err(format!(
"Adding the CodeQL database {what} stopped unexpectedly"
)),
};
self.codeql_db_job = None;
match outcome {
Ok(dir) => self.register_codeql_database(&dir),
Err(why) => self.status = why,
}
true
}
/// Add a database folder to the saved list and make it current.
fn register_codeql_database(&mut self, dir: &std::path::Path) {
let path = Self::codeql_db_store_path();
let mut store = crate::codeql_db::DatabaseStore::load(&path);
match store.add(dir) {
Ok(i) => {
if let Err(e) = store.save(&path) {
self.status = format!("Could not save the database list: {e}");
return;
}
let db = &store.databases[i];
self.status = format!(
"Added CodeQL database {}{}",
db.name,
db.language
.as_deref()
.map(|l| format!(" ({l})"))
.unwrap_or_default()
);
self.refresh_codeql_databases();
}
Err(why) => self.status = why,
}
}
/// Unpack `zip` into `cache/<name>`. Runs on the add-database worker.
fn extract_codeql_zip(
cache: &std::path::Path,
zip: &std::path::Path,
name: &str,
) -> Result<PathBuf, String> {
let dest = cache.join(name);
crate::codeql_db::extract_zip(zip, &dest, None)?;
crate::codeql_db::find_database_in(&dest)
.ok_or_else(|| format!("{} holds no CodeQL database", zip.display()))
}
fn download_codeql_zip_from_url(cache: &std::path::Path, url: &str) -> Result<PathBuf, String> {
if !url.starts_with("https://") {
return Err(String::from("A database URL must be https://"));
}
let resp = ureq::get(url)
.timeout(std::time::Duration::from_secs(300))
.call()
.map_err(|e| format!("Download failed: {e}"))?;
let name = url
.rsplit('/')
.next()
.unwrap_or("database")
.trim_end_matches(".zip")
.to_string();
let tmp = cache.join(format!("{name}.download.zip"));
std::fs::create_dir_all(cache).map_err(|e| e.to_string())?;
let mut f = std::fs::File::create(&tmp).map_err(|e| e.to_string())?;
std::io::copy(&mut resp.into_reader(), &mut f).map_err(|e| e.to_string())?;
let out = Self::extract_codeql_zip(cache, &tmp, &name);
let _ = std::fs::remove_file(&tmp);
out
}
/// `owner/repo` or `owner/repo language`. With no language, the one
/// database GitHub has is used; several need the language named.
fn download_codeql_db_from_github(
gh: &std::path::Path,
cache: &std::path::Path,
value: &str,
) -> Result<PathBuf, String> {
let mut parts = value.split_whitespace();
let repo = parts
.next()
.map(|r| {
r.trim_start_matches("https://github.com/")
.trim_end_matches('/')
})
.filter(|r| r.split('/').count() == 2)
.ok_or_else(|| {
String::from("Give the repository as owner/repo (and optionally a language)")
})?
.to_string();
let language = match parts.next() {
Some(l) => l.to_string(),
None => {
let mut cmd = std::process::Command::new(gh);
cmd.args([
"api",
&format!("/repos/{repo}/code-scanning/codeql/databases"),
"--jq",
".[].language",
]);
let out = crate::review_ops::output_retrying_busy(&mut cmd)
.map_err(|e| format!("could not run gh: {e}"))?;
if !out.status.success() {
return Err(format!(
"{repo} has no CodeQL databases on GitHub: {}",
String::from_utf8_lossy(&out.stderr).trim()
));
}
let langs: Vec<String> = String::from_utf8_lossy(&out.stdout)
.lines()
.map(str::to_string)
.collect();
match langs.as_slice() {
[one] => one.clone(),
[] => return Err(format!("{repo} has no CodeQL databases on GitHub")),
many => {
return Err(format!(
"{repo} has databases for {}; add one with '{repo} <language>'",
many.join(", ")
));
}
}
}
};
// Streamed straight to disk: a database can be larger than the
// memory croft should hold at once.
let name = format!("{}-{language}", repo.replace('/', "-"));
let tmp = cache.join(format!("{name}.download.zip"));
std::fs::create_dir_all(cache).map_err(|e| e.to_string())?;
let file = std::fs::File::create(&tmp).map_err(|e| e.to_string())?;
let mut cmd = std::process::Command::new(gh);
cmd.args(crate::codeql_db::github_database_args(&repo, &language))
.stdin(std::process::Stdio::null())
.stdout(file)
.stderr(std::process::Stdio::piped());
let out = crate::review_ops::spawn_retrying_busy(&mut cmd)
.and_then(std::process::Child::wait_with_output)
.map_err(|e| format!("could not run gh: {e}"))?;
if !out.status.success() {
let _ = std::fs::remove_file(&tmp);
return Err(format!(
"Download failed: {}",
String::from_utf8_lossy(&out.stderr).trim()
));
}
let result = Self::extract_codeql_zip(cache, &tmp, &name);
let _ = std::fs::remove_file(&tmp);
result
}
/// Enable or disable an extension by id, persist the choice, and keep the
/// UI consistent with it: a disabled CodeQL takes its activity-bar icon
/// and its open side bar with it.
fn set_extension_enabled(&mut self, id: &str, enabled: bool) {
if enabled {
self.disabled_extensions.remove(id);
} else {
self.disabled_extensions.insert(id.to_string());
}
let _ =
crate::prefs::save_disabled_extensions_in(&self.config_dir, &self.disabled_extensions);
// Turning an extension off forgets its tools' fingerprints, so
// turning it back on re-approves a tool whose definition changed.
if !enabled {
let ids = crate::mcp::registry::command_ids_of_in_dir(&self.config_dir, id);
let _ = crate::prefs::forget_mcp_tool_fingerprints_in(&self.config_dir, &ids);
}
self.refresh_extensions();
if id == "codeql" {
if !enabled && self.sidebar_view == SidebarView::CodeQL {
self.set_sidebar_view(SidebarView::Explorer);
}
// The icon appears or disappears, so the baked bar redraws.
self.overlays.activity.mark_dirty();
}
}
/// 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_compound
.clone()
.or_else(|| 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.debug_sessions.is_empty() {
return false;
}
let mut changed_background = false;
// EVERY session is polled, not just the focused one (#310). `poll` is
// the protocol state machine, not a passive read: it is where
// `initialized` triggers the breakpoint push and `configurationDone`,
// and where js-debug's reverse requests are answered. An unpolled
// member never leaves the gate - its debuggee never runs, its
// breakpoints never bind, and a js-debug parent blocks forever on a
// reverse request nobody answered. It would be started, named in the
// status, and dead.
//
// Only the FOCUSED session's events drive the UI. A background
// member's output still reaches the console, tagged with its name,
// and everything else it reports is queued on it and replayed when it
// is focused (#567): dropping its `stopped` left a breakpoint hit that
// nothing showed, so the member looked hung.
const BACKLOG_CAP: usize = 256;
let focused = self.debug_sessions.focused_index();
// A session focused since the last poll first replays what it did
// while in the background.
let mut events = self.debug_sessions.take_focused_backlog();
let mut background_ended: Vec<usize> = Vec::new();
let mut background_output: Vec<String> = Vec::new();
// By index, not name: a compound can list one configuration twice,
// so two members can share a name.
let mut background_stopped: Option<usize> = None;
for (index, named) in self.debug_sessions.iter_named_mut_indexed() {
let drained = named.session.poll();
if index == focused {
events.extend(drained);
continue;
}
changed_background |= !drained.is_empty();
for ev in drained {
match ev {
// `exited` and `terminated` both end a member and often
// arrive together: name it once, or the removal below
// takes a live sibling for the second copy.
DapEvent::Terminated => {
if background_ended.last() != Some(&index) {
background_ended.push(index);
}
}
DapEvent::Output { category, text }
if crate::dap::session::output_is_user_visible(&category) =>
{
background_output.extend(
text.split('\n')
.filter(|l| !l.is_empty())
.map(|l| format!("[{}] {l}", named.name)),
);
}
DapEvent::Output { .. } => {}
other => {
if matches!(other, DapEvent::Stopped { .. }) {
background_stopped.get_or_insert(index);
}
named.backlog.push(other);
if named.backlog.len() > BACKLOG_CAP {
let overflow = named.backlog.len() - BACKLOG_CAP;
named.backlog.drain(..overflow);
}
}
}
}
}
for line in background_output {
self.debug_console_push(line);
}
// Highest index first, so removing one does not move the next.
let mut ended_names = Vec::new();
// Where the stopped member sits once the ended ones are gone: gone
// itself if it also ended, else shifted down past every removal below.
let background_stopped =
background_stopped.and_then(|i| index_after_removals(i, &background_ended));
for index in background_ended.into_iter().rev() {
if let Some(mut gone) = self.debug_sessions.remove(index) {
gone.session.disconnect();
ended_names.push(gone.name);
}
}
// `stopAll: true` (#567): a background member ending takes the set
// down with it, the same as the focused one ending does below.
if self.debug_stop_all && !ended_names.is_empty() && !self.debug_sessions.is_empty() {
self.debug_stop();
self.status = format!(
"{} ended — stopAll stopped the rest of the compound",
ended_names.join(", ")
);
self.run_post_debug_tasks();
return true;
}
if !ended_names.is_empty() && !self.debug_sessions.is_empty() {
self.report_member_ended(&ended_names.join(", "));
}
// A background member stopped (a breakpoint, an exception, a pause).
// If the member being looked at is still running, show the stopped
// one, as VS Code does; otherwise say so rather than steal the view
// from a stop the user is already inspecting.
if let Some(index) = background_stopped
&& let Some(name) = self.debug_sessions.names().get(index).cloned()
{
let focused_is_stopped = self
.debug_sessions
.focused()
.is_some_and(|s| s.phase == SessionPhase::Stopped)
|| events.iter().any(|e| matches!(e, DapEvent::Stopped { .. }));
// A focused member that ended this tick is torn down below, and
// the teardown reads the FOCUSED member: moving the view first
// would carry the ending into its backlog and leave it running.
let focused_ended = self
.debug_sessions
.focused()
.is_some_and(|s| s.phase == SessionPhase::Terminated)
|| events.iter().any(|e| matches!(e, DapEvent::Terminated));
if focused_is_stopped || focused_ended {
self.status =
format!("{name} stopped in the background · Cmd+Opt+Shift+G switches to it");
} else {
self.refocus_debug_session(index, &mut events);
self.status = format!("{name} stopped · now showing it");
}
}
let mut changed = !events.is_empty() || changed_background;
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;
}
// What the exception stop threw (#864): the panel's pill and
// the status line, which has the width the pill lacks.
DapEvent::ExceptionInfo { summary } => {
self.run_debug.feedback = Some(format!("Paused (exception): {summary}"));
self.status = format!("Paused on exception: {summary}");
}
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
.debug_sessions
.focused()
.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.debug_sessions.focused().map(|s| s.phase);
match phase {
Some(SessionPhase::Stopped) => {
self.debug_ever_stopped = true;
let loc = self
.debug_sessions
.focused()
.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.
// The session that ENDED, not the whole set (#310). Dropping
// the set reaches its siblings as a SIGKILL through the
// transport's drop - exactly the kill this handshake exists to
// avoid - and would make every compound behave as
// `stopAll: true`, which is neither VS Code's default nor what
// the file asked for.
let ended = self.debug_sessions.focused_index();
let ended_name = self
.debug_sessions
.focused_name()
.unwrap_or("the session")
.to_string();
// The adapter refused to start the program (#264): its reason
// is the message, not "Debug session ended".
let launch_error = self
.debug_sessions
.focused()
.and_then(|s| s.launch_error.clone());
if let Some(mut gone) = self.debug_sessions.remove(ended) {
gone.session.disconnect();
}
// `stopAll: true` (#567): the siblings go too, and the rest
// of this arm reports the ended run as for a lone session.
let stopped_all = self.debug_stop_all && !self.debug_sessions.is_empty();
if stopped_all {
self.debug_stop();
self.status =
format!("{ended_name} ended — stopAll stopped the rest of the compound");
}
if !self.debug_sessions.is_empty() {
// Siblings are still running, so the debugger is not torn
// down: the view moves to one of them.
self.report_member_ended(&ended_name);
return true;
}
// 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();
match launch_error {
Some(reason) => {
let msg = format!("Could not start debugging: {reason}");
self.status = msg.clone();
self.run_debug.feedback = Some(msg);
self.run_debug.feedback_is_error = true;
}
None => {
let msg =
debug_end_message(had_breakpoints, self.debug_ever_stopped).to_string();
// The status bar still read "Debugging x — F5
// continue · F10 step over" after the end (#867).
// stopAll's own explanation above is left standing,
// and a postDebugTask below may report over this.
if !stopped_all {
self.status = msg.clone();
}
self.run_debug.feedback = Some(msg);
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;
self.run_post_debug_tasks();
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.debug_sessions.focused() 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,
breakpoint_section_rows(self.breakpoint_items().len()),
);
}
let mut rows = Vec::new();
rows.push(DebugRow {
indent: 0,
kind: DebugRowKind::Header {
title: String::from("CALL STACK"),
},
});
// With more than one thread (goroutines, under delve), each gets a
// row and the selected one's frames sit under it, as in VS Code
// (#264). A single thread keeps the plain frame list.
let threaded = session.threads.len() > 1;
let mut frames_at = rows.len();
if threaded {
for (id, name) in &session.threads {
let selected = session.stopped_thread == Some(*id);
rows.push(DebugRow {
indent: 1,
kind: DebugRowKind::Thread {
id: *id,
name: name.clone(),
selected,
},
});
if selected {
frames_at = rows.len();
}
}
}
let mut frame_rows = Vec::new();
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();
frame_rows.push(DebugRow {
indent: if threaded { 2 } else { 1 },
kind: DebugRowKind::Frame {
id: f.id,
selected: Some(f.id) == session.selected_frame,
name: f.name.clone(),
location: format!("{loc}:{}", f.line),
},
});
}
rows.splice(frames_at..frames_at, frame_rows);
rows.push(DebugRow {
indent: 0,
kind: DebugRowKind::Header {
title: String::from("VARIABLES"),
},
});
for (index, scope) in session.scopes.iter().enumerate() {
let open = session.scope_open(index);
rows.push(DebugRow {
indent: 1,
kind: DebugRowKind::Scope {
name: scope.name.clone(),
index,
open: scope.expensive.then_some(open),
},
});
if !open {
continue;
}
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,
});
// Last, so `sync_breakpoint_list` can swap it without a rebuild.
rows.extend(breakpoint_section_rows(self.breakpoint_items().len()));
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
.debug_sessions
.focused_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
.debug_sessions
.focused_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. The line is mirrored to OUTPUT's
/// "Debug Console" channel (#867), where it reads at full width and can
/// be searched and copied; that channel keeps its own cap.
fn debug_console_push(&mut self, line: String) {
const CAP: usize = 1000;
crate::output::push(
crate::output::CHANNEL_DEBUG_CONSOLE,
crate::output::OutputLevel::Info,
&line,
);
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.debug_sessions.focused_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.debug_sessions.focused()?;
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::Thread { id, .. } => {
if let Some(session) = self.debug_sessions.focused_mut() {
session.select_thread(id);
}
self.debug_expanded.clear();
}
DebugRowKind::Frame { id, .. } => {
if let Some(session) = self.debug_sessions.focused_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.debug_sessions.focused_mut() {
session.expand_variable(reference);
}
}
}
DebugRowKind::WatchAdd => {
self.open_add_watch_prompt();
}
// An expensive scope opens (and is fetched) on click (#1421).
DebugRowKind::Scope {
index,
open: Some(_),
..
} => {
if let Some(session) = self.debug_sessions.focused_mut() {
session.toggle_expensive_scope(index);
}
}
_ => {}
}
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;
}
/// Run `launch` with every unsaved editor written first (#1400), as VS
/// Code's `debug.saveBeforeStart` does: the debuggee reads its files
/// from disk, while breakpoints and the stop arrow follow the buffer,
/// so launching over unsaved edits pauses on the wrong lines.
///
/// The tabs are written as typed, through the auto-save sweep: a
/// format-on-save reply lands later and could move lines the launch
/// already sent breakpoints for. The sweep never overwrites a file that
/// changed on disk (or writes a lossy encoding, a hex or sheet edit, an
/// unresolved merge); whatever is still unsaved after it, or everything
/// with `disable_save_before_debug`, is named in front of the launch's
/// own status.
fn launch_with_unsaved_saved(&mut self, launch: impl FnOnce(&mut Self)) {
self.run_with_unsaved_saved("the launch", launch);
}
/// [`Self::launch_with_unsaved_saved`] for anything that runs the
/// project's files: a task, a Testing run (#1639). VS Code saves before
/// a task by default (`task.saveBeforeRun`); without it a build or test
/// run reported on code the editor had already changed. `what` names
/// the run in the warning.
fn run_with_unsaved_saved(&mut self, what: &str, launch: impl FnOnce(&mut Self)) {
if self.save_before_debug && self.unsaved_count() > 0 {
self.sweep_dirty_buffers(false, false);
}
let unsaved = self.unsaved_editor_names();
launch(self);
if unsaved.is_empty() {
return;
}
let (names, verb) = match unsaved.as_slice() {
[one] => (one.clone(), "has"),
[first, second] => (format!("{first} and {second}"), "have"),
[first, rest @ ..] => (format!("{first} and {} more", rest.len()), "have"),
[] => unreachable!("checked above"),
};
let warning = format!("{names} {verb} unsaved changes: {what} uses the file on disk");
let running = std::mem::take(&mut self.status);
self.status = if running.is_empty() {
warning
} else {
format!("{warning} - {running}")
};
// The run registered its "Running …" status for its outcome to
// replace; that status now carries the warning, so the tracked text
// follows it, or the outcome would never land.
let tracked = self
.test_run_status
.iter_mut()
.chain(self.pane_run_statuses.iter_mut().map(|(_, run)| run));
for run in tracked {
if run.shown == running {
run.shown = self.status.clone();
}
}
}
/// [`Self::run_with_unsaved_saved`] for a Testing run: the saves it
/// makes are for this run, so a watched scope does not also hear
/// about them and rerun after it.
fn test_run_with_unsaved_saved(&mut self, launch: impl FnOnce(&mut Self)) {
let due = self.testing.watch.due_at();
self.run_with_unsaved_saved("the test run", |app| {
app.testing.watch.set_due_at(due);
launch(app);
});
}
/// File names of the editors with unsaved edits, deduped, the active
/// tab first: what [`Self::launch_with_unsaved_saved`] warns about.
fn unsaved_editor_names(&self) -> Vec<String> {
let mut seen: Vec<&std::path::Path> = Vec::new();
let mut names = Vec::new();
let groups = std::iter::once(&self.editor).chain(self.editor_layout.inactive_groups());
let active = self.editor.editors.get(self.editor.active_index());
let tabs = active
.into_iter()
.chain(groups.flat_map(|g| g.editors.iter()));
for ed in tabs.filter(|e| e.dirty) {
let Some(path) = ed.path.as_deref() else {
continue;
};
if seen.contains(&path) {
continue;
}
seen.push(path);
names.push(
path.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| path.display().to_string()),
);
}
names
}
/// 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.debug_sessions.focused_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) {
self.launch_with_unsaved_saved(Self::start_selected_debug_now);
}
fn start_selected_debug_now(&mut self) {
if let Some(name) = self.selected_debug_compound.clone() {
let root = self.active_workspace_root();
self.debug_compounds = crate::dap::configs::discover_compounds(&root);
if let Some(compound) = self
.debug_compounds
.iter()
.find(|c| c.name == name)
.cloned()
{
self.launch_compound(&compound);
return;
}
self.selected_debug_compound = None;
self.run_debug.selected_config = None;
self.status =
format!("Debug compound \"{name}\" no longer exists — debugging the active file");
self.start_debug_session();
return;
}
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();
}
/// Launch a launch.json compound: resolve its members against the
/// un-deduped config list, refuse what croft cannot honour, then start
/// one or several sessions. Shared by the picker and by F5/restart once
/// the compound is the selected target (#567).
fn launch_compound(&mut self, compound: &crate::dap::configs::Compound) {
// 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());
let folders = self.workspace_folders();
// #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, &folders) {
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.
// Asked of BOTH arities (#310). It sat on the
// one-member arm because the other refused anyway;
// now that both launch, a malformed key would be
// refused at one member and ignored at two - the
// "silently debug something other than what was
// asked for" outcome this guard exists to prevent.
Ok(members) if !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"
};
// Name EVERY member, not `members[0]`. The
// guard now covers both arities, and telling
// the user of a three-member compound to run
// the first one directly is advice to launch
// a SUBSET - the precise outcome this arm
// refuses to produce itself.
let all = members
.iter()
.map(|m| format!("\"{}\"", m.name))
.collect::<Vec<_>>()
.join(", ");
let run_them = if members.len() > 1 {
format!("or run {all} directly, in that order")
} else {
format!("or run {all} directly")
};
self.debug_error(format!(
"compound \"{}\" sets {}, which croft cannot read — fix {} to launch {} through the compound, {}",
compound.name, keys, plural, all, run_them
));
}
Ok(members) if members.len() == 1 => {
let cfg = members[0].clone();
// One member has no siblings to stop, so its `stopAll` is set
// false rather than inherited from whatever ran before.
self.debug_stop_all = false;
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(members) => {
// Several sessions at once: what #310 built
// the set for. Members start in DECLARATION
// order, which is the order the file asked
// for and the order a client-then-server
// compound depends on.
let label = compound.name.clone();
match compound.pre_launch_task.clone() {
Some(task) => self.launch_after_compound_task_all(
&task,
members,
label,
compound.stop_all,
),
None => self.launch_compound_members(members, label, compound.stop_all),
}
}
}
}
/// Debug: Add Configuration… (#250): the native form for a launch.json
/// entry, one step at a time, written to `.croft/launch.json` at the end.
/// Starts with the adapter.
pub fn open_add_debug_config(&mut self) {
use crate::widgets::list_picker::{ListPicker, ListPurpose, ListRow};
self.debug_config_draft = None;
let rows = crate::dap::configs::DRAFT_TYPES
.iter()
.map(|(id, label)| ListRow {
id: (*id).to_string(),
label: (*label).to_string(),
})
.collect();
self.open_list_picker(
ListPicker::new(
ListPurpose::DebugConfigType,
"Add Configuration: Debugger",
rows,
),
"",
);
}
/// Ask for `field` of the draft, seeded with `retry` (a value just
/// refused) or the field's default; `None` means the draft is complete,
/// so write it.
fn prompt_debug_config_field(
&mut self,
field: Option<crate::dap::configs::DraftField>,
retry: Option<&str>,
) {
use crate::widgets::input_prompt::{InputPrompt, InputPurpose};
let Some(draft) = self.debug_config_draft.as_ref() else {
return;
};
let Some(field) = field else {
self.finish_debug_config_draft();
return;
};
let (title, hint, seed) = draft.prompt(field);
let mut prompt = InputPrompt::new(InputPurpose::DebugConfigField { field }, title, hint)
.with_value(retry.map_or(seed, str::to_string));
if crate::dap::configs::ConfigDraft::optional(field) {
prompt = prompt.allowing_blank();
}
self.open_input_prompt(prompt);
}
/// Take a field's value: on to the next field, or back to this one with
/// the reason when it does not fit.
fn submit_debug_config_field(&mut self, field: crate::dap::configs::DraftField, value: &str) {
let Some(draft) = self.debug_config_draft.as_mut() else {
return;
};
match draft.set(field, value) {
Ok(()) => {
let next = draft.next_field(Some(field));
self.prompt_debug_config_field(next, None);
}
Err(why) => {
self.status = why;
self.prompt_debug_config_field(Some(field), Some(value));
}
}
}
/// Write the finished draft to `.croft/launch.json` and pick up the file
/// again, so the new configuration is in the picker and F5 at once.
fn finish_debug_config_draft(&mut self) {
let Some(draft) = self.debug_config_draft.take() else {
return;
};
let root = self.active_workspace_root();
match crate::dap::configs::add_to_croft_launch_json(&root, &draft) {
Ok(_) => {
self.debug_configs = crate::dap::configs::discover_configs(&root);
self.selected_debug_config = Some(draft.name.clone());
self.selected_debug_compound = None;
self.run_debug.selected_config = Some(draft.name.clone());
self.status = format!(
"Added \"{}\" to .croft/launch.json and selected it; F5 starts it",
draft.name
);
}
Err(why) => self.status = why,
}
}
/// 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),
);
rows.push(ListRow {
id: String::from("add"),
label: String::from("Add Configuration…"),
});
self.open_list_picker(
ListPicker::new(ListPurpose::DebugConfig, "Debug Configuration", rows),
"No debug configurations (.croft/launch.json or .vscode/launch.json)",
);
}
/// Launch one member INTO the running set, leaving its siblings alone.
///
/// `launch_debug_config` opens by stopping whatever is running, which is
/// right for a configuration the user picked and fatal for a compound's
/// second member. This is the same path with that first step removed and
/// the session added rather than substituted.
///
/// A member with its own `preLaunchTask` is NOT parked here: parking is a
/// one-at-a-time mechanism, and a compound whose members each park would
/// interleave unpredictably. Its task is skipped with a status saying so,
/// which is honest, and #310 is where the general form belongs.
fn launch_member_into_set(&mut self, cfg: &crate::dap::configs::DebugConfig) -> MemberOutcome {
// A member from another workspace folder resolves there (#1425).
let root = cfg
.root
.clone()
.unwrap_or_else(|| self.active_workspace_root());
let ctx = crate::dap::configs::SubstCtx {
workspace_folder: root,
file: self.editor.path.clone(),
folders: self.workspace_folders(),
};
let rc = match crate::dap::configs::resolve(cfg, &ctx) {
Ok(rc) => rc,
Err(e) => {
self.debug_error(format!("config \"{}\": {e}", cfg.name));
return MemberOutcome::Failed;
}
};
self.record_post_debug_task(&rc);
if rc.pre_launch_task.is_some() {
// NOT launched. Running it anyway would debug whatever the last
// build left behind, which is exactly what the single-member path
// refuses to do for the same hazard - and a status message would
// not have helped, since the caller overwrites it before a frame
// is drawn. The caller collects the name and says so.
return MemberOutcome::TaskUnrun;
}
// Ask the SET whether a session appeared, rather than trusting the
// call to have made one: `launch_resolved_into_set` returns `()` on
// every validation, spawn and attach failure alike, so reporting
// `Launched` unconditionally counted members that never started and
// made "N of M started" name an N the user does not have.
let before = self.debug_sessions.len();
let building = self.pending_cargo_launches.len();
self.launch_resolved_into_set(rc);
if self.debug_sessions.len() > before {
MemberOutcome::Launched
} else if self.pending_cargo_launches.len() > building {
MemberOutcome::Building
} else {
MemberOutcome::Failed
}
}
/// Park a whole compound behind its own `preLaunchTask` (#310).
///
/// The single-member form parks one config; this parks the list, because
/// the members have to start together once the task exits 0. Running them
/// through the single-member path in turn would stop each previous one.
fn launch_after_compound_task_all(
&mut self,
task_label: &str,
members: Vec<crate::dap::configs::DebugConfig>,
compound: String,
stop_all: bool,
) {
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 = self
.task_command_line(&task)
.unwrap_or_else(|_| 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::Members(Box::new(CompoundLaunch {
members,
compound,
stop_all,
})),
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 — its sessions start when it exits 0"
);
}
/// Launch every member of a compound, in declaration order (#310).
///
/// The first member REPLACES whatever was running, matching what starting
/// any configuration has always done; the rest are pushed beside it. That
/// asymmetry is the point - `launch_debug_config` stops the world before
/// it starts, so calling it per member would leave only the last one
/// alive, which is the bug this path exists to avoid.
///
/// A member that fails to start does not abort the ones already running:
/// they are real processes, and killing them because a later sibling
/// could not resolve would be a second failure caused by the first. The
/// error names the member, and the survivors stay.
fn launch_compound_members(
&mut self,
members: Vec<crate::dap::configs::DebugConfig>,
compound: String,
stop_all: bool,
) {
self.debug_stop();
self.debug_post_tasks.clear();
// Set only here, once the old set is gone: a compound refused before
// this point leaves the running set untouched, and must leave its
// `stopAll` out of it too (#567).
self.debug_stop_all = stop_all;
// A launch supersedes any older one still parked behind its task:
// left in place, that task's exit would launch its config and stop
// this set (#567). The task-gated path reaches here via `take()`, so
// this only ever drops a STALE parking.
self.pending_debug_launch = None;
let total = members.len();
let mut started = 0usize;
let mut building: Vec<String> = Vec::new();
let mut unrun: Vec<String> = Vec::new();
for cfg in members {
match self.launch_member_into_set(&cfg) {
MemberOutcome::Launched => started += 1,
MemberOutcome::Building => building.push(cfg.name.clone()),
MemberOutcome::TaskUnrun => unrun.push(cfg.name.clone()),
MemberOutcome::Failed => {}
}
}
if started == 0 && !building.is_empty() {
// Every member that could start is still building with cargo
// (#1392): each joins the set when its build lands.
self.debug_compound = Some(compound.clone());
self.run_debug.feedback = Some(format!(
"compound {compound}: building {} \u{2014} sessions start when cargo finishes",
building.join(", ")
));
self.run_debug.feedback_is_error = building.len() != total;
self.status = format!(
"compound \"{compound}\": building {} \u{2014} sessions start when cargo finishes",
building.join(", ")
);
return;
}
if started == 0 {
// Nothing started. Each member has already said why, so this names
// the compound and, if that is the reason, the members croft
// declined to launch against a build it could not run.
let why = if unrun.is_empty() {
String::new()
} else {
format!(
" — {} declares a preLaunchTask croft cannot run as part of a set, and starting it anyway would debug the last build",
unrun.join(", ")
)
};
self.debug_error(format!("compound \"{compound}\" started no sessions{why}"));
return;
}
// The FIRST member takes focus, not the last: a compound is usually
// written server-first, and landing the user on whichever happened to
// start last would put them in the wrong one.
self.debug_sessions.focus(0);
self.debug_compound = Some(compound.clone());
// Reveal FIRST, then write the feedback: `reveal_debug_view` runs
// `refresh_run_debug`, which clears `feedback` unconditionally, so
// doing it afterwards wiped every line built below - including the
// only place a skipped member is ever named - before it was drawn.
//
// Once for the compound, not once per member: each member's launch
// reveals the view too, and doing it per member clears the console
// and re-focuses the pane for every one of them.
self.reveal_debug_view();
// Name them. With one session "the debugger" was unambiguous; with
// several the user has to be told which are running and which one the
// call stack and variables belong to, or the view describes a session
// they cannot identify.
let mut running = self.debug_sessions.names().join(", ");
if !building.is_empty() {
// Not failed: they join the set when their cargo builds land.
running = format!("{running}; building {}", building.join(", "));
}
let started = started + building.len();
self.run_debug.feedback = Some(if started == total {
format!("Debugging compound {compound}: {running}")
} else if unrun.is_empty() {
format!("Debugging compound {compound}: {running} ({started} of {total} started)")
} else {
// Named, not silent: the member is absent because croft would
// otherwise debug an unbuilt binary, and the user has to know
// which one to run themselves.
format!(
"Debugging compound {compound}: {running} ({started} of {total}; {} needs its preLaunchTask run first)",
unrun.join(", ")
)
});
self.run_debug.feedback_is_error = started != total;
let focused = self
.debug_sessions
.focused_name()
.unwrap_or("?")
.to_string();
self.status = format!(
"Debugging compound {compound} — {started} session(s), showing {focused} · Shift+F5 stops all"
);
}
/// 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),
// NOT back through the front door, unlike the single member above:
// `launch_debug_config` stops the world first, so the second
// member would kill the first (#310). The members' own
// `preLaunchTask`s are skipped, with a status saying so per
// member - parking is one-at-a-time and a set of parked members
// would interleave.
PendingLaunchStep::Members(launch) => {
self.launch_compound_members(launch.members, launch.compound, launch.stop_all)
}
}
}
/// 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.debug_sessions.is_empty() {
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 = self
.task_command_line(&task)
.unwrap_or_else(|_| 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.debug_sessions.is_empty() {
self.debug_stop();
}
self.pending_debug_launch = None;
self.pending_cargo_launches.clear();
// A new run: the previous run's cleanup is not this one's.
self.debug_post_tasks.clear();
// A compound member from another workspace folder resolves, and
// finds its preLaunchTask, there (#1425).
let root = cfg
.root
.clone()
.unwrap_or_else(|| self.active_workspace_root());
let ctx = configs::SubstCtx {
workspace_folder: root.clone(),
file: self.editor.path.clone(),
folders: self.workspace_folders(),
};
let rc = match configs::resolve(cfg, &ctx) {
Ok(rc) => rc,
Err(e) => {
self.debug_error(e);
return;
}
};
self.record_post_debug_task(&rc);
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 = self
.task_command_line_in(&task, root.clone())
.unwrap_or_else(|_| task.command.clone());
let Some(pane) = self.run_project_task_in(task, root) 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.
/// Launch a resolved config, replacing whatever was running.
fn launch_resolved_config(&mut self, rc: crate::dap::configs::ResolvedConfig) {
self.launch_resolved_in(rc, LaunchSlot::Replace);
}
/// Launch a resolved config BESIDE what is running, for a compound member.
fn launch_resolved_into_set(&mut self, rc: crate::dap::configs::ResolvedConfig) {
self.launch_resolved_in(rc, LaunchSlot::Add);
}
fn launch_resolved_in(
&mut self,
mut rc: crate::dap::configs::ResolvedConfig,
slot: LaunchSlot,
) {
use crate::dap::configs::{self, RequestKind};
use crate::dap::session::AdapterKind;
// The picker attaches by pid, which is lldb's attach; debugpy and
// js-debug attach by other means, and dropping the key silently would
// launch something the config did not ask for.
if rc.pick_process && rc.kind != AdapterKind::LldbDap {
self.debug_error(format!(
"config \"{}\": ${{command:pickProcess}} is supported for lldb attach only",
rc.name
));
return;
}
// `${command:pickProcess}`: ask first, then come back here with the
// pid filled in (#250). Asked before the adapter lookup so the choice
// does not depend on it; a missing lldb-dap is reported on resume.
if rc.pick_process && rc.process_id.is_none() {
self.open_attach_process_picker(rc, slot);
return;
}
// A CodeLLDB `cargo` launch names no program: cargo builds it first
// (#1392), off the UI thread, and the launch resumes here with it.
if rc.kind == AdapterKind::LldbDap
&& rc.request == RequestKind::Launch
&& rc.program.is_none()
&& let Some(spec) = configs::cargo_spec(&rc)
{
match spec {
Ok(spec) => self.start_cargo_program_build(rc, slot, spec),
Err(e) => self.debug_error(format!("config \"{}\": {e}", rc.name)),
}
return;
}
let breakpoints = self.collect_editor_breakpoints();
let cwd = rc
.cwd
.clone()
.unwrap_or_else(|| self.active_workspace_root());
let name = rc.name.clone();
// The debuggee interpreter's note (#864), for a Python launch.
let mut python_note = None;
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")];
let program_py =
config_project_python(&rc, &cwd, &self.active_workspace_root(), &py);
let request = configs::debugpy_request(&rc, &program_py);
// Whichever interpreter runs the program, the
// config's own included (#864).
if rc.request == RequestKind::Launch {
match launch_request_python(&request, &cwd)
.as_deref()
.map_or(Ok(None), debuggee_python_note)
{
Ok(note) => python_note = note,
Err(refusal) => {
self.debug_error(format!("config \"{name}\": {refusal}"));
return;
}
}
}
crate::dap::session::DapSession::launch_with(
&py.to_string_lossy(),
&adapter_args,
&cwd,
request,
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;
}
}
}
// By pid, by program name or through attachCommands
// (gdb-remote), sent as written (#1419).
RequestKind::Attach => {
if !configs::lldb_attach_has_target(&rc) {
self.debug_error(format!(
"config \"{name}\": an lldb attach needs a numeric \"processId\", a \"program\" or \"attachCommands\""
));
return;
}
}
}
crate::dap::session::DapSession::launch_with(
&adapter,
&[],
&cwd,
configs::lldb_request(&rc),
breakpoints,
)
}
AdapterKind::Delve => {
if rc.request == RequestKind::Launch && rc.program.is_none() {
self.debug_error(format!(
"config \"{name}\": a go launch needs a \"program\" (a package directory or file)"
));
return;
}
// "Connect to server" (#1418): a headless delve already
// serves DAP at host:port, so croft connects to it rather
// than starting a dlv of its own.
let remote = configs::delve_remote_address(&rc);
if rc.request == RequestKind::Attach && rc.process_id.is_none() && remote.is_none()
{
let remote_mode =
rc.extra.get("mode").and_then(serde_json::Value::as_str) == Some("remote");
self.debug_error(if remote_mode {
format!("config \"{name}\": a go remote attach needs a \"port\"")
} else {
format!(
"config \"{name}\": a go attach needs a \"processId\", or \"mode\": \"remote\" with a \"port\""
)
});
return;
}
if let Some((host, port)) = remote {
crate::dap::session::DapSession::attach_delve_server(
&host,
port,
configs::delve_request(&rc),
breakpoints,
)
.with_context(|| {
format!(
"nothing answered on {host}:{port}; start it first, e.g. `dlv debug <package> --headless --listen=:{port} --api-version=2 --accept-multiclient`"
)
})
} else {
match crate::dap::install::dlv_program() {
Ok(dlv) => crate::dap::session::DapSession::launch_delve(
&dlv,
&cwd,
configs::delve_request(&rc),
breakpoints,
),
Err(e) => {
self.debug_error(format!("{e}"));
return;
}
}
}
}
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(mut session) => {
// Held until `initialized`, then pushed with the rest (#611).
session.set_function_breakpoints(self.function_breakpoints.clone());
match slot {
LaunchSlot::Replace => self.debug_sessions.replace_with(&name, session),
LaunchSlot::Add => self.debug_sessions.push(&name, 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;
let lead = with_python_note(format!("{verb} {name}"), python_note.as_deref());
self.status = format!("{lead} — F5 continue · F10 step over · Shift+F5 stop");
self.reveal_debug_view();
if python_note.is_some() {
self.debug_console_push(lead);
}
// A cppdbg configuration runs under lldb-dap (#1394): say
// which of its gdb settings have no effect there. Here, not
// at the call site, so a preLaunchTask resume and a compound
// member say it too.
if !rc.ignored_keys.is_empty() {
self.debug_console_push(format!(
"config \"{name}\" runs under lldb-dap, which ignores its {}",
rc.ignored_keys.join(", ")
));
}
}
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;
// Same as every other launch path: a parked older launch must not
// fire later and replace this one (#567).
self.pending_debug_launch = None;
// Zero-config "Debug active file" declares no postDebugTask.
self.debug_post_tasks.clear();
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;
}
Some(AdapterKind::Delve) => {
self.start_delve_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 debug_root = self
.roots
.owning_root(&path)
.unwrap_or_else(|| self.roots.primary())
.to_path_buf();
// The debug venv hosts only the adapter; the program runs under
// the interpreter Run would use, so its packages import (#864).
// One debugpy cannot run under is refused before any setup.
let program_py = debuggee_python(
path.parent().unwrap_or(&debug_root),
&debug_root,
std::env::var_os("PATH").as_deref(),
);
let note = match program_py.as_deref().map_or(Ok(None), debuggee_python_note) {
Ok(note) => note,
Err(refusal) => {
self.debug_error(refusal);
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 program_py = program_py.unwrap_or_else(|| py.clone());
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();
match crate::dap::session::DapSession::launch(
&py_str,
&adapter_args,
&debug_root,
&path,
&program_py,
breakpoints,
false,
) {
Ok(session) => {
let name = path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
self.debug_sessions.replace_with(name.clone(), session);
self.run_debug.feedback = Some(format!("Debugging {name}"));
self.run_debug.feedback_is_error = false;
let lead = with_python_note(format!("Debugging {name}"), note.as_deref());
self.status = format!("{lead} — F5 continue · F10 step over · Shift+F5 stop");
self.reveal_debug_view();
// After the reveal, which clears the console; it outlasts
// the status line.
if note.is_some() {
self.debug_console_push(lead);
}
}
Err(e) => {
self.debug_error(format!("Failed to start debugger: {e}"));
}
}
}
/// Debug the Go file at `path` under delve (#264): its package's `main`,
/// or its tests for a `_test.go` file. delve builds the package itself.
fn start_delve_debug_session(&mut self, path: &Path) {
let dlv = match crate::dap::install::dlv_program() {
Ok(d) => d,
Err(e) => {
self.debug_error(format!("{e}"));
return;
}
};
let breakpoints = self.collect_editor_breakpoints();
let cwd = path
.parent()
.map(Path::to_path_buf)
.unwrap_or_else(|| self.roots.primary().to_path_buf());
let request = crate::dap::session::delve_zero_config_request(path);
match crate::dap::session::DapSession::launch_delve(&dlv, &cwd, request, breakpoints) {
Ok(session) => {
let name = path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
self.debug_sessions.replace_with(name.clone(), session);
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}"));
}
}
}
/// Debug one Go test under delve's `test` mode (#264), scoped to it
/// with `-test.run`. `name` is a tree id (`./pkg::TestName`), or a bare
/// function name from the caret, whose package is the open file's.
fn start_delve_test_session(
&mut self,
root: &Path,
name: &str,
breakpoints: std::collections::BTreeMap<
PathBuf,
Vec<crate::dap::session::SourceBreakpoint>,
>,
) {
let dir = match name.split_once("::") {
Some((pkg, _)) => crate::testing::gotest::package_dir(root, pkg),
None => self
.editor
.path
.as_deref()
.and_then(Path::parent)
.map(Path::to_path_buf),
};
let Some(dir) = dir else {
self.disarm_failure_breakpoint();
self.status = format!("Debug Test: no package directory for {name}");
return;
};
let dlv = match crate::dap::install::dlv_program() {
Ok(d) => d,
Err(e) => {
self.disarm_failure_breakpoint();
self.debug_error(format!("{e}"));
return;
}
};
let request = crate::dap::session::delve_test_request(
&dir,
&crate::testing::gotest::test_binary_args(name),
);
match crate::dap::session::DapSession::launch_delve(&dlv, &dir, request, breakpoints) {
Ok(session) => {
self.debug_sessions.replace_with(name.to_string(), 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}")),
}
}
/// 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) => {
let name = path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
self.debug_sessions.replace_with(name.clone(), session);
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) => {
let name = label_path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
self.debug_sessions.replace_with(name.clone(), session);
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();
// Every session, not the focused one (#310): breakpoints are
// global editor state, handed to every session at launch, so a
// breakpoint set mid-run in a shared file must bind in all of
// them or it binds in the server and not the client.
for session in self.debug_sessions.iter_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();
// Every session (#310); see `debug_toggle_breakpoint_line`.
for session in self.debug_sessions.iter_mut() {
session.update_breakpoints(&path, &specs);
}
}
/// A one-line prompt with no pre-fill, for the #611 breakpoint kinds.
fn open_debug_prompt(&mut self, label: String, buffer: String, kind: PromptKind) {
let target_dir = self.tree.root.clone();
self.prompt = Some(Prompt {
label,
buffer,
kind,
target_dir,
error: None,
});
}
/// Debug: Add Hit Count Breakpoint (#611), on the cursor line.
pub fn debug_edit_hit_condition(&mut self) {
let Some(path) = self.editor.path.clone() else {
self.status = String::from("Open a file to set a hit count breakpoint");
return;
};
let line = self.editor.cursor_row + 1;
let existing = self
.editor
.breakpoint_hit_conditions
.get(&path)
.and_then(|h| h.get(&line))
.cloned()
.unwrap_or_default();
self.open_debug_prompt(
format!("Pause after how many hits? · line {line}"),
existing,
PromptKind::HitCondition { path, line },
);
}
/// Commit the hit-count popup: ensure a breakpoint on the line, attach
/// the count (or clear it when blank), and push the file's set to every
/// session.
fn commit_hit_condition(&mut self, path: PathBuf, line: usize, hits: &str) {
self.editor
.breakpoints
.entry(path.clone())
.or_default()
.insert(line);
let hits = hits.trim();
if hits.is_empty() {
if let Some(h) = self.editor.breakpoint_hit_conditions.get_mut(&path) {
h.remove(&line);
}
self.status = format!("Plain breakpoint at line {line}");
} else {
self.editor
.breakpoint_hit_conditions
.entry(path.clone())
.or_default()
.insert(line, hits.to_string());
self.status = format!("Breakpoint at line {line} pauses on hit {hits}");
}
let specs = self
.editor
.breakpoints
.get(&path)
.map(|l| self.editor.source_breakpoints(&path, l))
.unwrap_or_default();
for session in self.debug_sessions.iter_mut() {
session.update_breakpoints(&path, &specs);
}
}
/// Debug: Add Function Breakpoint (#611).
pub fn debug_add_function_breakpoint(&mut self) {
self.open_debug_prompt(
String::from("Break on entry to function"),
String::new(),
PromptKind::FunctionBreakpoint,
);
}
fn commit_function_breakpoint(&mut self, name: String) {
if name.is_empty() || self.function_breakpoints.contains(&name) {
return;
}
self.function_breakpoints.push(name.clone());
self.push_function_breakpoints();
self.status = format!("Function breakpoint: {name}");
}
/// Debug: Remove All Function Breakpoints (#611).
pub fn debug_clear_function_breakpoints(&mut self) {
self.function_breakpoints.clear();
self.push_function_breakpoints();
self.status = String::from("Function breakpoints removed");
}
fn push_function_breakpoints(&mut self) {
let names = self.function_breakpoints.clone();
let mut refused = false;
for session in self.debug_sessions.iter_mut() {
if session.supports("supportsFunctionBreakpoints") {
session.set_function_breakpoints(names.clone());
} else {
refused = true;
}
}
if refused && !names.is_empty() {
self.status = String::from("This debugger does not support function breakpoints");
}
}
/// Debug: Run to Cursor (#611, Ctrl+F10): resume and pause once at the
/// caret line, without leaving a breakpoint behind.
pub fn debug_run_to_cursor(&mut self) {
let Some(path) = self.editor.path.clone() else {
return;
};
let line = self.editor.cursor_row as u32 + 1;
match self.debug_sessions.focused_mut() {
Some(session) if session.stopped_thread.is_some() => {
session.run_to_cursor(&path, line);
self.status = format!("Running to line {line}");
}
Some(_) => self.status = String::from("Run to Cursor needs the debugger paused"),
None => self.status = String::from("Run to Cursor: no debug session"),
}
}
/// Debug: Break When Value Changes (#611): prompt for a variable of the
/// paused frame.
pub fn debug_break_on_value_change(&mut self) {
match self.debug_sessions.focused() {
Some(s) if s.stopped_thread.is_none() => {
self.status = String::from("Break When Value Changes needs the debugger paused");
}
Some(s) if !s.supports("supportsDataBreakpoints") => {
self.status = String::from("This debugger does not support data breakpoints");
}
Some(_) => self.open_debug_prompt(
String::from("Break when this variable changes"),
String::new(),
PromptKind::DataBreakpoint,
),
None => self.status = String::from("Break When Value Changes: no debug session"),
}
}
fn commit_data_breakpoint(&mut self, name: &str) {
let Some(session) = self.debug_sessions.focused_mut() else {
return;
};
// The variable's container: the scope (or expanded variable) that
// lists it, which is what `dataBreakpointInfo` is asked against.
let container = session.scopes.iter().map(|s| s.variables_ref).find(|r| {
session
.variables
.get(r)
.is_some_and(|vs| vs.iter().any(|v| v.name == name))
});
match container {
Some(reference) => {
session.break_on_change(reference, name);
self.status = format!("Pausing when {name} changes");
}
None => self.status = format!("No variable named {name} in the paused frame"),
}
}
/// Debug: Remove All Data Breakpoints (#611).
pub fn debug_clear_data_breakpoints(&mut self) {
for session in self.debug_sessions.iter_mut() {
session.clear_data_breakpoints();
}
self.status = String::from("Data breakpoints removed");
}
/// 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();
// Every session (#310); see `debug_toggle_breakpoint_line`.
for session in self.debug_sessions.iter_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.debug_sessions.focused_mut() {
session.step(command);
self.editor.stop_line = None;
self.clear_inline_values();
}
}
/// Toggle "break on raised exceptions" for the active session, with the
/// filter id this adapter uses for it (#1426). `uncaught` stays on so
/// unhandled exceptions still pause. No-op without a session.
pub fn debug_toggle_raised_exceptions(&mut self) {
let Some(session) = self.debug_sessions.focused_mut() else {
self.status = String::from("Start debugging first to set exception breakpoints");
return;
};
let Some(on) = session.toggle_raised_exceptions() else {
self.status = String::from(
"This debugger has no filter for raised exceptions; exception breakpoints are unchanged",
);
return;
};
let uncaught = session.has_exception_filter("uncaught");
self.status = String::from(match (on, uncaught) {
(true, true) => "Breaking on raised exceptions (and uncaught)",
(true, false) => "Breaking on raised exceptions",
(false, true) => "Breaking on uncaught exceptions only",
(false, false) => "No longer breaking on raised exceptions",
});
}
/// F6: interrupt a running program so it stops at the current line.
pub fn debug_pause(&mut self) {
match self.debug_sessions.focused_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.debug_sessions.is_empty() {
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;
}
/// A compound member ended and siblings survive (#567): rebuild the
/// status and the panel line from the live set, naming what ended, which
/// session the view now shows, and every one still running. Without this
/// both kept naming the ended session.
fn report_member_ended(&mut self, ended: &str) {
let running = self.debug_sessions.names().join(", ");
let focused = self
.debug_sessions
.focused_name()
.unwrap_or("?")
.to_string();
let what = self
.debug_compound
.as_deref()
.map_or_else(String::new, |c| format!(" compound {c}"));
self.run_debug.feedback = Some(format!("Debugging{what}: {running} ({ended} ended)"));
self.run_debug.feedback_is_error = false;
self.status =
format!("{ended} ended — showing {focused}; running: {running} · Shift+F5 stops all");
}
/// Move the UI to the session at `index` (#567). `events` holds what the
/// previously focused session produced this tick: its output goes to the
/// console now, and the rest goes back on its own backlog so it replays
/// when that session is focused again, rather than being applied to the
/// wrong one. `events` is then the new session's queued backlog, so the
/// caller's event loop replays its stop as if it had been focused all
/// along.
fn refocus_debug_session(
&mut self,
index: usize,
events: &mut Vec<crate::dap::session::DapEvent>,
) {
use crate::dap::session::DapEvent;
let old = self.debug_sessions.focused_index();
if index == old || !self.debug_sessions.focus(index) {
return;
}
let mut keep = Vec::new();
for ev in events.drain(..) {
match ev {
DapEvent::Output { category, text }
if crate::dap::session::output_is_user_visible(&category) =>
{
for line in text.split('\n').filter(|l| !l.is_empty()) {
self.debug_console_push(line.to_string());
}
}
DapEvent::Output { .. } => {}
other => keep.push(other),
}
}
if let Some((_, named)) = self
.debug_sessions
.iter_named_mut_indexed()
.find(|(i, _)| *i == old)
{
keep.append(&mut named.backlog);
named.backlog = keep;
}
*events = self.debug_sessions.take_focused_backlog();
// The arrow belongs to the session that was focused; the phase pass
// after the event loop redraws it for the new one.
self.editor.stop_line = None;
}
/// Debug: Switch Session (#567): focus the next member of a compound, so
/// one stopped in the background can be inspected. Its queued events
/// replay on the next poll.
fn switch_debug_session(&mut self) {
if self.debug_sessions.len() < 2 {
self.status = String::from("Only one debug session is running");
return;
}
let next = (self.debug_sessions.focused_index() + 1) % self.debug_sessions.len();
let mut none = Vec::new();
self.refocus_debug_session(next, &mut none);
// Nothing drained this tick belongs to the old session here, so the
// new session's backlog goes back to wait for the next poll.
if let Some((_, named)) = self
.debug_sessions
.iter_named_mut_indexed()
.find(|(i, _)| *i == next)
{
none.append(&mut named.backlog);
named.backlog = none;
}
let name = self
.debug_sessions
.focused_name()
.unwrap_or("?")
.to_string();
let running = self.debug_sessions.names().join(", ");
self.status = format!("Debugging {name} · running: {running}");
self.refresh_debug_panel();
}
/// Every breakpoint for the BREAKPOINTS list (#250), by file then line,
/// with its condition or log message.
fn breakpoint_items(&self) -> Vec<crate::widgets::run_debug::BreakpointItem> {
let mut paths: Vec<&PathBuf> = self.editor.breakpoints.keys().collect();
paths.sort();
let mut items = Vec::new();
for path in paths {
let name = path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| path.display().to_string());
for &line in &self.editor.breakpoints[path] {
let condition = self
.editor
.breakpoint_conditions
.get(path)
.and_then(|m| m.get(&line));
let log = self
.editor
.breakpoint_logs
.get(path)
.and_then(|m| m.get(&line));
let detail = match (log, condition) {
(Some(msg), _) => Some(format!("log {msg}")),
(None, Some(cond)) => Some(format!("if {cond}")),
(None, None) => None,
};
items.push(crate::widgets::run_debug::BreakpointItem {
path: path.clone(),
line,
label: format!("{name}:{line}"),
detail,
});
}
}
items
}
/// Bring the panel's BREAKPOINTS list up to date, and the tree's section
/// with it while a session is shown. A no-op when nothing changed.
fn sync_breakpoint_list(&mut self) {
use crate::widgets::run_debug::DebugRowKind;
let items = self.breakpoint_items();
if items == self.run_debug.breakpoints {
return;
}
let n = items.len();
self.run_debug.breakpoints = items;
if self.run_debug.debug_active {
let rows = &mut self.run_debug.debug_rows;
if let Some(pos) = rows.iter().position(
|r| matches!(&r.kind, DebugRowKind::Header { title } if title == "BREAKPOINTS"),
) {
rows.truncate(pos);
}
rows.extend(breakpoint_section_rows(n));
}
}
/// A click in the BREAKPOINTS list: jump to the breakpoint, or remove it
/// when the click landed on its `✕`.
fn breakpoint_list_click(&mut self, index: usize, remove: bool) {
let Some(bp) = self.run_debug.breakpoints.get(index).cloned() else {
return;
};
if remove {
self.remove_breakpoint_at(&bp.path, bp.line);
} else if let Err(e) = self.open_at(&bp.path, bp.line.saturating_sub(1), 0) {
self.status = format!("Could not open {}: {e}", bp.path.display());
}
self.sync_breakpoint_list();
}
/// Remove the breakpoint at `path:line` (1-based) with its condition or
/// log message, and push the file's breakpoints to every live session so
/// it stops binding mid-run too, as F9 does.
fn remove_breakpoint_at(&mut self, path: &Path, line: usize) {
if let Some(lines) = self.editor.breakpoints.get_mut(path) {
lines.remove(&line);
if lines.is_empty() {
self.editor.breakpoints.remove(path);
}
}
if let Some(m) = self.editor.breakpoint_conditions.get_mut(path) {
m.remove(&line);
}
if let Some(m) = self.editor.breakpoint_logs.get_mut(path) {
m.remove(&line);
}
let specs = self
.editor
.breakpoints
.get(path)
.map(|lines| self.editor.source_breakpoints(path, lines))
.unwrap_or_default();
let owned = path.to_path_buf();
for session in self.debug_sessions.iter_mut() {
session.update_breakpoints(&owned, &specs);
}
self.status = format!(
"Breakpoint removed from {}:{line}",
path.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default()
);
}
/// Open the process picker for a `${command:pickProcess}` attach (#250),
/// parking the resolved config until a process is chosen.
fn open_attach_process_picker(
&mut self,
rc: crate::dap::configs::ResolvedConfig,
slot: LaunchSlot,
) {
use crate::widgets::list_picker::{ListPicker, ListPurpose, ListRow};
let processes = list_user_processes();
if processes.is_empty() {
self.debug_error(format!(
"config \"{}\": no processes found to attach to",
rc.name
));
return;
}
let rows = processes
.into_iter()
.map(|(pid, comm)| ListRow {
id: pid.to_string(),
label: format!("{pid:>7} {comm}"),
})
.collect();
let title = format!("Attach \"{}\" to process", rc.name);
self.pending_attach = Some((rc, slot));
self.list_picker = Some(ListPicker::new(ListPurpose::AttachProcess, title, rows));
}
/// The parked attach with its `processId` set to the chosen `pid`, taken
/// out so a second confirm cannot launch it twice.
fn take_pending_attach(
&mut self,
pid: i64,
) -> Option<(crate::dap::configs::ResolvedConfig, LaunchSlot)> {
let (mut rc, slot) = self.pending_attach.take()?;
rc.process_id = Some(pid);
Some((rc, slot))
}
/// Remember a launched configuration's `postDebugTask` for the end of
/// this run (#250). A compound's members may name the same one; it runs
/// once.
fn record_post_debug_task(&mut self, rc: &crate::dap::configs::ResolvedConfig) {
if let Some(task) = &rc.post_debug_task
&& !self.debug_post_tasks.contains(task)
{
self.debug_post_tasks.push(task.clone());
}
}
/// Run the finished run's `postDebugTask`s, each once, in launch order.
/// A label no tasks.json declares is reported rather than skipped, the
/// same contract `preLaunchTask` has.
fn run_post_debug_tasks(&mut self) {
let labels = std::mem::take(&mut self.debug_post_tasks);
if labels.is_empty() {
return;
}
let tasks = crate::tasks::discover_tasks(&self.active_workspace_root());
for label in labels {
match tasks.iter().find(|t| t.label == label) {
Some(task) => {
self.run_project_task(task.clone());
}
None => {
self.status = format!(
"postDebugTask \"{label}\" not found — Tasks: Run Task lists what the workspace declares"
);
}
}
}
}
/// Shift+F5 and Debug: Stop Debugging. The user ending the run is when a
/// `postDebugTask` runs (#250); the internal `debug_stop` a relaunch uses
/// to replace the set is not, so it lives here rather than in there.
fn debug_stop_by_user(&mut self) {
let was_running = !self.debug_sessions.is_empty();
self.debug_stop();
if was_running {
self.run_post_debug_tasks();
} else {
self.debug_post_tasks.clear();
}
}
/// Shift+F5: stop debugging and tear the session down.
pub fn debug_stop(&mut self) {
// EVERY session, not the focused one (#310). A compound launches
// several; disconnecting only the one the user happens to be looking
// at would leave its siblings running with nothing on screen owning
// them, which is the orphaning the issue names.
for session in self.debug_sessions.iter_mut() {
session.disconnect();
}
self.debug_sessions.clear();
// A `cargo` build still running for a launch (#1392) must not start
// its debuggee after the user stopped debugging.
self.pending_cargo_launches.clear();
self.debug_compound = 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) {
if self.editor.path.is_none() {
self.run_debug.feedback = Some(String::from("Open a file first"));
self.run_debug.feedback_is_error = true;
return;
}
self.launch_with_unsaved_saved(Self::run_active_file_now);
}
fn run_active_file_now(&mut self) {
let Some(path) = self.editor.path.clone() else {
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
}
}
}
}
// A submodule has no HEAD blob to diff against (`git show
// HEAD:lib` is "bad object"): show what moved in it, read-only,
// the way a commit's patch opens (#1235).
ChangeKind::Modified | ChangeKind::StagedModified
if crate::git::is_submodule(&scm_root, &entry.path) =>
{
match crate::git::submodule_diff(&scm_root, &entry.path) {
Ok(text) => {
let label = format!("{} (submodule)", entry.path);
match self.editor.open_text_buffer(Path::new(&label), &text) {
Ok(()) => {
self.status = format!("Submodule {}", entry.path);
true
}
Err(e) => {
self.status = format!("Open failed: {e}");
false
}
}
}
Err(e) => {
self.status = format!("git diff on submodule failed: {e}");
false
}
}
}
ChangeKind::Modified | ChangeKind::StagedModified => {
// Both sides decoded the way the file's open tab decodes it,
// so a windows-1252 or UTF-16 file diffs too (#1242).
let enc = self.open_tab_encoding(&abs);
let texts =
crate::git::read_bytes_at_head(&scm_root, &entry.path).and_then(|head| {
let working = std::fs::read(&abs).map_err(|e| e.to_string())?;
let decode = |b: &[u8]| crate::widgets::editor::decode_blob(b, enc);
decode(&head)
.zip(decode(&working))
.ok_or_else(|| format!("{} is not {}", entry.path, enc.name()))
});
match texts {
Ok((head_text, working_text)) => {
let label = std::path::PathBuf::from(format!("{} (HEAD)", entry.path));
// The working side is the open tab's unsaved text
// when it has edits, in any split group.
let unsaved = self.unsaved_text_in_any_group(&abs);
match self.editor.open_head_diff_with_texts(
label,
&head_text,
unsaved.as_deref().unwrap_or(&working_text),
&abs,
true,
unsaved.is_some(),
) {
Ok(()) => {
self.tag_open_diff(
crate::widgets::diff::DiffSource::HeadVsWorking {
root: scm_root.to_path_buf(),
rel: entry.path.clone(),
},
);
if let Some(diff) = self.editor.diff.as_mut() {
diff.text_encoding = enc;
}
true
}
Err(e) => {
self.status = format!("Diff failed: {e}");
false
}
}
}
Err(e) => {
let why = self.git_error_line("show HEAD", &e);
self.status = format!("git show HEAD failed: {why}");
// 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) => {
let why = self.git_error_line("show HEAD", &e);
self.status = format!("git show HEAD failed: {why}");
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 <file>` and `croft <root> --open-file <path>` (the new
/// window spawned by Move / Copy into New Window opens the handed-off file
/// this way). Best-effort: an unreadable file, or a missing one whose
/// folder is missing too, leaves the editor on the welcome screen.
/// A relative `path` is taken under the workspace root, so the tab gets
/// the absolute path its language server is keyed by; a file that can't
/// be opened says why instead of opening nothing (#1193). Returns whether
/// it opened.
pub fn open_file_at_launch(&mut self, path: &Path) -> bool {
let path = self.workspace_root().join(path);
// `croft new.md` for a file not written yet opens an empty buffer
// that the first save creates (#1157).
let new = std::fs::symlink_metadata(&path).is_err();
match self.editor.open_new_pinned(&path) {
Ok(_) => {
if new {
self.status =
format!("New file {}: saving creates it", self.status_path(&path));
}
// 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();
true
}
Err(e) => {
self.status = format!("Couldn't open {}: {e}", path.display());
false
}
}
}
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();
let why = self.git_error_line("init", &err);
self.status = format!("git init failed: {why}");
}
Err(e) => {
self.status = format!("git init failed: {e}");
}
}
}
pub fn stage_selected_source_control_entries(&mut self) {
if self.repo_git_busy() {
return;
}
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) => {
let why = self.git_error_line("add", &err);
self.status = format!("Stage failed: {why}");
self.source_control.commit_feedback = Some(why);
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) {
let root = self.scm_root();
self.spawn_git_net("push", move || {
let r = crate::git::push_or_publish(&root);
Box::new(move |app: &mut App| app.finish_push(r))
});
}
/// Report a finished push on one line (#858): git's ref update, or its
/// error, from [`crate::git::summary_line`]; the Git Output log keeps the
/// `remote:` chatter and the rest.
fn finish_push(&mut self, result: Result<String, String>) {
self.log_git("push", &result);
let result = result
.map(|out| crate::git::summary_line(&out))
.map_err(|err| crate::git::error_line(&err));
match result {
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 = if summary.is_empty() {
String::from("Pushed")
} else {
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) {
let root = self.scm_root();
self.spawn_git_net("pull", move || {
let r = crate::git::pull_current_branch(&root);
Box::new(move |app: &mut App| app.finish_pull(r))
});
}
/// Report a finished pull. One that stopped on conflicts names them, and
/// a failure names git's `error:` or `fatal:` line, on one line (#858);
/// the Git Output log keeps git's whole text.
fn finish_pull(&mut self, result: Result<String, String>) {
self.log_git("pull", &result);
match result {
Ok(summary) => {
// git's result ("Fast-forward", "Already up to date."), not
// the `From <url>` / `Updating a..b` lines before it (#858).
let summary = crate::git::result_line(&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 = if summary.is_empty() {
String::from("Pulled")
} else {
format!("Pulled: {summary}")
};
}
Err(err) => {
self.source_control.commit_feedback = Some(crate::git::failure_line("pull", &err));
self.source_control.commit_feedback_is_error = true;
self.status = crate::git::failure_line("Pull", &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. A
/// branch with no upstream has nothing to pull, so it is published.
pub fn sync_source_control(&mut self) {
let root = self.scm_root();
self.spawn_git_net("sync", move || {
let pull = match crate::git::unpublished_branch(&root) {
Some(_) => Ok(String::from("nothing, branch not published yet")),
None => crate::git::pull_current_branch(&root),
};
// Never push on top of a failed pull.
let push = pull.is_ok().then(|| crate::git::push_or_publish(&root));
Box::new(move |app: &mut App| app.finish_sync(pull, push))
});
}
/// Report a finished Sync on one line (#858): what the pull did and the
/// push's ref update ("Synced: pulled: Fast-forward | pushed: a..b main
/// -> main"), or why either half failed; the Git Output log keeps both
/// of git's texts.
fn finish_sync(&mut self, pull: Result<String, String>, push: Option<Result<String, String>>) {
self.log_git("pull", &pull);
let pull_summary = match pull {
Ok(s) => crate::git::result_line(&s),
Err(err) => {
// One line (#858): the conflicts the pull stopped on, or
// git's error line; the Git Output log has the rest.
let why = crate::git::error_line(&err);
self.source_control.commit_feedback = Some(format!("sync: pull failed: {why}"));
self.source_control.commit_feedback_is_error = true;
self.status = format!("Sync failed on pull: {why}");
self.active_git_bypass_debounce();
self.refresh_git_status_debounced();
self.refresh_source_control();
return;
}
};
let push = push.unwrap_or_else(|| Err(String::from("push did not run")));
self.log_git("push", &push);
match push {
Ok(push_summary) => {
let push_summary = crate::git::summary_line(&push_summary);
let combined = [("pulled", pull_summary), ("pushed", push_summary)]
.into_iter()
.filter(|(_, summary)| !summary.is_empty())
.map(|(half, summary)| format!("{half}: {summary}"))
.collect::<Vec<_>>()
.join(" | ");
let (feedback, status) = if combined.is_empty() {
(String::from("synced"), String::from("Synced"))
} else {
(format!("synced: {combined}"), format!("Synced: {combined}"))
};
self.source_control.commit_feedback = Some(feedback);
self.source_control.commit_feedback_is_error = false;
self.status = status;
}
Err(err) => {
let why = crate::git::error_line(&err);
self.source_control.commit_feedback = Some(format!("pull ok; push failed: {why}"));
self.source_control.commit_feedback_is_error = true;
self.status = format!("Sync: pull ok; push failed: {why}");
}
}
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. Reported on one line (#858); the Git Output
/// log keeps git's text.
pub fn stash_source_control(&mut self) {
if self.hold_for_unsaved(ScmWrite::Stash) {
return;
}
self.ask_stash_message(crate::git::StashKind::Tracked);
}
/// Ask what to call the stash before making it (#1581), as VS Code's
/// Git: Stash does, seeded with the commit box's first line. Without a
/// name every stash on a commit read `WIP on <branch>: <commit>`, and
/// the Apply / Pop / Drop pickers chose between identical rows.
fn ask_stash_message(&mut self, kind: crate::git::StashKind) {
use crate::widgets::input_prompt::{InputPrompt, InputPurpose};
let title = match kind {
crate::git::StashKind::Tracked => "Stash",
crate::git::StashKind::IncludeUntracked => "Stash (Include Untracked)",
crate::git::StashKind::Staged => "Stash Staged",
};
let seed = self
.source_control
.message
.lines()
.next()
.unwrap_or_default()
.trim()
.to_string();
self.open_input_prompt(
InputPrompt::new(
InputPurpose::StashMessage { kind },
title,
"Message (optional)",
)
.allowing_blank()
.with_hint("Enter names the stash \u{b7} left blank, git names it WIP on <branch>")
.with_value(seed),
);
}
/// Make the stash the prompt asked about, named `message` when given.
fn perform_stash(&mut self, kind: crate::git::StashKind, message: Option<&str>) {
match kind {
crate::git::StashKind::Tracked => self.stash_tracked(message),
crate::git::StashKind::IncludeUntracked => {
let r = crate::git::stash_push_untracked(&self.scm_root(), message);
self.run_scm_op(
"stash push -u",
r,
"Stashed (incl. untracked)",
"Stash (incl. untracked)",
);
}
crate::git::StashKind::Staged => {
let r = crate::git::stash_push_staged(&self.scm_root(), message);
self.run_scm_op("stash push --staged", r, "Stashed staged", "Stash staged");
}
}
}
fn stash_tracked(&mut self, message: Option<&str>) {
let stashed = crate::git::stash_push(&self.scm_root(), message);
self.log_git("stash push", &stashed);
match stashed {
Ok(summary) => {
let summary = crate::git::result_line(&summary);
let (feedback, status) = if summary.is_empty() {
(String::from("stashed"), String::from("Stashed"))
} else {
(format!("stashed: {summary}"), format!("Stashed: {summary}"))
};
self.source_control.commit_feedback = Some(feedback);
self.source_control.commit_feedback_is_error = false;
self.status = status;
}
Err(err) => {
self.source_control.commit_feedback = Some(crate::git::failure_line("stash", &err));
self.source_control.commit_feedback_is_error = true;
self.status = crate::git::failure_line("Stash", &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 that stops on
/// conflicts names them on one line (#858), so the user can resolve
/// them; the Git Output log keeps git's whole text.
pub fn stash_pop_source_control(&mut self) {
let popped = crate::git::stash_pop(&self.scm_root());
self.log_git("stash pop", &popped);
match popped {
Ok(summary) => {
// The stash it dropped, not the `git status` dump before it.
let summary = crate::git::result_line(&summary);
let (feedback, status) = if summary.is_empty() {
(String::from("popped"), String::from("Stash popped"))
} else {
(
format!("popped: {summary}"),
format!("Stash popped: {summary}"),
)
};
self.source_control.commit_feedback = Some(feedback);
self.source_control.commit_feedback_is_error = false;
self.status = status;
}
Err(err) => {
self.source_control.commit_feedback =
Some(crate::git::failure_line("stash pop", &err));
self.source_control.commit_feedback_is_error = true;
self.status = crate::git::failure_line("Stash pop", &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) {
if self.repo_git_busy() {
return;
}
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) => {
let why = self.git_error_line("reset -q HEAD --", &err);
self.status = format!("Unstage failed: {why}");
self.source_control.commit_feedback = Some(why);
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);
}
}
/// Git's error `err` on the one line the status bar and the Source
/// Control panel show ([`crate::git::error_line`]), its whole text sent
/// to the Git Output log under `label` (#858).
fn git_error_line(&mut self, label: &str, err: &str) -> String {
self.log_git(label, &Err(err.to_string()));
crate::git::error_line(err)
}
/// The repository's operation in progress (#1356), read fresh, or
/// `None` with a status saying there is none.
fn git_operation_or_say(&mut self) -> Option<crate::git::RepoOp> {
let op = crate::git::repo_operation(&self.scm_root());
if op.is_none() {
self.status =
String::from("No merge, rebase, cherry-pick, revert or bisect in progress");
}
op
}
/// Abort the merge, rebase, cherry-pick or revert in progress, or reset
/// a bisect (#1356; VS Code's Abort Merge / Abort Rebase).
fn abort_git_operation(&mut self) {
if self.repo_git_busy() {
return;
}
let Some(op) = self.git_operation_or_say() else {
return;
};
let r = crate::git::abort_operation(&self.scm_root(), op);
let done = match op {
crate::git::RepoOp::Bisect => String::from("Bisect reset"),
_ => format!("Aborted the {}", op.command()),
};
self.run_scm_op(op.command(), r, &done, &format!("Git {}", op.command()));
}
/// Continue the rebase, cherry-pick or revert in progress once its
/// conflicts are resolved and staged (#1356; VS Code's Continue Rebase).
fn continue_git_operation(&mut self) {
if self.repo_git_busy() {
return;
}
let Some(op) = self.git_operation_or_say() else {
return;
};
let r = crate::git::continue_operation(&self.scm_root(), op);
self.report_git_operation_step(op, r, "Continued");
}
/// Skip the commit the rebase, cherry-pick or revert stopped on
/// (#1356).
fn skip_git_operation(&mut self) {
if self.repo_git_busy() {
return;
}
let Some(op) = self.git_operation_or_say() else {
return;
};
let r = crate::git::skip_operation(&self.scm_root(), op);
self.report_git_operation_step(op, r, "Skipped a commit of");
}
/// Mark the commit a bisect is on good or bad (#1356).
fn bisect_mark_source_control(&mut self, good: bool) {
if self.repo_git_busy() {
return;
}
let r = crate::git::bisect_mark(&self.scm_root(), good);
self.run_scm_op(
"bisect",
r,
if good { "Marked good" } else { "Marked bad" },
"Bisect",
);
}
/// Report a Continue or Skip, saying where the operation stands now:
/// finished, or stopped again (the next conflict, with its step).
fn report_git_operation_step(
&mut self,
op: crate::git::RepoOp,
r: Result<String, String>,
verb: &str,
) {
let now = crate::git::repo_operation(&self.scm_root());
let done = match now {
None => format!("{verb} the {}, which is done", op.command()),
Some(next) => format!("{verb} the {}, now {}", op.command(), next.label()),
};
self.run_scm_op(op.command(), r, &done, &format!("Git {}", op.command()));
}
/// After a commit made from Source Control mid-rebase (#1356, the #989
/// path): carry on with the rebase, as VS Code's Commit button does
/// there, instead of leaving HEAD detached with the rest unapplied.
fn continue_rebase_after_commit(&mut self) -> bool {
let root = self.scm_root();
let Some(op @ crate::git::RepoOp::Rebase { .. }) = crate::git::repo_operation(&root) else {
return true;
};
let r = crate::git::continue_operation(&root, op);
let continued = r.is_ok();
self.report_git_operation_step(op, r, "Committed and continued");
continued
}
/// 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.
/// `ok_prefix` heads a success ("Merged: …"); `noun` names the operation
/// when it fails ("Merge failed: …", "Merge: 1 conflict (pricing.py)"),
/// on one line from [`crate::git::failure_line`] (#858).
fn run_scm_op(
&mut self,
label: &str,
outcome: Result<String, String>,
ok_prefix: &str,
noun: &str,
) {
self.log_git(label, &outcome);
match outcome {
Ok(summary) => {
// git's result line, past a fetch's `From <url>`, a push's
// `To <url>` and the like (#858).
let summary = crate::git::result_line(&summary);
let line = if summary.is_empty() {
ok_prefix.to_string()
} else {
format!("{ok_prefix}: {summary}")
};
self.source_control.commit_feedback = Some(line.clone());
self.source_control.commit_feedback_is_error = false;
self.status = line;
}
Err(err) => {
let line = crate::git::failure_line(noun, &err);
self.source_control.commit_feedback = Some(line.clone());
self.source_control.commit_feedback_is_error = true;
self.status = line;
}
}
self.active_git_bypass_debounce();
self.refresh_git_status_debounced();
self.refresh_source_control();
}
/// Run a network git operation (push, pull, fetch, clone...) on a
/// worker thread. Run inline, a slow remote or a large clone froze the
/// whole UI until git returned. `job` runs off the UI thread and returns
/// the half that updates the app, which `drain_git_net` applies. One at
/// a time: two pushes racing each other help nobody.
fn spawn_git_net(&mut self, what: &str, job: impl FnOnce() -> GitNetDone + Send + 'static) {
if self.git_net_busy() {
return;
}
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let _ = tx.send(job());
});
self.git_net_job = Some((what.to_string(), rx));
self.status = format!("Git: {what}\u{2026}");
}
/// Run a read-only git view off the UI thread; its finisher is applied by
/// [`Self::drain_git_view`]. A newer request supersedes a pending one,
/// whose result is then dropped.
fn spawn_git_view(&mut self, job: impl FnOnce() -> GitNetDone + Send + 'static) {
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let _ = tx.send(job());
});
self.git_view_job = Some(rx);
}
/// Apply a finished git view. True when one landed.
fn drain_git_view(&mut self) -> bool {
let Some(rx) = &self.git_view_job else {
return false;
};
match rx.try_recv() {
Ok(done) => {
self.git_view_job = None;
done(self);
true
}
Err(std::sync::mpsc::TryRecvError::Empty) => false,
Err(std::sync::mpsc::TryRecvError::Disconnected) => {
self.git_view_job = None;
false
}
}
}
/// Whether a network operation on THIS repository is still running,
/// saying so: what a commit, stage or branch switch must not overlap
/// (they fight over `index.lock`, and a pull would land on the switched
/// branch). A clone writes into another directory and blocks nothing here.
fn repo_git_busy(&mut self) -> bool {
match &self.git_net_job {
Some((running, _)) if running != "clone" => {
self.status = format!("Git: {running} is still running");
true
}
_ => false,
}
}
/// Whether a network git operation is still running, saying so.
fn git_net_busy(&mut self) -> bool {
let Some((running, _)) = &self.git_net_job else {
return false;
};
self.status = format!("Git: {running} is still running");
true
}
/// [`spawn_git_net`] for an operation whose result is reported by
/// [`run_scm_op`].
fn spawn_scm_op(
&mut self,
label: &'static str,
ok_prefix: &'static str,
noun: &'static str,
op: impl FnOnce(&Path) -> Result<String, String> + Send + 'static,
) {
let root = self.scm_root();
self.spawn_git_net(label, move || {
let r = op(&root);
Box::new(move |app: &mut App| app.run_scm_op(label, r, ok_prefix, noun))
});
}
fn finish_clone(&mut self, result: Result<PathBuf, String>, origin: &Path) {
match result {
Ok(dest) => {
self.log_git("clone", &Ok(format!("into {}", dest.display())));
self.status = format!("Cloned into {}", self.status_path(&dest));
// Opened only if the user is still where the clone started:
// one who has moved to another folder meanwhile is not
// pulled out of it when the clone lands.
if self.tree.root == origin {
self.change_workspace_root(dest);
}
}
Err(err) => {
let why = self.git_error_line("clone", &err);
self.source_control.commit_feedback = Some(format!("clone failed: {why}"));
self.source_control.commit_feedback_is_error = true;
self.status = format!("Clone failed: {why}");
}
}
}
/// Apply a finished network git operation. True when one landed.
fn drain_git_net(&mut self) -> bool {
let Some((what, rx)) = &self.git_net_job else {
return false;
};
match rx.try_recv() {
Ok(done) => {
self.git_net_job = None;
done(self);
true
}
Err(std::sync::mpsc::TryRecvError::Empty) => false,
Err(std::sync::mpsc::TryRecvError::Disconnected) => {
self.status = format!("Git: {what} ended without a result");
self.git_net_job = None;
true
}
}
}
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", "Stage 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", "Unstage 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",
"Discard all changes",
);
}
/// `git stash push -u` from the commit dropdown.
fn stash_include_untracked_source_control(&mut self) {
if self.hold_for_unsaved(ScmWrite::StashIncludeUntracked) {
return;
}
self.ask_stash_message(crate::git::StashKind::IncludeUntracked);
}
/// `git stash push --staged` from the commit dropdown.
fn stash_staged_source_control(&mut self) {
if self.hold_for_unsaved(ScmWrite::StashStaged) {
return;
}
self.ask_stash_message(crate::git::StashKind::Staged);
}
/// The files of tabs with unsaved edits under the repository, each
/// once, in tab order. Untitled tabs and files outside the repository
/// are not the commit's business (#1438). A spreadsheet cell still being
/// typed into counts: its value is on screen but not yet in the buffer.
fn unsaved_repo_files(&self) -> Vec<PathBuf> {
let root = self.scm_root();
let mut files: Vec<PathBuf> = Vec::new();
let groups = std::iter::once(&self.editor).chain(self.editor_layout.inactive_groups());
let unsaved = |e: &&crate::widgets::editor::Editor| {
e.dirty
|| e.sheet
.as_ref()
.is_some_and(|s| s.editable() && s.editing.is_some())
};
for ed in groups.flat_map(|g| g.editors.iter()).filter(unsaved) {
if let Some(p) = ed.path.as_ref()
&& p.starts_with(&root)
&& !files.contains(p)
{
files.push(p.clone());
}
}
files
}
/// Whether `op` must wait for the unsaved-changes prompt (#1438). A
/// commit or stash records the files on disk, so an edit still only in
/// a tab would be left out with nothing said; VS Code asks first
/// (`git.promptToSaveFilesBeforeCommit` / `...BeforeStash`). True when
/// the prompt opened and the caller must stop.
fn hold_for_unsaved(&mut self, op: ScmWrite) -> bool {
if std::mem::take(&mut self.scm_unsaved_cleared) {
return false;
}
let files = self.unsaved_repo_files();
if files.is_empty() {
return false;
}
let root = self.scm_root();
self.pending_unsaved_scm = Some(PendingUnsavedScm { op, root, files });
true
}
/// Whether Source Control now points at a repository other than `root`,
/// the one `op` was asked for (focus moved to another root's tab while
/// the prompt was open). The write is then dropped rather than run
/// against the wrong repository, and the status says so.
fn scm_root_moved(&mut self, op: ScmWrite, root: &Path) -> bool {
if self.scm_root() == root {
return false;
}
let msg = format!(
"{} cancelled: Source Control moved to another repository",
op.verb()
);
self.status = msg.clone();
self.source_control.commit_feedback = Some(msg);
self.source_control.commit_feedback_is_error = true;
true
}
/// Run `op` past the unsaved-changes check, which already had its say.
fn run_scm_write(&mut self, op: ScmWrite) {
self.scm_unsaved_cleared = true;
match op {
ScmWrite::Commit => self.commit_source_control(),
ScmWrite::CommitStaged => self.commit_staged_source_control(),
ScmWrite::CommitAll => self.commit_all_source_control(),
ScmWrite::Amend => self.commit_amend_source_control(),
ScmWrite::CommitAndSync => self.commit_and_sync_source_control(),
ScmWrite::CommitAndPush => self.commit_and_push_source_control(),
ScmWrite::Stash => self.stash_source_control(),
ScmWrite::StashIncludeUntracked => self.stash_include_untracked_source_control(),
ScmWrite::StashStaged => self.stash_staged_source_control(),
}
// A write that stopped before its check (busy git, empty message)
// must not carry the clearance to the next request.
self.scm_unsaved_cleared = false;
}
/// "Save All & Commit" (or Stash): save every dirty tab, then run the
/// write only when nothing under the repository is left unsaved, so the
/// commit never records half of the edits.
pub fn save_all_then_pending_scm(&mut self) {
let Some(pending) = self.pending_unsaved_scm.take() else {
return;
};
if self.scm_root_moved(pending.op, &pending.root) {
return;
}
// A cell still being typed into is part of the save, as Cmd+S
// treats it (#1140): commit it so Save All writes it.
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(view) = ed.sheet.as_mut()
&& view.editable()
&& view.commit_edit().is_some()
{
ed.dirty = true;
}
}
}
self.save_all();
if self.save_after_format.is_some() {
// The active tab is written when its formatter replies.
self.scm_after_format_save = Some((pending.op, pending.root));
return;
}
self.finish_scm_after_save(pending.op, &pending.root);
}
/// Run `op` once Save All is done, or say which files kept it from
/// running.
fn finish_scm_after_save(&mut self, op: ScmWrite, root: &Path) {
if self.scm_root_moved(op, root) {
return;
}
let left = self.unsaved_repo_files();
if left.is_empty() {
self.run_scm_write(op);
return;
}
let names: Vec<String> = left
.iter()
.map(|p| {
p.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default()
})
.collect();
self.status = format!(
"{} cancelled: {} still unsaved - open it and press Cmd+S",
op.verb(),
names.join(", ")
);
self.source_control.commit_feedback = Some(format!(
"{} cancelled: {} not saved",
op.verb(),
names.join(", ")
));
self.source_control.commit_feedback_is_error = true;
}
/// "Commit Anyway" (or Stash): run the write on the files as they are on
/// disk, as croft did before it asked.
pub fn continue_pending_scm_without_saving(&mut self) {
if let Some(pending) = self.pending_unsaved_scm.take()
&& !self.scm_root_moved(pending.op, &pending.root)
{
self.run_scm_write(pending.op);
}
}
pub fn cancel_pending_unsaved_scm(&mut self) {
self.pending_unsaved_scm = None;
}
/// 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;
};
if self.hold_for_unsaved(ScmWrite::CommitStaged) {
return;
}
let root = self.scm_root();
let committed = message.clone();
self.spawn_commit(
message,
move || crate::git::commit_staged(&root, &committed),
|app, r| {
let committed = r.is_ok();
app.run_scm_op("commit -m", r, "Committed staged", "Commit staged");
if committed {
app.continue_rebase_after_commit();
}
},
);
}
fn commit_all_source_control(&mut self) {
let Some(message) = self.require_commit_message() else {
return;
};
// Before `add -A`, which would mark a conflict resolved with its
// markers still in it (#989).
if let Err(err) = crate::git::refuse_unmerged(&self.scm_root()) {
self.run_scm_op("add -A", Err(err), "Stage all", "Stage all");
return;
}
if self.hold_for_unsaved(ScmWrite::CommitAll) {
return;
}
let root = self.scm_root();
let committed = message.clone();
self.spawn_commit(
message,
move || {
crate::git::stage_all(&root).map_err(|err| format!("stage all failed: {err}"))?;
crate::git::commit_staged(&root, &committed)
},
|app, r| {
let committed = r.is_ok();
app.run_scm_op("commit (all)", r, "Committed all", "Commit all");
if committed {
app.continue_rebase_after_commit();
}
},
);
}
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.
if self.hold_for_unsaved(ScmWrite::Amend) {
return;
}
let message = self.source_control.message.trim().to_string();
let root = self.scm_root();
let committed = message.clone();
self.spawn_commit(
message,
move || {
if committed.is_empty() {
crate::git::commit_amend_no_edit(&root)
} else {
crate::git::commit_amend(&root, &committed)
}
},
|app, r| app.run_scm_op("commit --amend", r, "Amended commit", "Amend commit"),
);
}
/// Undo Last Commit (#1350): the last commit goes back to Staged and
/// its message back into an empty box, so a reword or a re-pick of the
/// files is one step away. A commit already on the upstream is undone
/// only on a second ask, after a warning that it means a force push.
fn undo_last_commit_source_control(&mut self) {
let root = self.scm_root();
let head = crate::git::query(&root).head_oid;
if head.is_some()
&& crate::git::head_is_on_upstream(&root)
&& self.undo_pushed_commit_armed != head
{
self.undo_pushed_commit_armed = head;
let warning = String::from(
"The last commit is already pushed: undoing it means a force push later. Undo Last Commit again to undo it anyway",
);
self.source_control.commit_feedback = Some(warning.clone());
self.source_control.commit_feedback_is_error = true;
self.status = warning;
return;
}
self.undo_pushed_commit_armed = None;
let outcome = crate::git::undo_last_commit(&root);
if let Ok(message) = &outcome
&& self.source_control.message.trim().is_empty()
{
self.source_control.clear_message();
self.source_control.insert_str(message.trim());
}
let summary = outcome.map(|m| m.lines().next().unwrap_or("").trim().to_string());
self.run_scm_op(
"reset --soft HEAD~1",
summary,
"Undid last commit",
"Undo last commit",
);
}
fn commit_and_sync_source_control(&mut self) {
if self.git_net_busy() {
return;
}
let Some(message) = self.require_commit_message() else {
return;
};
if self.hold_for_unsaved(ScmWrite::CommitAndSync) {
return;
}
let root = self.scm_root();
let committed = message.clone();
self.spawn_commit(
message,
move || crate::git::commit_all_tracked(&root, &committed),
|app, commit| {
app.log_git("commit -am", &commit);
if let Err(err) = commit {
app.report_commit_failure(&err);
return;
}
// Mid-rebase, sync only once the rebase is back on its branch.
if !app.continue_rebase_after_commit() {
return;
}
app.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;
};
self.spawn_scm_op("push -u", "Published", "Publish branch", move |root| {
crate::git::publish_branch(root, &branch)
});
}
/// 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();
}
/// The list picker closed with no row chosen (Esc, a click outside).
fn dismiss_list_picker(&mut self) {
let purpose = self.list_picker.as_ref().map(|p| p.purpose);
self.close_list_picker();
if purpose == Some(crate::widgets::list_picker::ListPurpose::NotebookKernel) {
self.kernel_choice_dismissed();
}
}
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();
// Nothing else touches the repository while a push, pull or fetch
// runs in the background: a commit or branch switch under it fights
// over `index.lock`, and a pull would land on the switched branch.
if !matches!(action, ScmAction::ShowGitOutput) && self.repo_git_busy() {
return;
}
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 => {
self.spawn_scm_op(
"fetch --all --prune",
"Fetched",
"Fetch",
crate::git::fetch_all,
);
}
ScmAction::ShowGitOutput => self.show_git_output(),
ScmAction::ContinueOperation => self.continue_git_operation(),
ScmAction::SkipOperation => self.skip_git_operation(),
ScmAction::AbortOperation => self.abort_git_operation(),
ScmAction::BisectGood => self.bisect_mark_source_control(true),
ScmAction::BisectBad => self.bisect_mark_source_control(false),
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::UndoLastCommit => self.undo_last_commit_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 => {
self.spawn_scm_op(
"pull --rebase",
"Pulled (rebase)",
"Pull (rebase)",
crate::git::pull_rebase,
);
}
ScmAction::PushTo => self.open_push_to_remote_picker(),
ScmAction::PushForce => {
self.spawn_scm_op(
"push --force-with-lease",
"Force-pushed",
"Force push",
crate::git::push_force,
);
}
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 => self.stash_include_untracked_source_control(),
ScmAction::StashStaged => self.stash_staged_source_control(),
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::ViewStash => self.open_stash_picker(ListPurpose::StashView),
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(),
ScmAction::PushTags => self.push_tags_source_control(),
ScmAction::DeleteRemoteTag => self.open_remote_tag_picker(),
}
}
/// Source Control > Tags > Push Tags (#1582): every local tag to the
/// remote a new branch would be published to.
fn push_tags_source_control(&mut self) {
let remote = match crate::git::tag_remote(&self.scm_root()) {
Ok(remote) => remote,
Err(err) => {
self.status = format!("Push tags: {err}");
return;
}
};
self.spawn_scm_op("push --tags", "Pushed tags", "Push tags", move |root| {
crate::git::push_tags(root, &remote)
});
}
/// Source Control > Tags > Delete Remote Tag (#1582): list the push
/// remote's tags off the UI thread, then pick one to delete there.
fn open_remote_tag_picker(&mut self) {
let root = self.scm_root();
let remote = match crate::git::tag_remote(&root) {
Ok(remote) => remote,
Err(err) => {
self.status = format!("Delete remote tag: {err}");
return;
}
};
self.spawn_git_net("ls-remote --tags", move || {
let tags = crate::git::list_remote_tags(&root, &remote);
Box::new(move |app: &mut App| app.show_remote_tags(&root, &remote, tags))
});
}
/// Whether Source Control now points at a repository other than
/// `root`, the one whose remote tags were listed (#1582). The deletion
/// is then dropped rather than sent to another repository's remote of
/// the same name, and the status says so.
fn remote_tag_root_moved(&mut self, root: &Path) -> bool {
if self.scm_root() == root {
return false;
}
self.status =
String::from("Delete remote tag cancelled: Source Control moved to another repository");
true
}
/// The picker over `remote`'s tags in `root`, once listed (#1582).
fn show_remote_tags(&mut self, root: &Path, remote: &str, tags: Result<Vec<String>, String>) {
use crate::widgets::list_picker::{ListPicker, ListPurpose, ListRow};
if self.remote_tag_root_moved(root) {
return;
}
let tags = match tags {
Ok(tags) => tags,
Err(err) => {
self.status = format!("Remote tags: {}", crate::git::result_line(&err));
return;
}
};
self.status.clear();
self.remote_tag_root = Some(root.to_path_buf());
let rows = tags
.into_iter()
.map(|tag| ListRow {
id: format!("{remote}\t{tag}"),
label: tag,
})
.collect();
self.open_list_picker(
ListPicker::new(
ListPurpose::DeleteRemoteTag,
format!("Delete Remote Tag from {remote}"),
rows,
),
&format!("No tags on {remote}"),
);
}
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: s.label(),
})
.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",
crate::widgets::list_picker::ListPurpose::StashView => "View 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::StashMessage { kind } => {
self.close_input_prompt();
let message = (!value.is_empty()).then_some(value.as_str());
self.perform_stash(kind, message);
}
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::SyncConfigHost => {
self.close_input_prompt();
self.sync_config_to(&value);
}
InputPurpose::PullRequestNumber => {
self.close_input_prompt();
self.submit_pr_number(&value);
}
InputPurpose::CodeqlDatabase { source } => {
self.close_input_prompt();
self.submit_codeql_database(source, &value);
}
InputPurpose::CodeqlRemoveDatabase { path } => {
self.close_input_prompt();
self.perform_remove_codeql_database(&path);
}
InputPurpose::CodeqlDeleteUnusedDatabases { paths } => {
self.close_input_prompt();
self.perform_delete_unused_codeql_databases(&paths);
}
InputPurpose::CodeqlRenameDatabase { path } => {
self.close_input_prompt();
self.submit_rename_codeql_database(&path, &value);
}
InputPurpose::CodeqlRemoveHistory { output } => {
self.close_input_prompt();
self.perform_remove_codeql_history(&output);
}
InputPurpose::CodeqlRenameHistory { output } => {
self.close_input_prompt();
self.submit_rename_codeql_history(&output, &value);
}
InputPurpose::CodeqlCreateQuery { dir, language } => {
self.close_input_prompt();
self.submit_create_codeql_query(&dir, language.as_deref(), &value);
}
InputPurpose::CodeqlControllerRepository => {
self.close_input_prompt();
self.submit_codeql_controller(&value);
}
InputPurpose::CodeqlAddVariantRepo { list } => {
self.close_input_prompt();
self.submit_add_codeql_variant_repo(list.as_deref(), &value);
}
InputPurpose::CodeqlAddVariantList => {
self.close_input_prompt();
self.submit_add_codeql_variant_list(&value);
}
InputPurpose::CodeqlAddVariantOwner => {
self.close_input_prompt();
self.submit_add_codeql_variant_owner(&value);
}
InputPurpose::CodeqlDownloadPacks => {
self.close_input_prompt();
self.submit_download_codeql_packs(&value);
}
InputPurpose::CodeqlRunPublishedPack => {
self.close_input_prompt();
self.run_codeql_published_pack(&value);
}
InputPurpose::CodeqlExportVariantResults { index } => {
self.close_input_prompt();
self.start_export_codeql_variant_results(index, &value);
}
InputPurpose::CodeqlExportResults { output } => {
self.close_input_prompt();
self.submit_export_codeql_results(&output, &value);
}
InputPurpose::CodeqlVariantCodeSearch { list } => {
self.close_input_prompt();
self.start_codeql_variant_code_search(list, &value);
}
InputPurpose::CodeqlRenameVariantList { name } => {
self.close_input_prompt();
self.submit_rename_codeql_variant_list(&name, &value);
}
InputPurpose::CodeqlRemoveVariantList { name } => {
self.close_input_prompt();
self.perform_remove_codeql_variant_list(&name);
}
InputPurpose::SarifAddLog => {
self.close_input_prompt();
self.submit_sarif_add_log(&value);
}
InputPurpose::SarifColumns => {
self.close_input_prompt();
self.submit_sarif_columns(&value);
}
InputPurpose::SarifBaseline => {
self.close_input_prompt();
self.submit_sarif_baseline(&value);
}
InputPurpose::SarifExport => {
self.close_input_prompt();
self.submit_sarif_export(&value);
}
InputPurpose::DismissAlertComment { number, reason } => {
self.close_input_prompt();
self.dismiss_code_scanning_alert(number, reason, &value);
}
InputPurpose::SarifLocate { .. } => {
self.close_input_prompt();
self.submit_sarif_locate(&value);
}
InputPurpose::CodeqlModelKind { endpoint, choice } => {
self.close_input_prompt();
self.save_codeql_model(endpoint, choice, &value);
}
InputPurpose::SarifTrustHost { uri, host, url } => {
self.close_input_prompt();
if value.trim().is_empty() {
if let Err(e) = crate::sarif::resolve::trust_host(&host) {
self.status = format!("Could not save {host} as trusted: {e}");
return;
}
self.start_sarif_download(&uri, &url);
} else {
self.submit_sarif_locate(&value);
}
}
InputPurpose::SettingValue { key } => {
self.close_input_prompt();
self.submit_setting_value(&key, &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());
let origin = self.tree.root.clone();
self.spawn_git_net("clone", move || {
let r = crate::git::clone_into(&parent, &value);
Box::new(move |app: &mut App| app.finish_clone(r, &origin))
});
}
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", "Rename 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", "Create branch");
}
InputPurpose::DebugConfigField { field } => {
self.close_input_prompt();
self.submit_debug_config_field(field, &value);
}
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", "Add remote");
}
InputPurpose::CreateTag => {
// Then the message, as VS Code asks (#1582): one makes an
// annotated tag, a blank field a lightweight one.
self.close_input_prompt();
self.open_input_prompt(
InputPrompt::new(
InputPurpose::CreateTagMessage {
name: value.clone(),
},
format!("Create Tag '{value}'"),
"Message (optional)",
)
.allowing_blank()
.with_hint(
"Enter with a message makes an annotated tag · blank, a lightweight one",
),
);
}
InputPurpose::CreateTagMessage { name } => {
self.close_input_prompt();
let message = (!value.is_empty()).then_some(value.as_str());
let r = crate::git::create_tag(&self.scm_root(), &name, message);
self.run_scm_op("tag", r, "Created tag", "Create tag");
}
InputPurpose::DeleteRemoteTag { root, remote, name } => {
self.close_input_prompt();
if self.remote_tag_root_moved(&root) {
return;
}
self.spawn_scm_op(
"push --delete",
"Deleted remote tag",
"Delete remote tag",
move |root| crate::git::delete_remote_tag(root, &remote, &name),
);
}
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();
if !value.eq_ignore_ascii_case("reload") {
self.status = String::from(
"Kept your unsaved edits; saving asks before overwriting the disk version",
);
return;
}
// Recoverable from TIMELINE: no answer, however deliberate,
// makes typed work unrecoverable (#910).
let kept = self.keep_unsaved_buffers_in_history(&paths);
// Every group: the prompt lists conflicts from the other
// splits too, and reverting only the focused one left theirs
// unreloaded with the prompt never coming back.
let mut reverted = self.editor.revert_paths_to_disk(&paths);
for group in self.editor_layout.inactive_groups_mut() {
for p in group.revert_paths_to_disk(&paths) {
if !reverted.contains(&p) {
reverted.push(p);
}
}
}
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"),
};
if kept > 0 && !reverted.is_empty() {
self.status
.push_str("; the discarded edits are in Local History (TIMELINE)");
}
}
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");
}
/// Session: Detach (#679): disconnect the client that asked, when only
/// one client can have (see `sole_detach_target`). The session keeps
/// running, and the client restores its terminal on the way out.
fn detach_session_client(&mut self) {
if self.session_channel.is_none() {
self.status =
String::from("Not attached to a persistent session: nothing to detach from");
return;
}
// Only a control holder's keys reach croft, so with one control
// holder (or one client) the invoker is known. With several, the
// typing attribution can race another writer's keys, so refuse
// rather than disconnect the wrong client: the chord, caught by the
// attach client itself, always detaches its own client.
let Some(id) = crate::session_host::sole_detach_target(&self.session_participants) else {
self.status = String::from(
"Several clients can type here: press Cmd+K Shift+Q in the client to leave, or use Session: Participants (Cmd+K A)",
);
return;
};
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;
};
self.status = if channel.kick(id) {
format!("{name} detached; the session keeps running")
} else {
String::from("Session host unreachable")
};
}
/// 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();
// A client older than this session is told here, in croft's own
// status line, never over its screen (#626, #652). The reference is
// the newer of this croft and its host: a host swap moves the host
// past this croft until the updater relaunches it, and a client
// still on the old binary is then out of date even though it
// matches us. Raised only
// when the notice changes (a client resizing churns the roster), and
// decided before the unchanged-roster return, since a swap can leave
// the roster identical while the host's version moved.
let host_version = crate::session_host::read_host_version(&channel.host_version);
let reference = crate::session_host::session_version(
env!("CARGO_PKG_VERSION"),
host_version.as_deref(),
);
let stale = crate::session_host::stale_client_notice_on_change(
self.session_stale_notice.as_deref(),
&roster,
reference,
);
self.session_stale_notice = crate::session_host::stale_client_notice(&roster, reference);
if roster == self.session_participants {
// Unchanged roster: redraw only for a newly raised notice.
let Some(notice) = stale else {
return false;
};
self.status = notice;
return true;
}
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)");
}
if let Some(notice) = stale {
self.status = notice;
}
// 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;
}
if self.reply_to_review_thread(focus.id, &reply) {
return;
}
let me = collab_display_name();
if self.change_note_box(focus.id, |n| {
n.replies.push(crate::sticky_notes::Reply {
author: me,
body: reply.clone(),
})
}) {
self.editor.comment_focus = None;
self.status = String::from("Reply added to the note");
return;
}
if Self::pending_review_index(focus.id).is_some() {
self.status =
String::from("A pending comment has no thread yet; submit the review first");
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}"),
}
}
/// The workspace-relative key a note on the open file uses.
fn note_file_key(&self) -> Option<String> {
let path = self.editor.path.as_deref()?;
repo_relative(&self.tree.root, path)
}
/// Notes: Add Note (Cmd+K N) (#367).
fn open_sticky_note_prompt(&mut self) {
if self.note_file_key().is_none() {
self.status = String::from("Notes go on files inside the workspace");
return;
}
self.prompt = Some(Prompt {
label: format!("Note on line {}", self.editor.cursor_row + 1),
buffer: String::new(),
kind: PromptKind::StickyNote,
target_dir: self.tree.root.clone(),
error: None,
});
}
fn add_sticky_note(&mut self, body: &str) {
let Some(file) = self.note_file_key() else {
return;
};
if body.is_empty() {
return;
}
let row = self.editor.cursor_row;
let anchor = self.editor.lines.get(row).cloned().unwrap_or_default();
let note = self
.notes
.add(&collab_display_name(), &file, row, &anchor, body);
self.publish_note(¬e);
self.status = String::from("Note added");
}
/// Send a changed note to the session and keep the store current.
fn publish_note(&mut self, note: &crate::sticky_notes::Note) {
let mut session = self.collab.take();
if let Some(s) = session.as_mut() {
s.send_note(note);
}
self.save_notes(session.as_ref());
self.collab = session;
}
/// The owner (or a lone croft) writes the notes; a guest's copy lives
/// with the owner.
fn save_notes(&mut self, session: Option<&crate::collab::CollabSession>) {
if session.is_some_and(|s| s.role == crate::collab::CollabRole::Guest) {
return;
}
if let Some(path) = &self.notes_path {
let _ = self.notes.save(path);
}
}
/// A note's comment-box id: high in the id space, clear of navigator
/// notes (from 1), GitHub ids (~4e9) and pending review comments (top).
fn note_box_id(id: &str) -> u64 {
let mut h: u64 = 0xcbf29ce484222325;
for b in id.bytes() {
h ^= u64::from(b);
h = h.wrapping_mul(0x100000001b3);
}
(1 << 62) | (h & ((1 << 61) - 1))
}
/// Change the note behind box `id`, if it is one. Returns whether it was.
fn change_note_box(
&mut self,
id: u64,
change: impl FnOnce(&mut crate::sticky_notes::Note),
) -> bool {
let Some(note_id) = self.note_box_ids.get(&id).cloned() else {
return false;
};
if let Some(note) = self.notes.update(¬e_id, change) {
self.publish_note(¬e);
}
true
}
/// Notes: Delete Note: the focused note, else the one on the caret's
/// line. A note further down is never reached for: a tombstone can't be
/// undone, so the command deletes only a note the user is on (#1131).
fn delete_sticky_note_here(&mut self) {
let id = self
.editor
.comment_focus
.as_ref()
.map(|f| f.id)
.filter(|id| self.note_box_ids.contains_key(id))
.or_else(|| {
let file = self.note_file_key()?;
let lines = &self.editor.lines;
self.notes
.on_file(&file)
.find(|n| n.place(lines) == self.editor.cursor_row)
.map(|n| Self::note_box_id(&n.id))
});
let Some(note) = id
.and_then(|id| self.note_box_ids.get(&id))
.and_then(|note_id| self.notes.get(note_id))
else {
self.status = String::from("No note on this line");
return;
};
let line = note.place(&self.editor.lines) + 1;
let first = note.body.lines().next().unwrap_or_default();
// The first words, cut at a space so the status doesn't end mid-word.
let mut gist = truncate_for_display(first, 40);
if gist.len() < first.len()
&& let Some(cut) = gist.rfind(' ')
{
gist.truncate(cut);
}
if id.is_some_and(|id| self.change_note_box(id, |n| n.deleted = true)) {
self.status = format!("Note deleted on line {line}: {gist}");
}
}
/// Box ids for pending comments count down from the top of the id
/// space, clear of navigator notes (from 1) and GitHub ids (~4e9).
const PENDING_REVIEW_ID: u64 = u64::MAX - 1_000_000;
/// The pending comment a box id names, as an index.
fn pending_review_index(id: u64) -> Option<usize> {
id.checked_sub(Self::PENDING_REVIEW_ID).map(|i| i as usize)
}
/// Review: Add Comment on This Line (#366).
fn open_review_comment_prompt(&mut self) {
let Some((_, _, rel, _)) = self.review_context() else {
return;
};
self.prompt = Some(Prompt {
label: format!("Comment on {rel}:{}", self.editor.cursor_row + 1),
buffer: String::new(),
kind: PromptKind::ReviewComment,
// Carries the repo-relative path, so the comment lands on the
// file it was asked about.
target_dir: PathBuf::from(rel),
error: None,
});
}
fn add_pending_review_comment(&mut self, body: &str, rel: PathBuf) {
if body.is_empty() {
return;
}
let Some((root, number)) = self.review_pr.clone() else {
return;
};
if !self.pending_is_for(&root, &number) {
return;
}
self.review_pending_pr = Some((root, number));
self.review_pending
.push(crate::review_threads::PendingComment {
path: rel.to_string_lossy().into_owned(),
line: self.editor.cursor_row,
body: body.to_string(),
});
self.status = format!(
"{} pending comment(s): Review: Submit Review sends them",
self.review_pending.len()
);
}
/// Whether the pending comments (if any) were written on PR `number` in
/// `root`. Comments written on another PR (another branch, another
/// repository of the workspace) must never post here; the status says
/// which PR they belong to.
fn pending_is_for(&mut self, root: &Path, number: &str) -> bool {
match &self.review_pending_pr {
Some((r, n)) if !self.review_pending.is_empty() && (r != root || n != number) => {
self.status = format!(
"{} pending comment(s) belong to PR #{n} in {}: submit or discard them there first",
self.review_pending.len(),
r.display()
);
false
}
_ => true,
}
}
/// Review: Submit Review: pick the verdict, then type the summary.
fn open_review_submit(&mut self) {
if self.review_context().is_none() {
return;
}
let rows = [
("COMMENT", "Comment"),
("APPROVE", "Approve"),
("REQUEST_CHANGES", "Request Changes"),
]
.into_iter()
.map(|(id, label)| crate::widgets::list_picker::ListRow {
id: id.to_string(),
label: format!("{label} ({} pending comment(s))", self.review_pending.len()),
})
.collect();
self.open_list_picker(
crate::widgets::list_picker::ListPicker::new(
crate::widgets::list_picker::ListPurpose::ReviewVerdict,
"Submit Review",
rows,
),
"",
);
}
fn submit_review(&mut self, summary: String) {
use crate::review_threads::ReviewEvent;
let event = self.review_verdict.take().unwrap_or(ReviewEvent::Comment);
let Some((root, number)) = self.review_pr.clone() else {
return;
};
if !self.pending_is_for(&root, &number) {
return;
}
if self.review_submitting {
self.status = String::from("A review is already being submitted");
return;
}
if event == ReviewEvent::Comment && summary.is_empty() && self.review_pending.is_empty() {
self.status = String::from("Nothing to submit: add a comment or a summary");
return;
}
crate::review_ops::spawn(
self.review_gh.clone(),
root,
crate::review_ops::Job::Submit {
number,
event,
summary,
pending: self.review_pending.clone(),
settles: crate::review_ops::Settles {
pending: self.review_pending.clone(),
..Default::default()
},
},
self.review_tx.clone(),
);
self.review_submitting = true;
self.status = String::from("Submitting review…");
}
/// Review: Resolve or Unresolve Thread: the focused box, else the next
/// one from the caret.
fn toggle_review_thread_resolved(&mut self) {
let id = self
.editor
.comment_focus
.as_ref()
.map(|f| f.id)
.or_else(|| self.next_comment_from_caret().map(|(id, _)| id));
let Some(thread) = id.and_then(|id| {
self.review_boxes
.as_ref()
.and_then(|(_, ts)| ts.iter().find(|t| t.id == id).cloned())
}) else {
self.status = String::from("No review thread here");
return;
};
let (Some(node), Some((root, _))) = (
self.review_nodes.get(&thread.id).cloned(),
self.review_pr.clone(),
) else {
self.status =
String::from("GitHub didn't report this thread's id; reload the comments");
return;
};
crate::review_ops::spawn(
self.review_gh.clone(),
root,
crate::review_ops::Job::Resolve {
thread: thread.id,
node,
resolve: !thread.resolved,
},
self.review_tx.clone(),
);
}
/// A reply typed into a review thread's box goes to GitHub. Returns
/// false when the focused box is not a review thread.
fn reply_to_review_thread(&mut self, id: u64, text: &str) -> bool {
let is_thread = self
.review_boxes
.as_ref()
.is_some_and(|(_, ts)| ts.iter().any(|t| t.id == id));
if !is_thread {
return false;
}
let Some((root, number)) = self.review_pr.clone() else {
return false;
};
crate::review_ops::spawn(
self.review_gh.clone(),
root,
crate::review_ops::Job::Reply {
number,
thread: id,
text: text.to_string(),
},
self.review_tx.clone(),
);
self.editor.comment_focus = None;
self.status = String::from("Replying…");
true
}
/// Apply finished review jobs.
pub fn drain_review_ops(&mut self) -> bool {
use crate::review_ops::Outcome;
let mut changed = false;
while let Ok(out) = self.review_rx.try_recv() {
changed = true;
match out {
Outcome::Replied { thread, text } => {
if let Some((_, ts)) = &mut self.review_boxes
&& let Some(t) = ts.iter_mut().find(|t| t.id == thread)
{
t.body.push_str(&format!("\n\nyou: {text}"));
}
self.status = String::from("Reply posted");
}
Outcome::Resolved { thread, resolved } => {
if let Some((_, ts)) = &mut self.review_boxes
&& let Some(t) = ts.iter_mut().find(|t| t.id == thread)
{
t.resolved = resolved;
}
self.status = String::from(if resolved {
"Thread resolved"
} else {
"Thread reopened"
});
}
Outcome::Submitted {
inline,
folded,
settles,
} => {
self.review_submitting = false;
self.review_pending.retain(|c| !settles.pending.contains(c));
if self.review_pending.is_empty() {
self.review_pending_pr = None;
}
// Exported navigator notes now live on GitHub; reload
// shows them there, as threads, rather than twice.
// Exported sticky notes are settled: resolved for everyone.
for id in settles.sticky {
if let Some(n) = self.notes.update(&id, |n| n.resolved = true) {
self.publish_note(&n);
}
}
let exported = settles.notes;
if !exported.is_empty() {
for id in &exported {
if let Some(host) = &self.pair_host {
host.remove_note(*id);
}
}
for list in self.navigator_notes.values_mut() {
list.retain(|(id, ..)| !exported.contains(id));
}
if self.editor.path.is_some() {
self.load_review_threads();
}
}
self.status = match folded {
0 => format!("Review submitted with {inline} comment(s)"),
n => format!(
"Review submitted: {inline} inline, {n} outside the diff moved into the summary"
),
};
}
Outcome::Threads {
root,
number,
path,
rel,
threads,
states,
} => self.show_review_threads(root, number, path, rel, threads, states),
Outcome::ExportReady {
root,
number,
comments,
notes,
inline,
} => self.show_export_ready(root, number, comments, notes, inline),
Outcome::NoPr => {
self.status = String::from("No PR for this branch — check it out first");
}
Outcome::SubmitFailed(e) => {
self.review_submitting = false;
self.status = e;
}
// A failed reply or load leaves a submission in flight alone.
Outcome::Failed(e) => self.status = e,
}
}
changed
}
/// 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) {
// A note's ✕ resolves it (and a resolved note's reopens it): notes
// are shared, so dismissing one is a decision for everyone.
if self.change_note_box(id, |n| n.resolved = !n.resolved) {
self.status = String::from("Note resolved or reopened");
return;
}
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 let Some(i) = Self::pending_review_index(id)
&& i < self.review_pending.len()
{
self.review_pending.remove(i);
}
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())),
);
}
// Unresolved sticky notes (#367) too: F4 is how they are walked.
if let Some(file) = self.note_file_key() {
let lines = &self.editor.lines;
notes.extend(
self.notes
.on_file(&file)
.filter(|n| !n.resolved)
.map(|n| (Self::note_box_id(&n.id), n.place(lines), n.body.clone())),
);
notes.sort_by_key(|(_, row, _)| *row);
}
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) = crate::highlight::lang_for_path(&path) 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) => {
let mut session = CollabSession::new(ch, collab_display_name());
if session.role == CollabRole::Guest {
session.send_notes_request();
}
self.collab = Some(session);
}
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));
// One undo step per author per file per tick (#1207): a peer's edit
// reaches us as one op per changed run, and undoing them run by run
// walked through texts nobody ever wrote.
let mut tick_groups: std::collections::HashMap<(String, u64), u64> =
std::collections::HashMap::new();
for event in events {
changed = true;
match event {
CollabEvent::RemoteEdit { file, site, spans } => {
let doc_gen = session.doc_gen(&file).unwrap_or(0);
// An AI stream's fragments span many ticks; the whole
// stream is one step, as its cancel already is.
let group = match self.collab_stream.as_ref() {
Some(st) if st.file == file && st.site == site => st.undo_group,
_ => *tick_groups
.entry((file.clone(), site))
.or_insert_with(next_remote_undo_group),
};
self.apply_collab_spans(&root, &file, &spans, doc_gen, group);
}
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::OwnerLeft => {
self.status = String::from("The session owner left; saves now write to disk");
}
CollabEvent::OwnerReturned { files } => {
// The new owner starts from the file on disk, so that is
// the merge base for this guest's work since the owner
// left (#1147): only this side's changes replay, and any
// the new owner already made survive.
for file in files {
match crate::collab::contained_path(&root, &file)
.and_then(|p| std::fs::read_to_string(p).ok())
{
Some(disk) => {
self.collab_offline_base
.insert(file, disk.replace("\r\n", "\n"));
}
None => {
self.collab_offline_base.remove(&file);
}
}
}
self.status = String::from("The session owner is back; rejoining shared files");
}
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();
let same = |st: &CollabStreamInfo| st.file == file && st.site == site;
let previous = self.collab_stream.take();
let undo_group = match &previous {
Some(st) if active && same(st) => st.undo_group,
_ => next_remote_undo_group(),
};
// A stream that ended (or gave way to another) closes
// its undo step; one whose cancel restored the text
// leaves none.
if let Some(st) = previous.filter(|st| !(active && same(st))) {
self.end_collab_undo_group(&root, &st.file, st.undo_group);
}
self.collab_stream = active.then_some(CollabStreamInfo {
file,
name,
site,
undo_group,
});
}
// The cancel request is for the streaming pilot, not for
// viewers; the badge clears via StreamState(inactive).
CollabEvent::StreamCancel => {}
CollabEvent::Note(note) => {
if self.notes.merge(note) {
self.save_notes(Some(&session));
}
}
CollabEvent::NotesRequested => {
for note in self.notes.all().to_vec() {
session.send_note(¬e);
}
}
}
}
// 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"))
}
/// Close a remote undo group in every text tab of `file` (#1207).
fn end_collab_undo_group(&mut self, root: &Path, file: &str, group: u64) {
let Some(path) = crate::collab::contained_path(root, file) else {
return;
};
let groups = self.editor_layout.inactive_groups_mut();
for ed in self
.editor
.editors
.iter_mut()
.chain(groups.into_iter().flat_map(|g| g.editors.iter_mut()))
{
if ed.path.as_deref() == Some(path.as_path()) && !ed.has_non_text_view() {
ed.end_remote_undo_group(group);
}
}
}
/// 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_remote_span_edits` one at a time, all in
/// `undo_group`'s one undo step (#1207). 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,
undo_group: 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_remote_span_edits(
&[crate::widgets::editor::TextSpanEdit {
start: (sr, sc),
end: (er, ec),
new_text: s.inserted.clone(),
utf16: false,
}],
undo_group,
);
}
// 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;
};
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;
let selected = picker.selected;
self.close_list_picker();
let index = row.id.parse::<usize>().unwrap_or(0);
match purpose {
ListPurpose::AgentLaneFile => {
if let Some((agent, path)) = self.pending_lane_picks.get(index).cloned() {
self.diff_agent_lane_row(&agent, &path);
}
}
ListPurpose::StashApply => {
let r = crate::git::stash_apply(&self.scm_root(), index);
self.run_scm_op("stash apply", r, "Applied stash", "Apply stash");
}
ListPurpose::StashPop => {
let r = crate::git::stash_pop_at(&self.scm_root(), index);
self.run_scm_op("stash pop", r, "Popped stash", "Pop stash");
}
ListPurpose::StashView => self.open_stash_patch(index),
ListPurpose::StashDrop => {
let r = crate::git::stash_drop(&self.scm_root(), index);
self.run_scm_op("stash drop", r, "Dropped stash", "Drop stash");
}
ListPurpose::RemoveRemote => {
let r = crate::git::remove_remote(&self.scm_root(), &row.id);
self.run_scm_op("remote remove", r, "Removed remote", "Remove remote");
}
ListPurpose::DeleteTag => {
let r = crate::git::delete_tag(&self.scm_root(), &row.id);
self.run_scm_op("tag -d", r, "Deleted tag", "Delete tag");
}
ListPurpose::DeleteRemoteTag => {
// Deleting from a remote reaches everyone who fetches it,
// so it is confirmed first (#1582).
let Some(root) = self.remote_tag_root.take() else {
return;
};
if self.remote_tag_root_moved(&root) {
return;
}
if let Some((remote, name)) = row.id.split_once('\t') {
use crate::widgets::input_prompt::{InputPrompt, InputPurpose};
self.open_input_prompt(
InputPrompt::new(
InputPurpose::DeleteRemoteTag {
root,
remote: remote.to_string(),
name: name.to_string(),
},
format!("Delete tag '{name}' from {remote}?"),
"Enter to delete · Esc to keep",
)
.with_value("delete"),
);
}
}
ListPurpose::PushToRemote => {
let remote = row.id.clone();
self.spawn_scm_op("push", "Pushed", "Push", move |root| {
crate::git::push_to_remote(root, &remote)
});
}
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::DismissAlert => {
if let Some((number, reason)) = row.id.split_once(':') {
let number = number.parse().unwrap_or(0);
let reason = reason.parse().unwrap_or(0);
use crate::widgets::input_prompt::{InputPrompt, InputPurpose};
self.open_input_prompt(InputPrompt::new(
InputPurpose::DismissAlertComment { number, reason },
format!("Dismiss Alert #{number}"),
String::from("comment (optional)"),
));
}
}
ListPurpose::CodeqlModel => self.choose_codeql_model(&row.id),
ListPurpose::CodeqlDbSource => {
if let Some((action, _)) = CODEQL_DB_SOURCES.get(index) {
self.activate_codeql(crate::widgets::codeql::Hit::Action(*action));
}
}
ListPurpose::CodeqlDatabase => {
if let Ok(i) = row.id.parse::<usize>() {
self.activate_codeql(crate::widgets::codeql::Hit::Action(
crate::widgets::codeql::Action::SelectDatabase(i),
));
}
}
ListPurpose::CodeqlMultiDb => self.choose_codeql_multi_db(&row.id, selected),
ListPurpose::CodeqlResultSet => {
let path = PathBuf::from(&row.id);
match self.editor.open(&path) {
Ok(()) => self.status = format!("Result set {}", row.label),
Err(e) => self.status = format!("{}: {e}", path.display()),
}
}
ListPurpose::CodeScanningAnalysis => {
if let Ok(id) = row.id.parse::<u64>() {
self.open_code_scanning_analysis(id);
}
}
ListPurpose::RunTask => {
if let Some(task) = self.run_tasks.get(index).cloned() {
self.start_project_task(task);
}
}
ListPurpose::ReviewPullRequest => {
if row.id == crate::widgets::list_picker::PR_BY_NUMBER {
self.open_pr_number_prompt();
} else {
self.start_pr_review(row.id.clone());
}
}
ListPurpose::AttachProcess => {
if let Some((rc, slot)) = row
.id
.parse::<i64>()
.ok()
.and_then(|pid| self.take_pending_attach(pid))
{
self.launch_resolved_in(rc, slot);
}
}
ListPurpose::DebugConfigType => {
self.debug_config_draft = Some(crate::dap::configs::ConfigDraft::new(
&row.id,
crate::dap::configs::RequestKind::Launch,
));
self.open_list_picker(
crate::widgets::list_picker::ListPicker::new(
ListPurpose::DebugConfigRequest,
"Add Configuration: Launch or Attach",
vec![
crate::widgets::list_picker::ListRow {
id: String::from("launch"),
label: String::from(
"Launch — start the program under the debugger",
),
},
crate::widgets::list_picker::ListRow {
id: String::from("attach"),
label: String::from("Attach — to a program already running"),
},
],
),
"",
);
}
ListPurpose::DebugConfigRequest => {
if let Some(draft) = self.debug_config_draft.as_mut() {
draft.request = if row.id == "attach" {
crate::dap::configs::RequestKind::Attach
} else {
crate::dap::configs::RequestKind::Launch
};
let first = draft.next_field(None);
self.prompt_debug_config_field(first, None);
}
}
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.cloned() {
self.selected_debug_config = None;
self.selected_debug_compound = Some(compound.name.clone());
self.run_debug.selected_config = Some(compound.name.clone());
self.launch_with_unsaved_saved(|app| app.launch_compound(&compound));
}
} else if row.id == "add" {
self.open_add_debug_config();
} else if row.id == "active" {
self.selected_debug_config = None;
self.selected_debug_compound = 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.selected_debug_compound = None;
self.run_debug.selected_config = Some(cfg.name.clone());
self.launch_with_unsaved_saved(|app| app.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::ExportComments => {
if row.id == "post" {
self.post_exported_comments();
} else {
// A comment row is information; the preview stays up
// until the post row or Esc.
self.show_export_preview();
}
}
ListPurpose::ReviewVerdict => {
use crate::review_threads::ReviewEvent;
self.review_verdict = Some(match row.id.as_str() {
"APPROVE" => ReviewEvent::Approve,
"REQUEST_CHANGES" => ReviewEvent::RequestChanges,
_ => ReviewEvent::Comment,
});
self.prompt = Some(Prompt {
label: String::from("Review summary"),
buffer: String::new(),
kind: PromptKind::ReviewSummary,
target_dir: self.tree.root.clone(),
error: None,
});
}
ListPurpose::Profiles => match row.id.as_str() {
"new" => {
let target_dir = self.tree.root.clone();
self.prompt = Some(Prompt {
label: String::from("New profile name"),
buffer: String::new(),
kind: PromptKind::NewProfile,
target_dir,
error: None,
});
}
"workspace" => {
let active = crate::profiles::active();
match crate::profiles::set_workspace_default(&self.tree.root, active.as_deref())
{
Ok(()) => {
self.status = format!(
"This workspace now opens with profile {}",
active.unwrap_or_default()
)
}
Err(e) => self.status = format!("Could not save: {e}"),
}
}
"workspace-clear" => {
match crate::profiles::set_workspace_default(&self.tree.root, None) {
Ok(()) => {
self.status = String::from("This workspace no longer picks a profile")
}
Err(e) => self.status = format!("Could not save: {e}"),
}
}
id => {
if let Some(name) = id.strip_prefix("profile:") {
let name = (!name.is_empty()).then(|| name.to_string());
self.switch_profile(name);
}
}
},
ListPurpose::KeyboardShortcuts => {
if let Some(cmd) = row
.id
.strip_prefix("kb:")
.and_then(crate::widgets::command_palette::Command::from_id)
{
self.recording_shortcut = Some((cmd, std::time::Instant::now()));
self.status = format!(
"Press the new shortcut for \u{201c}{}\u{201d} (a function key or a chord with Cmd/Ctrl/Alt; Esc cancels)",
cmd.title()
);
}
}
ListPurpose::OutputChannel => {
self.output.sync();
self.output.select_by_name(&row.id);
self.set_bottom_panel_tab(BottomPanelTab::Output);
}
ListPurpose::PanelAlignment => {
if let Some((al, ..)) = PanelAlignment::OPTIONS
.iter()
.find(|(_, id, _)| *id == row.id)
{
self.set_panel_alignment(*al);
}
}
ListPurpose::NotebookKernel => self.choose_notebook_kernel(&row.id),
ListPurpose::QuickInputPosition => {
if let Some((pos, ..)) = QuickInputPosition::OPTIONS
.iter()
.find(|(_, id, _)| *id == row.id)
{
self.set_quick_input_position(*pos);
}
}
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:vim_mode" => self.toggle_vim_mode(),
"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(),
"toggle:code_lens" => self.toggle_code_lens(),
"toggle:terminal_suggestions" => self.toggle_terminal_suggestions(),
"toggle:screen_reader" => self.toggle_screen_reader(),
"cmd:keyboard_shortcuts" => {
self.open_keyboard_shortcuts();
return;
}
"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:vim_mode"),
label: format!(
"Editor: Vim Mode: {}{}",
on_off(self.vim.enabled),
prov("vim_mode")
),
},
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"),
},
ListRow {
id: String::from("cmd:keyboard_shortcuts"),
label: String::from(
"Keyboard Shortcuts\u{2026} (record a new chord for any command)",
),
},
ListRow {
id: String::from("toggle:code_lens"),
label: format!("Editor: CodeLens: {}", on_off(self.code_lens_enabled)),
},
ListRow {
id: String::from("toggle:terminal_suggestions"),
label: format!(
"Terminal: Command Suggestions: {}",
on_off(self.term_suggest_enabled)
),
},
ListRow {
id: String::from("toggle:screen_reader"),
label: format!(
"Accessibility: Screen Reader Mode: {}",
on_off(self.screen_reader)
),
},
];
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, go.mod, CMakeLists.txt, .vscode/tasks.json)",
);
}
/// The line `run_project_task` types for `task`: tasks.json variables
/// expanded against the active workspace and file. The preLaunchTask
/// gate matches the pane's finished command against this same line.
fn task_command_line(&self, task: &crate::tasks::Task) -> Result<String, String> {
self.task_command_line_in(task, self.active_workspace_root())
}
/// [`Self::task_command_line`] against the workspace folder `root`: a
/// compound member's preLaunchTask from another folder (#1425) expands
/// `${workspaceFolder}` to that folder, not the active one.
fn task_command_line_in(
&self,
task: &crate::tasks::Task,
root: PathBuf,
) -> Result<String, String> {
task.command_line(&crate::dap::configs::SubstCtx {
workspace_folder: root,
file: self.editor.path.clone(),
folders: self.workspace_folders(),
})
}
/// 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 root = self.active_workspace_root();
self.run_project_task_in(task, root)
}
/// [`Self::run_project_task`] in the workspace folder `folder`: the pane
/// starts there and the task's variables expand against it, so a
/// compound member's preLaunchTask from another folder (#1425) builds
/// that folder's project.
fn run_project_task_in(&mut self, task: crate::tasks::Task, folder: PathBuf) -> 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 line = match self.task_command_line_in(&task, folder.clone()) {
Ok(line) => line,
Err(e) => {
self.status = format!("Task \u{201c}{}\u{201d} not run: {e}", task.label);
return None;
}
};
let command = format!("\x05\x15{line}\r");
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 canonical = folder.canonicalize().unwrap_or_else(|_| folder.clone());
if let Some(idx) = self
.terminals
.iter()
.position(|t| pane_is_idle_at(t, &pane_name, &canonical))
{
// 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.await_pane_outcome(uid, task.label);
self.assign_task_matcher(uid, matcher);
return Some(uid);
}
match crate::widgets::terminal::PtyTerminal::new(&folder) {
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);
self.await_pane_outcome(uid, 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.start_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.start_project_task(task),
None => self.status = "No task has run yet".to_string(),
}
}
/// Run `task` as the user asked for it (Run Task, the build task, Rerun
/// Last Task), unsaved tabs written first (#1639).
fn start_project_task(&mut self, task: crate::tasks::Task) {
self.run_with_unsaved_saved("the task", |app| {
app.run_project_task(task);
});
}
/// Resolve the branch-picker selection per its open purpose.
fn apply_branch_picker_selection(&mut self) {
if self.repo_git_busy() {
return;
}
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", "Delete 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", "Merge");
}
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", "Rebase");
}
}
}
/// 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) => {
let why = self.git_error_line("diff --staged", &err);
self.source_control.commit_feedback = Some(format!("diff failed: {why}"));
self.source_control.commit_feedback_is_error = true;
self.status = format!("View Staged Changes failed: {why}");
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) => {
let why = self.git_error_line(&format!("diff {branch}"), &err);
self.source_control.commit_feedback = Some(format!("diff failed: {why}"));
self.source_control.commit_feedback_is_error = true;
self.status = format!("View Changes vs {branch} failed: {why}");
return;
}
};
// Name the base the diff starts from (#1444): the merge base, or
// the branch tip when the two share no history.
let (title, said) = match crate::git::merge_base(&self.scm_root(), &branch) {
Some(base) => (
format!(
"git diff {} (merge base with {branch})",
&base[..base.len().min(7)]
),
format!("Showing changes since this branch left {branch}"),
),
None => (
format!("git diff {branch}"),
format!("Showing git diff {branch}: no history in common, so against its tip"),
),
};
let label = std::path::PathBuf::from(title);
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 = said;
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) => {
let why = self.git_error_line("diff HEAD~1", &err);
self.source_control.commit_feedback = Some(format!("diff failed: {why}"));
self.source_control.commit_feedback_is_error = true;
self.status = format!("View Changes vs previous failed: {why}");
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) {
// Checked before committing: a commit whose push is then refused
// would leave the user thinking it had been pushed.
if self.git_net_busy() {
return;
}
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;
}
if self.hold_for_unsaved(ScmWrite::CommitAndPush) {
return;
}
let root = self.scm_root();
let committed = message.clone();
self.spawn_commit(
message,
move || crate::git::commit_all_tracked(&root, &committed),
|app, r| {
app.log_git("commit -am", &r);
let commit_summary = match r {
Ok(s) => crate::git::headline(&s).to_string(),
Err(err) => {
app.report_commit_failure(&err);
return;
}
};
// Mid-rebase, push only once the rebase is back on its
// branch, never from the detached HEAD it works on.
if !app.continue_rebase_after_commit() {
return;
}
let root = app.scm_root();
app.spawn_git_net("push", move || {
let r = crate::git::push_or_publish(&root);
Box::new(move |app: &mut App| app.finish_commit_and_push(commit_summary, r))
});
app.active_git_bypass_debounce();
app.refresh_git_status_debounced();
app.refresh_source_control();
},
);
}
/// Report Commit & Push on one line (#858): the commit's headline and
/// the push's ref update, or why the push failed; the Git Output log
/// keeps git push's whole text.
fn finish_commit_and_push(&mut self, commit_summary: String, push: Result<String, String>) {
self.log_git("push", &push);
let push = push
.map(|out| crate::git::summary_line(&out))
.map_err(|err| crate::git::error_line(&err));
match push {
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) {
if self.repo_git_busy() {
return;
}
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) => {
let why = self.git_error_line("add", &err);
self.status = format!("Stage failed: {why}");
self.source_control.commit_feedback = Some(why);
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 built = match self.editor.diff.as_ref() {
None => self.editor_hunk_patch_at_caret().map_err(str::to_string),
Some(diff) if !diff.left_is_git_head => {
Err("Hunk actions need a working-tree diff from Source Control".to_string())
}
Some(diff) if diff.right_is_unsaved => {
Err("Save the file first: hunk actions apply to the file on disk".to_string())
}
// The patch is built from the decoded text, which would put UTF-8
// bytes into a blob stored in another encoding (#1242).
Some(diff) if diff.text_encoding != encoding_rs::UTF_8 => Err(format!(
"Hunk actions work on UTF-8 files only; this diff is {}: stage the whole file",
diff.text_encoding.name()
)),
Some(diff) => match self.repo_relative_path(&diff.right_path) {
None => Err("File is outside the repository".to_string()),
Some(rel) => match diff.hunk_range_at(diff.action_row()) {
None => Err("No change hunk at the cursor".to_string()),
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
}
}
}
/// Stage / Unstage / Revert Hunk from an editor tab (#1352): the hunk
/// whose change bar the caret is on, as a patch of the file on disk
/// against HEAD, the same pair the gutter's bars come from. Refused
/// with unsaved edits, since the patch is applied to the saved file.
fn editor_hunk_patch_at_caret(&mut self) -> Result<(String, String), &'static str> {
let Some(path) = self.editor.path.clone() else {
return Err("Hunk actions need a file in a git repository");
};
if self.editor.dirty {
return Err("Save the file first: hunk actions apply to the file on disk");
}
let row = self.editor.cursor_row;
let Some(mark) = self.editor.current_git_mark_at(row) else {
return Err("No change at the cursor");
};
let rel = self
.repo_relative_path(&path)
.ok_or("File is outside the repository")?;
let head = crate::git::read_file_at_head(&self.scm_root(), &rel)
.map_err(|_| "This file has no version in HEAD")?;
let disk = std::fs::read_to_string(&path).map_err(|_| "Could not read the file")?;
let data = crate::widgets::diff::DiffData::build_with_byte_check(
PathBuf::from(&rel),
path,
head.lines().map(str::to_string).collect(),
disk.lines().map(str::to_string).collect(),
Some(&head),
Some(&disk),
);
// The diff row showing this line; a deletion bar sits on the line
// after the removed run, so its hunk is the row just above.
use crate::widgets::diff::DiffRow;
let at = data
.rows
.iter()
.position(|r| match *r {
DiffRow::Equal { right, .. }
| DiffRow::Added { right }
| DiffRow::Replaced { right, .. } => right == row,
DiffRow::Removed { .. } => false,
})
.map(|i| {
if mark == crate::widgets::editor::GitMark::Deleted {
i.saturating_sub(1)
} else {
i
}
})
.ok_or("No change at the cursor")?;
let range = data.hunk_range_at(at).ok_or("No change at the cursor")?;
Ok((rel.clone(), data.hunk_patch(&rel, range)))
}
/// 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 diff = self.editor.diff.as_ref()?;
// Not UTF-8: left to the hunk path, which refuses it with a reason.
if !diff.left_is_git_head
|| diff.right_is_unsaved
|| diff.text_encoding != encoding_rs::UTF_8
{
return None;
}
let sel = diff.selection?;
if !sel.has_area() {
return None;
}
let rel = self.repo_relative_path(&diff.right_path)?;
let (start, end) = sel.normalized();
let patch = diff.selected_lines_patch(&rel, (start.0, end.0))?;
Some((rel, patch))
}
/// `path` relative to the repository top level, where `git apply` runs
/// (#139's convention). Relative to the WORKSPACE, a workspace opened on
/// `repo/sub` sent `x` for `sub/x`, and every hunk action failed or hit
/// a same-named file at the top level.
fn repo_relative_path(&self, path: &Path) -> Option<String> {
let root = self.scm_root();
let rel = match path.strip_prefix(&root) {
Ok(rel) => rel.to_path_buf(),
Err(_) => path
.canonicalize()
.ok()?
.strip_prefix(root.canonicalize().ok()?)
.ok()?
.to_path_buf(),
};
Some(
rel.components()
.map(|c| c.as_os_str().to_string_lossy())
.collect::<Vec<_>>()
.join("/"),
)
}
/// 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;
}
if diff.right_is_unsaved {
// The seat map is keyed on the saved file's lines (#1572).
self.status = String::from("Save the file first: group by seat reads the saved file");
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();
// Reverted from an editor tab (#1352): show the restored text
// now rather than on the next file-system sweep.
if self.editor.diff.is_none() && self.editor.reload_if_clean().is_some() {
self.sync_open_file_poll_mtime();
}
// 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();
}
}
/// The unsaved text of `path` in whichever editor group holds it dirty
/// (#1572): a split shows the same file in several groups, and the dirty
/// copy may sit in an inactive one while the active group's is clean.
fn unsaved_text_in_any_group(&self, path: &Path) -> Option<String> {
std::iter::once(&self.editor)
.chain(self.editor_layout.inactive_groups())
.find_map(|group| group.unsaved_text_of(path))
}
/// Open a two-file diff in the active group, each side's unsaved text
/// resolved across every editor group.
fn open_diff_across_groups(&mut self, left: &Path, right: &Path) -> anyhow::Result<()> {
let left_unsaved = self.unsaved_text_in_any_group(left);
let right_unsaved = self.unsaved_text_in_any_group(right);
self.editor
.open_diff_resolved(left, right, left_unsaved, right_unsaved)
}
/// 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;
// A rebuild reads the right side from disk: rows
// identical to an unsaved view mean the save landed,
// so hunk actions apply again (#1572).
cur.right_is_unsaved = fresh.right_is_unsaved;
}
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);
let staged = matches!(
entry.kind,
ChangeKind::StagedAdded
| ChangeKind::StagedModified
| ChangeKind::StagedDeleted
| ChangeKind::StagedRenamed
);
self.pending_discard = Some(PendingDiscard {
rel_path: entry.path,
untracked,
staged,
});
}
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, pd.staged) {
Ok(()) => {
self.status = format!("Discarded {}", pd.rel_path);
self.active_git_bypass_debounce();
self.refresh_git_status_debounced();
self.refresh_source_control();
}
Err(err) => {
let why = self.git_error_line("checkout -- (discard)", &err);
self.status = format!("Discard failed: {why}");
self.source_control.commit_feedback = Some(why);
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) {
if self.repo_git_busy() {
return;
}
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;
}
if self.hold_for_unsaved(ScmWrite::Commit) {
return;
}
let root = self.scm_root();
let committed = message.clone();
self.spawn_commit(
message,
move || crate::git::commit_all_tracked(&root, &committed),
|app, r| {
app.log_git("commit -am", &r);
match r {
Ok(summary) => {
let headline = crate::git::headline(&summary);
app.source_control.commit_feedback = Some(headline.to_string());
app.source_control.commit_feedback_is_error = false;
app.status = format!("Committed: {headline}");
app.active_git_bypass_debounce();
app.refresh_git_status_debounced();
app.refresh_source_control();
app.continue_rebase_after_commit();
}
Err(err) => app.report_commit_failure(&err),
}
},
);
}
/// Run a commit on the git worker (#1153). The repository's hooks
/// (pre-commit, commit-msg) can run for minutes; inline, the whole UI
/// froze until they ended and every key pressed meanwhile fired at once.
/// The message stays in the box until the commit lands, and is cleared
/// then only if it is still the one committed. `done` applies the
/// result on the UI thread.
fn spawn_commit(
&mut self,
message: String,
commit: impl FnOnce() -> Result<String, String> + Send + 'static,
done: impl FnOnce(&mut App, Result<String, String>) + Send + 'static,
) {
if self.git_net_busy() {
return;
}
self.spawn_git_net("commit", move || {
let r = commit();
Box::new(move |app: &mut App| {
if r.is_ok() && app.source_control.message.trim() == message.trim() {
app.source_control.clear_after_commit();
}
done(app, r)
})
});
let running = String::from("Committing\u{2026} (running hooks)");
self.source_control.commit_feedback = Some(running.clone());
self.source_control.commit_feedback_is_error = false;
self.status = running;
}
/// A refused `git commit` (#858): the panel and the status bar name why
/// on one line ("nothing to commit, working tree clean", not the "On
/// branch main" git prints first); the Git Output log has the rest.
fn report_commit_failure(&mut self, err: &str) {
let why = crate::git::error_line(err);
self.source_control.commit_feedback = Some(why.clone());
self.source_control.commit_feedback_is_error = true;
self.status = format!("Commit failed: {why}");
}
/// 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)");
let cwd_at_offer = self.pane_cwd_report(pane);
self.ssh_offer = Some(SshOffer {
pane,
host,
since: std::time::Instant::now(),
cwd_at_offer,
});
}
}
}
/// The pane's last OSC 7 report: its shell's directory and host.
fn pane_cwd_report(&self, pane: u64) -> Option<crate::remote::CwdReport> {
let term = self.terminals.iter().find(|t| t.uid() == pane)?;
Some((term.shell_cwd()?, term.shell_host()))
}
/// Take the open offer for launching (#364), clearing it: the host, and
/// the remote shell's directory when the pane reported one that can be
/// trusted to be on that host (see `remote::remote_workspace_path`).
fn accept_ssh_offer(&mut self) -> Option<(String, Option<String>)> {
let offer = self.ssh_offer.take()?;
if self.status.starts_with("Connected to ") {
self.status.clear();
}
let now = self.pane_cwd_report(offer.pane);
let path = crate::remote::remote_workspace_path(
&offer.host,
offer.cwd_at_offer.as_ref(),
now.as_ref(),
);
Some((offer.host, path))
}
/// 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, detail: &str) {
crate::output::push(
crate::output::CHANNEL_REMOTE,
crate::output::OutputLevel::Error,
&format!("Could not install croft on {host}: {detail}"),
);
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) {
crate::output::push(
crate::output::CHANNEL_REMOTE,
crate::output::OutputLevel::Info,
&format!("croft is installed on {host}; launching the remote workspace"),
);
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>) {
// The launch ends this croft once the remote one is up (#862).
self.guard_unsaved(UnsavedExit::RemoteLaunch { host, path });
}
fn start_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();
// The far side's OSC 7 report opens the workspace where the
// remote shell is. With no earlier report to tell a fresh one
// from a stale one, it is trusted only when it names this
// host; otherwise the login directory, as before.
let uid = self.terminals[self.active_terminal].uid();
let report = self.pane_cwd_report(uid);
let path =
crate::remote::remote_workspace_path(&alias, report.as_ref(), report.as_ref());
self.request_remote_launch(alias, path);
}
// 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,
}
}
/// Start the guided tour (#377) in a fresh scratch project, never the
/// user's workspace, and perform its first step.
pub fn start_demo(&mut self) {
// A second start would record the first tour's scratch project as
// the workspace to return to, and the user's own would be lost.
if self.tour.is_some() {
self.status = String::from("The tour is already running (Esc leaves it)");
return;
}
let tour = match crate::tour::Tour::parse(&crate::tour::tour_source()) {
Ok(t) => t,
Err(e) => {
self.status = format!("The tour could not start: {e}");
return;
}
};
// A tour ended by closing croft's terminal left its scratch folder
// behind (#863): clear those whose croft is gone before adding one.
let demo_dir = croft_cache_dir().join("demo");
crate::tour::sweep_dead_scratch(&demo_dir, process_is_alive);
let scratch = match crate::tour::create_scratch(&demo_dir) {
Ok(d) => d,
Err(e) => {
self.status = format!("The tour could not create its sample project: {e}");
return;
}
};
let previous_root = self.workspace_root().to_path_buf();
self.change_workspace_root(scratch.clone());
let first = tour.current().map(|s| s.action.clone());
self.tour = Some(TourRun {
tour,
scratch,
previous_root,
step_opened_modal: false,
});
if let Some(action) = first {
self.perform_tour_action(action);
}
}
/// Perform the next tour step, or finish after the last one.
pub fn advance_tour(&mut self) {
let Some(run) = self.tour.as_mut() else {
return;
};
match run.tour.advance().map(|s| s.action.clone()) {
Some(action) => self.perform_tour_action(action),
None => self.finish_tour(),
}
}
/// Leave the tour: back to the workspace it started from, and the
/// scratch project deleted.
pub fn finish_tour(&mut self) {
let Some(run) = self.tour.take() else {
return;
};
// Finished or skipped, the welcome panel stops offering it.
self.tour_done = true;
let _ = crate::prefs::save_tour_done_in(&self.config_dir);
// The sample's tabs go with it, edited or not: left open they name
// deleted files, and saving one would write a scratch file back.
let mut sample: Vec<PathBuf> = self
.open_tab_paths()
.into_iter()
.filter(|p| p.starts_with(&run.scratch))
.collect();
sample.dedup();
for path in sample {
self.close_tabs_with_path_everywhere(&path);
}
self.change_workspace_root(run.previous_root);
self.status = match crate::tour::remove_scratch(&run.scratch) {
Ok(()) => String::from("Tour finished"),
Err(e) => format!("Tour finished, but its sample project was not removed: {e}"),
};
}
fn perform_tour_action(&mut self, action: crate::tour::TourAction) {
use crate::tour::TourAction as A;
let Some(run) = self.tour.as_mut() else {
return;
};
run.step_opened_modal = matches!(
action,
A::QuickOpen | A::FindFile(_) | A::CommandPalette | A::Palette(_) | A::ThemePicker
);
let scratch = run.scratch.clone();
match action {
A::Open(rel) => {
if let Err(e) = self.open_at(&scratch.join(rel), 0, 0) {
self.status = format!("Tour: {e}");
}
}
A::QuickOpen => self.open_file_finder(),
A::FindFile(query) => {
self.open_file_finder();
if let Some(finder) = self.file_finder.as_mut() {
finder.set_query(&query);
}
}
A::SplitEditor => self.split_editor(),
A::Terminal => {
if !self.show_terminal {
self.toggle_terminal();
}
self.focus_pane(Pane::Terminal);
}
A::Run(cmd) => {
if !self.show_terminal {
self.toggle_terminal();
}
if let Some(term) = self.terminals.get_mut(self.active_terminal) {
term.write_input(format!("{cmd}\r").as_bytes());
}
}
A::JumpToError => {
let lines = self
.terminals
.get(self.active_terminal)
.map(|t| t.visible_lines().0)
.unwrap_or_default();
match crate::tour::first_error_ref(&lines) {
Some((file, line)) => {
let path = if std::path::Path::new(&file).is_absolute() {
PathBuf::from(file)
} else {
scratch.join(file)
};
let _ = self.open_at(&path, line.saturating_sub(1), 0);
}
// The command may still be running: open where the
// sample's mistake is, which is what it would find.
None => {
let _ = self.open_at(&scratch.join("app.py"), 3, 0);
}
}
}
A::CommandPalette => self.open_command_palette(),
A::Palette(query) => {
self.open_command_palette();
if let Some(palette) = self.command_palette.as_mut() {
palette.set_query(&query);
}
}
A::ThemePicker => self.open_theme_picker(),
A::Done => {}
}
}
/// The caption panel (#377): the step's caption, wrapped, over a row of
/// its own for the progress and the keys, above the status bar.
///
/// The keys have that row so no caption can push them off (#863): one
/// clamped line of progress, caption, then keys cut the keys first, and
/// at 80 columns every step lost them.
fn render_tour_caption(&mut self, frame: &mut ratatui::Frame) {
let Some((rect, caption)) = self.tour_caption_panel(frame.area()) else {
return;
};
let Some(run) = self.tour.as_ref() else {
return;
};
let style = Style::default()
.fg(self.theme.accent_contrast_fg())
.bg(self.theme.accent())
.add_modifier(Modifier::BOLD);
let body = Rect {
x: rect.x + 1,
width: rect.width.saturating_sub(2),
height: rect.height - 1,
..rect
};
let keys = Rect {
y: rect.bottom() - 1,
height: 1,
..body
};
frame.render_widget(ratatui::widgets::Clear, rect);
frame.render_widget(ratatui::widgets::Block::new().style(style), rect);
frame.render_widget(
Paragraph::new(caption).wrap(ratatui::widgets::Wrap { trim: true }),
body,
);
let progress = run.tour.progress();
let gap = (keys.width as usize)
.saturating_sub(progress.len() + Line::from(Self::TOUR_KEYS).width());
// Too narrow for both, the keys win: they are what moves the tour.
let row = if gap >= 2 {
Line::from(format!("{progress}{}{}", " ".repeat(gap), Self::TOUR_KEYS))
} else {
Line::from(Self::TOUR_KEYS).right_aligned()
};
frame.render_widget(Paragraph::new(row), keys);
}
/// The caption panel's key hint, on the panel's last row.
const TOUR_KEYS: &str = "Enter next \u{b7} Esc leave";
/// Where the tour's caption panel goes in `area`, with the caption it
/// shows: centred above the status bar, as tall as the wrapped caption
/// plus the keys row. A menu it would overlap moves it beside the menu
/// (#863): the theme picker a step opens stands the frame's full height
/// on the left, and covered the caption's start. `None` between steps,
/// or in a frame too small to hold it.
fn tour_caption_panel(&self, area: Rect) -> Option<(Rect, String)> {
let run = self.tour.as_ref()?;
let step = run.tour.current()?;
if area.width < 20 || area.height < 4 {
return None;
}
let caption = step.caption_text();
let status_h: u16 = if self.status_bar_visible { 1 } else { 0 };
let bottom = area.bottom().saturating_sub(status_h);
// As wide as the caption on one row, or as the keys row, within the
// columns `left..right`; a column of padding on each side.
let needed = Line::from(caption.as_str())
.width()
.max(run.tour.progress().len() + 2 + Line::from(Self::TOUR_KEYS).width())
+ 2;
let panel = |left: u16, right: u16| {
let room = right.saturating_sub(left);
let width = u16::try_from(needed).unwrap_or(u16::MAX).min(room);
let rows = Paragraph::new(caption.as_str())
.wrap(ratatui::widgets::Wrap { trim: true })
.line_count(width.saturating_sub(2)) as u16;
let height = rows.saturating_add(1).min(bottom.saturating_sub(area.y));
Rect {
x: left + (room - width) / 2,
y: bottom - height,
width,
height,
}
};
let mut rect = panel(area.x + 1, area.right() - 1);
if let Some(menu) = self.menu_rect()
&& menu.intersects(rect)
{
// The wider side of the menu, while it leaves a readable column;
// on a frame too narrow for that, the panel covers the menu.
let before = (area.x + 1, menu.x.saturating_sub(1));
let after = (menu.right() + 1, area.right() - 1);
let span = |(l, r): (u16, u16)| r.saturating_sub(l);
let side = if span(after) >= span(before) {
after
} else {
before
};
if span(side) >= 40 {
rect = panel(side.0, side.1);
}
}
Some((rect, caption))
}
/// Close every picker and palette a tour step may have opened.
#[cfg(test)]
pub fn close_all_modals_for_test(&mut self) {
self.command_palette = None;
self.file_finder = None;
self.context_menu = None;
}
/// 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);
self.scrub_view = None;
self.scrub_view_key = None;
self.tree.scrub_tree = None;
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, Enter opens a commit's version, Home returns to your working tree"
);
self.prefetch_scrub_views();
}
/// Keep symbol tabs (#369) and the other tabs of their files in step.
/// Runs once per tick; returns true when anything visible changed.
///
/// A symbol tab holds the whole file, as a split does, and like a split
/// it is a buffer of its own. So the tabs of a file that has a symbol tab
/// MIRROR each other here: the one edited since the last pass (the
/// focused one first, when several were) is copied into the rest, and
/// saving any of them clears the dirty dot on all. A file that is live in
/// a collab session is left to the session, which converges its panes
/// already. Then each symbol tab follows the edit so its clip stays on
/// its symbol, and closes once the symbol is gone (or, holding unsaved
/// text no whole-file tab holds, turns into a tab of the whole file).
pub(crate) fn sync_symbol_views(&mut self) -> bool {
let paths = self.symbol_view_paths();
if paths.is_empty() {
return false;
}
let mut changed = false;
for path in &paths {
if !self.symbol_path_is_live(path) {
changed |= self.mirror_symbol_siblings(path);
}
}
changed | self.follow_symbol_views()
}
/// Every path some symbol tab shows, once each.
fn symbol_view_paths(&self) -> Vec<PathBuf> {
let mut paths: Vec<PathBuf> = Vec::new();
for group in std::iter::once(&self.editor).chain(self.editor_layout.inactive_groups()) {
for ed in &group.editors {
if ed.symbol_view.is_some()
&& let Some(p) = ed.path.as_ref()
&& !paths.contains(p)
{
paths.push(p.clone());
}
}
}
paths
}
/// A file live in a collab session: its tabs follow the session, not
/// each other, so [`Self::sync_symbol_views`] leaves them alone.
fn symbol_path_is_live(&self, path: &Path) -> bool {
self.collab.as_ref().is_some_and(|session| {
collab_file_key(&self.tree.root, path).is_some_and(|f| session.is_live(&f))
})
}
/// Mirror the text tabs of `path` against each other; see
/// [`Self::sync_symbol_views`].
fn mirror_symbol_siblings(&mut self, path: &Path) -> bool {
let active = self.editor.active_index();
let mut members: Vec<(bool, &mut crate::widgets::editor::Editor)> = self
.editor
.editors
.iter_mut()
.enumerate()
.map(|(i, ed)| (i == active, ed))
.chain(
self.editor_layout
.inactive_groups_mut()
.into_iter()
.flat_map(|g| g.editors.iter_mut().map(|ed| (false, ed))),
)
.filter(|(_, ed)| ed.path.as_deref() == Some(path) && !ed.has_non_text_view())
.collect();
members.sort_by_key(|(focused, _)| !*focused);
let settled = members
.iter()
.all(|(_, ed)| ed.mirror_seq == Some(ed.edit_seq));
let mixed_dirty =
members.iter().any(|(_, ed)| ed.dirty) && members.iter().any(|(_, ed)| !ed.dirty);
if settled && !mixed_dirty {
return false;
}
// The source is a buffer edited since the last pass. A tab that has
// never been mirrored (`None`) may hold older text, such as a fresh
// open from disk beside unsaved edits, so it is a source only when
// nothing else can be.
let source = members
.iter()
.position(|(_, ed)| ed.mirror_seq.is_some_and(|seq| seq != ed.edit_seq))
.or_else(|| members.iter().position(|(_, ed)| ed.mirror_seq.is_some()))
.unwrap_or(0);
// Lent out for the pass rather than cloned: this runs after every
// editor key on a file with a symbol tab.
let lines = std::mem::take(&mut members[source].1.lines);
let step = members[source].1.undo_step_id;
let caret = (members[source].1.cursor_row, members[source].1.cursor_col);
let mut changed = false;
for (i, (_, ed)) in members.iter_mut().enumerate() {
if i != source {
changed |= ed.mirror_lines_from(&lines, step, caret);
}
}
members[source].1.lines = lines;
// Every member now holds the same text, so one that is clean (just
// saved, or undone back to its saved state) proves they all match
// the file on disk.
if members.iter().any(|(_, ed)| !ed.dirty) {
for (_, ed) in members.iter_mut().filter(|(_, ed)| ed.dirty) {
ed.mark_clean_like_sibling();
changed = true;
}
}
for (_, ed) in members.iter_mut() {
ed.mirror_seq = Some(ed.edit_seq);
}
changed
}
/// Move every symbol tab's clip with the edits since its last look, and
/// close the tabs whose symbol is gone, except an orphan with unsaved
/// text, which turns into a tab of the whole file.
fn follow_symbol_views(&mut self) -> bool {
let mut changed = false;
let mut notes: Vec<String> = Vec::new();
let mut follow = |ed: &mut crate::widgets::editor::Editor| -> bool {
let seq = ed.edit_seq;
if ed.symbol_view.as_ref().is_none_or(|v| v.seen_seq == seq) {
return false;
}
let kind = ed.path.as_deref().and_then(syntax_kind_of);
let text = ed.lines.join("\n");
// The caret that made the edit: a sibling's, mirrored in, or
// this tab's own. A collaborator's edit, applied and pinned as
// synced, has no caret here and is not this tab's own.
let caret = match ed.mirror_caret.take() {
Some((row, col)) => Some(crate::symbol_range::Caret {
row,
col,
own: false,
}),
None if ed.collab_doc_gen != 0 && ed.edit_seq == ed.collab_synced_seq => None,
None => Some(crate::symbol_range::Caret {
row: ed.cursor_row,
col: ed.cursor_col,
own: true,
}),
};
let Some(view) = ed.symbol_view.as_mut() else {
return false;
};
changed = true;
match view.follow(text, seq, kind, caret) {
crate::symbol_range::ViewUpdate::Kept => false,
crate::symbol_range::ViewUpdate::Renamed(old) => {
notes.push(format!("{old} is now {}", view.name));
false
}
crate::symbol_range::ViewUpdate::Gone => true,
}
};
let gone_here: Vec<usize> = (0..self.editor.editors.len())
.filter(|&i| follow(&mut self.editor.editors[i]))
.collect();
let mut gone_inactive: Vec<Vec<usize>> = Vec::new();
for group in self.editor_layout.inactive_groups_mut() {
gone_inactive.push(
(0..group.editors.len())
.filter(|&i| follow(&mut group.editors[i]))
.collect(),
);
}
// A gone symbol tab holding unsaved text that no tab of the whole
// file also holds (its file tab was closed) becomes that file tab
// instead of closing, or its edits, in and out of the clip, would
// be lost with it.
let mut kept_paths: Vec<PathBuf> = Vec::new();
// Said last, so the status (the last note) names the kept edits
// even when a sibling tab of the same symbol closed beside it.
let mut kept_notes: Vec<String> = Vec::new();
let mut keep = |ed: &mut crate::widgets::editor::Editor,
whole_file_open: &dyn Fn(&Path) -> bool|
-> bool {
let name = ed
.symbol_view
.as_ref()
.map(|v| v.name.clone())
.unwrap_or_default();
let orphan = ed.dirty
&& ed
.path
.as_deref()
.is_some_and(|p| !whole_file_open(p) && !kept_paths.iter().any(|k| k == p));
if orphan {
kept_paths.extend(ed.path.clone());
// Its mirror state stays: it is in step with its siblings
// (mirrored this pass, or left to the collab session), so
// its next edit is the source, not overwritten by them, and
// folds into the undo step it already has.
ed.drop_symbol_clip();
kept_notes.push(format!(
"{name} is gone; its tab now shows the whole file with the unsaved edits"
));
} else {
notes.push(format!("Closed the {name} tab: that symbol is gone"));
}
orphan
};
let any_gone = !gone_here.is_empty() || gone_inactive.iter().any(|g| !g.is_empty());
let whole_file_tabs: Vec<PathBuf> = if any_gone {
std::iter::once(&self.editor)
.chain(self.editor_layout.inactive_groups())
.flat_map(|g| g.editors.iter())
.filter(|e| e.symbol_view.is_none() && !e.has_non_text_view())
.filter_map(|e| e.path.clone())
.collect()
} else {
Vec::new()
};
let whole_file_open = |p: &Path| whole_file_tabs.iter().any(|w| w == p);
let gone_here: Vec<usize> = gone_here
.into_iter()
.filter(|&i| !keep(&mut self.editor.editors[i], &whole_file_open))
.collect();
for (g, group) in self
.editor_layout
.inactive_groups_mut()
.into_iter()
.enumerate()
{
gone_inactive[g].retain(|&i| !keep(&mut group.editors[i], &whole_file_open));
}
notes.extend(kept_notes);
for &i in gone_here.iter().rev() {
self.editor.close_tab(i);
}
// A group this emptied folds away, as closing its last tab by hand
// would; one the user left blank on purpose stays.
let pre_blank: Vec<bool> = self
.editor_layout
.inactive_groups()
.iter()
.map(|g| g.is_blank_initial())
.collect();
let mut doomed = Vec::new();
for (g, group) in self
.editor_layout
.inactive_groups_mut()
.into_iter()
.enumerate()
{
for &i in gone_inactive[g].iter().rev() {
group.close_tab(i);
}
if !gone_inactive[g].is_empty() && group.is_blank_initial() && !pre_blank[g] {
doomed.push(g);
}
}
if !doomed.is_empty() {
self.editor_layout.prune_inactive_at(&doomed);
}
if let Some(note) = notes.pop() {
self.status = note;
}
changed
}
/// The outline of the ACTIVE buffer: the Outline view's symbols when they
/// describe this file, else a tree-sitter outline of the live text (the
/// Outline may be hidden, or still waiting on its language server).
fn active_file_symbols(&self, path: &Path) -> Vec<crate::lsp::manager::OutlineSymbol> {
if self.outline.path() == Some(path) && !self.outline.symbols().is_empty() {
return self.outline.symbols().to_vec();
}
self.compute_syntax_outline(path)
}
/// 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 Some(path) = self.editor.path.clone() else {
self.status = String::from("Save this buffer before opening a symbol from it");
return;
};
let line = self.editor.cursor_row;
let symbols = self.active_file_symbols(&path);
let Some(sym) = crate::symbol_range::enclosing_symbol(&symbols, line as u32) 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, first, last) = (
sym.name.clone(),
sym.range_start_line as usize,
sym.range_end_line as usize,
);
self.open_symbol_tab_for(name, first, last);
}
/// Open lines `first..=last` of the active file as a symbol tab named
/// `name`, placed after the active tab, or focus the symbol tab already
/// showing that symbol, matched by its tree-sitter identity: two
/// symbols can start on one line, and pickers spell some symbols and
/// their first lines differently. The new tab starts from the live
/// buffer, unsaved edits included, and keeps the caret if it sits
/// inside the symbol.
pub(crate) fn open_symbol_tab_for(&mut self, name: String, first: usize, last: usize) {
let Some(path) = self.editor.path.clone() else {
self.status = String::from("Save this buffer before opening a symbol from it");
return;
};
if self.editor.has_non_text_view() {
self.status = String::from("Symbol tabs open from a text editor");
return;
}
let identity = crate::symbol_range::syntax_identity(
&self.editor.lines.join("\n"),
syntax_kind_of(&path),
&name,
first,
last,
);
if let Some(i) = self.editor.editors.iter().position(|ed| {
ed.path.as_deref() == Some(path.as_path())
&& ed
.symbol_view
.as_ref()
.is_some_and(|v| v.shows(&name, first, identity.as_ref()))
}) {
self.editor.select(i);
self.focus_pane(Pane::Editor);
return;
}
let lines = self.editor.lines.clone();
let dirty = self.editor.dirty;
let caret = (self.editor.cursor_row, self.editor.cursor_col);
if let Err(e) = self.editor.open_in_new_tab(&path) {
self.status = format!("Could not open {}: {e}", path.display());
return;
}
let kind = syntax_kind_of(&path);
let active = self.editor.active_index();
let ed = &mut self.editor.editors[active];
if ed.lines != lines {
ed.seed_unsaved(lines, dirty);
}
let last = last.min(ed.lines.len().saturating_sub(1));
let first = first.min(last);
let view = crate::symbol_range::SymbolView::new(
name.clone(),
ed.lines.join("\n"),
first,
last,
ed.edit_seq,
kind,
);
ed.symbol_view = Some(view);
ed.preview = false;
if (first..=last).contains(&caret.0) {
(ed.cursor_row, ed.cursor_col) = caret;
} else {
(ed.cursor_row, ed.cursor_col) = (first, 0);
}
ed.scroll = first;
ed.clamp_to_symbol_view();
self.sync_open_file_poll_mtime();
self.focus_pane(Pane::Editor);
self.status = format!("Opened {name} as its own tab");
}
/// The status bar's kernel chip for the notebook in the editor (#355):
/// the kernel's name once it is up, and whether a cell is running.
/// `None` for any other file, or before a kernel has started.
fn notebook_kernel_chip(&self) -> Option<String> {
let run = self.notebook_kernels.get(self.editor.path.as_ref()?)?;
let name = run.kernel.as_deref()?;
Some(if run.running_indices().is_empty() {
format!(" kernel: {name} ")
} else {
format!(" kernel: {name} \u{b7} busy ")
})
}
/// 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()),
}
}
/// The open file's review context (#366): (repo root the `gh` calls run
/// in, the file, its repo-relative path, the branch's PR number), or
/// `None` with the reason in the status bar.
fn review_context(&mut self) -> Option<(PathBuf, PathBuf, String, String)> {
let (root, path, rel) = self.review_file_context()?;
let number = self.review_pr_number(&root)?;
Some((root, path, rel, number))
}
/// [`Self::review_context`] without the PR number, which costs a `gh`
/// call: the root, the file and its repo-relative path.
fn review_file_context(&mut self) -> Option<(PathBuf, PathBuf, String)> {
let Some(path) = self.editor.path.clone() else {
self.status = String::from("Open a file from the PR first");
return None;
};
// 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 None;
};
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 None;
};
// 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("/");
Some((root, path, rel))
}
/// Remember the PR under review, with the branch it belongs to.
fn set_review_pr(&mut self, root: PathBuf, number: String) {
self.review_pr_branch = self.git_worker_for_root(&root).status().branch.clone();
self.review_pr = Some((root, number));
}
/// The PR number for `root`'s branch, remembered for the write side, or
/// `None` with the reason in the status bar.
fn review_pr_number(&mut self, root: &Path) -> Option<String> {
// The PR already loaded for this root, when there is one: this runs
// on the UI thread for every comment and submit, and asking GitHub
// each time froze croft on a slow network or a gh auth prompt.
let branch = self.git_worker_for_root(root).status().branch.clone();
if let Some((r, number)) = &self.review_pr
&& r == root
&& branch.is_some()
&& branch == self.review_pr_branch
{
return Some(number.clone());
}
let out = bounded_output(
std::process::Command::new(&self.review_gh)
.args(["pr", "view", "--json", "number", "--jq", ".number"])
.current_dir(root),
std::time::Duration::from_secs(5),
);
let number = match out {
Some((status, stdout)) if status.success() => {
String::from_utf8_lossy(&stdout).trim().to_string()
}
_ => {
self.status = String::from("No PR for this branch — check it out first");
return None;
}
};
self.set_review_pr(root.to_path_buf(), number.clone());
Some(number)
}
/// Source Control: Export Comments to Pull Request (#368): the
/// navigator's notes (marked as AI-authored) and your pending comments,
/// previewed as a list before anything is posted.
fn open_export_comments(&mut self) {
let root = self.active_workspace_root();
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 prefix = self.review_ai_prefix.clone();
let mut comments = self.review_pending.clone();
let mut notes = Vec::new();
for (file, list) in &self.navigator_notes {
let Some(rel) = repo_relative(&repo_root, &self.tree.root.join(file)) else {
continue;
};
for (id, row, body) in list {
comments.push(crate::review_threads::PendingComment {
path: rel.clone(),
line: *row,
body: format!("{prefix}{body}"),
});
notes.push(*id);
}
}
// Unresolved sticky notes (#367), each with its author and replies.
let mut exported_notes = Vec::new();
for n in self.notes.live().filter(|n| !n.resolved) {
let Some(rel) = repo_relative(&repo_root, &self.tree.root.join(&n.file)) else {
continue;
};
let lines = std::fs::read_to_string(self.tree.root.join(&n.file))
.map(|t| t.lines().map(str::to_string).collect::<Vec<_>>())
.unwrap_or_default();
comments.push(crate::review_threads::PendingComment {
path: rel,
line: n.place(&lines),
body: format!("{}: {}", n.author, n.text()),
});
exported_notes.push(n.id.clone());
}
self.review_export_sticky = exported_notes;
if comments.is_empty() {
self.status = String::from("No comments to export");
return;
}
comments.sort_by(|a, b| (&a.path, a.line).cmp(&(&b.path, b.line)));
// Finding the PR and reading its diff are `gh` calls, which can take
// as long as the network does: off the frame loop, the preview
// opens when they answer.
crate::review_ops::spawn(
self.review_gh.clone(),
root,
crate::review_ops::Job::ExportPreview { comments, notes },
self.review_tx.clone(),
);
self.status = String::from("Preparing the export\u{2026}");
}
/// Open the export preview once its PR and diff are known.
fn show_export_ready(
&mut self,
root: PathBuf,
number: String,
comments: Vec<crate::review_threads::PendingComment>,
notes: Vec<u64>,
inline: usize,
) {
self.set_review_pr(root.clone(), number.clone());
self.review_export_pr = Some((root, number.clone()));
let mut rows = vec![crate::widgets::list_picker::ListRow {
id: String::from("post"),
label: format!(
"Post to PR #{number}: {inline} inline, {} in the summary",
comments.len() - inline
),
}];
rows.extend(comments.iter().enumerate().map(|(i, c)| {
crate::widgets::list_picker::ListRow {
id: format!("c{i}"),
label: format!(
" {}:{} {}",
c.path,
c.line + 1,
c.body.lines().next().unwrap_or_default()
),
}
}));
self.review_export = Some((comments, notes, rows));
self.show_export_preview();
}
fn show_export_preview(&mut self) {
let Some((_, _, rows)) = &self.review_export else {
return;
};
let rows = rows.clone();
self.open_list_picker(
crate::widgets::list_picker::ListPicker::new(
crate::widgets::list_picker::ListPurpose::ExportComments,
"Export Comments to Pull Request",
rows,
),
"",
);
}
/// Post the previewed export as a Comment review.
fn post_exported_comments(&mut self) {
let Some((comments, notes, _)) = self.review_export.take() else {
return;
};
let Some((root, number)) = self.review_export_pr.take() else {
return;
};
let sticky = std::mem::take(&mut self.review_export_sticky);
if !self.pending_is_for(&root, &number) {
return;
}
if self.review_submitting {
self.status = String::from("A review is already being submitted");
return;
}
let pending: Vec<_> = self
.review_pending
.iter()
.filter(|c| comments.contains(c))
.cloned()
.collect();
crate::review_ops::spawn(
self.review_gh.clone(),
root,
crate::review_ops::Job::Submit {
number,
event: crate::review_threads::ReviewEvent::Comment,
summary: String::new(),
pending: comments,
settles: crate::review_ops::Settles {
notes,
sticky,
pending,
},
},
self.review_tx.clone(),
);
self.review_submitting = true;
self.status = String::from("Posting comments…");
}
/// 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((root, path, rel)) = self.review_file_context() else {
return;
};
// `gh` over the network, several calls for a big PR: off the frame
// loop. The threads come back keyed to `path`, the file asked about.
crate::review_ops::spawn(
self.review_gh.clone(),
root,
crate::review_ops::Job::LoadThreads { path, rel },
self.review_tx.clone(),
);
self.status = String::from("Loading review comments\u{2026}");
}
/// Show threads read by [`Self::load_review_threads`].
fn show_review_threads(
&mut self,
root: PathBuf,
number: String,
path: PathBuf,
rel: String,
mut threads: Vec<crate::review_threads::Thread>,
states: std::collections::HashMap<u64, (String, bool)>,
) {
self.set_review_pr(root, number);
for t in &mut threads {
if let Some((node, resolved)) = states.get(&t.id) {
t.resolved = *resolved;
self.review_nodes.insert(t.id, node.clone());
}
}
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 file the `gh` query was about, carried through the
// worker, not whatever `editor.path` says now: the user may have
// switched tabs while it ran.
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 mut known: Vec<String> = crate::remote::discover_ssh_targets()
.into_iter()
.map(|t| t.alias)
.collect();
let no_ssh_hosts = known.is_empty();
// `localhost` and running containers can be named explicitly; `*`
// still means the ssh hosts only (see `parse_request_with_groups`).
known.extend(crate::fleet::local_targets_in(command, &self.fleet_groups));
if no_ssh_hosts
&& !crate::fleet::split_request(command).is_some_and(|(spec, _)| {
spec.split(',')
.any(|n| crate::fleet::is_local_target(n.trim()))
})
{
self.status = String::from(
"No hosts in ~/.ssh/config to run on (localhost and docker:<container> work too)",
);
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 (picked, command) =
match crate::fleet::parse_request_with_groups(command, &known, &self.fleet_groups) {
Ok(parsed) => parsed,
Err(refusal) => {
self.status = refusal.message(&known);
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_command = command.clone();
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}] ({:.1}s) {}",
r.host,
r.elapsed.as_secs_f64(),
r.output.replace('\n', " ")
),
);
// A differing host lists the lines that differ from the
// reference, so the row says WHAT differs, not only that
// something does.
if mark == "DIFFERS"
&& let Some(reference) = reference.as_deref()
{
for line in crate::fleet::differing_lines(reference, &r.output) {
crate::output::push(
crate::output::CHANNEL_FLEET,
crate::output::OutputLevel::Info,
&format!(" {line}"),
);
}
}
}
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());
// The tiles (#363); OUTPUT keeps the text record above.
self.editor
.open_fleet(crate::widgets::fleet::FleetView::new(
self.fleet_command.clone(),
results,
));
self.focus_pane(Pane::Editor);
}
true
}
/// FLEET tab keys (#363).
fn handle_fleet_key(&mut self, key: KeyEvent) {
let Some(view) = self.editor.fleet.as_mut() else {
return;
};
let cols = view.columns.max(1) as isize;
match key.code {
KeyCode::Left | KeyCode::Char('h') => view.move_selection(-1),
KeyCode::Right | KeyCode::Char('l') => view.move_selection(1),
KeyCode::Up | KeyCode::Char('k') => view.move_selection(-cols),
KeyCode::Down | KeyCode::Char('j') => view.move_selection(cols),
KeyCode::Char('d') => view.diff_mode = !view.diff_mode,
KeyCode::Char('r') => {
view.toggle_reference();
self.status = match &view.reference_host {
Some(h) => format!("Fleet: comparing with {h}"),
None => String::from("Fleet: comparing with the most common output"),
};
}
KeyCode::Char('s') => self.save_fleet_capture(),
KeyCode::Enter => self.open_fleet_shell(),
KeyCode::Esc | KeyCode::Char('q') => {
self.editor.close_active();
self.status = String::from("Closed the fleet results");
}
_ => {}
}
}
/// Save the fleet tab's run to `fleet-<time>.txt` in the workspace
/// (#363): the command, the summary and every host's full output.
fn save_fleet_capture(&mut self) {
let Some(view) = self.editor.fleet.as_ref() else {
return;
};
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!("fleet-{stamp}.txt"));
self.status = match std::fs::write(&path, view.capture()) {
Ok(()) => format!("Fleet run saved to {}", path.display()),
Err(e) => format!("Could not save the fleet run: {e}"),
};
}
/// "Open shell here" (#363): a terminal pane on the selected tile's
/// host: `ssh` for a host, a shell for localhost, `docker exec` for a
/// container. Typed into a fresh pane so the user sees what runs.
fn open_fleet_shell(&mut self) {
let Some(host) = self
.editor
.fleet
.as_ref()
.and_then(|v| v.selected_result())
.map(|r| r.host.clone())
else {
return;
};
let command = fleet_shell_command(&host);
match crate::widgets::terminal::PtyTerminal::new(self.workspace_root()) {
Ok(mut term) => {
term.set_manual_name(Some(host.clone()));
if let Some(cmd) = command {
term.write_input(format!("{cmd}\r").as_bytes());
}
self.insert_terminal(term);
self.show_terminal = true;
self.focus_pane(Pane::Terminal);
self.status = format!("Shell on {host}");
}
Err(e) => self.status = format!("Could not open a terminal: {e}"),
}
}
/// 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(),
// Enter at a commit opens that version as a tab of its own; at
// the working tree there is nothing to open, so it passes
// through to the live buffer like any other typing.
KeyCode::Enter if scrub.commit().is_some() => {
self.scrub_open_here();
return true;
}
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.scrub_view = None;
self.scrub_view_key = None;
self.scrub_views.clear();
self.scrub_plain.clear();
self.scrub_outlines.clear();
self.scrub_builder = None;
self.sync_scrub_tree();
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"),
};
self.rebuild_scrub_view();
true
}
/// The active file at the scrubber's commit (#371): its path, its
/// workspace-relative name, the commit, and its text there (`None` when
/// the file did not exist yet). `None` with a status line when there is
/// no scrubbed commit or no file to show.
fn scrubbed_file(
&mut self,
) -> Option<(
PathBuf,
String,
crate::git::GraphCommit,
Option<std::sync::Arc<str>>,
)> {
let Some(commit) = self.scrubber.as_ref().and_then(|s| s.commit()).cloned() else {
self.status = String::from("Step the scrubber to a commit first");
return None;
};
let Some(path) = self.editor.path.clone() else {
self.status = String::from("No file is open to scrub");
return None;
};
let root = self.workspace_root().to_path_buf();
let Ok(rel) = path
.strip_prefix(&root)
.map(|p| p.to_string_lossy().into_owned())
else {
self.status = String::from("The open file is outside the workspace");
return None;
};
let text = self
.scrub_cache
.entry((commit.hash.clone(), rel.clone()))
.or_insert_with(|| {
crate::git::read_file_at_rev(&root, &commit.hash, &rel)
.ok()
.map(std::sync::Arc::from)
})
.clone();
Some((path, rel, commit, text))
}
/// Leave the scrubber for a tab that shows what it was showing.
fn close_scrubber_for_tab(&mut self) {
self.scrubber = None;
self.scrub_view = None;
self.scrub_view_key = None;
self.scrub_views.clear();
self.scrub_plain.clear();
self.scrub_outlines.clear();
self.scrub_builder = None;
self.sync_scrub_tree();
self.focus_pane(Pane::Editor);
}
/// **Open here** (#371): the scrubbed version of the file as a normal
/// tab, highlighted as its language, labelled with the commit. It has no
/// file on disk behind it, so nothing reloads or overwrites it.
fn scrub_open_here(&mut self) {
let Some((path, rel, commit, text)) = self.scrubbed_file() else {
return;
};
let Some(text) = text else {
self.status = format!("{rel} did not exist at {}", commit.short_hash);
return;
};
let label = PathBuf::from(format!("{rel} @ {}", commit.short_hash));
if let Err(e) = self.editor.open_text_buffer(&label, &text) {
self.status = format!("Could not open {rel} at {}: {e}", commit.short_hash);
return;
}
// Highlighting only: no language server hears about a tab with no
// file behind it.
self.editor
.set_language(crate::highlight::lang_for_path(&path));
self.close_scrubber_for_tab();
self.status = format!("{rel} at {} — {}", commit.short_hash, commit.summary);
}
/// **Diff to working tree** (#371): the scrubbed version against the
/// working copy (its open tab's unsaved edits, else the file on disk),
/// in the side-by-side diff.
fn scrub_diff_to_working_tree(&mut self) {
let Some((path, rel, commit, text)) = self.scrubbed_file() else {
return;
};
let label = PathBuf::from(format!("{rel} @ {}", commit.short_hash));
let unsaved = self.unsaved_text_in_any_group(&path);
// A file the commit predates diffs as all added, which is what
// happened to it since.
let text = text.unwrap_or_default();
if let Err(e) = self
.editor
.open_head_diff_with_text_resolved(label, &text, &path, false, unsaved)
{
self.status = format!("Could not diff {rel}: {e}");
return;
}
self.tag_open_diff(crate::widgets::diff::DiffSource::FixedLeft {
left_text: text.to_string(),
});
self.close_scrubber_for_tab();
self.status = format!("{rel}: {} → working tree", commit.short_hash);
}
/// Seek the scrubber to the stop under screen column `col` on the
/// slider, and show that commit.
fn scrub_seek_column(&mut self, col: u16) {
let track = self.scrub_slider;
if track.width == 0 {
return;
}
let Some(scrub) = self.scrubber.as_mut() else {
return;
};
let span = track.width.saturating_sub(1).max(1) as f32;
let f = (col.saturating_sub(track.x) as f32 / span).clamp(0.0, 1.0);
let before = scrub.position();
scrub.seek_fraction(f);
if scrub.position() == before {
return;
}
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"),
};
self.rebuild_scrub_view();
}
/// The history scrubber's slider (#371), on the editor body's last row
/// while scrubbing: where the cursor is (a commit's short hash and its
/// place in the history, or the working tree), then a track from the
/// oldest loaded commit on the left to the working tree on the right,
/// with the handle where the view is.
fn render_scrub_slider(&mut self, frame: &mut ratatui::Frame) {
self.scrub_slider = Rect::default();
let Some(scrub) = self.scrubber.as_ref() else {
return;
};
let body = self.editor.last_body;
if body.width < 20 || body.height < 2 {
return;
}
let row = Rect {
x: body.x,
y: body.y + body.height - 1,
width: body.width,
height: 1,
};
let label = match (scrub.position(), scrub.commit()) {
(crate::scrubber::Position::At(i), Some(c)) => {
format!(" {} {}/{} ", c.short_hash, scrub.len() - i, scrub.len())
}
_ => String::from(" working tree "),
};
let label_w = (label.chars().count() as u16).min(row.width / 2);
let track = Rect {
x: row.x + label_w + 1,
y: row.y,
width: row.width.saturating_sub(label_w + 2),
height: 1,
};
let bar_bg = self.theme.ui(Color::Rgb(0x1c, 0x21, 0x2b));
let buf = frame.buffer_mut();
buf.set_style(row, Style::default().bg(bar_bg));
buf.set_stringn(
row.x,
row.y,
&label,
label_w as usize,
Style::default()
.fg(self.theme.accent())
.bg(bar_bg)
.add_modifier(Modifier::BOLD),
);
let handle = (scrub.fraction() * track.width.saturating_sub(1) as f32).round() as u16;
for dx in 0..track.width {
let (sym, fg) = if dx == handle {
("\u{25cf}", self.theme.accent())
} else {
("\u{2500}", self.theme.ui(Color::Rgb(0x5a, 0x63, 0x73)))
};
buf.set_string(
track.x + dx,
track.y,
sym,
Style::default().fg(fg).bg(bar_bg),
);
}
self.scrub_slider = track;
}
/// While a commit is on screen (#371), an Outline or breadcrumb jump
/// lands in the historical view, whose symbols they list, not in the
/// hidden live buffer. Returns whether it did.
fn jump_in_scrub_view(&mut self, line: u32) -> bool {
let Some(view) = self.scrub_view.as_mut() else {
return false;
};
let line = (line as usize).min(view.lines.len().saturating_sub(1));
view.cursor_row = line;
view.cursor_col = 0;
let rows = (self.editor.last_body.height as usize).max(1);
view.scroll = line.saturating_sub(rows / 3);
true
}
/// Point the Explorer's dimming at the scrubber's commit (#371), or
/// clear it at the working tree and once the scrubber closes. The tree
/// listing is cached per commit like the file text, so stepping back
/// over a visited commit costs no git process.
fn sync_scrub_tree(&mut self) {
let Some(commit) = self.scrubber.as_ref().and_then(|s| s.commit()) else {
self.tree.scrub_tree = None;
return;
};
let root = self.workspace_root().to_path_buf();
let present = self
.scrub_trees
.entry(commit.hash.clone())
.or_insert_with(|| crate::git::tree_paths(&root, &commit.hash).map(std::sync::Arc::new))
.clone();
self.tree.scrub_tree = present.map(|set| (root, set));
}
/// Build the read-only view of the active file at the scrubber's commit
/// (#371), or drop it at the working tree. File text is cached per
/// (commit, path), so stepping back and forth after the first visit
/// costs no git process.
fn rebuild_scrub_view(&mut self) {
self.sync_scrub_tree();
self.scrub_for = self.editor.path.clone();
// Read before the view is parked: the next one looks where it did.
let anchor = self.scrub_view_anchor();
self.park_scrub_view();
let Some(commit) = self.scrubber.as_ref().and_then(|s| s.commit()).cloned() else {
self.scrub_view = None;
self.scrub_view_key = None;
// At the working tree: have the first steps back ready.
self.prefetch_scrub_views();
return;
};
let Some(path) = self.editor.path.clone() else {
self.scrub_view = None;
self.scrub_view_key = None;
return;
};
let root = self.workspace_root().to_path_buf();
let Ok(rel) = path
.strip_prefix(&root)
.map(|p| p.to_string_lossy().into_owned())
else {
self.scrub_view = None;
self.scrub_view_key = None;
return;
};
let key = crate::scrubber::ViewKey {
hash: commit.hash.clone(),
rel: rel.clone(),
};
// A finished view when one is ready; otherwise a plain stand-in (the
// builder keeps those ready around the cursor) and the finished view
// when it lands, so a step never waits on highlighting a big file.
let take = |kept: &mut crate::scrubber::KeptViews| {
kept.iter()
.position(|(k, _)| *k == key)
.and_then(|i| kept.remove(i))
.map(|(_, v)| v)
};
let (view, finished) = match take(&mut self.scrub_views) {
Some(v) => (Some(v), true),
None => (take(&mut self.scrub_plain), false),
};
// Neither ready (the first step, or a jump): build the stand-in here.
let view = view.or_else(|| {
let text = self
.scrub_cache
.entry((commit.hash.clone(), rel.clone()))
.or_insert_with(|| {
crate::git::read_file_at_rev(&root, &commit.hash, &rel)
.ok()
.map(std::sync::Arc::from)
})
.clone();
Some(crate::scrubber::plain_view(
&path,
&rel,
&commit.short_hash,
text.as_deref(),
))
});
let Some(mut view) = view else { return };
Self::align_scrub_view(&mut view, anchor);
self.scrub_view = Some(view);
self.scrub_view_key = Some((key, finished));
self.request_scrub_views(&root, &path, &rel);
}
/// Put the finished view being left back among the kept ones, so
/// stepping back to it is free; drop the least recently used beyond
/// `SCRUB_VIEWS_KEPT` (a big file's view holds its whole text and
/// highlighting).
fn park_scrub_view(&mut self) {
let Some((key, finished)) = self.scrub_view_key.take() else {
return;
};
let Some(view) = self.scrub_view.take() else {
return;
};
if finished {
self.keep_scrub_view(key, view);
} else {
Self::keep_view(&mut self.scrub_plain, key, view);
}
}
fn keep_scrub_view(
&mut self,
key: crate::scrubber::ViewKey,
view: crate::widgets::editor::Editor,
) {
// Its stand-in is no longer needed.
if let Some(i) = self.scrub_plain.iter().position(|(k, _)| *k == key)
&& let Some(stale) = self.scrub_plain.remove(i)
{
fs_watch::offload_drop(stale);
}
Self::keep_view(&mut self.scrub_views, key, view);
}
/// Keep `view` as the most recently used in `kept`, dropping the least
/// recently used beyond `SCRUB_VIEWS_KEPT`. Dropped off the UI thread:
/// a big file's view is tens of thousands of strings, and freeing them
/// is a frame's worth of work a held arrow key cannot spare.
fn keep_view(
kept: &mut crate::scrubber::KeptViews,
key: crate::scrubber::ViewKey,
view: crate::widgets::editor::Editor,
) {
if let Some(i) = kept.iter().position(|(k, _)| *k == key)
&& let Some(old) = kept.remove(i)
{
fs_watch::offload_drop(old);
}
kept.push_back((key, view));
while kept.len() > SCRUB_VIEWS_KEPT {
if let Some(evicted) = kept.pop_front() {
fs_watch::offload_drop(evicted);
}
}
}
/// Request the views around the cursor for the active file, when it is
/// one the scrubber can show.
fn prefetch_scrub_views(&mut self) {
let Some(path) = self.editor.path.clone() else {
return;
};
let root = self.workspace_root().to_path_buf();
let Ok(rel) = path
.strip_prefix(&root)
.map(|p| p.to_string_lossy().into_owned())
else {
return;
};
self.request_scrub_views(&root, &path, &rel);
}
/// Where a new view of the active file should look: where the view on
/// screen was looking (a symbol jump moves it), else where the live
/// buffer is. `(scroll, cursor_row)`.
fn scrub_view_anchor(&self) -> (usize, usize) {
match self.scrub_view.as_ref() {
Some(prev) if prev.path.is_some() && prev.path == self.editor.path => {
(prev.scroll, prev.cursor_row)
}
_ => (self.editor.scroll, self.editor.cursor_row),
}
}
/// Look at the stretch of the file `anchor` names.
fn align_scrub_view(view: &mut crate::widgets::editor::Editor, (scroll, row): (usize, usize)) {
let last = view.lines.len().saturating_sub(1);
view.scroll = scroll.min(last);
view.cursor_row = row.min(last);
}
/// Ask the builder for what the commits around the cursor still lack:
/// stand-ins for the ones with neither a stand-in nor a finished view,
/// and finished views for the ones without one; most urgent first.
fn request_scrub_views(&mut self, root: &Path, path: &Path, rel: &str) {
let Some(scrub) = self.scrubber.as_ref() else {
return;
};
let jobs: Vec<crate::scrubber::ViewJob> = scrub
.around()
.into_iter()
.map(|c| crate::scrubber::ViewJob {
key: crate::scrubber::ViewKey {
hash: c.hash.clone(),
rel: rel.to_string(),
},
path: path.to_path_buf(),
short: c.short_hash.clone(),
parent: c.parents.first().cloned(),
text: self
.scrub_cache
.get(&(c.hash.clone(), rel.to_string()))
.cloned(),
parent_text: c
.parents
.first()
.and_then(|p| self.scrub_cache.get(&(p.clone(), rel.to_string())).cloned()),
})
.collect();
let shown = self.scrub_view_key.as_ref();
let has_finished = |key: &crate::scrubber::ViewKey| {
self.scrub_views.iter().any(|(k, _)| k == key)
|| shown.is_some_and(|(k, f)| k == key && *f)
};
let has_plain = |key: &crate::scrubber::ViewKey| {
self.scrub_plain.iter().any(|(k, _)| k == key) || shown.is_some_and(|(k, _)| k == key)
};
let finished: Vec<crate::scrubber::ViewJob> = jobs
.iter()
.filter(|j| !has_finished(&j.key))
.cloned()
.collect();
let plain: Vec<crate::scrubber::ViewJob> = jobs
.into_iter()
.filter(|j| !has_finished(&j.key) && !has_plain(&j.key))
.collect();
let builder = self
.scrub_builder
.get_or_insert_with(|| crate::scrubber::ViewBuilder::start(root.to_path_buf()));
builder.want(plain, finished);
}
/// Take in what the builder produced (#371): keep each view, and swap a
/// finished one in for the stand-in on screen. True when the screen
/// changed.
pub fn drain_scrub_views(&mut self) -> bool {
let Some(builder) = self.scrub_builder.as_ref() else {
return false;
};
let built = builder.drain();
let mut changed = false;
for b in built {
let rel = b.key.rel.clone();
self.scrub_cache
.entry((b.key.hash.clone(), rel.clone()))
.or_insert(b.text);
if let Some((parent, text)) = b.parent_text {
self.scrub_cache.entry((parent, rel)).or_insert(text);
}
if let Some(outline) = b.outline {
// Symbols are small next to a view, but a long session visits
// many commits: keep a bounded set.
if self.scrub_outlines.len() >= SCRUB_OUTLINES_KEPT {
self.scrub_outlines.clear();
}
self.scrub_outlines.insert(b.key.clone(), outline);
changed = true;
}
let mut view = b.view;
let on_screen = self.scrubber.is_some()
&& self.scrub_view.is_some()
&& self
.scrub_view_key
.as_ref()
.is_some_and(|(k, _)| *k == b.key);
if b.finished {
if on_screen && matches!(self.scrub_view_key, Some((_, false))) {
Self::align_scrub_view(&mut view, self.scrub_view_anchor());
if let Some(stand_in) = self.scrub_view.replace(view) {
fs_watch::offload_drop(stand_in);
}
self.scrub_view_key = Some((b.key, true));
changed = true;
} else if on_screen {
fs_watch::offload_drop(view);
} else {
self.keep_scrub_view(b.key, view);
}
} else if !on_screen && !self.scrub_views.iter().any(|(k, _)| *k == b.key) {
Self::keep_view(&mut self.scrub_plain, b.key, view);
} else {
fs_watch::offload_drop(view);
}
}
changed
}
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,
));
crate::output::push(
crate::output::CHANNEL_REMOTE,
crate::output::OutputLevel::Info,
&format!(
"Preparing croft on {host}: checking for an install, provisioning if missing"
),
);
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 launch = RemoteLaunch {
host: session.host.clone(),
path: session.path.clone(),
adopted: Some(adopted),
};
self.hand_off_to_remote(launch);
}
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, &detail);
}
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 launch = RemoteLaunch {
host: session.host.clone(),
path: session.path.clone(),
adopted: Some(adopted),
};
self.hand_off_to_remote(launch);
}
changed = true;
}
changed
}
/// The croft on the remote is ready: quit so the terminal goes to it
/// (the main loop launches `launch` once this one has let go). The quit
/// ends this croft, so edits made since the connect was asked for are
/// asked about first (#862); what the user already chose to leave then
/// goes without asking again.
fn hand_off_to_remote(&mut self, launch: RemoteLaunch) {
let host = launch.host.clone();
self.note_provisioning_succeeded(&host);
self.remote_launch = Some(launch);
self.status = format!("Launching croft on {host}");
self.connect_dialog = None;
let handoff = UnsavedExit::RemoteHandoff { host };
let left_as_agreed = self
.remote_handoff_ok
.take()
.is_some_and(|ok| Some(ok) == self.unsaved_stamp());
if left_as_agreed {
self.finish_unsaved_exit(handoff);
} else {
self.guard_unsaved(handoff);
}
}
/// 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,
));
}
/// Stop the language servers while croft compiles itself on this host,
/// and start them again once it is done (#694).
///
/// The remote source build writes a marker while it runs. On an 8 GB
/// host a compile next to rust-analyzer exhausted memory, and the OOM
/// killer then took whatever was largest — croft, or a terminal pane.
/// Only a remote-launched croft watches: the build is the fallback of
/// `croft remote`'s update, and a local croft never runs one under it.
fn poll_source_build_marker(&mut self) -> bool {
if self.update_watch.is_none() {
return false;
}
let now = std::time::Instant::now();
if self
.build_marker_checked
.is_some_and(|t| now.duration_since(t) < std::time::Duration::from_secs(1))
{
return false;
}
self.build_marker_checked = Some(now);
let building = crate::update_watch::source_build_running(
&croft_cache_dir(),
crate::update_watch::boot_id,
crate::update_watch::boot_time,
process_is_alive,
);
self.apply_source_build_state(building)
}
/// Pause or resume the language servers for a source build that has
/// started (`true`) or ended (`false`). Split from the polling so tests
/// drive it without a marker file or the 1 Hz gate.
fn apply_source_build_state(&mut self, building: bool) -> bool {
match (building, self.lsp_paused_for_build) {
(true, false) => {
// Nothing running is nothing to pause, and nothing to restart
// later either: a manager that failed to start stays down.
if self.lsp.is_none() {
return false;
}
// Dropping the manager shuts its servers down, which is what
// frees the memory. Its Drop waits up to 3 s for them, so it
// runs off the UI thread: nothing the user did asked for a
// freeze (the build script waits long enough for it).
if let Some(old) = self.lsp.take() {
fs_watch::offload_drop(old);
}
self.lsp_paused_for_build = true;
// A format-on-save in flight dies with the manager, and its
// armed save would otherwise fire on some later, unrelated
// format reply. Save now, unformatted, as when a reply fails.
if self.format_request_id.take().is_some() {
self.complete_pending_save();
}
// Re-open every tab against the servers that come back. The
// diagnostics are kept: they are still the best answer until
// the restarted servers publish fresh ones.
self.lsp_last_seen.clear();
self.lsp_progress.clear();
let msg = "Language servers stopped while croft builds its update on this host";
crate::output::push("Language Servers", crate::output::OutputLevel::Info, msg);
self.status = String::from(msg);
true
}
(false, true) => {
self.lsp_paused_for_build = false;
self.lsp = match crate::lsp::LspManager::new(self.workspace_root().to_path_buf()) {
Ok(m) => {
m.set_extra_roots(
self.roots.iter().skip(1).map(Path::to_path_buf).collect(),
);
crate::output::push(
"Language Servers",
crate::output::OutputLevel::Info,
"Update build finished; language servers restarted",
);
Some(m)
}
Err(e) => {
let msg = format!("Language servers could not restart: {e}");
crate::output::push(
"Language Servers",
crate::output::OutputLevel::Error,
&msg,
);
self.status = msg;
None
}
};
self.lsp_last_seen.clear();
self.lsp_progress.clear();
// The new manager numbers semantic replies from 0 again; the
// old high-water marks would reject every reply for a file
// until the new count caught up with the old one.
self.semantic_generation_seen.clear();
// A tab closed during the pause was never in `lsp_last_seen`
// again, so nothing would drop its diagnostics: drop what no
// open buffer owns. That includes workspace-scope diagnostics
// for files never opened, which the old servers published
// unasked; the new servers publish those again as they index,
// and until then keeping them would show findings nothing can
// retract.
let open = self.open_buffer_paths();
self.lsp_diagnostics.retain(|p, _| open.contains(p));
self.rebuild_problems();
true
}
_ => false,
}
}
/// 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,
failed: None,
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) {
// Homebrew owns a Cellar binary (#375): staging and swapping it
// would leave brew's records describing a file croft replaced.
if self.install_source == crate::update_check::InstallSource::Homebrew {
self.status = format!(
"croft v{version} is available - this install is managed by Homebrew: run `{}`",
crate::update_check::BREW_UPGRADE
);
return;
}
self.staged_status = UpdateStatus::Idle;
if let Some(t) = self.update_toast.as_mut() {
t.failed = None;
}
// Tests never download or build croft: they get a staging that has
// only started.
#[cfg(test)]
{
self.staged_install = Some(crate::update_check::StagedInstall::preloaded(
&[],
PathBuf::new(),
&version,
));
}
#[cfg(not(test))]
{
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 the updater chord 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 {UPDATE_CROFT_CHORD} 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 "Ctrl+Shift+F9 to relaunch" flow
/// a remote background update uses.
fn start_local_reinstall(&mut self) {
// Tests take the offer too, and must never `cargo install` croft
// over the one on PATH: they get an install that has only started.
#[cfg(test)]
{
self.self_install = Some(crate::update_watch::SelfInstall::preloaded(&[]));
}
#[cfg(not(test))]
{
self.self_install = Some(crate::update_watch::SelfInstall::start(
String::from(env!("CARGO_MANIFEST_DIR")),
self_install_log_path(),
));
}
}
/// True when the updater has something to do: either a landed update
/// waiting to re-exec, or an armed drift hint waiting to rebuild.
fn 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 presses 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 the updater the same way.
&& self.self_install.is_none()
&& self.staged_install.is_none())
}
/// croft's own updater (#865), on `Ctrl+Shift+F9` and a click on an
/// update pill: re-exec into a landed update (`run()` swaps a staged
/// binary in first), else start the rebuild an armed drift hint offers,
/// else say why there is nothing to do. It had bare F9, which toggled
/// no breakpoint while an update was on offer or building.
fn update_croft(&mut self) {
if self.any_update_ready() {
self.arm_reexec();
} else if self.update_armed() {
self.start_local_reinstall();
} else if self.self_install.is_some()
|| self.staged_install.is_some()
|| self.any_update_in_progress()
{
self.status = String::from("croft is already updating in the background");
} else if let Some(version) = self
.update_toast
.as_ref()
.filter(|t| !t.ready)
.map(|t| t.version.clone())
{
// The popup's Update, from the keyboard (#1844).
self.start_staged_update(version);
} else if self.manual_update_check.is_some() {
self.status = String::from("Already checking for croft updates");
} else if let Some(why) = manual_update_check_refusal(
std::env::var_os("CROFT_REMOTE_AUTOUPDATE").is_some(),
std::env::var_os("CROFT_NO_UPDATE_CHECK").is_some(),
) {
self.status = String::from(why);
} else {
// Nothing on offer: ask now, and say what the answer was, a
// missing network included (#1844).
self.status = String::from("Checking for croft updates\u{2026}");
self.manual_update_check = Some(crate::update_check::ManualCheck::start_with(
croft_cache_dir(),
String::from(env!("CARGO_PKG_VERSION")),
self.update_fetch,
));
}
}
/// The answer to a check Help: Update croft asked for (#1844).
fn poll_manual_update_check(&mut self) -> bool {
let Some(verdict) = self.manual_update_check.as_ref().and_then(|c| c.take()) else {
return false;
};
self.manual_update_check = None;
self.status = match verdict {
Ok(Some(version)) => {
let status = format!("croft v{version} is available");
self.update_toast = Some(UpdateToast {
version,
ready: false,
failed: None,
buttons: Vec::new(),
});
status
}
Ok(None) => format!("croft v{} is up to date", env!("CARGO_PKG_VERSION")),
Err(reason) => format!("Could not check for croft updates: {reason}"),
};
true
}
pub fn poll_update_watch(&mut self) -> bool {
let mut changed = self.poll_drift_probe();
changed |= self.poll_source_build_marker();
changed |= self.poll_update_check();
changed |= self.poll_manual_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 staging = self.staged_install.take();
let reason = staging
.as_ref()
.and_then(|s| s.failure_reason())
.unwrap_or("the build failed");
let version = staging.map(|s| s.version).unwrap_or_default();
// The user just asked for this version, so the
// popup comes back saying why it failed, with
// Retry and Later one click away (#1844).
self.update_toast = Some(UpdateToast {
version: version.clone(),
ready: false,
failed: Some(reason),
buttons: Vec::new(),
});
format!(
"croft v{version} was not installed: {reason} - 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" prompt in the status bar and let them
// pick the moment. The re-exec only fires on the updater
// chord (#865), a click on that pill, or Relaunch on the
// popup (#333).
self.status = format!(
"Update ready - press {UPDATE_CROFT_CHORD} 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,
failed: None,
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,
}
}
/// Quit into the freshly installed binary, but only once the session,
/// with every dirty buffer's unsaved text, is safely on disk: the
/// relaunch used to go ahead when the save failed (a full disk, an
/// unwritable cache) and those edits were gone.
fn arm_reexec(&mut self) {
// Tests arm the relaunch too, and must not write into the real cache.
let path = if cfg!(test) {
std::env::temp_dir().join(format!(
"croft-test-session-{}-{:?}.json",
std::process::id(),
std::thread::current().id()
))
} else {
crate::session_state::handoff_path()
};
if let Err(e) = self.capture_session_state().save(&path) {
self.status = format!("Relaunch cancelled: could not save the session ({e:#})");
return;
}
self.pending_reexec = true;
self.quit = true;
}
/// The session an update relaunch hands to the new process: every
/// unsaved buffer, a merge editor's Result included, since the
/// relaunch exits at once and the Result exists nowhere else.
pub fn capture_session_state(&self) -> crate::session_state::SessionState {
self.capture_session_state_with(true)
}
/// `keep_merge_results` false leaves a merge editor's unsaved Result
/// out (#1588), for hot exit, whose backup outlives the conflict it was
/// taken from.
fn capture_session_state_with(
&self,
keep_merge_results: bool,
) -> crate::session_state::SessionState {
let mut tabs = Vec::new();
let mut active_tab = 0;
let mut active_path: Option<PathBuf> = None;
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;
}
// An untitled buffer has no file to reopen, so it is carried only
// for its unsaved text; a blank one would reappear as clutter.
if ed.path.is_none() && !ed.dirty {
continue;
}
let path = ed.path.clone();
// A symbol tab is a view over its file's tab (#369): the file tab
// carries the text, so only an orphaned symbol tab is kept, as a
// plain file tab, to keep its unsaved edits.
if let Some(path) = path.clone().filter(|_| ed.symbol_view.is_some())
&& (self.editor.find_tab_with_path(&path).is_some()
|| tabs.iter().any(|t: &crate::session_state::OpenTabState| {
t.path.as_ref() == Some(&path)
}))
{
if idx == self.editor.active_index() {
active_path = Some(path);
}
continue;
}
if idx == self.editor.active_index() {
active_tab = tabs.len();
}
// A merge editor's buffer is its Result pane, not an edit of the
// file (#1588): kept in a hot-exit backup it came back as a plain
// tab whose Ctrl+S wrote the Result over the user's own
// resolution, so there the tab reopens on the file as it is on
// disk. A relaunch carries it, or the Result would be lost.
let dirty = ed.dirty && (keep_merge_results || ed.merge.is_none());
let unsaved_text = if 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,
unsaved_text,
});
}
// The other editor groups too: their tabs are not in `self.editor`,
// and a relaunch dropped the unsaved text of every split but the
// focused one. Only dirty tabs are carried; a file already captured
// (the same file open in two splits) keeps the dirty copy.
for group in self.editor_layout.inactive_groups() {
for ed in &group.editors {
if ed.has_non_text_view()
|| !ed.dirty
|| (!keep_merge_results && ed.merge.is_some())
{
continue;
}
let unsaved = Some(ed.lines.join("\n"));
if let Some(existing) = ed
.path
.as_ref()
.and_then(|p| tabs.iter_mut().find(|t| t.path.as_ref() == Some(p)))
{
if !existing.dirty {
existing.dirty = true;
existing.unsaved_text = unsaved;
}
continue;
}
tabs.push(crate::session_state::OpenTabState {
path: ed.path.clone(),
cursor_row: ed.cursor_row,
cursor_col: ed.cursor_col,
scroll: ed.scroll,
scroll_col: ed.scroll_col,
dirty: true,
unsaved_text: unsaved,
});
}
}
if let Some(path) = active_path
&& let Some(i) = tabs.iter().position(|t| t.path.as_ref() == Some(&path))
{
active_tab = i;
}
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 {
self.restore_open_tab(tab);
}
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)
// A CodeQL view saved before the extension was disabled restores
// to the Explorer rather than to a side bar with no icon.
&& (view != SidebarView::CodeQL || self.is_extension_enabled("codeql"))
{
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
};
}
/// Reopen one captured tab, the update relaunch's or hot exit's (#862):
/// its file at the saved cursor and scroll, with its unsaved text over
/// what the file holds now. Returns the tab, or `None` when there was
/// nothing to bring back.
fn restore_open_tab(
&mut self,
tab: &crate::session_state::OpenTabState,
) -> Option<&mut Editor> {
let unsaved = tab.unsaved_text.as_deref().filter(|_| tab.dirty);
let opened = tab
.path
.as_deref()
.is_some_and(|p| self.editor.open_pinned(p).is_ok());
let ed = if opened {
let path = tab.path.as_deref();
self.editor
.editors
.iter_mut()
.find(|e| e.path.as_deref() == path)?
} else if unsaved.is_some() {
// An untitled buffer, or a file that can no longer be read
// (deleted, permissions changed while the update ran): the
// unsaved text is the only copy, so it comes back (below) as a
// dirty tab rather than being dropped.
self.editor.open_unreadable_tab(tab.path.clone())
} else {
return None;
};
if let Some(text) = unsaved {
// As an edit, not a bare assignment: the text is re-highlighted
// (it kept the disk file's colours) and the LSP and the rest
// resync to it. It also stamps the edit time auto save keys on.
ed.restore_unsaved_text(text);
}
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;
Some(ed)
}
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;
self.remote_handoff_ok = 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_to_prompt(&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_to_prompt(&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 = crate::widgets::search::as_typed(&self.search.query);
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");
}
// Saved as the mode the next launch starts in (#1286). Under test
// only into a config dir the test chose, never the developer's.
self.vim_mode_pref = self.vim.enabled;
if !cfg!(test) || self.config_dir != crate::prefs::config_dir() {
let _ = crate::prefs::save_vim_mode_in(&self.config_dir, self.vim.enabled);
}
}
/// Follow the `vim_mode` pref (#1286) at launch and on a settings
/// reload: Vim mode on when it is set and the `vim` extension is
/// enabled. Only a change of the pref moves the live mode, so a reload
/// for another setting leaves the mode, and Insert or Normal, as it is.
fn follow_vim_mode_pref(&mut self, want: bool) {
if want == self.vim_mode_pref {
return;
}
self.vim_mode_pref = want;
let on = want && self.is_extension_enabled("vim");
if on != self.vim.enabled {
self.vim.toggle();
if !on {
self.editor
.set_search_highlight(None, crate::widgets::search::SearchOpts::default());
}
}
}
/// 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()
}
/// Increment (`delta` 1) or decrement (`delta` -1) the number under the
/// cursor, reporting in the status bar when there is nothing to bump so
/// the keystroke never looks broken.
fn bump_number_under_cursor(&mut self, delta: i64) {
if !self.editor_is_text() {
return;
}
if !self.editor.bump_number(delta) {
self.status = String::from("No number at or after the cursor on this line");
}
}
/// Toggle a bookmark on the cursor's line and report the new state in the
/// status bar. A buffer with no path on disk cannot hold marks, and says so
/// rather than silently doing nothing.
fn toggle_bookmark(&mut self) {
if !self.editor_is_text() {
return;
}
let line = self.editor.cursor_row + 1;
self.status = match self.editor.toggle_bookmark() {
Some(true) => format!("Bookmark set on line {line}"),
Some(false) => format!("Bookmark cleared on line {line}"),
None => String::from("Save the file before bookmarking a line"),
};
}
/// Jump to the next (`forward`) or previous bookmark in the open file,
/// wrapping at the ends. Explains an empty set instead of doing nothing.
fn goto_bookmark(&mut self, forward: bool) {
if !self.editor_is_text() {
return;
}
let jumped = if forward {
self.editor.goto_next_bookmark()
} else {
self.editor.goto_prev_bookmark()
};
self.status = match jumped {
Some(line) => {
// Position among the marks, 1-based, then the line itself:
// "Bookmark 2 of 3 (line 42)", never a line number over a count.
let marks = self.editor.bookmarked_lines();
let total = marks.len();
let idx = marks.iter().position(|&l| l == line).map_or(0, |i| i + 1);
format!("Bookmark {idx} of {total} (line {line})")
}
None => String::from("No bookmarks in this file (Cmd+Opt+Shift+K sets one)"),
};
}
/// Clear every bookmark in the open file, reporting how many went.
fn clear_bookmarks(&mut self) {
// Every path in (chord and palette) goes through here, so the guard
// lives here: a preview or non-text view must not clear marks it does
// not show.
if !self.editor_is_text() {
return;
}
let gone = self.editor.clear_bookmarks();
self.status = if gone == 0 {
String::from("No bookmarks in this file")
} else if gone == 1 {
String::from("Cleared 1 bookmark")
} else {
format!("Cleared {gone} bookmarks")
};
}
/// Emmet: Expand Abbreviation. Says why nothing happened rather than
/// failing silently — the two reasons (wrong language, unparseable
/// abbreviation) need different fixes from the user.
fn expand_emmet_abbreviation(&mut self) {
if !self.editor_is_text() {
return;
}
self.status = if !self.editor.emmet_available() {
format!(
"Emmet: not available in {} files",
self.editor.language_label()
)
} else if self.editor.expand_emmet_abbreviation() {
String::from("Emmet: expanded abbreviation")
} else {
String::from("Emmet: no abbreviation at the cursor")
};
}
/// 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;
}
// F7 / Shift+F7 elsewhere: Go to Next / Previous Change over the
// gutter's change bars (#1352), as the diff view walks its hunks.
if matches!(key.code, KeyCode::F(7)) && self.editor.merge.is_none() {
self.jump_editor_change(!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. The sheet grid is editable and F2 is its
// own "edit this cell" key (#1618), so there F2 falls through to it.
if is_rename_symbol_key(key) && self.editor.sheet.is_none() {
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_select_all_occurrences_key(key) {
self.select_all_occurrences();
return;
}
if is_add_cursors_to_line_ends_key(key) {
self.add_cursors_to_line_ends();
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) {
// The palette's message too: a key that does nothing because the
// language has no comment must say so (#1181); a blank line in
// one that has does nothing quietly.
if self.editor_is_text()
&& !self.editor.toggle_line_comment()
&& !self.editor.has_line_comment_syntax()
{
self.status = String::from("Toggle Line Comment: no comment for this language");
}
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;
}
// Alt+O: C/C++: Switch Header/Source (#1360), as VS Code's clangd
// extension binds it. Other files keep the chord.
if is_switch_header_source_key(key)
&& self
.editor
.path
.as_deref()
.is_some_and(crate::header_source::is_c_family)
{
self.switch_header_source();
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;
}
// Bookmarks: toggle on the cursor's line, then walk them with
// Cmd+Opt+. / Cmd+Opt+, (VS Code's Bookmarks extension, nvim marks).
if is_toggle_bookmark_key(key) {
self.toggle_bookmark();
return;
}
if is_next_bookmark_key(key) {
self.goto_bookmark(true);
return;
}
if is_prev_bookmark_key(key) {
self.goto_bookmark(false);
return;
}
if is_clear_bookmarks_key(key) {
self.clear_bookmarks();
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;
}
if is_increment_number_key(key) {
self.bump_number_under_cursor(1);
return;
}
if is_decrement_number_key(key) {
self.bump_number_under_cursor(-1);
return;
}
if is_emmet_expand_key(key) {
self.expand_emmet_abbreviation();
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;
}
// Rebase todo (#620): single-key actions on commit lines.
if self.rebase_todo_key(key) {
return;
}
// Inline suggestion (#607): Tab accepts, Esc dismisses.
if self.inline_suggestion_key(key) {
return;
}
// Search Editor (#615): Enter or F12 on a result row opens the match;
// anywhere else both keep their usual meaning.
if (key.code == KeyCode::Enter && key.modifiers.is_empty() || is_go_to_definition_key(key))
&& self.open_search_editor_result()
{
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_peek_references_key(key) {
if self.editor.diff.is_none()
&& self.editor.sheet.is_none()
&& self.editor.image.is_none()
{
self.peek_references_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.request_close_tab(self.editor.active_index());
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;
}
if self.editor.pr_review.is_some() {
self.handle_pr_review_key(key);
return;
}
if self.editor.fleet.is_some() {
self.handle_fleet_key(key);
return;
}
if self.editor.sarif.is_some() {
self.handle_sarif_key(key);
self.refresh_sarif_preview();
return;
}
if self.editor.log.is_some() && self.handle_log_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) {
self.kill_to_end_of_line();
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.arrow_up(),
KeyCode::Down => self.editor.arrow_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_key(),
KeyCode::End => self.editor.end_key(),
KeyCode::PageUp => self.editor.page_up_one_screen(),
KeyCode::PageDown => self.editor.page_down_one_screen(),
_ => {}
}
self.editor.extend_selection_to_cursor();
self.editor.ensure_cursor_col_visible();
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.arrow_up(),
KeyCode::Down => self.editor.arrow_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_key(),
KeyCode::End => self.editor.end_key(),
KeyCode::Backspace => {
self.editor.backspace();
self.note_incomplete_completion_edit();
}
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);
// With an incomplete list pending but none of it on screen,
// typing on still re-asks (#1529).
self.note_incomplete_completion_edit();
// `.` 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.request_completion_at_caret(false);
}
// 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();
}
}
_ => {}
}
// Home, End, typing, Backspace, Delete and Enter move the caret
// sideways too; only ←/→ pulled the view along, so End on a wide
// line or typing past the edge left the caret off-screen (#1215).
self.editor.ensure_cursor_col_visible();
}
/// 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;
// A symbol tab's operator stays inside its symbol (#369): `dgg`
// from its second line reaches its first line, not the file's.
let (lo, hi) = self
.editor
.symbol_clip()
.unwrap_or((0, self.editor.lines.len().max(1)));
let first = start_row.clamp(lo, hi - 1);
let end = (start_row + count.max(1)).clamp(first + 1, hi);
self.editor.cursor_row = first;
let n = end - first;
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;
// A motion can leave a symbol tab's lines (`db` at its first
// column); the operator covers only the part inside them (#369).
let start = self.clamp_to_symbol_clip(start);
if let Some(sel) = self.editor.selection {
self.editor.selection = Some(crate::widgets::editor::EditorSelection {
anchor: self.clamp_to_symbol_clip(sel.anchor),
head: self.clamp_to_symbol_clip(sel.head),
});
}
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 --");
}
}
}
/// `pos` pulled inside a symbol tab's lines: above them to the first
/// line's start, below them to the last line's end. Unchanged on an
/// ordinary tab.
fn clamp_to_symbol_clip(&self, pos: (usize, usize)) -> (usize, usize) {
match self.editor.symbol_clip() {
Some((first, _)) if pos.0 < first => (first, 0),
Some((_, end)) if pos.0 >= end => (end - 1, self.vim_line_len(end - 1)),
_ => pos,
}
}
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" | "quit" => self.request_close_tab(self.editor.active_index()),
// vim's `!` is the answer to "discard the changes?" given up
// front, so these two never ask (#862).
"q!" => self.close_tab_now(self.editor.active_index()),
"qa!" => {
self.clear_hot_exit();
self.quit = true;
}
"wq" | "x" | "wq!" => {
self.save();
// A save that did not land (a disk conflict, a format still
// running) leaves the tab dirty, and the close asks.
self.request_close_tab(self.editor.active_index());
}
"qa" | "quitall" => self.guard_unsaved(UnsavedExit::Quit),
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_wrapped();
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;
// Wrapped rows are masked as the logical line they form, so a secret
// cut by a soft wrap is masked on both rows.
let plains: Vec<String> = rows_both[..last].iter().map(|r| r.0.clone()).collect();
let wraps: Vec<bool> = rows_both[..last].iter().map(|r| r.2).collect();
let masked_rows = crate::triggers::mask_rows(&plains, &wraps, &self.triggers);
for ((plain, ansi, _), masked) in rows_both[..last].iter().zip(masked_rows) {
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_any_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_any_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::variables(&text, 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 {} (set it with @name = … in the file, in {} beside it, 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) {
self.split_terminal_reporting();
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) {
self.close_terminal_reporting(self.active_terminal);
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+Shift+V: paste local clipboard into the embedded
// shell; Cmd+V, when not eaten by the host terminal's menu
// shortcut, would otherwise do nothing useful. Plain Ctrl+V is the
// app's (#1290): vim's visual block and nano's page down need the
// 0x16 byte, as in VS Code's terminal on Linux.
if is_clipboard_paste_key(key) && !is_plain_ctrl_v(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();
}
// Right arrow at the end of the typed line accepts the suggestion
// painted after it (#614), as in fish; anywhere else it moves.
if key.code == KeyCode::Right
&& key.modifiers.is_empty()
&& let Some((pane, typed, rest)) = self.term_suggestion.take()
&& pane == self.active_terminal
&& !self.terminal().awaiting_echo()
&& self.terminal().prompt_tail().is_some_and(|t| t.0 == typed)
{
self.terminal_mut().write_input(rest.as_bytes());
return;
}
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();
self.status = self.copy_where_pasted(text).status(&format!("{n} chars"));
}
/// The copy `deliver_copied_text` makes, without the status line, for a
/// caller that words its own. Every terminal copy goes this way (#1667):
/// Copy Output, copy mode, quick select and copy on select all wrote
/// the remote box's clipboard on a relay session.
fn copy_where_pasted(&mut self, text: &str) -> CopyLanding {
if self.is_relay_session && self.push_clipboard_via_relay(text) {
CopyLanding::Local
} else if copy_to_clipboard(text) {
CopyLanding::Clipboard
} else {
CopyLanding::Osc52
}
}
/// 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+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, fr.end_line)
}
/// 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, &block_script_dir()),
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;
};
// A notebook cell runs in its kernel straight away, as in Jupyter:
// no pane, no confirm.
if let Some(cell) = block.kernel_cell {
let text = self.editor.lines.join("\n");
if let Some(cell) = crate::notebook_kernel::code_cell(&text, cell) {
self.run_notebook_cells(vec![cell]);
}
return;
}
self.pending_run_block = Some(self.pending_run_block_for(idx, &block));
}
/// Send `cells` to the active notebook's kernel, starting it on the
/// first run. Each cell's old outputs are cleared now, in one edit,
/// so what the file shows is always this run's.
fn run_notebook_cells(&mut self, cells: Vec<crate::notebook_kernel::CellRef>) {
use crate::notebook_kernel::{CellEdit, KernelSession, NotebookRun, apply, kernel_name};
let Some(path) = self.editor.path.clone() else {
return;
};
if cells.is_empty() {
self.status = String::from("No code cells to run");
return;
}
let mut text = self.editor.lines.join("\n");
let root = self.workspace_root().to_path_buf();
let starting = !self.notebook_kernels.contains_key(&path);
let run = self
.notebook_kernels
.entry(path.clone())
.or_insert_with(|| {
let dir = path.parent().unwrap_or(&root);
NotebookRun::new(KernelSession::start(&root, dir, &kernel_name(&text)))
});
for cell in cells {
if let Some(next) = apply(&text, &cell, CellEdit::Begin) {
text = next;
}
run.execute(cell);
}
self.editor.notebook_running = run.running_indices();
self.editor
.replace_all_lines(text.split('\n').map(str::to_string).collect());
if starting {
self.status = String::from("Starting kernel…");
}
}
/// Fold what each kernel said into its notebook. A notebook that is not
/// the active tab keeps its events until it is.
fn poll_notebook_kernels(&mut self) -> bool {
let active = self.editor.path.clone();
let mut changed = self.poll_kernel_listing();
let mut choice = None;
for (path, run) in self.notebook_kernels.iter_mut() {
if !run.collect() || active.as_ref() != Some(path) {
continue;
}
let text = self.editor.lines.join("\n");
let (next, notes) = run.fold(&text);
self.editor.notebook_running = run.running_indices();
if let Some(next) = next {
self.editor
.replace_all_lines(next.split('\n').map(str::to_string).collect());
}
if let Some(note) = notes.last() {
self.status = note.clone();
}
if let Some(c) = run.choice.take() {
choice = Some((path.clone(), c));
}
changed = true;
}
if let Some((path, c)) = choice {
self.open_kernel_picker(path, c.specs, Some(c.requested));
}
changed
}
/// Notebook: Select Kernel (#1377): ask the bridge which kernels are
/// installed; the picker opens when it answers.
fn select_notebook_kernel(&mut self) {
let Some(path) = self.editor.path.clone().filter(|_| {
self.editor
.markdown_preview
.as_ref()
.is_some_and(|m| m.notebook)
}) else {
self.status = String::from("Select Kernel works on a notebook's rendered view");
return;
};
let listing = self.start_kernel_session(&path, crate::notebook_kernel::LIST_KERNELS);
self.kernel_listing = Some((path, listing));
self.status = String::from("Looking for installed kernels…");
}
/// A kernel bridge for the notebook at `path`, run in its folder.
fn start_kernel_session(
&self,
path: &Path,
kernel: &str,
) -> crate::notebook_kernel::KernelSession {
#[cfg(test)]
if let Some(start) = &self.kernel_start_override {
return start(kernel);
}
let root = self.workspace_root();
let dir = path.parent().unwrap_or(root);
crate::notebook_kernel::KernelSession::start(root, dir, kernel)
}
/// The installed kernels arriving for Select Kernel.
fn poll_kernel_listing(&mut self) -> bool {
use crate::notebook_kernel::Event;
let Some((path, listing)) = self.kernel_listing.as_ref() else {
return false;
};
let path = path.clone();
for event in listing.try_events() {
match event {
Event::Specs { specs } => {
self.kernel_listing = None;
if self.editor.path.as_ref() == Some(&path) {
self.status.clear();
self.open_kernel_picker(path, specs, None);
}
return true;
}
Event::Error { message } => {
self.kernel_listing = None;
self.status = format!("Kernel: {message}");
return true;
}
_ => {}
}
}
false
}
/// The kernel picker for the notebook at `path`, opened on its own
/// kernel when installed, else on one for its language. `missing` is
/// the kernel it names that this machine does not have.
fn open_kernel_picker(
&mut self,
path: PathBuf,
specs: Vec<crate::notebook_kernel::KernelSpec>,
missing: Option<String>,
) {
use crate::notebook_kernel::{kernel_name, notebook_language, preferred_kernel};
use crate::widgets::list_picker::{ListPicker, ListPurpose, ListRow};
if self.editor.path.as_ref() != Some(&path) {
return;
}
let text = self.editor.lines.join("\n");
let rows = specs
.iter()
.map(|s| ListRow {
id: s.name.clone(),
label: format!("{} ({})", s.display, s.name),
})
.collect();
let title = match &missing {
Some(k) => format!("Kernel '{k}' is not installed: Select Kernel"),
None => String::from("Select Kernel"),
};
let mut picker = ListPicker::new(ListPurpose::NotebookKernel, title, rows);
picker.selected = preferred_kernel(
&specs,
&kernel_name(&text),
notebook_language(&text).as_deref(),
);
self.kernel_choice = Some((path, specs, missing));
self.open_list_picker(picker, "No Jupyter kernels are installed");
}
/// The kernel picked for a notebook: written to its
/// `metadata.kernelspec` (Save keeps it, as in Jupyter), and a kernel
/// already started, or waiting on a missing one, is replaced by it.
fn choose_notebook_kernel(&mut self, name: &str) {
let Some((path, specs, _)) = self.kernel_choice.take() else {
return;
};
let Some(spec) = specs.into_iter().find(|s| s.name == name) else {
return;
};
if self.editor.path.as_ref() != Some(&path) {
return;
}
let text = self.editor.lines.join("\n");
if let Some(next) = crate::notebook_kernel::set_kernelspec(&text, &spec) {
self.editor
.replace_all_lines(next.split('\n').map(str::to_string).collect());
}
if !self.notebook_kernels.contains_key(&path) {
self.status = format!("Kernel: {} (starts on the next run)", spec.display);
return;
}
let session = self.start_kernel_session(&path, &spec.name);
if let Some(run) = self.notebook_kernels.get_mut(&path) {
run.restart_with(session);
self.editor.notebook_running = run.running_indices();
self.status = format!("Starting kernel {}…", spec.display);
}
}
/// The kernel picker closed without a choice. Cells waiting on a
/// kernel that is not installed cannot run, so they stop waiting.
fn kernel_choice_dismissed(&mut self) {
let Some((path, _, Some(missing))) = self.kernel_choice.take() else {
return;
};
if self.notebook_kernels.remove(&path).is_some() && self.editor.path.as_ref() == Some(&path)
{
self.editor.notebook_running.clear();
}
self.status = format!(
"Kernel '{missing}' is not installed: run Notebook: Select Kernel to pick another"
);
}
/// Interrupt or restart the active notebook's kernel.
fn notebook_kernel_request(&mut self, request: crate::notebook_kernel::Request) {
let run = self
.editor
.path
.as_ref()
.and_then(|p| self.notebook_kernels.get(p));
match run {
Some(run) => run.send(request),
None => self.status = String::from("This notebook has no running kernel"),
}
}
/// 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(
"Run code block: 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);
let uid = self.terminals[idx].uid();
self.await_pane_outcome(uid, 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());
let uid = term.uid();
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);
self.await_pane_outcome(uid, 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());
}
/// Whether the active editor view shows a selection for Copy to take,
/// read as [`Self::copy_editor_selection`] reads it: a rendered preview's
/// or log's own selection, a diff's, else the buffer's in a text view.
fn editor_view_has_selection(&self) -> bool {
if let Some(md) = self.editor.markdown_preview.as_ref() {
return !md.selection_text().is_empty();
}
if let Some(log) = self.editor.log.as_ref() {
return log.has_selection();
}
if let Some(diff) = self.editor.diff.as_ref() {
return diff.selection_text().is_some_and(|t| !t.is_empty());
}
self.editor_is_text() && self.editor.selection.is_some_and(|s| s.has_area())
}
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.paste_str(s, self.paste_reindent);
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);
}
}
self.follow_quick_open_prefix();
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.paste_str(s, self.paste_reindent);
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 updater's 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() + self.view_drain_budget;
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 = if crate::rebase_todo::is_todo(path) {
String::from(crate::rebase_todo::HINT)
} else {
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();
// The long-command notice, with the pane it is about.
let mut finished: Option<(u64, 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;
// The newest OSC 52 copy any pane's program made this tick (#678).
let mut copied: Option<String> = None;
// A task's or fenced block's command ended (#856): (pane uid, exit,
// duration), settled against its "Running …" status after the sweep.
let mut runs_ended: Vec<(u64, Option<i32>, std::time::Duration)> = Vec::new();
for t in &self.terminals {
if let Some(text) = t.take_clipboard_store() {
copied = Some(text);
}
// 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() {
// Empty output included (#1488): see the scan loop below.
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);
}
// The first command the pane finishes after the run was
// typed is the run's, as for a block's output capture.
let awaited = self
.pane_run_statuses
.iter()
.any(|(uid, _)| *uid == t.uid());
if awaited {
runs_ended.push((t.uid(), f.exit, f.dur));
}
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((
t.uid(),
format!(
"Command in {} finished: exit {code} in {}",
t.label(),
crate::widgets::terminal::human_duration(f.dur)
),
));
}
}
let mut run_settled = false;
for (pane, exit, dur) in runs_ended {
let Some(i) = self
.pane_run_statuses
.iter()
.position(|(uid, _)| *uid == pane)
else {
continue; // a second command the same sweep saw end
};
let (_, run) = self.pane_run_statuses.remove(i);
if run.settle(&mut self.status, |label, _| {
pane_run_outcome(label, exit, dur)
}) {
run_settled = true;
// The outcome says what the long-command notice would, by
// the run's own name. Unsettled (a newer status showing),
// the notice still comes.
if finished.as_ref().is_some_and(|(uid, _)| *uid == pane) {
finished = None;
}
}
}
// A pane that closed will never report its run's end.
let terminals = &self.terminals;
self.pane_run_statuses
.retain(|(uid, _)| terminals.iter().any(|t| t.uid() == *uid));
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 {
// A command that printed nothing (`cd`, `clear`) says nothing
// about the build, so the pane's problems stay. It still ends
// the pane's command, so it uses up a watcher's one-shot skip:
// a watcher that clears the screen erases its own output, and
// with the skip left armed the next build was the one skipped,
// leaving the watcher's stale problems in place (#1488).
if output.is_empty() {
self.watch_published_panes.remove(&pane);
continue;
}
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);
}
// A program in a pane copied through OSC 52 (Claude Code, tmux,
// nvim): send it where a paste comes from, exactly as croft's own
// selection copy does, so a remote session copies to the user's
// machine and not to a box with no clipboard (#678). An empty store
// is a program clearing the clipboard at startup, not a copy the
// user made, so it never wipes what they copied.
let copied = copied.filter(|text| !text.is_empty());
if let Some(text) = &copied {
self.deliver_copied_text(text);
}
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 copied.is_some() || run_settled;
};
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();
let what = if lines == 1 {
String::from("command output (1 line)")
} else {
format!("command output ({lines} lines)")
};
self.status = self.copy_where_pasted(&text).status(&what);
}
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 {
crumb: None,
scroll: Default::default(),
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);
} else {
self.status = String::from("croft is already updating in the background");
}
}
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.arm_reexec();
}
}
}
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();
// Kept: an autosave seconds later must not replace the baseline the
// review diff points at, nor may this replace the user's own save.
let _ = crate::history::record_kept_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)
}
/// Agents: Review a Changed File (#345): every lane's files in a picker,
/// labelled as the AGENT LANE section labels them; Enter opens the
/// chosen file's diff since review, as a click on its row does.
fn pick_agent_lane_file(&mut self) {
use crate::widgets::agent_lane::LaneRow;
use crate::widgets::list_picker::{ListPicker, ListPurpose, ListRow};
let mut rows = Vec::new();
self.pending_lane_picks.clear();
for row in self.agent_lane_panel_rows() {
if let LaneRow::File {
agent,
path,
label,
unreviewed,
changes,
} = row
{
let mark = if unreviewed { "\u{25cf}" } else { " " };
let counts = changes
.filter(|&(a, r)| a + r > 0)
.map(|(a, r)| format!(" +{a} \u{2212}{r}"))
.unwrap_or_default();
rows.push(ListRow {
id: self.pending_lane_picks.len().to_string(),
label: format!("{mark} {label} ({agent}){counts}"),
});
self.pending_lane_picks.push((agent, path));
}
}
if rows.is_empty() {
self.status = String::from("No agent has changed a file");
return;
}
self.list_picker = Some(ListPicker::new(
ListPurpose::AgentLaneFile,
String::from("Review a file an agent changed"),
rows,
));
}
/// 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)"));
let unsaved = self.unsaved_text_in_any_group(path);
if let Err(e) = self
.editor
.open_head_diff_with_text_resolved(label, &text, path, false, unsaved)
{
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, scoped to the paths it searched from the focused pane's
/// directory. Returns false when `input` isn't a recognisable search.
fn seed_search_from_command(&mut self, input: &str) -> bool {
let cwd = self
.terminals
.get(self.active_terminal)
.and_then(|t| t.pid())
.and_then(cwd_of_pid)
.filter(|p| p.is_dir());
let Some(cwd) = cwd else {
// Guessing the workspace root would widen `rg foo` run from a
// subdirectory to every file (#1201).
if crate::quickfix::parse_search_command(input).is_none() {
return false;
}
self.status = String::from(
"Search not seeded: can't tell which directory the terminal searched from",
);
return true;
};
self.seed_search_from_command_in(input, &cwd)
}
/// [`Self::seed_search_from_command`] for a command run in `cwd`. A
/// search whose scope can't be reproduced exactly is refused with the
/// reason in the status bar and leaves the panel alone (still true:
/// the input was a search), so Replace All never widens past it (#1201).
fn seed_search_from_command_in(&mut self, input: &str, cwd: &Path) -> bool {
let Some(sc) = crate::quickfix::parse_search_command(input) else {
return false;
};
let (include, exclude) =
match crate::quickfix::scope_filters(&sc, cwd, self.workspace_root()) {
Ok(filters) => filters,
Err(why) => {
self.status = format!("Search not seeded: {why}");
return true;
}
};
self.search.seed(sc.pattern.clone(), include, exclude);
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, fr.end_line)
}
/// 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, fr.end_line),
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(|| diagnostics_source(server).to_string())
})
})
.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,
code: d.code,
},
))
}
/// 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. With
/// `end_line`, a `path:line-end` range, the lines `line..=end_line` are
/// selected (#804). 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>,
end_line: Option<u32>,
) -> bool {
self.open_resolved_file_ref_inner(abs, line, column, end_line, 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>,
end_line: 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);
let range = end_line.filter(|&e| e > line).and_then(|end| {
let last = self.editor.lines.len().checked_sub(1)?;
let end0 = (end as usize - 1).min(last);
(line0 <= end0).then_some((end0, end))
});
self.status = match range {
Some((end0, end)) => {
// The whole lines, caret at the top so the view
// opens on the start of the range.
let len = self.editor.lines[end0].chars().count();
self.editor.selection = Some(crate::widgets::editor::EditorSelection {
anchor: (end0, len),
head: (line0, 0),
});
self.editor.cursor_row = line0;
self.editor.cursor_col = 0;
format!("{}:{}-{}", self.status_path(abs), line, end)
}
None => 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, None, 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, None, 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, fr.end_line) {
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);
// A per-run nonce as well as the pid: claims outlive the process in
// the relay dir, and a later croft reusing this pid (after a reboot,
// in a container) would find every one of its ids already claimed.
static NONCE: std::sync::OnceLock<u128> = std::sync::OnceLock::new();
let nonce = NONCE.get_or_init(|| {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_nanos())
});
let n = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
format!("{kind}-{}-{nonce:x}-{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) {
// Forwarded already: reuse the tunnel. Asking again found the remote
// port held locally by croft's own first tunnel and fell back to a
// random one, so every click on the same link opened one more tunnel
// and one more browser tab at a new 127.0.0.1 address (#648).
if let Some(local) = self.ports.forwarded_local_port(port) {
if open {
self.request_remote_url_open(format!("http://127.0.0.1:{local}/"));
self.status = format!("Opening port {port} (forwarded to {local})");
} else {
self.status = format!("Port {port} is already forwarded to {local}");
}
return;
}
// And one request per port at a time: a second click before the
// first forward answered sent a duplicate.
if self.pending_remote_pulls.iter().any(
|p| matches!(p.kind, RemotePullKind::Forward { remote_port } if remote_port == port),
) {
self.status = format!("Port {port} is already being forwarded");
return;
}
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");
}
_ => {}
}
}
/// The merged settings as the Settings editor sees them: the user layers
/// from `self.config_dir`, the workspace layers from the primary root.
fn merged_settings_here(&self) -> crate::config_layers::MergedConfig {
crate::config_layers::load_merged_from(
&self.config_dir,
Some(self.roots.primary()),
crate::config_layers::current_platform(),
)
}
/// Open the Settings editor (#612).
fn open_settings_editor(&mut self) {
let merged = self.merged_settings_here();
self.settings_editor = Some(crate::widgets::settings_editor::SettingsEditor::new(
crate::settings_editor::rows(&merged.prefs, &merged.provenance),
));
}
/// Write `key = value` into the Settings editor's target layer, re-merge
/// and apply it live, and refresh the editor's rows.
fn write_setting(&mut self, key: &str, value: serde_json::Value) {
use crate::config_layers::LayerKind;
let Some(target) = self.settings_editor.as_ref().map(|e| e.target) else {
return;
};
let path = match target {
LayerKind::Workspace => {
if !crate::config_layers::WORKSPACE_ALLOWED_KEYS.contains(&key) {
self.status =
format!("{key} can only be set in your user settings (Tab switches layer)");
return;
}
crate::config_layers::workspace_config_path(self.roots.primary())
}
_ => self.config_dir.join("config.json"),
};
let text = std::fs::read_to_string(&path).unwrap_or_default();
let new = match crate::settings_editor::set_key(&text, key, value) {
Ok(t) => t,
Err(e) => {
self.status = format!("{}: {e}", path.display());
return;
}
};
let written = path
.parent()
.map_or(Ok(()), std::fs::create_dir_all)
.and_then(|()| std::fs::write(&path, new));
if let Err(e) = written {
self.status = format!("{}: {e}", path.display());
return;
}
// Applied just below, so the settings watch must not apply it again.
self.config_watch.note(&path);
let merged = self.merged_settings_here();
for w in &merged.warnings {
crate::output::push("Settings", crate::output::OutputLevel::Warn, w);
}
self.apply_merged_settings(&merged.prefs);
self.settings_provenance = merged.provenance.clone();
if let Some(ed) = self.settings_editor.as_mut() {
ed.rows = crate::settings_editor::rows(&merged.prefs, &merged.provenance);
}
self.status = format!("{key} saved to {}", path.display());
}
/// Keys while the Settings editor is open (#612): typing searches, Enter
/// edits the selected setting, Tab switches between the user and the
/// workspace layer.
fn handle_settings_editor_key(&mut self, key: KeyEvent) {
use crate::config_layers::LayerKind;
use crate::settings_editor::Kind;
let Some(ed) = self.settings_editor.as_mut() else {
return;
};
match (key.code, key.modifiers) {
(KeyCode::Esc, _) => self.settings_editor = None,
(KeyCode::Up, _) => ed.move_selection(-1),
(KeyCode::Down, _) => ed.move_selection(1),
(KeyCode::PageUp, _) => ed.move_selection(-10),
(KeyCode::PageDown, _) => ed.move_selection(10),
(KeyCode::Tab, _) | (KeyCode::BackTab, _) => {
ed.target = if ed.target == LayerKind::Workspace {
LayerKind::User
} else {
LayerKind::Workspace
};
}
(KeyCode::Enter, _) => {
let Some(row) = ed.selected_row().cloned() else {
return;
};
match row.kind {
Kind::Bool | Kind::Choice(_) => {
if let Some(v) = crate::settings_editor::next_value(&row) {
self.write_setting(&row.key, v);
}
}
Kind::Number | Kind::Text => {
use crate::widgets::input_prompt::{InputPrompt, InputPurpose};
let now = crate::settings_editor::display(&row.value);
self.open_input_prompt(
InputPrompt::new(
InputPurpose::SettingValue {
key: row.key.clone(),
},
row.key.replace('_', " "),
String::from("new value"),
)
.with_value(now),
);
}
Kind::Json => {
self.settings_editor = None;
self.status =
format!("{} is edited in the JSON file", row.key.replace('_', " "));
self.open_config_file_in_editor(
self.config_dir.join("config.json"),
ConfigFileSeed::Settings,
);
}
}
}
(KeyCode::Backspace, _) => {
let mut q = ed.query.clone();
q.pop();
ed.set_query(q);
}
(KeyCode::Char(c), m) if !m.intersects(KeyModifiers::CONTROL | KeyModifiers::SUPER) => {
let mut q = ed.query.clone();
q.push(c);
ed.set_query(q);
}
_ => {}
}
}
/// A typed value for setting `key` (#612): numbers must parse as one.
fn submit_setting_value(&mut self, key: &str, value: &str) {
let Some(row) = self
.settings_editor
.as_ref()
.and_then(|e| e.rows.iter().find(|r| r.key == key).cloned())
else {
return;
};
let v = value.trim();
let parsed = match row.kind {
crate::settings_editor::Kind::Number => match v.parse::<u64>() {
Ok(n) => serde_json::Value::from(n),
Err(_) => {
self.status = format!("{key} needs a whole number, not \"{v}\"");
return;
}
},
_ => serde_json::Value::from(v),
};
self.write_setting(key, parsed);
}
fn render_settings_editor(&mut self, frame: &mut ratatui::Frame) {
let area = frame.area();
let theme = self.theme;
if let Some(ed) = self.settings_editor.as_mut() {
crate::widgets::settings_editor::render(ed, area, frame.buffer_mut(), theme);
}
}
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;
let visible = self.without_project_excludes(arc);
if let Some(finder) = self.file_finder.as_mut() {
finder.replace_entries(visible);
}
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;
}
/// C/C++: Switch Header/Source (#1360): open the header of the source
/// in the editor, or the source of the header, found beside it, across
/// an `include/` ↔ `src/` split, or anywhere in the workspace.
fn switch_header_source(&mut self) {
let Some(path) = self.editor.path.clone() else {
self.status = String::from("No file in the active tab");
return;
};
if !crate::header_source::is_c_family(&path) {
self.status =
String::from("Switch Header/Source works on C, C++ and Objective-C files");
return;
}
self.poll_file_finder_index();
// The root that owns the file, so a file in a secondary root of a
// multi-root workspace finds its counterpart in that root.
let root = self
.roots
.owning_root(&path)
.unwrap_or_else(|| self.roots.primary())
.to_path_buf();
let name = path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
let index_paths = |app: &Self| -> Vec<PathBuf> {
app.file_finder_index
.as_ref()
.map(|entries| entries.iter().map(|e| e.path.clone()).collect())
.unwrap_or_default()
};
let is_file = |p: &Path| p.is_file();
let mut found =
crate::header_source::counterpart(&path, &root, &index_paths(self), &is_file);
// The background index has not landed yet: walk the workspace
// synchronously this once, as Go to File does, so the
// anywhere-in-the-workspace fallback is not answered from nothing.
if found.is_none() && 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;
found = crate::header_source::counterpart(&path, &root, &index_paths(self), &is_file);
}
let Some(found) = found else {
self.status = format!("No header/source counterpart for {name}");
return;
};
// A tab-aware open: the counterpart gets its own tab (or its
// existing one), so unsaved edits in the current buffer survive.
match self.editor.open_pinned(&found) {
Ok(()) => {
self.sync_open_file_poll_mtime();
self.focus_pane(Pane::Editor);
let shown = found.strip_prefix(&root).unwrap_or(&found);
self.status = format!("{name} \u{2194} {}", shown.display());
}
Err(e) => self.status = format!("Could not open {}: {e}", found.display()),
}
}
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 entries = self.without_project_excludes(entries);
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);
}
}
}
self.follow_quick_open_prefix();
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);
}
_ => {}
}
self.follow_quick_open_prefix();
}
/// VS Code's shared quick input: the first character of Quick Open's
/// query picks the mode, and the text after it carries over as the new
/// query. `#` is Go to Symbol in Workspace, `>` the Command Palette
/// (#1306), `@` Go to Symbol in Editor, and `:` Go to Line, which is
/// Go to Symbol's own `:N` mode. Anything else stays a file search,
/// `name:12` included.
fn follow_quick_open_prefix(&mut self) {
let Some(query) = self.file_finder.as_ref().map(|f| f.query.clone()) else {
return;
};
let mut chars = query.chars();
let (Some(prefix), rest) = (chars.next(), chars.as_str()) else {
return;
};
if !matches!(prefix, '#' | '>' | '@' | ':') {
return;
}
self.close_file_finder();
match prefix {
'#' => self.open_workspace_symbols(rest),
'>' => {
self.open_command_palette();
if let Some(palette) = self.command_palette.as_mut() {
palette.set_query(rest);
}
}
_ => {
self.open_go_to_symbol();
if let Some(picker) = self.go_to_symbol.as_mut() {
let carried = if prefix == ':' { &query } else { rest };
for c in carried.chars() {
picker.push_char(c);
}
}
}
}
}
/// 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);
// VS Code offers Pin Editor on an unpinned tab and Unpin Editor on
// a pinned one (#852), never the one that would do nothing.
palette.set_hidden(vec![if self.editor.is_pinned(self.editor.active_index()) {
crate::widgets::command_palette::Command::PinEditor
} else {
crate::widgets::command_palette::Command::UnpinEditor
}]);
// The chords as keybindings.json leaves them (#1482): a user's own
// chord, and no built-in chord a user binding gave to another command.
palette.hint_overrides = crate::widgets::command_palette::ALL_COMMANDS
.iter()
.filter_map(|&cmd| match self.keymap.chord_for(cmd) {
Some(user) => Some((cmd, crate::keymap::display_chord(&user))),
None => self
.keymap
.shadows_builtin(cmd)
.then(|| (cmd, String::new())),
})
.collect();
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(),
// Alt+Enter: go, then view that symbol in a tab of its own (#369).
(KeyCode::Enter, m) if m.contains(KeyModifiers::ALT) => {
let target = picker.selected_item().map(|i| i.path.clone());
self.jump_to_workspace_symbol_selection();
// The server's path may be spelled differently from the
// tab's (a symlink, `..`): a landed jump is the same file.
let landed = match (target, self.editor.path.as_ref()) {
(Some(t), Some(p)) => {
&t == p
|| std::fs::canonicalize(&t)
.is_ok_and(|t| std::fs::canonicalize(p).is_ok_and(|p| p == t))
}
_ => false,
};
if landed {
self.open_symbol_tab();
}
}
(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 config_dir = self.config_dir.clone();
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,
&config_dir,
&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);
}
// Written by croft itself: nothing for the config watch to reload.
self.config_watch.note(&self.macros_path.clone());
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;
// The tab a tab command acts on (#1427): the clicked tab when a
// tab-strip mouse binding runs it directly, as VS Code's tab commands
// act on the clicked tab, else the active tab. Taken here so a
// command this one runs in turn never sees it.
let tab_target = self
.tab_click_target
.take()
.unwrap_or_else(|| self.editor.active_index());
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.editor.has_line_comment_syntax() {
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::KillToEndOfLine => self.kill_to_end_of_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::IncrementNumber => self.bump_number_under_cursor(1),
Cmd::DecrementNumber => self.bump_number_under_cursor(-1),
Cmd::TrimTrailingWhitespace => {
if self.editor.trim_trailing_whitespace() {
self.status = String::from("Trimmed trailing whitespace");
}
}
Cmd::EmmetExpandAbbreviation => self.expand_emmet_abbreviation(),
Cmd::ExpandSelection => self.expand_selection(),
Cmd::ShrinkSelection => self.shrink_selection(),
Cmd::SwitchHeaderSource => self.switch_header_source(),
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::SelectAllOccurrences => self.select_all_occurrences(),
Cmd::AddCursorsToLineEnds => self.add_cursors_to_line_ends(),
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::ToggleLiveRun => self.toggle_live_run(),
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+Enter's run from any terminal (#843): the same confirm popup.
Cmd::RunCodeBlockAtCursor => {
if !self.run_fence_at_cursor() {
self.status = String::from(
"Run code block: open a Markdown file's source (not its preview) and put the caret in a runnable fence",
);
}
}
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(),
Cmd::ToggleFindInSelection => self.toggle_editor_find_in_selection(),
// 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::GoToNextChange => self.jump_editor_change(true),
Cmd::GoToPrevChange => self.jump_editor_change(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(),
Cmd::PeekReferences => self.peek_references_at_cursor(),
// The caret-driven LSP actions (#1212), the same calls the F-key
// chords make. A palette run or a rebound chord on a non-text
// view says why nothing happened instead of staying silent.
Cmd::GoToDefinition
| Cmd::GoToReferences
| Cmd::GoToDeclaration
| Cmd::GoToTypeDefinition
| Cmd::GoToImplementations
| Cmd::RenameSymbol
if self.editor.has_non_text_view() =>
{
self.status = format!("{} needs a text file", cmd.title());
}
Cmd::GoToDefinition => self.request_definition_at_cursor(),
Cmd::GoToReferences => self.request_references_at_cursor(),
Cmd::GoToDeclaration => self.request_declaration_at_cursor(),
Cmd::GoToTypeDefinition => self.request_type_definition_at_cursor(),
Cmd::GoToImplementations => self.request_implementation_at_cursor(),
Cmd::RenameSymbol => self.start_rename_symbol(),
// 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::GitViewStash => {
self.open_stash_picker(crate::widgets::list_picker::ListPurpose::StashView)
}
Cmd::GitUndoLastCommit => {
self.dispatch_scm_action(crate::widgets::scm_menu::ScmAction::UndoLastCommit)
}
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::ToggleOverviewRuler => {
self.editor.overview_ruler = !self.editor.overview_ruler;
self.status = if self.editor.overview_ruler {
String::from("Overview ruler on")
} else {
String::from("Overview ruler off")
};
}
Cmd::ToggleBookmark => self.toggle_bookmark(),
Cmd::NextBookmark => self.goto_bookmark(true),
Cmd::PreviousBookmark => self.goto_bookmark(false),
Cmd::ClearBookmarks => self.clear_bookmarks(),
Cmd::SaveFile => self.save(),
Cmd::SaveAs => self.open_save_as_prompt(),
Cmd::RevertFile => self.revert_file(),
Cmd::SaveAll => self.save_all(),
Cmd::NewUntitledFile => self.new_untitled_file(),
Cmd::NewFile => {
let target = self.palette_create_target_dir();
self.open_create_prompt(CreateKind::File, target);
}
Cmd::NewFolder => {
let target = self.palette_create_target_dir();
self.open_create_prompt(CreateKind::Folder, target);
}
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")
};
}
// The keyboard route on Linux, where Ctrl+A is line start and a
// terminal without Super forwarding never delivers Cmd+A (#852).
Cmd::SelectAll => {
self.focus_pane(Pane::Editor);
self.editor.select_all();
self.status = format!(
"Selected {} chars",
self.editor.selection_text().chars().count()
);
}
Cmd::CloseEditor => self.request_close_tab(tab_target),
Cmd::ReopenClosedEditor => self.reopen_closed_tab(),
// The Explorer's Cmd+Z (#843), which has no `Ctrl` form.
Cmd::ZoxideJump => self.open_zoxide_jump(),
// The tab menu's rows (#852), on the active tab and through the
// same methods its clicks and the Cmd+K chords use.
Cmd::CloseOtherEditors => self.close_other_tabs(tab_target),
Cmd::CloseEditorsToTheRight => self.close_tabs_to_right(tab_target),
Cmd::CloseSavedEditors => self.close_saved_tabs(),
Cmd::CloseAllEditors => self.close_all_tabs(),
Cmd::PinEditor => self.set_active_tab_pinned(true),
Cmd::UnpinEditor => self.set_active_tab_pinned(false),
Cmd::KeepEditor => self.keep_tab_open(tab_target),
Cmd::MoveEditorLeftInGroup => self.move_active_tab(false),
Cmd::MoveEditorRightInGroup => self.move_active_tab(true),
Cmd::MoveEditorToNextGroup => self.move_active_editor_to_adjacent_group(true),
Cmd::MoveEditorToPreviousGroup => self.move_active_editor_to_adjacent_group(false),
Cmd::SplitEditor => self.split_editor(),
// The chords' own moves (#843): Cmd+Opt+Left / Right have no
// `Ctrl` form off macOS.
Cmd::FocusLeftEditorGroup => self.focus_editor_group(true),
Cmd::FocusRightEditorGroup => self.focus_editor_group(false),
Cmd::QuickOpen => self.open_file_finder(),
Cmd::TakeTheTour => self.start_demo(),
Cmd::SarifNextResult => self.step_sarif_result(true),
Cmd::SarifPreviousResult => self.step_sarif_result(false),
Cmd::SarifOpenCodeScanning => self.open_code_scanning_picker(),
Cmd::SarifLoadCodeScanning => match self.code_scan_branch() {
Some(branch) => self.start_code_scan_lookup(branch, true),
None => self.status = String::from("Code scanning: not in a git repository"),
},
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::FocusBreadcrumbs => self.focus_breadcrumbs(),
Cmd::ShowSearch => self.set_sidebar_view(SidebarView::Search),
Cmd::ReplaceInFiles => self.open_replace_in_files(),
// Run from the palette the side bar may be hidden, so it is
// revealed first: a toggle flipped out of sight is a toggle the
// user cannot confirm.
Cmd::SearchToggleMatchCase => {
self.set_sidebar_view(SidebarView::Search);
self.toggle_search_opt(crate::widgets::search::SearchToggle::CaseSensitive);
}
Cmd::SearchToggleWholeWord => {
self.set_sidebar_view(SidebarView::Search);
self.toggle_search_opt(crate::widgets::search::SearchToggle::WholeWord);
}
Cmd::SearchToggleRegex => {
self.set_sidebar_view(SidebarView::Search);
self.toggle_search_opt(crate::widgets::search::SearchToggle::UseRegex);
}
Cmd::SearchTogglePreserveCase => {
self.set_sidebar_view(SidebarView::Search);
self.toggle_search_opt(crate::widgets::search::SearchToggle::PreserveCase);
}
Cmd::SearchToggleDetails => {
self.set_sidebar_view(SidebarView::Search);
self.search.toggle_details();
}
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, and a Reopen-as-Preview
// log view's (#1537), which a reload would restore.
self.editor.force_text = false;
self.editor.force_log = 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::NotebookRunAll => {
let text = self.editor.lines.join("\n");
if self
.editor
.markdown_preview
.as_ref()
.is_some_and(|m| m.notebook)
{
self.run_notebook_cells(crate::notebook_kernel::code_cells(&text));
} else {
self.status = String::from("Run All works on a notebook's rendered view");
}
}
Cmd::NotebookInterrupt => {
self.notebook_kernel_request(crate::notebook_kernel::Request::Interrupt)
}
Cmd::NotebookRestart => {
self.notebook_kernel_request(crate::notebook_kernel::Request::Restart)
}
Cmd::NotebookSelectKernel => self.select_notebook_kernel(),
Cmd::TestingRunWithCoverage => self.run_all_tests_with_coverage(),
Cmd::CoverageClear => self.clear_coverage(),
Cmd::TestingInstallCoverageTool => self.install_coverage_tool(),
Cmd::TestingShowCoverageReport => self.show_coverage_report(),
Cmd::DeveloperShowMemoryUsage => self.show_memory_usage(),
Cmd::RunTestAtCursorWithCoverage => self.run_test_at_cursor_with_coverage(),
Cmd::TestingToggleWatchAll => {
self.toggle_test_watch(crate::testing::watch::WatchScope::All)
}
Cmd::TestingGoToFirstFailure => self.go_to_first_failed_test(),
Cmd::TestingCancelRun => self.cancel_test_run(),
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;
self.editor.force_log = false;
match self.editor.open(&p) {
// Plain text with no grammar (#1537): a `.txt` or
// `.out` capture, or a `.log`, gets the rendered
// log view's colours instead of a refusal. The
// log view reads raw bytes as UTF-8, so a UTF-16 or
// legacy-encoded buffer keeps its decoded text.
Ok(())
if !self.editor.has_non_text_view()
&& self.editor.markdown_preview.is_none()
&& self.editor.language().is_none()
&& self.editor.encoding == encoding_rs::UTF_8 =>
{
self.editor.force_log = true;
if let Err(e) = self.editor.open(&p) {
self.status = format!("Reopen as preview: {e}");
} else if self.editor.log.is_none() {
self.editor.force_log = false;
self.status =
String::from("No preview for this file type; showing the text");
}
}
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::CodeqlRunQuery => self.run_codeql_query(),
Cmd::CodeqlRemoveDatabase => {
if let Some(i) = self.current_codeql_database() {
self.confirm_remove_codeql_database(i);
}
}
Cmd::CodeqlRenameDatabase => {
if let Some(i) = self.current_codeql_database() {
self.prompt_rename_codeql_database(i);
}
}
Cmd::CodeqlSortDatabases => self.sort_codeql_databases(),
Cmd::CodeqlRevealDatabase => {
if let Some(i) = self.current_codeql_database() {
self.reveal_codeql_database(i);
}
}
Cmd::CodeqlUpgradeDatabase => {
if let Some(i) = self.current_codeql_database() {
self.upgrade_codeql_database(i);
}
}
Cmd::CodeqlClearCache | Cmd::CodeqlTrimCache | Cmd::CodeqlTrimCacheToOverlay => {
use crate::codeql_query::DbJob;
let job = match cmd {
Cmd::CodeqlClearCache => DbJob::ClearCache,
Cmd::CodeqlTrimCache => DbJob::TrimCache,
_ => DbJob::TrimCacheToOverlay,
};
if let Some(i) = self.current_codeql_database() {
self.start_codeql_db_job(i, job);
}
}
Cmd::CodeqlAddDatabaseSource => {
if let Some(i) = self.current_codeql_database() {
self.add_codeql_database_source(i);
}
}
Cmd::CodeqlDeleteUnusedDatabases => self.confirm_delete_unused_codeql_databases(),
Cmd::CodeqlRemoveHistory => {
if let Some(i) = self.current_codeql_history() {
self.confirm_remove_codeql_history(i);
}
}
Cmd::CodeqlRenameHistory => {
if let Some(i) = self.current_codeql_history() {
self.prompt_rename_codeql_history(i);
}
}
Cmd::CodeqlSortHistory => self.sort_codeql_history(),
Cmd::CodeqlViewQuery => {
if let Some(i) = self.current_codeql_history() {
self.view_codeql_history_query(i);
}
}
Cmd::CodeqlCreateQuery => self.prompt_create_codeql_query(),
Cmd::CodeqlRunQueryOnDatabases => self.run_codeql_query_on_databases(),
Cmd::CodeqlRunPack => match self.codeql.selected_pack() {
Some(p) => self.run_codeql_pack(p),
None => {
self.status = String::from(
"Select a query pack or one of its queries in the CodeQL side bar first",
);
}
},
Cmd::CodeqlCancelQueue => self.cancel_codeql_queue(),
Cmd::CodeqlCopyVersion => self.copy_codeql_version(),
Cmd::CodeqlDownloadCli => self.download_codeql_cli(),
Cmd::CodeqlCheckCliUpdates => self.check_codeql_cli_updates(),
Cmd::CodeqlInstallPackDependencies => match self.codeql.selected_pack() {
Some(p) => self.install_codeql_pack_dependencies(p),
None => {
self.status = String::from(
"Select a query pack or one of its queries in the CodeQL side bar first",
);
}
},
Cmd::CodeqlDownloadPacks => self.prompt_download_codeql_packs(),
Cmd::CodeqlRunPublishedPack => self.prompt_run_codeql_published_pack(),
Cmd::CodeqlQuickQuery => self.open_codeql_quick_query(),
Cmd::CodeqlCompareResults => {
if let Some(i) = self.current_codeql_history() {
self.compare_codeql_results(i);
}
}
Cmd::CodeqlShowEvaluatorLog => {
if let Some(i) = self.current_codeql_history() {
self.show_codeql_evaluator_log(i);
}
}
Cmd::CodeqlShowQueryLog => {
if let Some(i) = self.current_codeql_history() {
self.show_codeql_query_log(i);
}
}
Cmd::CodeqlShowEvaluatorLogSummary => {
if let Some(i) = self.current_codeql_history() {
self.show_codeql_evaluator_log_summary(i);
}
}
Cmd::CodeqlShowEvaluatorLogViewer => {
if let Some(i) = self.current_codeql_history() {
self.show_codeql_evaluator_log_viewer(i);
}
}
Cmd::CodeqlComparePerformance => {
if let Some(i) = self.current_codeql_history() {
self.compare_codeql_performance(i);
}
}
Cmd::CodeqlPreviewQueryHelp => self.preview_codeql_query_help(),
Cmd::CodeqlExportResults => self.prompt_export_codeql_results(),
Cmd::CodeqlRunQuerySuite => self.run_codeql_query_suite(),
Cmd::CodeqlSetUpController => self.prompt_codeql_controller(),
Cmd::CodeqlAddVariantRepo => self.prompt_add_codeql_variant_repo(),
Cmd::CodeqlAddVariantList => self.prompt_add_codeql_variant_list(),
Cmd::CodeqlAddVariantOwner => self.prompt_add_codeql_variant_owner(),
Cmd::CodeqlVariantCodeSearch => self.prompt_codeql_variant_code_search(),
Cmd::CodeqlOpenVariantConfig => self.open_codeql_variant_config(),
Cmd::CodeqlOpenVariantOnGithub => self.open_codeql_variant_on_github(),
Cmd::CodeqlRunVariantAnalysis => self.run_codeql_variant_analysis(),
Cmd::CodeqlExportVariantResults => {
self.prompt_export_codeql_variant_results(self.codeql.selected_variant_run())
}
Cmd::CodeqlCopyVariantRepoList => {
self.copy_codeql_variant_repo_list(self.codeql.selected_variant_run())
}
Cmd::CodeqlViewVariantLogs => {
self.view_codeql_variant_logs(self.codeql.selected_variant_run())
}
Cmd::CodeqlOpenVariantResults => {
self.open_codeql_variant_results(self.codeql.selected_variant_run())
}
Cmd::CodeqlRunTests => self.run_codeql_tests(),
Cmd::CodeqlDebugQuery => self.debug_codeql_query(),
Cmd::CodeqlDebugSelection => self.quick_eval_codeql(false),
Cmd::CodeqlResultsUp => self.walk_codeql_results(-1, 0),
Cmd::CodeqlResultsDown => self.walk_codeql_results(1, 0),
Cmd::CodeqlResultsLeft => self.walk_codeql_results(0, -1),
Cmd::CodeqlResultsRight => self.walk_codeql_results(0, 1),
Cmd::SheetSortByColumn => self.sort_sheet_by_column(),
Cmd::CodeqlQuickEval => self.quick_eval_codeql(false),
Cmd::CodeqlQuickEvalCount => self.quick_eval_codeql(true),
Cmd::CodeqlViewAst => self.view_codeql_ast(),
Cmd::CodeqlOpenModelEditor => self.open_codeql_model_editor(),
Cmd::CodeqlModelEndpoint => {
self.model_codeql_endpoint(self.codeql.selected_model_endpoint())
}
Cmd::CodeqlOpenReferencedFile => self.open_codeql_referenced_file(),
Cmd::CodeqlViewAlertsCsv => self.view_codeql_alerts(true),
Cmd::CodeqlViewAlertsSarif => self.view_codeql_alerts(false),
Cmd::CodeqlViewResultsCsv => self.view_codeql_raw_results(),
Cmd::CodeqlShowResultSet => self.show_codeql_result_sets(),
Cmd::CodeqlViewCfg => self.view_codeql_cfg(),
Cmd::CodeqlRunAllQueries => self.run_all_codeql_queries(),
Cmd::CodeqlRunSelectedQueries => self.run_selected_codeql_queries(),
Cmd::CodeqlCancelRunningQuery => self.cancel_codeql_run(),
Cmd::CodeqlAcceptTestOutput => self.accept_codeql_test_output(),
Cmd::CodeqlFocusSideBar => {
// Show it and take the keys, as VS Code's "Focus" does.
self.open_codeql_view();
if self.sidebar_view == SidebarView::CodeQL {
self.focus = Pane::Tree;
}
}
Cmd::CodeqlOpenResultsDirectory => self.open_codeql_results_directory(),
Cmd::ShowCodeQL => self.open_codeql_view(),
Cmd::RunTestAtCursor => self.run_test_at_cursor(),
Cmd::TestingRunAll => {
if !self.testing_busy_says_so() {
self.run_all_tests();
}
}
Cmd::TestingRunFile => self.run_tests_in_current_file(),
Cmd::TestingRerunFailed => self.rerun_failed_tests(),
Cmd::TestingRerunLast => self.rerun_last_test_run(),
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::ToggleCenteredLayout => self.toggle_centered_layout(),
Cmd::ToggleTerminal => self.toggle_terminal(),
// Each tab names the command that shows it, so the palette reads
// the tab from there rather than keeping a second mapping.
Cmd::FocusTerminal
| Cmd::ShowProblems
| Cmd::ShowOutput
| Cmd::ShowPorts
| Cmd::ShowCaptures => {
if let Some(tab) = BottomPanelTab::ALL
.into_iter()
.find(|tab| tab.show_command() == cmd)
{
self.set_bottom_panel_tab(tab);
}
}
Cmd::OutputSelectChannel => self.open_output_channel_picker(),
// The Customize Layout popup's rows (#852), through the same
// setters its clicks use.
Cmd::ToggleActivityBar => self.toggle_activity_bar(),
Cmd::ToggleStatusBar => self.toggle_status_bar(),
Cmd::ToggleSideBarPosition => {
self.set_side_bar_position(match self.side_bar_position {
SideBarPosition::Left => SideBarPosition::Right,
SideBarPosition::Right => SideBarPosition::Left,
})
}
Cmd::SetPanelAlignment => self.open_panel_alignment_picker(),
Cmd::SetQuickInputPosition => self.open_quick_input_position_picker(),
Cmd::CustomizeLayout => self.open_customize_layout_menu(),
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(ProjectCheck::Empty) => {
self.status =
String::from("Whole-project check: tsconfig.json includes no files");
}
Some(_) if self.project_check_running => {
self.status = String::from("A whole-project check is already running");
}
Some(ProjectCheck::Run(runs)) => {
// 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. One run per referenced project,
// merged: both streams concatenated, and the
// last failing status kept, so one failing
// project fails the sweep.
let mut done: Option<std::io::Result<std::process::Output>> = None;
for (program, args) in runs {
let out = std::process::Command::new(&program)
.args(&args)
.current_dir(&root_for_thread)
.output();
done = Some(match (done, out) {
(Some(Ok(mut acc)), Ok(o)) => {
acc.stdout.extend(o.stdout);
acc.stderr.extend(o.stderr);
if !o.status.success() {
acc.status = o.status;
}
Ok(acc)
}
(Some(Err(e)), _) | (_, Err(e)) => Err(e),
(None, Ok(o)) => Ok(o),
});
if matches!(done, Some(Err(_))) {
break;
}
}
if let Some(done) = done {
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::RunSelectedText => self.run_selected_text_in_terminal(),
// Cmd+] / Cmd+[ (#843), which have no `Ctrl` form. The chords
// work in the terminal pane; from the palette the commands bring
// it up and focus it first, as VS Code's do.
Cmd::FocusNextTerminal | Cmd::FocusPreviousTerminal => {
self.show_terminal = true;
self.focus_pane(Pane::Terminal);
if cmd == Cmd::FocusNextTerminal {
self.cycle_terminal();
} else {
self.cycle_terminal_back();
}
}
Cmd::TerminalClear
| Cmd::TerminalRename
| Cmd::TerminalKill
| Cmd::TerminalSplit
| Cmd::TerminalNewWithProfile
| Cmd::TerminalQuickSelect
| Cmd::TerminalCopyMode
| Cmd::TerminalCommandHistory
| Cmd::TerminalOpenScrollback => self.run_terminal_command(cmd),
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::AddDebugConfig => self.open_add_debug_config(),
Cmd::StopDebugging => self.debug_stop_by_user(),
Cmd::PauseDebugging => self.debug_pause(),
Cmd::SwitchDebugSession => self.switch_debug_session(),
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::ShowSupertypes => self.request_type_hierarchy_at_cursor(true),
Cmd::ToggleCodeLens => self.toggle_code_lens(),
Cmd::OpenSearchEditor => self.open_search_editor(),
Cmd::RebaseAbort => self.abort_rebase_todo(),
Cmd::GitContinueOperation => self.continue_git_operation(),
Cmd::GitSkipOperation => self.skip_git_operation(),
Cmd::GitAbortOperation => self.abort_git_operation(),
Cmd::GitCreateTag => {
self.dispatch_scm_action(crate::widgets::scm_menu::ScmAction::CreateTag)
}
Cmd::GitPushTags => {
self.dispatch_scm_action(crate::widgets::scm_menu::ScmAction::PushTags)
}
Cmd::GitDeleteRemoteTag => {
self.dispatch_scm_action(crate::widgets::scm_menu::ScmAction::DeleteRemoteTag)
}
Cmd::ToggleTerminalSuggestions => self.toggle_terminal_suggestions(),
Cmd::ToggleScreenReader => self.toggle_screen_reader(),
Cmd::OpenKeyboardShortcuts => self.open_keyboard_shortcuts(),
Cmd::SwitchProfile => self.open_profiles(),
Cmd::ToggleInlineSuggestions => self.toggle_inline_suggestions(),
Cmd::RerunSearchEditor => self.rerun_search_editor(),
Cmd::DebugAddHitCountBreakpoint => self.debug_edit_hit_condition(),
Cmd::DebugAddFunctionBreakpoint => self.debug_add_function_breakpoint(),
Cmd::DebugRemoveFunctionBreakpoints => self.debug_clear_function_breakpoints(),
Cmd::DebugRunToCursor => self.debug_run_to_cursor(),
Cmd::DebugBreakOnValueChange => self.debug_break_on_value_change(),
Cmd::DebugRemoveDataBreakpoints => self.debug_clear_data_breakpoints(),
Cmd::RunCodeLens => self.run_code_lens_at_cursor(),
Cmd::ShowSubtypes => self.request_type_hierarchy_at_cursor(false),
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::SessionDetach => self.detach_session_client(),
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::DebugInstallDelve => self.install_delve(),
Cmd::RemoteSyncConfigNow => {
self.open_input_prompt(crate::widgets::input_prompt::InputPrompt::new(
crate::widgets::input_prompt::InputPurpose::SyncConfigHost,
String::from("Sync config to host"),
String::from("an ssh host alias"),
))
}
Cmd::StopAutoApprove => self.stop_auto_approve(),
Cmd::ScrubOpenHere => self.scrub_open_here(),
Cmd::ScrubDiffToWorkingTree => self.scrub_diff_to_working_tree(),
Cmd::OpenAsSymbolTab => self.open_symbol_tab(),
Cmd::LoadReviewThreads => self.load_review_threads(),
Cmd::ReviewAddComment => self.open_review_comment_prompt(),
Cmd::ReviewSubmit => self.open_review_submit(),
Cmd::ReviewToggleResolved => self.toggle_review_thread_resolved(),
Cmd::ExportCommentsToPr => self.open_export_comments(),
Cmd::NoteAdd => self.open_sticky_note_prompt(),
Cmd::NoteDelete => self.delete_sticky_note_here(),
Cmd::ReviewDiscardPending => {
let n = self.review_pending.len();
self.review_pending.clear();
self.review_pending_pr = None;
self.status = format!("Discarded {n} pending comment(s)");
}
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::ReviewPullRequest => {
// The open PRs first, fetched off the UI thread; the typed
// prompt stays one row away (and is the fallback when gh
// cannot list).
self.status = String::from("Listing open pull requests…");
self.spawn_pr_gh(PrGhJob::List, crate::pr_review::list_args());
}
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::OpenAgentLaneSection => self.show_agent_lane_section(),
Cmd::PickAgentLaneFile => self.pick_agent_lane_file(),
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::UpdateCroft => self.update_croft(),
Cmd::OpenSettings => self.open_settings_view(),
Cmd::OpenSettingsEditor => self.open_settings_editor(),
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 => SETTINGS_TEMPLATE.to_string(),
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_pinned(&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, label, name) = match &action {
BranchAction::Checkout(name) => (
crate::git::checkout_branch(&self.scm_root(), name),
"Switched to",
"switch",
name,
),
BranchAction::Track { remote_ref, name } => (
crate::git::track_remote_branch(&self.scm_root(), remote_ref, name),
"Switched to",
"switch --track",
name,
),
BranchAction::Create(name) => (
crate::git::create_branch(&self.scm_root(), name),
"Created",
"switch -c",
name,
),
};
self.log_git(label, &result);
match result {
Ok(summary) => {
// One line (#858): git's result, or, when git said only which
// edits it carried over (`M\tpath`) or how the branch stands
// against its upstream, where the switch went.
let summary = crate::git::result_line(&summary);
let (feedback, status) = if summary.is_empty() {
let line = format!("{verb} {name}");
(line.clone(), line)
} else {
(summary.clone(), format!("{verb}: {summary}"))
};
self.close_branch_picker();
self.source_control.commit_feedback = Some(feedback);
self.source_control.commit_feedback_is_error = false;
self.status = status;
self.active_git_bypass_debounce();
self.refresh_git_status_debounced();
self.refresh_source_control();
}
Err(err) => {
let why = crate::git::error_line(&err);
self.source_control.commit_feedback = Some(format!("branch: {why}"));
self.source_control.commit_feedback_is_error = true;
self.status = format!("Branch: {why}");
}
}
}
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.dismiss_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.dismiss_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() {
self.reselect_editor_find();
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 = self.editor_find_seed();
let mut state = crate::widgets::editor_find::EditorFind::new(initial.clone(), opts);
// Selected, so what the user types next replaces the seed (#1278).
state.query_selected = !initial.is_empty();
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 = find_texts(self.terminal().find_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 = find_texts(self.terminal().find_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;
}
// Logical lines, soft-wrapped rows joined, so a match the pane's
// width cut in two is found (#1275). A match is named by its line's
// first row and a char index into the joined text.
let (find_lines, now) = self.terminal().find_lines_and_clock();
if find_lines.is_empty() {
return;
}
let lines: Vec<String> = find_lines.iter().map(|l| l.text.clone()).collect();
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 = find_lines.iter().rposition(|l| l.start <= abs).unwrap_or(0);
(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 = find_lines[m.row].start;
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(find_lines[m.row].line_of(m.col_chars));
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() {
// Over wrapped rows joined, as the painter masks them.
let masked = crate::triggers::redacted_row_ranges(&lines, &wraps, &self.triggers);
let clear = |row: usize, start: usize, len: usize| {
masked.get(row).is_none_or(|ranges| {
ranges
.iter()
.all(|&(s, l)| start + len <= s || start >= s + l)
})
};
// 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 {
self.deliver_copied_text(&text);
}
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();
let copied = self
.copy_where_pasted(&text)
.status(&format!("{} chars", text.chars().count()));
if shifted {
self.terminal_mut().paste_input(text.as_bytes());
self.status = format!("{copied} and pasted into the shell");
} else {
self.status = copied;
}
} 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() {
// Every tab's: a range taken in one tab and left there when the
// bar closes from another would clip that tab's next find.
for tab in self.editor.editors.iter_mut() {
tab.find_range = None;
}
for group in self.editor_layout.inactive_groups_mut() {
for tab in group.editors.iter_mut() {
tab.find_range = None;
}
}
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 range = self.editor_find_range();
let (scope, _, window) = editor_find_lines(&self.editor, range);
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_in(scope, &state.query, opts, window),
false,
);
if state.query.is_empty() {
state.match_index = None;
self.editor.active_search_match = None;
self.editor.set_search_highlight(None, opts);
return;
}
let query = state.query.clone();
self.editor.set_search_highlight(Some(query.clone()), opts);
let from_row = self.editor.cursor_row;
let from_col = self.editor.cursor_col;
if let Some(m) = self.editor_find_step(true, &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) = self.editor_find_step(
true,
&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) = self.editor_find_step(
false,
&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();
let indexing = log.indexing();
// A reload's kept place may lie past what was indexed so far.
if changed {
self.editor.settle_log_reload();
}
if indexing {
return changed;
}
let Some(log) = self.editor.log.as_ref() else {
return true;
};
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 match is the reader's place now; a reload still settling its
// own place must not scroll it away on the next index batch.
self.editor.cancel_log_reload();
// 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();
}
/// The next (`forward`) or previous find-bar match from `(row, col)`,
/// searching and wrapping within a symbol tab's symbol only (#369).
fn editor_find_step(
&self,
forward: bool,
needle: &str,
opts: crate::widgets::search::SearchOpts,
row: usize,
col: usize,
skip_current: bool,
) -> Option<crate::widgets::editor_find::MatchPos> {
let range = self.editor_find_range();
let (scope, first, window) = editor_find_lines(&self.editor, range);
let (row, col) = editor_find_scope_pos(scope, first, window, (row, col))?;
let step = if forward {
crate::widgets::editor_find::find_next_match_in
} else {
crate::widgets::editor_find::find_prev_match_in
};
let mut m = step(scope, needle, opts, window, row, col, skip_current)?;
m.row += first;
Some(m)
}
fn refresh_editor_find_index(&mut self) {
let range = self.editor_find_range();
let (scope, first, window) = editor_find_lines(&self.editor, range);
let caret = (self.editor.cursor_row, self.editor.cursor_col);
// A caret outside the selection is on none of its matches.
let outside = range.is_some_and(|(a, b)| caret < a || caret > b);
let at = editor_find_scope_pos(scope, first, window, caret);
let Some(state) = self.editor_find.as_mut() else {
return;
};
let opts = state.opts;
state.match_index = at.filter(|_| !outside).and_then(|(row, col)| {
crate::widgets::editor_find::match_index_at_in(
scope,
&state.query,
opts,
window,
row,
col,
)
});
}
/// The range Find in Selection limits the open find bar to: the active
/// tab's own (#1577), so another tab never searches by its coordinates.
fn editor_find_range(&self) -> Option<crate::widgets::editor_find::FindRange> {
self.editor_find.as_ref()?;
self.editor.find_range
}
/// Find in Selection (#1577, `Alt+L` in the find bar, VS Code's `≡`):
/// limit the matches, the count and Replace All to the selection (the
/// caret's line with none), or lift the limit again. From outside the
/// find bar it opens it first.
fn toggle_editor_find_in_selection(&mut self) {
if !self.editor_is_text() || self.editor.diff.is_some() {
self.status = String::from("Find in Selection works on text tabs");
return;
}
let range = self
.editor
.selection
.as_ref()
.filter(|s| s.anchor != s.head)
.map(|s| s.normalised())
.unwrap_or_else(|| {
let row = self.editor.cursor_row;
(
(row, 0),
(
row,
self.editor.lines.get(row).map_or(0, |l| l.chars().count()),
),
)
});
if self.editor_find.is_none() {
self.open_editor_find();
}
let Some(state) = self.editor_find.as_mut() else {
return;
};
// The range belongs to the tab it was taken in (#1577): another
// tab under the same find bar searches whole until it gets its own.
let on = self.editor.find_range.is_none();
self.editor.find_range = on.then_some(range);
state.in_selection = self.editor.find_range;
self.status = String::from(if on {
"Find in Selection: on"
} else {
"Find in Selection: off"
});
self.editor_find_recount();
}
/// Recount the find bar's matches and re-place the active one, after
/// its scope changed under an unchanged query.
fn editor_find_recount(&mut self) {
let range = self.editor_find_range();
let (scope, _, window) = editor_find_lines(&self.editor, range);
let Some(state) = self.editor_find.as_mut() else {
return;
};
let (needle, opts) = (state.query.clone(), state.opts);
state.set_match_count(
crate::widgets::editor_find::count_matches_in(scope, &needle, opts, window),
false,
);
self.editor.active_search_match = None;
if needle.is_empty() {
return;
}
let (row, col) = (self.editor.cursor_row, self.editor.cursor_col);
if let Some(m) = self.editor_find_step(true, &needle, opts, row, col, false) {
self.jump_editor_to_match(m);
}
self.refresh_editor_find_index();
}
/// 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);
}
/// What Ctrl+F puts in the find bar: a one-line selection, else the
/// whole word under the caret or just left of it (#1278; the half of
/// the word before the caret made typing build `loadOrsave`).
fn editor_find_seed(&self) -> String {
let selection = self.editor.selection_text();
if !selection.is_empty() && !selection.contains('\n') {
return selection;
}
let (row, col) = (self.editor.cursor_row, self.editor.cursor_col);
self.editor
.word_string_at(row, col)
.or_else(|| {
col.checked_sub(1)
.and_then(|c| self.editor.word_string_at(row, c))
})
.unwrap_or_default()
}
/// Ctrl+F on an open find bar, as in VS Code: take a one-line selection
/// if there is one, focus the query and select it, so typing replaces it.
fn reselect_editor_find(&mut self) {
let selection = self.editor.selection_text();
if self.editor.diff.is_none() && !selection.is_empty() && !selection.contains('\n') {
self.editor_find_set_query(selection);
}
if let Some(s) = self.editor_find.as_mut() {
s.focus = crate::widgets::editor_find::FindField::Query;
s.query_selected = !s.query.is_empty();
}
}
fn handle_editor_find_key(&mut self, key: KeyEvent) {
if is_editor_replace_key(key) {
self.open_editor_replace();
return;
}
if is_editor_find_key(key) {
self.reselect_editor_find();
return;
}
// Find in Selection (#1577): VS Code's `Alt+L`. A bare Alt only, so
// a macOS keyboard typing `¬` with Option keeps it.
// Ahead of the selected query below, which `Alt+L` must not clear.
if key.modifiers == KeyModifiers::ALT && matches!(key.code, KeyCode::Char('l' | 'L')) {
self.toggle_editor_find_in_selection();
return;
}
// A selected query (#1278) is replaced by what is typed or pasted
// and cleared by Backspace / Delete; any other editing or caret key
// drops the selection and then acts as usual.
let selected = !self.editor_find_replace_focused()
&& self.editor_find.as_ref().is_some_and(|s| s.query_selected);
if selected {
let plain_char = matches!(key.code, KeyCode::Char(_))
&& !key
.modifiers
.intersects(KeyModifiers::CONTROL | KeyModifiers::SUPER);
let paste = matches!(key.code, KeyCode::Char('v'))
&& key
.modifiers
.intersects(KeyModifiers::CONTROL | KeyModifiers::SUPER);
let keeps = matches!(
key.code,
KeyCode::Enter | KeyCode::F(3) | KeyCode::Tab | KeyCode::BackTab | KeyCode::Esc
) || (matches!(key.code, KeyCode::Char('a'))
&& key
.modifiers
.intersects(KeyModifiers::CONTROL | KeyModifiers::SUPER));
if let Some(s) = self.editor_find.as_mut()
&& !keeps
{
s.query_selected = false;
}
if plain_char || paste || matches!(key.code, KeyCode::Backspace | KeyCode::Delete) {
self.editor_find_set_query(String::new());
if matches!(key.code, KeyCode::Backspace | KeyCode::Delete) {
return;
}
}
}
let word_delete = key.code == KeyCode::Backspace
&& key
.modifiers
.intersects(KeyModifiers::CONTROL | KeyModifiers::ALT);
if word_delete {
// The word before the end, with any spaces after it, as in a
// text field; a lone punctuation mark goes on its own.
self.editor_find_edit_focused(|s| {
let kept = s.trim_end().len();
let word_start = s[..kept]
.char_indices()
.rev()
.find(|&(_, c)| !crate::widgets::editor::is_word_char(c))
.map_or(0, |(i, c)| i + c.len_utf8());
let cut = if word_start == kept {
s[..kept].char_indices().next_back().map_or(0, |(i, _)| i)
} else {
word_start
};
s.truncate(cut);
});
return;
}
if matches!(key.code, KeyCode::Char('a'))
&& key
.modifiers
.intersects(KeyModifiers::CONTROL | KeyModifiers::SUPER)
{
if let Some(s) = self.editor_find.as_mut()
&& s.focus == crate::widgets::editor_find::FindField::Query
{
s.query_selected = !s.query.is_empty();
}
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);
// The selected range ends further on (or sooner) by what the
// replacement added (#1577).
if let Some(s) = self.editor_find.as_mut()
&& let Some((start, end)) = self.editor.find_range.as_mut()
{
// As `replace_find_match` put it in: a `\r` is a line break too.
let text = crate::widgets::editor::normalize_newlines(&text);
let breaks = text.matches('\n').count();
if row == end.0 {
let after = end.1.saturating_sub(col + len);
end.1 = match text.rfind('\n') {
Some(i) => text[i + 1..].chars().count() + after,
None => col + text.chars().count() + after,
};
}
if row <= end.0 {
end.0 += breaks;
}
debug_assert!(*start <= *end);
s.in_selection = self.editor.find_range;
}
self.editor.active_search_match = None;
self.editor.set_search_highlight(Some(needle.clone()), opts);
let range = self.editor_find_range();
let (scope, _, window) = editor_find_lines(&self.editor, range);
if let Some(s) = self.editor_find.as_mut() {
s.set_match_count(
crate::widgets::editor_find::count_matches_in(scope, &needle, opts, window),
false,
);
}
if let Some(m) = self.editor_find_step(
true,
&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);
// A symbol tab replaces within its symbol only (#369), and Find in
// Selection within the selected range (#1577).
let range = self.editor_find_range();
let (scope, first, window) = editor_find_lines(&self.editor, range);
let scope_end = first + scope.len();
let Some((replaced, n)) = crate::widgets::editor_find::replace_all_in_lines_in(
scope,
&needle,
&replacement,
opts,
window,
) else {
return;
};
if n == 0 {
self.status = String::from("Replace All: no matches");
return;
}
// Text after the range's end is untouched, so the end keeps its
// distance from the end of its (now last replaced) line.
let new_range = window.map(|(start, (_, c1))| {
let tail = scope
.last()
.map_or(0, |l| l.chars().count().saturating_sub(c1));
let last = replaced.last().map_or(0, |l| l.chars().count());
(
(first + start.0, start.1),
(
first + replaced.len().saturating_sub(1),
last.saturating_sub(tail),
),
)
});
let mut new_lines = self.editor.lines[..first].to_vec();
new_lines.extend(replaced);
new_lines.extend_from_slice(&self.editor.lines[scope_end..]);
self.editor.replace_all_lines(new_lines);
self.editor.active_search_match = None;
if range.is_some() {
self.editor.find_range = new_range;
if let Some(s) = self.editor_find.as_mut() {
s.in_selection = new_range;
}
}
let (scope, _, window) = editor_find_lines(&self.editor, new_range);
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_in(scope, &needle, opts, window),
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;
};
// The chip shows the active tab's range, not one left in another.
state.in_selection = self.editor.find_range;
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) {
self.editor.sync_occurrence_word_sel();
self.recording_file_switches(|app| app.handle_mouse_inner(m));
}
fn handle_mouse_inner(&mut self, m: MouseEvent) {
// So does a click (#1609), except on the message itself, which opens
// its full text below.
let on_message = rect_contains(self.status_message_rect, m.column, m.row);
if matches!(m.kind, MouseEventKind::Down(_)) && !on_message {
self.status_wide = false;
}
// A click means the user moved on from a pending shortcut prompt.
if matches!(m.kind, MouseEventKind::Down(_))
&& (self.recording_shortcut.take().is_some()
| self.confirming_shortcut.take().is_some())
{
self.status = String::from("Shortcut unchanged");
}
// 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;
}
// The approval popup takes no clicks, and none reach what it covers.
if self.approval_ui.is_some() {
return;
}
// Nor does the unsaved-changes prompt (#862): a click behind it must
// not close or move the tabs it is asking about.
if self.pending_unsaved.is_some() {
return;
}
// The history scrubber's slider (#371): a press on the track seeks
// there, and a drag that started on it keeps seeking wherever the
// pointer goes, so the handle can be dragged off the row and back.
if self.scrubber.is_some() && !self.modal_overlay_open() {
let on_track = rect_contains(self.scrub_slider, m.column, m.row);
match m.kind {
MouseEventKind::Down(MouseButton::Left) if on_track => {
self.scrub_dragging = true;
self.scrub_seek_column(m.column);
return;
}
MouseEventKind::Drag(MouseButton::Left) if self.scrub_dragging => {
self.scrub_seek_column(m.column);
return;
}
MouseEventKind::Up(MouseButton::Left) if self.scrub_dragging => {
self.scrub_dragging = false;
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_codeql_rect, m.column, m.row) {
self.cancel_codeql_run();
return;
}
if rect_contains(self.status_update_rect, m.column, m.row) {
self.update_croft();
return;
}
if rect_contains(self.status_diag_rect, m.column, m.row) {
self.set_bottom_panel_tab(BottomPanelTab::Problems);
return;
}
if on_message {
self.show_status_messages();
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,
SidebarView::CodeQL => self.codeql.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.tab_click_target = self.editor.tab_at(m.column, m.row);
self.run_command(cmd);
self.last_mouse_pos = None;
self.tab_click_target = None;
return;
}
}
// A middle-click on a tab closes that tab (#1427), as in VS Code and
// browsers, asking about unsaved edits first as Ctrl+W does. The
// active tab stays active. A `middle_click` binding in `tab_strip`
// has already run above instead.
if matches!(m.kind, MouseEventKind::Down(MouseButton::Middle))
&& let Some(idx) = self.editor.tab_at(m.column, m.row)
{
self.dismiss_click_overlays(m);
self.focus_pane(Pane::Editor);
self.request_close_tab(idx);
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);
// The wheel over a hover scrolls its text rather than dismissing it
// (#1254): a long docstring's Returns/Raises sit below the box.
if let Some(popup) = self.hover_popup.as_mut()
&& rect_contains(popup.last_area, m.column, m.row)
{
match m.kind {
MouseEventKind::ScrollDown => {
popup.scroll_by(3);
return;
}
MouseEventKind::ScrollUp => {
popup.scroll_by(-3);
return;
}
_ => {}
}
}
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;
}
// An OUTLINE row: go to the symbol, or open it as its own
// tab (#369).
if rect_contains(self.outline.last_area, m.column, m.row)
&& let Some(idx) = self.outline.row_at(m.row)
&& let Some((path, line, col)) = self.outline.jump_target(idx)
&& let Some(sym) = self.outline.symbols().get(idx)
{
let (name, first, last) = (
sym.name.clone(),
sym.range_start_line as usize,
sym.range_end_line as usize,
);
self.context_menu = Some(ContextMenu::flat(
(m.column, m.row),
vec![
(
String::from("Go to Symbol"),
MenuAction::GoToOutlineSymbol {
path: path.clone(),
line,
col,
},
),
(
String::from("Open Symbol in Its Own Tab"),
MenuAction::OpenSymbolTab {
path,
name,
first,
last,
},
),
],
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 {
crumb: None,
scroll: Default::default(),
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),
});
// Split and Kill, as in VS Code's terminal menu (#1598):
// GNOME Terminal and Konsole keep Ctrl+Shift+T / W for
// their own New Tab and Close Tab, so off the kitty
// protocol this menu is the keyboard-free route. Split
// opens beside the ACTIVE pane, so a folded one offers
// only Kill, which carries its own index; a lone pane
// cannot be closed, so it offers no Kill.
if !folded {
items.push(MenuEntry::Item {
label: String::from("Split Terminal"),
action: MenuAction::SplitTerminal,
});
}
if self.terminals.len() > 1 {
items.push(MenuEntry::Item {
label: String::from("Kill Terminal"),
action: MenuAction::KillTerminal(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 {
crumb: None,
scroll: Default::default(),
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 },
));
}
let mut menu =
ContextMenu::flat((m.column, m.row), items, self.tree.root.clone());
// Then the clipboard and the palette, as VS Code's editor
// menu ends (#1117): the way to copy where the keys are
// awkward (Linux terminals, the `croft web` canvas).
// Cut and Paste edit the buffer, so only an editable text
// view offers them: a rendered preview hides its source
// and swallows those keys too. Copy takes the selection
// the view shows.
let editable = self.editor_is_text();
let mut clipboard = Vec::new();
if editable && self.editor.selection.is_some_and(|s| s.has_area()) {
clipboard.push(MenuEntry::item("Cut", MenuAction::EditorCut));
}
if self.editor_view_has_selection() {
clipboard.push(MenuEntry::item("Copy", MenuAction::EditorCopy));
}
if editable {
clipboard.push(MenuEntry::item("Paste", MenuAction::EditorPaste));
}
if !clipboard.is_empty() {
menu.items.push(MenuEntry::Separator);
menu.items.extend(clipboard);
}
menu.items.push(MenuEntry::Separator);
menu.items.push(MenuEntry::item(
"Command Palette",
MenuAction::ShowCommandPalette,
));
self.context_menu = Some(menu);
}
}
MouseEventKind::Down(MouseButton::Left) => {
// A new press starts a new gesture, even if the release of a
// breakpoint-lane press never arrived.
self.breakpoint_lane_press = false;
// 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.
// A code lens (#608) is a button, not text: run it.
if in_editor && let Some(idx) = self.editor.code_lens_at(m.column, m.row) {
self.focus_pane(Pane::Editor);
self.run_code_lens(idx);
return;
}
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), and one on an accept
// button above a conflict sets it. 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;
}
// An accept button above a conflict (#1169).
let action_hit = self.editor.merge.as_ref().and_then(|mv| {
mv.action_spans
.iter()
.find(|(y, xs, _, _)| *y == m.row && xs.contains(&m.column))
.map(|(_, _, idx, state)| (*idx, *state))
});
if let Some((idx, state)) = action_hit {
self.focus_pane(Pane::Editor);
self.merge_set_conflict(idx, state);
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_save_all(m.column, m.row) {
// VS Code's Save All on the section header (#852),
// checked first: the header row holds the button.
self.save_all();
} 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;
}
// AGENT LANE (#345): the header collapses it; a file row opens
// that file's diff against its reviewed snapshot.
if rect_contains(self.agent_lane_panel.last_area, m.column, m.row) {
if self.agent_lane_panel.hit_header(m.column, m.row) {
self.agent_lane_panel.toggle_collapse();
} else if let Some(crate::widgets::agent_lane::LaneRow::Agent {
name, ..
}) = self.agent_lane_panel.row_at(m.row).cloned()
{
// An agent's row folds its files away, or back.
self.agent_lane_panel.toggle_agent(&name);
} else if let Some(crate::widgets::agent_lane::LaneRow::File {
agent,
path,
label,
..
}) = self.agent_lane_panel.row_at(m.row).cloned()
{
// The ● marks the file reviewed; the rest of the row
// opens its diff.
if self.agent_lane_panel.hit_dot(m.column, m.row) {
if self.mark_agent_file_reviewed(&agent, &path) {
self.status = format!("{label}: reviewed");
}
} else {
self.diff_agent_lane_row(&agent, &path);
}
}
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.jump_in_scrub_view(line)
{
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.welcome_tour_button, m.column, m.row) {
self.start_demo();
return;
}
if rect_contains(self.sidebar_areas.testing_icon, m.column, m.row) {
self.open_testing_view();
return;
}
if rect_contains(self.sidebar_areas.codeql_icon, m.column, m.row) {
self.open_codeql_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;
}
if self.search.project_exclude_toggle_at(m.column, m.row) {
self.toggle_project_excludes();
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) {
self.toggle_search_opt(t);
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.operation = crate::git::repo_operation(&self.scm_root());
}
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 let Some(repo) = self.source_control.click_nested_repo(m.column, m.row) {
self.change_workspace_root(repo);
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 let Some((index, remove)) = self.run_debug.breakpoint_at(m.column, m.row) {
self.breakpoint_list_click(index, remove);
return;
}
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::CodeQL {
self.focus_pane(Pane::Tree);
if let Some((row, hit)) = self.codeql.hit_at(m.column, m.row) {
self.codeql.selected = row;
self.activate_codeql(hit);
}
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 if rect_contains(self.testing.last_watch_all, m.column, m.row) {
self.toggle_test_watch(crate::testing::watch::WatchScope::All);
} else if rect_contains(self.testing.last_cover_all, m.column, m.row) {
self.run_all_tests_with_coverage();
} else if rect_contains(self.testing.last_output_hint, m.column, m.row) {
self.show_test_runner_output();
} else if rect_contains(self.testing.last_stop, m.column, m.row) {
self.cancel_test_run();
} else {
match self.testing.hit_at(m.column, m.row) {
Some(crate::widgets::testing::RowHit::ToggleWatch(scope)) => {
self.toggle_test_watch(scope)
}
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)
}
Some(crate::widgets::testing::RowHit::CoverCase(name)) => {
self.run_scope_with_coverage(name, false)
}
Some(crate::widgets::testing::RowHit::CoverSuite(suite)) => {
self.run_scope_with_coverage(suite, true)
}
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 {
let crumb = self.editor.breadcrumb_index_at(m.column, m.row);
if let Some(i) = crumb.filter(|_| self.scrub_view.is_none()) {
// A crumb opens its picker (#1608): a folder's
// entries, the file's folder, or the symbol's
// siblings.
self.focus_pane(Pane::Editor);
self.open_breadcrumb_picker(i);
} else if let Some((line, col)) =
self.editor.breadcrumb_target_at(m.column, m.row)
{
// While scrubbing a symbol crumb jumps in the
// commit's view, as before.
self.focus_pane(Pane::Editor);
if !self.jump_in_scrub_view(line)
&& 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.request_close_tab(idx);
}
} 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();
}
// A drag from here reorders the tab (#1565).
self.editor_tab_drag_from = Some(idx);
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 && view.commit_edit().is_some() {
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;
}
// Fleet tiles (#363): a click selects a tile.
if let Some(view) = self.editor.fleet.as_mut() {
if let Some(i) = view.tile_at(m.column, m.row) {
view.selected = i;
}
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;
}
// SARIF viewer (#577): click selects a row; a second
// click on the selected row opens it (a result) or
// folds it (a group).
if let Some(view) = self.editor.sarif.as_mut() {
if view.rows_visible > 0
&& m.row >= view.rows_top
&& m.row < view.rows_top + view.rows_visible
&& m.column >= view.list_x
&& m.column < view.list_x + view.list_width
{
let idx = view.scroll + (m.row - view.rows_top) as usize;
if idx < view.rows().len() {
if view.selected == idx {
if view.selected_entry().is_some() {
self.open_selected_sarif_result();
} else {
view.toggle_fold();
}
} 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;
}
// Breakpoint lane (#1544): a click in the sign cell
// toggles a breakpoint on that line, as a click in VS
// Code's glyph margin does, and leaves the caret where
// it is. It used to move the caret to column 1 and set
// nothing. After the play glyph and the chevron, which
// own their cells; Shift and Alt keep their selections.
if !m
.modifiers
.intersects(KeyModifiers::ALT | KeyModifiers::SHIFT)
&& let Some(line0) = self.editor.breakpoint_lane_line_at(m.column, m.row)
{
self.debug_toggle_breakpoint_line(line0 + 1);
self.breakpoint_lane_press = true;
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) => {
// Tab drag (#1565): live reorder, as the terminal panes below
// do. Crossing another tab of the same bar moves the dragged
// tab there; it stays active and the drag follows it.
if let Some(from) = self.editor_tab_drag_from {
if let Some(to) = self.editor.tab_at(m.column, m.row)
&& to != from
&& let Some(at) = self.editor.move_tab(from, to)
{
self.editor_tab_drag_from = Some(at);
self.poke_cursor();
}
return;
}
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;
}
// The lane press owns its gesture: no selection drag (#1544).
if self.breakpoint_lane_press {
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 => {}
SidebarView::CodeQL => {}
},
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
| SidebarView::CodeQL => {}
}
} 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) => {
self.editor_tab_drag_from = None;
// 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() {
self.copy_where_pasted(&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() {
self.copy_where_pasted(&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.breakpoint_lane_press) {
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.move_or_copy_in_explorer(&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),
SidebarView::CodeQL => self.codeql.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),
SidebarView::CodeQL => self.codeql.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 {
self.editor_language_supports(crate::lsp::LspManager::language_supports_formatting)
}
/// The overrides `"[<scope>]"` holds (#1440), if any.
fn language_prefs_for(&self, scope: &str) -> Option<&crate::prefs::LanguagePrefs> {
self.language_prefs.get(scope)
}
/// Format on save for a file in language `scope` (#1440): its language
/// block's value, else the global one.
fn format_on_save_for(&self, scope: &str) -> bool {
self.language_prefs_for(scope)
.and_then(|l| l.format_on_save)
.unwrap_or(self.format_on_save)
}
/// Format on type for a file in language `scope` (#1440).
fn format_on_type_for(&self, scope: &str) -> bool {
self.language_prefs_for(scope)
.and_then(|l| l.format_on_type)
.unwrap_or(self.format_on_type)
}
/// Auto-closing pairs for a file in language `scope` (#1440).
fn auto_close_pairs_for(&self, scope: &str) -> bool {
self.language_prefs_for(scope)
.and_then(|l| l.disable_auto_close_pairs)
.map_or(self.auto_close_pairs, |off| !off)
}
/// Inlay hints for a file in language `scope` (#1440).
fn inlay_hints_enabled_for(&self, scope: &str) -> bool {
inlay_hints_on_in(&self.language_prefs, self.inlay_hints_enabled, scope)
}
/// Whitespace rendering for a file in language `scope` (#1440).
#[cfg(test)]
fn whitespace_mode_for(&self, scope: &str) -> crate::widgets::editor::WhitespaceMode {
whitespace_mode_in(&self.language_prefs, self.whitespace_mode, scope)
}
/// 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_for(editor_scope_id(&self.editor))
&& supports_formatting
&& self.editor.path.is_some()
&& self.editor.diff.is_none()
&& self.editor.sheet.is_none()
&& self.editor.image.is_none()
}
/// The formatter the settings name for the active file when croft does
/// not run it (#1499), e.g. `biomejs.biome` for a TypeScript file.
/// `prettier` says croft formats the file with the project's own
/// Prettier (#1255), so the Prettier extension named for it is not
/// foreign.
fn foreign_formatter(&self, prettier: bool) -> Option<String> {
let lang = self
.editor
.path
.as_deref()
.and_then(crate::lsp::Language::from_path)
.map(|l| l.lsp_id());
crate::default_formatter::foreign(
self.default_formatter.as_deref(),
&self.language_formatters,
lang,
)
.filter(|f| !(prettier && f.eq_ignore_ascii_case("esbenp.prettier-vscode")))
.map(str::to_owned)
}
/// Save the active file as typed because the project formats it with
/// `formatter`, which croft does not run (#1499): formatting it with
/// the language server instead rewrites lines the project's formatter
/// laid out. The first such save per formatter says why.
fn save_for_foreign_formatter(&mut self, formatter: String) {
self.write_current_to_disk();
let Some(path) = self.editor.path.clone() else {
return;
};
if self.path_is_saved(&path) && self.foreign_formatters_noted.insert(formatter.clone()) {
self.status = format!(
"Saved {} without formatting: this project formats with {formatter}, which croft does not run",
self.status_path(&path)
);
}
}
/// 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();
self.format_save_deadline = Some(std::time::Instant::now() + FORMAT_ON_SAVE_TIMEOUT);
}
/// 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) {
self.format_save_deadline = None;
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();
} else {
self.write_tab_to_disk(&path);
}
// As in `save`: the file's other tabs hold the text just written.
self.sync_symbol_views();
if let Some((op, root)) = self.scm_after_format_save.take() {
self.finish_scm_after_save(op, &root);
}
}
/// 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
}
/// The terminal window croft runs in lost focus (#1622): alt-tab to the
/// browser, another tmux window. With auto save "onWindowChange" (or
/// `onFocusChange`) every dirty buffer is written now, the one being
/// edited included, since the whole window is what lost focus; VS Code
/// does the same. Returns true when anything changed on screen.
pub fn on_window_focus_lost(&mut self) -> bool {
if !self.auto_save_on_focus_change {
return false;
}
self.sweep_dirty_buffers(false, false)
}
/// 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 {
let skip_active = !require_delay && self.focus == Pane::Editor;
self.sweep_dirty_buffers(require_delay, skip_active)
}
/// Write every dirty buffer the auto-save rules allow, in every split,
/// leaving the active tab alone when `skip_active`. Shared by the
/// auto-save sweep and File: Save All (#852).
fn sweep_dirty_buffers(&mut self, require_delay: bool, skip_active: 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();
// And each saved tab's text, for a server whose didSave carries it
// (#854).
let mut saved_texts: Vec<String> = Vec::new();
// The tabs of a file with a symbol tab mirror each other (#369), so
// they hold one text: the first write saves them all, and writing a
// second would read the first as an external change. Settle them
// before the sweep (which may close a symbol tab, so before any tab
// index is taken) and mark the rest clean after it. A file live in a
// collab session is not mirrored, so each of its tabs saves itself:
// on the owner the second write then meets the first one's stamp and
// reports a disk conflict, as two split panes of a live file do.
let settled = self.sync_symbol_views();
let mirrored: Vec<PathBuf> = self
.symbol_view_paths()
.into_iter()
.filter(|p| !self.symbol_path_is_live(p))
.collect();
// The tab that still holds focus is not saved by the focus-change
// mode: only buffers that LOST focus are written. Save All skips it
// too, having just saved it the explicit way.
let keep_focused = skip_active.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
// A merge with conflicts still open: its Result holds only
// the base text there, and writing it would drop both
// sides from disk. Complete Merge (or an explicit Cmd+S) is
// the user's call.
&& !e.merge.as_ref().is_some_and(|m| m.unresolved_count() > 0)
&& !(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 lossy_paths: Vec<PathBuf> = 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;
if e.path.as_ref().is_some_and(|p| {
mirrored.contains(p) && saved_paths.iter().any(|(q, ..)| q == p)
}) {
continue;
}
// `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()));
saved_texts.push(e.lines.join("\n"));
}
}
// 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.
// A mirrored sibling holds the same text and stamp, so it
// meets the same outcome: each file is reported once.
Ok(crate::widgets::editor::SaveOutcome::DiskConflict) => {
if let Some(p) = e.path.clone()
&& !conflicted.contains(&p)
{
conflicted.push(p);
}
}
// 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(p) = e.path.as_ref()
&& !lossy_paths.contains(p)
&& let Some(name) = p.file_name()
{
lossy_paths.push(p.clone());
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);
}
if !saved_paths.is_empty() {
self.sync_symbol_views();
}
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 settled || 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, ..), text) in saved_paths.iter().zip(saved_texts) {
lsp.save_doc(path.clone(), text);
}
}
for (path, seats, described) in saved_paths {
self.record_history_snapshot_of(&path, seats, described);
}
true
}
/// File: Save All (#852, `Cmd+Opt+S` / `Ctrl+Alt+S`): the active tab
/// saves exactly as `Cmd+S` would (format on save, hex and sheet edits,
/// the overwrite prompt), then every other dirty buffer in every split
/// is written by the auto-save rules, which leave a tab that must not
/// be written blind (a disk conflict, a lossy encoding, an unresolved
/// merge, a hex or sheet edit) to its own `Cmd+S`.
fn save_all(&mut self) {
let before = self.unsaved_count();
if before == 0 {
self.status = String::from("Save All: nothing to save");
return;
}
if self.editor.dirty {
self.save();
}
let active_status = self.status.clone();
self.sweep_dirty_buffers(false, true);
// A format-on-save write lands with its formatter reply: it is on
// its way, not left behind.
let pending = self
.save_after_format
.clone()
.map(|path| self.status_path(&path));
let left = self
.unsaved_count()
.saturating_sub(usize::from(pending.is_some()));
let active_refusal = if self.editor.dirty {
active_status
} else {
String::new()
};
self.status = save_all_summary(before, left, pending.as_deref(), active_refusal);
}
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);
}
}
/// Profiles: Switch Profile (#618): the default, every profile, and the
/// actions to make a new one or pin one to this workspace.
fn open_profiles(&mut self) {
use crate::widgets::list_picker::{ListPicker, ListPurpose, ListRow};
let active = crate::profiles::active();
let mark = |on: bool| if on { " \u{2713}" } else { "" };
let mut rows = vec![ListRow {
id: String::from("profile:"),
label: format!("Default{}", mark(active.is_none())),
}];
for name in crate::profiles::list() {
rows.push(ListRow {
id: format!("profile:{name}"),
label: format!("{name}{}", mark(active.as_deref() == Some(name.as_str()))),
});
}
rows.push(ListRow {
id: String::from("new"),
label: String::from("New Profile from Current Setup\u{2026}"),
});
if active.is_some() {
rows.push(ListRow {
id: String::from("workspace"),
label: String::from("Use the Active Profile for This Workspace"),
});
}
if crate::profiles::workspace_choice_path(&self.tree.root).exists() {
rows.push(ListRow {
id: String::from("workspace-clear"),
label: String::from("Stop Using a Profile for This Workspace"),
});
}
self.open_list_picker(ListPicker::new(ListPurpose::Profiles, "Profiles", rows), "");
}
/// Make `name` (or the default) the active profile and apply what can be
/// applied live: keybindings and snippets. Settings are read at startup.
fn switch_profile(&mut self, name: Option<String>) {
if let Err(e) = crate::profiles::switch(name.as_deref()) {
self.status = format!("Could not switch profile: {e}");
return;
}
// Recorded shortcuts go to the active profile's file from now on.
if !cfg!(test) {
self.keybindings_file = crate::keymap::keybindings_path();
}
let (map, _) = crate::keymap::Keymap::load_with_warnings(&self.keybindings_file);
self.keymap = map;
self.snippets = load_snippets(&crate::snippets::snippets_path());
self.status = format!(
"Profile: {}; keybindings and snippets applied, settings apply at the next launch",
name.as_deref().unwrap_or("Default")
);
}
/// Preferences: Open Keyboard Shortcuts (#612, Cmd+K Cmd+S): every
/// command with its shortcut, searchable; choosing one records a new one.
pub(crate) fn open_keyboard_shortcuts(&mut self) {
use crate::widgets::list_picker::{ListPicker, ListPurpose, ListRow};
let rows = crate::widgets::command_palette::ALL_COMMANDS
.iter()
.map(|&cmd| {
let shown = match self.keymap.chord_for(cmd) {
Some(user) => format!("{user} (yours)"),
// Its built-in chord now runs another command (#1482).
None if self.keymap.shadows_builtin(cmd) => String::from("\u{2014}"),
None if !cmd.keybinding_hint().is_empty() => {
crate::widgets::command_palette::platform_hint(cmd.keybinding_hint())
.into_owned()
}
None => String::from("\u{2014}"),
};
ListRow {
id: format!("kb:{}", cmd.id()),
label: format!("{} \u{00b7} {shown}", cmd.title()),
}
})
.collect();
self.open_list_picker(
ListPicker::new(ListPurpose::KeyboardShortcuts, "Keyboard Shortcuts", rows),
"No commands",
);
}
/// Bind `cmd` to the chord `key` in keybindings.json (#612) and reload.
/// Plain typing cannot be a shortcut (it would stop being typing), so
/// only function keys and Cmd/Ctrl/Alt chords are accepted, the same rule
/// the keymap itself applies.
fn record_shortcut(&mut self, cmd: crate::widgets::command_palette::Command, key: KeyEvent) {
if key.code == KeyCode::Esc {
self.status = String::from("Shortcut unchanged");
return;
}
if !is_rebindable_chord(key) {
self.status = String::from(
"A shortcut needs a function key or Cmd/Ctrl/Alt; press Keyboard Shortcuts again to retry",
);
return;
}
// The command the chord runs now: a user binding, else a built-in
// shortcut no user binding has taken (#1482). Taking it from that
// command waits for Enter, so a slip of the finger cannot silently
// cost a shortcut like Toggle Line Comment's.
let chord = crate::keymap::Chord::from_event(key);
// A built-in chord can be shared (F7 is both Merge: Next Conflict
// and Go to Next Change), and a user binding takes it from all of
// them, so every other owner is named.
let owners: Vec<_> = match self.keymap.command_for(key) {
Some(bound) => vec![bound],
None => crate::keymap::builtin_commands_on(chord),
}
.into_iter()
.filter(|c| *c != cmd)
.collect();
if !owners.is_empty() {
self.status = format!(
"{} is {}'s shortcut: Enter to give it to \u{201c}{}\u{201d}, Esc to cancel",
chord.to_config_string(),
quoted_titles(&owners),
cmd.title()
);
self.confirming_shortcut = Some((cmd, key, owners));
return;
}
self.write_shortcut(cmd, key, &[]);
}
/// Write `key` as `cmd`'s shortcut in keybindings.json (#612) and
/// reload; `previous` are the other commands the chord ran until now.
fn write_shortcut(
&mut self,
cmd: crate::widgets::command_palette::Command,
key: KeyEvent,
previous: &[crate::widgets::command_palette::Command],
) {
let chord = crate::keymap::Chord::from_event(key).to_config_string();
let path = self.keybindings_file.clone();
// Only a missing file starts fresh: one that exists but cannot be
// read would otherwise be overwritten with this single binding.
let src = match std::fs::read_to_string(&path) {
Ok(s) => Some(s),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
Err(e) => {
self.status = format!("Could not read {}: {e}", path.display());
return;
}
};
let Some(text) = crate::keymap::rebind_text(src.as_deref(), cmd.id(), &chord) else {
self.status = format!(
"{} does not parse; fix it before recording a shortcut",
path.display()
);
return;
};
if let Some(dir) = path.parent() {
let _ = std::fs::create_dir_all(dir);
}
if let Err(e) = std::fs::write(&path, text) {
self.status = format!("Could not write {}: {e}", path.display());
return;
}
let (map, _) = crate::keymap::Keymap::load_with_warnings(&path);
self.keymap = map;
self.status = if previous.is_empty() {
format!("{chord} now runs \u{201c}{}\u{201d}", cmd.title())
} else {
format!(
"{chord} now runs \u{201c}{}\u{201d} (it ran {})",
cmd.title(),
quoted_titles(previous)
)
};
}
/// Editor: Toggle Inline Suggestions (#607, Cmd+K Shift+G). Turning it on
/// resolves the backend first and says plainly when there is none.
fn toggle_inline_suggestions(&mut self) {
if self.inline_enabled {
self.inline_enabled = false;
self.editor.ghost = None;
self.inline_job = None;
self.inline_asked = None;
self.status = String::from("Inline suggestions: off");
return;
}
let local =
crate::session::read_pair_record(&crate::session::pair_record_path(&self.tree.root))
.filter(|r| r.provider.as_deref() == Some("ollama"))
.map(|r| {
(
r.base_url
.unwrap_or_else(|| String::from("http://localhost:11434")),
r.model,
)
});
match crate::inline_complete::resolve(local, |k| std::env::var(k).ok()) {
Ok(config) => {
self.status = format!(
"Inline suggestions: on ({}); Tab accepts, Esc dismisses",
config.model
);
self.inline_config = Some(config);
self.inline_worker
.get_or_insert_with(crate::inline_complete::Worker::spawn);
self.inline_enabled = true;
}
Err(why) => self.status = format!("Inline suggestions need a model: {why}"),
}
}
/// Ask for a suggestion once typing has paused with the caret at the end
/// of a non-blank line, and land answers that still apply (#607).
pub fn tick_inline_complete(&mut self) -> bool {
if !self.inline_enabled {
return false;
}
let mut changed = false;
if let Some(worker) = &self.inline_worker {
while let Some(done) = worker.try_recv() {
let Some((id, path, seq, row, col)) = self.inline_job.clone() else {
continue;
};
if done.id != id {
continue;
}
self.inline_job = None;
let still = self.editor.path.as_ref() == Some(&path)
&& self.editor.edit_seq == seq
&& self.editor.cursor_row == row
&& self.editor.cursor_col == col;
match done.result {
Ok(Some(text)) if still => {
self.editor.ghost = Some((row, col, seq, text));
changed = true;
}
Ok(_) => {}
Err(e) => self.status = format!("Inline suggestion: {e}"),
}
}
}
let ed = &*self.editor;
let Some(path) = ed.path.clone() else {
return changed;
};
let row = ed.cursor_row;
let col = ed.cursor_col;
let seq = ed.edit_seq;
let at_line_end = ed
.lines
.get(row)
.is_some_and(|l| !l.trim().is_empty() && l.chars().skip(col).all(char::is_whitespace));
let settled = ed
.last_edit_at
.is_some_and(|t| t.elapsed() >= crate::inline_complete::DEBOUNCE);
let already = ed
.ghost
.as_ref()
.is_some_and(|g| (g.0, g.1, g.2) == (row, col, seq))
// Asked already at this caret and edit: an empty answer, an
// error or an Esc'd ghost must not send the request again on
// the next tick, which looped hundreds of paid calls a second.
|| self
.inline_asked
.as_ref()
.is_some_and(|a| a.0 == path && (a.1, a.2, a.3) == (seq, row, col))
|| self
.inline_job
.as_ref()
.is_some_and(|j| j.1 == path && (j.2, j.3, j.4) == (seq, row, col));
if self.focus != Pane::Editor
|| !at_line_end
|| !settled
|| already
|| ed.selection.is_some()
|| ed.has_non_text_view()
|| self.completion_popup.is_some()
{
return changed;
}
let (Some(worker), Some(config)) = (&self.inline_worker, &self.inline_config) else {
return changed;
};
let id = self.inline_next_id;
self.inline_next_id += 1;
worker.submit(crate::inline_complete::Job {
id,
config: config.clone(),
prompt: crate::inline_complete::prompt(&ed.lines, row, col),
});
self.inline_asked = Some((path.clone(), seq, row, col));
self.inline_job = Some((id, path, seq, row, col));
changed
}
/// Tab takes a live suggestion (#607), recorded as the navigator's
/// writing; Esc drops it. Returns whether the key was used.
fn inline_suggestion_key(&mut self, key: KeyEvent) -> bool {
if !key.modifiers.is_empty()
|| self.completion_popup.is_some()
|| self.editor.snippet_active()
{
return false;
}
let Some(text) = self.editor.live_ghost().map(str::to_string) else {
return false;
};
match key.code {
KeyCode::Tab => {
self.editor.ghost = None;
self.editor
.insert_str_as(&text, crate::provenance::Seat::Navigator);
true
}
KeyCode::Esc => {
self.editor.ghost = None;
true
}
_ => false,
}
}
/// What screen reader mode describes this frame (#621).
fn a11y_snapshot(&self) -> crate::a11y::Snapshot {
use crate::a11y::Snapshot;
let tr = |s: &str| crate::i18n::tr(s).into_owned();
let status = tr(&self.status);
if let Some(p) = &self.prompt {
return Snapshot {
focus: p.label.clone(),
item: p.error.clone(),
status,
..Default::default()
};
}
if let Some(menu) = &self.context_menu {
let item = match menu.cursor_entry() {
Some(MenuEntry::Item { label, .. } | MenuEntry::Submenu { label, .. }) => {
Some(label.clone())
}
_ => None,
};
return Snapshot {
focus: tr("Menu"),
item,
status,
..Default::default()
};
}
if let Some(p) = &self.command_palette {
return Snapshot {
focus: tr("Command Palette"),
item: p.selected_item().map(|i| tr(i.title())),
status,
..Default::default()
};
}
if let Some(f) = &self.file_finder {
return Snapshot {
focus: tr("Go to File"),
item: f.selected_entry().map(|e| e.rel.clone()),
status,
..Default::default()
};
}
if let Some(p) = &self.list_picker {
return Snapshot {
focus: p.title.clone(),
item: p.selected_row().map(|r| r.label.clone()),
status,
..Default::default()
};
}
match self.focus {
Pane::Editor => {
let name = self
.editor
.path
.as_deref()
.and_then(|p| p.file_name())
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| tr("Untitled"));
let row = self.editor.cursor_row;
let diagnostic = self
.editor
.diagnostics_at(row, self.editor.cursor_col)
.into_iter()
.next()
.map(|(_, m)| m);
Snapshot {
focus: format!("{} {name}", tr("Editor")),
line: Some((
row + 1,
self.editor.lines.get(row).cloned().unwrap_or_default(),
)),
diagnostic,
item: self
.completion_popup
.as_ref()
.and_then(|c| c.selected_item())
.map(|c| c.label.clone()),
status,
}
}
Pane::Terminal => {
let (focus, item) = self.bottom_panel_a11y();
Snapshot {
focus,
item,
status,
..Default::default()
}
}
Pane::Tree => {
let (focus, item) = match self.sidebar_view {
SidebarView::Explorer => (
tr("Explorer"),
self.tree
.selected_path()
.and_then(|p| p.file_name())
.map(|n| n.to_string_lossy().into_owned()),
),
SidebarView::Search => self.search_a11y(),
SidebarView::SourceControl => self.source_control_a11y(),
SidebarView::Remote => (tr("Remote"), None),
SidebarView::RunDebug => (tr("Run and Debug"), None),
SidebarView::Extensions => (tr("Extensions"), None),
SidebarView::Testing => (tr("Testing"), None),
SidebarView::CodeQL => (tr("CodeQL"), None),
};
Snapshot {
focus,
item,
status,
..Default::default()
}
}
}
}
/// What screen reader mode says for the bottom panel's front tab
/// (#1295): the tab's name with what it holds, and its row in focus.
/// The panel is one `Pane` whichever tab is in front, so the tab, not
/// the pane, decides.
fn bottom_panel_a11y(&self) -> (String, Option<String>) {
let tr = |s: &str| crate::i18n::tr(s).into_owned();
let with = |name: &str, what: String| format!("{}, {what}", tr(name));
match self.bottom_panel_tab {
BottomPanelTab::Terminal => (
format!("{} {}", tr("Terminal"), self.active_terminal + 1),
None,
),
BottomPanelTab::Problems => {
let errors = self.problems.error_count();
let warnings = self.problems.warning_count();
let others = self.problems.total_count() - errors - warnings;
let counts: Vec<String> = [
(errors, "error", "errors"),
(warnings, "warning", "warnings"),
(others, "info", "infos"),
]
.into_iter()
.filter(|(n, ..)| *n > 0)
.map(|(n, one, many)| a11y_count(n, one, many))
.collect();
let counts = if counts.is_empty() {
String::from("no problems")
} else {
counts.join(", ")
};
let item = self.problems.top_diagnostic().map(|(group, it)| {
let source = match &it.code {
Some(code) => code.label(&it.source),
None => it.source.clone(),
};
let source = if source.is_empty() {
String::new()
} else {
format!(" ({source})")
};
format!(
"{} line {}: {}{source}",
group.name,
it.line + 1,
it.message
)
});
(with("Problems", counts), item)
}
BottomPanelTab::Output => (
match self.output.selected_name() {
Some(channel) => with("Output", channel),
None => tr("Output"),
},
None,
),
BottomPanelTab::Ports => {
let n = self.ports.len();
let item = self.ports.selected().map(|p| {
let mut said = format!("Port {}", p.port);
for part in [&p.process, &p.url].into_iter().flatten() {
said.push_str(", ");
said.push_str(part);
}
said
});
let count = if n == 0 {
String::from("none")
} else {
a11y_count(n, "port", "ports")
};
(with("Ports", count), item)
}
BottomPanelTab::Captures => {
let n = self.captures.len();
let item = self
.captures
.selected_entry()
.map(|c| format!("{}, from {}", c.message, c.pane));
let count = if n == 0 {
String::from("none")
} else {
a11y_count(n, "capture", "captures")
};
(with("Captures", count), item)
}
}
}
/// The Search sidebar for screen reader mode (#1295): how many matches
/// in how many files, and the selected match as `file line N: text`.
fn search_a11y(&self) -> (String, Option<String>) {
let name = crate::i18n::tr("Search").into_owned();
let hits = &self.search.hits;
if hits.is_empty() {
return (name, None);
}
// The Search header's own totals: a line with two matches counts two.
let (matches, files) = self.search.result_counts();
let focus = format!(
"{name}, {} in {}",
a11y_count(matches, "match", "matches"),
a11y_count(files, "file", "files")
);
let item = self.search.selected_hit().map(|h| {
let rel = h
.path
.strip_prefix(self.workspace_root())
.unwrap_or(&h.path);
format!("{} line {}: {}", rel.display(), h.line_no, h.line_text)
});
(focus, item)
}
/// The Source Control sidebar for screen reader mode (#1295): how many
/// changes, and the selected one as `path, what happened to it`.
fn source_control_a11y(&self) -> (String, Option<String>) {
use crate::git::ChangeKind;
let name = crate::i18n::tr("Source Control").into_owned();
let entries = &self.source_control.entries;
if entries.is_empty() {
return (name, None);
}
let focus = format!("{name}, {}", a11y_count(entries.len(), "change", "changes"));
let item = self
.source_control
.selected_change
.and_then(|i| entries.get(i))
.map(|e| {
let what = match e.kind {
ChangeKind::StagedAdded => "added, staged",
ChangeKind::StagedModified => "modified, staged",
ChangeKind::StagedDeleted => "deleted, staged",
ChangeKind::StagedRenamed => "renamed, staged",
ChangeKind::Modified => "modified",
ChangeKind::Deleted => "deleted",
ChangeKind::Untracked => "untracked",
ChangeKind::Conflicted => "conflicted",
};
format!("{}, {what}", e.path)
});
(focus, item)
}
/// Feed this frame's snapshot to the announcer (#621).
fn update_announcer(&mut self) {
if !self.screen_reader {
return;
}
let snap = self.a11y_snapshot();
let speak = self.screen_reader_command.clone();
self.announcer.update(snap, speak.as_deref());
}
/// Accessibility: Toggle Screen Reader Mode (#621), persisted.
fn toggle_screen_reader(&mut self) {
self.screen_reader = !self.screen_reader;
self.announcer.reset();
self.status = String::from(if self.screen_reader {
"Screen reader mode: on"
} else {
"Screen reader mode: off"
});
if !cfg!(test) {
let _ = crate::prefs::save_screen_reader(self.screen_reader);
}
}
/// Where screen reader mode parks the cursor when no caret is showing:
/// the terminal's own cursor, else the start of the announcement.
fn park_screen_reader_cursor(&self, frame: &mut ratatui::Frame) {
if !self.screen_reader {
return;
}
// A picker covers the caret: read its selection from the status bar.
let picker = self.command_palette.is_some()
|| self.file_finder.is_some()
|| self.list_picker.is_some();
if picker && let Some(pos) = self.announce_pos {
frame.set_cursor_position(pos);
return;
}
if self.cursor_should_be_visible() {
return;
}
if self.focus == Pane::Terminal
&& self.prompt.is_none()
&& self.context_menu.is_none()
&& self.command_palette.is_none()
&& self.file_finder.is_none()
&& self.list_picker.is_none()
&& let Some(pos) = self
.terminals
.get(self.active_terminal)
.and_then(|t| t.screen_cursor())
{
frame.set_cursor_position(pos);
return;
}
if let Some(pos) = self.announce_pos {
frame.set_cursor_position(pos);
}
}
/// Paint the history suggestion after the focused terminal's typed line
/// (#614) and remember it for Right arrow. Cleared whenever it does not
/// apply, so a stale suggestion can never be accepted.
fn paint_terminal_suggestion(&mut self, frame: &mut ratatui::Frame) {
self.term_suggestion = None;
if !self.term_suggest_enabled
|| self.focus != Pane::Terminal
|| self.context_menu.is_some()
|| self.prompt.is_some()
{
return;
}
let idx = self.active_terminal;
let Some(term) = self.terminals.get(idx) else {
return;
};
// Typed keys not echoed yet: the line on screen is behind, and a
// suggestion for it would be accepted after the keys that followed.
if term.awaiting_echo() {
return;
}
let Some((typed, x, y, right)) = term.prompt_tail() else {
return;
};
let cwd = term
.shell_cwd()
.map(|p| p.to_string_lossy().into_owned())
.unwrap_or_default();
let Some(cmd) = self.command_history.suggest(&typed, &cwd, "") else {
return;
};
let rest = cmd[typed.len()..].to_string();
if x >= right {
return;
}
let shown: String = rest.chars().take((right - x) as usize).collect();
frame
.buffer_mut()
.set_string(x, y, &shown, Style::default().fg(self.theme.ignored_fg()));
self.term_suggestion = Some((idx, typed, rest));
}
/// Terminal: Toggle Command Suggestions (#614).
fn toggle_terminal_suggestions(&mut self) {
self.term_suggest_enabled = !self.term_suggest_enabled;
self.term_suggestion = None;
self.status = format!(
"Terminal suggestions: {}",
if self.term_suggest_enabled {
"on"
} else {
"off"
}
);
}
/// Answer `croft edit --wait`'s poll (#620): whether `path` is still open
/// in any tab of any group. Opens nothing.
fn probe_view_path(&self, path: &Path) -> crate::view_ipc::ViewReply {
let canon = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
let is_it = |p: &Path| p == path || p.canonicalize().is_ok_and(|c| c == canon);
let open = self
.editor
.editors
.iter()
.chain(
self.editor_layout
.inactive_groups()
.into_iter()
.flat_map(|g| g.editors.iter()),
)
.any(|t| t.path.as_deref().is_some_and(is_it));
if open {
crate::view_ipc::ViewReply::Err {
message: String::from(crate::view_ipc::PROBE_OPEN),
}
} else {
crate::view_ipc::ViewReply::Err {
message: String::from(crate::view_ipc::PROBE_CLOSED),
}
}
}
/// In a `git-rebase-todo` tab (#620), a plain p/r/e/s/f/d on a commit
/// line sets its action and moves to the next commit line. Off in vim mode,
/// where those letters are vim commands. Returns whether it acted.
fn rebase_todo_key(&mut self, key: KeyEvent) -> bool {
let KeyCode::Char(c) = key.code else {
return false;
};
if !key.modifiers.is_empty()
|| self.vim.enabled
|| !self
.editor
.path
.as_deref()
.is_some_and(crate::rebase_todo::is_todo)
{
return false;
}
let Some(action) = crate::rebase_todo::action_for_key(c) else {
return false;
};
let row = self.editor.cursor_row;
let Some(line) = self.editor.lines.get(row).cloned() else {
return false;
};
// A blank line takes no action and must not take the letter either:
// git stops the rebase on a stray `s` (#1228).
if line.trim().is_empty() {
self.status = String::from(crate::rebase_todo::HINT);
return true;
}
let Some(new_line) = crate::rebase_todo::set_action(&line, action) else {
return false;
};
if matches!(action, "squash" | "fixup")
&& !crate::rebase_todo::has_kept_commit_above(&self.editor.lines, row)
{
self.status = format!("Can't {action} the first commit: no commit above it");
return true;
}
self.editor
.apply_span_edits(&[crate::widgets::editor::TextSpanEdit {
start: (row, 0),
end: (row, line.chars().count()),
new_text: new_line,
utf16: false,
}]);
// On to the next commit line, past comments and the trailing blank;
// the last commit keeps the caret (#1228).
if let Some(next) = self.editor.lines[row + 1..]
.iter()
.position(|l| crate::rebase_todo::is_commit_line(l))
{
self.editor.cursor_row = row + 1 + next;
}
self.editor.cursor_col = 0;
self.status = String::from(crate::rebase_todo::HINT);
true
}
/// Rebase: Abort (#620): empty the plan, save it and close its tab, which
/// git reads as "abort the rebase".
fn abort_rebase_todo(&mut self) {
if !self
.editor
.path
.as_deref()
.is_some_and(crate::rebase_todo::is_todo)
{
// Outside the plan tab, a rebase stopped on a conflict is the
// one this means (#1356).
if matches!(
crate::git::repo_operation(&self.scm_root()),
Some(crate::git::RepoOp::Rebase { .. })
) {
self.abort_git_operation();
return;
}
self.status = String::from("Rebase: Abort works in a git-rebase-todo tab");
return;
}
let end = self.editor.lines.len().saturating_sub(1);
let end_col = self
.editor
.lines
.last()
.map(|l| l.chars().count())
.unwrap_or(0);
self.editor
.apply_span_edits(&[crate::widgets::editor::TextSpanEdit {
start: (0, 0),
end: (end, end_col),
new_text: String::new(),
utf16: false,
}]);
self.save();
self.run_command(crate::widgets::command_palette::Command::CloseEditor);
self.status = String::from("Rebase aborted");
}
/// Search: Open Results in Editor (#615, Cmd+K Shift+F): the sidebar's
/// query and results as a Search Editor tab.
fn open_search_editor(&mut self) {
let header = crate::search_editor::Header {
query: self.search.query.clone(),
opts: self.search.opts,
include: self.search.include.clone(),
exclude: self.search.exclude.clone(),
};
let text = crate::search_editor::render(&header, &self.search.hits, &self.tree.root);
let label = search_editor_label(&header.query);
match self.editor.open_text_buffer(&label, &text) {
Ok(()) => {
self.focus_pane(Pane::Editor);
self.status = if header.query.is_empty() {
String::from(
"Search Editor: type a query on the first line, then Cmd+K Shift+R",
)
} else {
format!("Search Editor: {} result(s)", self.search.hits.len())
};
}
Err(e) => self.status = format!("Search Editor: {e}"),
}
}
/// Search Editor: Rerun (#615, Cmd+K Shift+R): search again for the query
/// the active Search Editor's header spells, off the UI thread.
fn rerun_search_editor(&mut self) {
let header = is_search_editor_tab(self.editor.path.as_deref())
.then(|| crate::search_editor::parse_header(&self.editor.lines))
.flatten();
let Some(header) = header else {
self.status = String::from("Not a Search Editor");
return;
};
let Some(label) = self.editor.path.clone() else {
return;
};
let root = self.tree.root.clone();
let (tx, rx) = std::sync::mpsc::channel();
let query = header.query.clone();
let header_query = query.clone();
let opts = header.opts;
let filter = crate::widgets::search::PathFilter::new(&header.include, &header.exclude);
std::thread::spawn(move || {
let hits = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
let sink = hits.clone();
let cancel = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
crate::widgets::search::search_workspace_streaming_filtered(
&root,
&query,
opts,
&cancel,
&std::collections::HashSet::new(),
&filter,
move |batch| {
if let Ok(mut all) = sink.lock() {
all.extend(batch);
}
},
);
let all = hits.lock().map(|h| h.clone()).unwrap_or_default();
let _ = tx.send(all);
});
self.search_editor_job = Some((label, header, rx));
self.status = format!(
"Searching for {}\u{2026}",
header_query_for_status(&header_query)
);
}
/// Land a finished Search Editor rerun in its tab (#615).
pub fn drain_search_editor(&mut self) -> bool {
let Some((_, _, rx)) = self.search_editor_job.as_ref() else {
return false;
};
let Ok(hits) = rx.try_recv() else {
return false;
};
let (label, header, _) = self.search_editor_job.take().expect("checked");
let text = crate::search_editor::render(&header, &hits, &self.tree.root);
let lines: Vec<String> = text.lines().map(str::to_string).collect();
let mut landed = false;
self.for_each_tab_of(&label, |tab| {
tab.lines = lines.clone();
tab.cursor_row = tab.cursor_row.min(tab.lines.len().saturating_sub(1));
tab.cursor_col = 0;
landed = true;
});
if landed {
self.status = format!("Search Editor: {} result(s)", hits.len());
}
landed
}
/// Open the match under the caret when the active tab is a Search Editor
/// and the caret is on a result row. Returns whether it did.
fn open_search_editor_result(&mut self) -> bool {
if !is_search_editor_tab(self.editor.path.as_deref())
|| !crate::search_editor::is_search_editor(&self.editor.lines)
{
return false;
}
let Some((path, line)) = crate::search_editor::location_at(
&self.editor.lines,
self.editor.cursor_row,
&self.tree.root,
) else {
return false;
};
self.go_to_definition(path, line.saturating_sub(1) as u32, 0);
true
}
/// Ask for the active file's code lenses once its edits have settled
/// (#608). Lenses cost a server real work (rust-analyzer resolves each
/// one), so this waits out [`CODE_LENS_SETTLE`] rather than riding every
/// edit the way inlay hints do.
pub fn tick_code_lens(&mut self) {
if !self.code_lens_enabled {
return;
}
let Some(path) = self.editor.path.clone() else {
return;
};
let Some(&seq) = self.lsp_last_seen.get(&path) else {
return;
};
if self.code_lens_requested.get(&path) == Some(&seq)
|| self
.editor
.last_edit_at
.is_some_and(|t| t.elapsed() < CODE_LENS_SETTLE)
{
return;
}
if let Some(lsp) = self.lsp.as_ref() {
lsp.request_code_lens(path.clone(), seq);
self.code_lens_requested.insert(path, seq);
}
}
/// Land code-lens replies on every tab showing the file (#608). A reply
/// for an older seq is dropped; the tab keeps its lenses, each shown only
/// while its own line is unchanged.
pub fn drain_lsp_code_lens(&mut self) -> bool {
let Some(lsp) = self.lsp.as_ref() else {
return false;
};
let mut updates = Vec::new();
while let Some(u) = lsp.drain_code_lens() {
updates.push(u);
}
let mut changed = false;
for u in updates {
if !self.code_lens_enabled || self.lsp_last_seen.get(&u.path) != Some(&u.seq) {
continue;
}
self.for_each_tab_of(&u.path, |tab| {
tab.code_lenses = u
.lenses
.iter()
.filter_map(|l| {
let line = l.line as usize;
Some(crate::code_lens::EditorLens {
line,
line_text: tab.lines.get(line)?.clone(),
title: l.title.clone(),
command: l.command.clone(),
arguments: l.arguments.clone(),
server_side: l.server_side,
})
})
.collect();
});
changed = true;
}
changed
}
/// Run the active editor's code lens at `idx` (#608).
pub(crate) fn run_code_lens(&mut self, idx: usize) {
let Some(lens) = self.editor.code_lenses.get(idx).cloned() else {
return;
};
match crate::code_lens::action_for(&lens) {
crate::code_lens::LensAction::ShowLocations(targets) => {
if targets.len() == 1 {
let (path, line, col) = targets.into_iter().next().expect("len 1");
self.go_to_definition(path, line, col);
} else {
self.open_location_picker(targets, "references");
}
}
crate::code_lens::LensAction::RunInTerminal { label, command } => {
self.start_project_task(crate::tasks::Task {
label,
command,
source: String::from("code lens"),
is_build: false,
is_default: false,
problem_matcher: None,
vscode: None,
});
}
crate::code_lens::LensAction::DebugAt(line) => {
self.editor.cursor_row = line.min(self.editor.lines.len().saturating_sub(1));
self.editor.cursor_col = 0;
self.debug_test_at_cursor();
}
crate::code_lens::LensAction::ServerCommand { command, arguments } => {
if let (Some(lsp), Some(path)) = (self.lsp.as_mut(), self.editor.path.clone()) {
lsp.execute_command(path, command, arguments);
self.status = format!("Ran \u{201c}{}\u{201d}", lens.title);
}
}
crate::code_lens::LensAction::Unsupported(why) => {
self.status = format!("Code lens: {why}");
}
}
}
/// The caret line's code lenses from the keyboard (Cmd+K Shift+E): one
/// runs at once, several open a menu to pick from (#608).
fn run_code_lens_at_cursor(&mut self) {
let lenses = self.editor.lenses_on_line(self.editor.cursor_row);
match lenses.as_slice() {
[] => self.status = String::from("No code lens on this line"),
[one] => self.run_code_lens(*one),
many => {
let items: Vec<(String, MenuAction)> = many
.iter()
.map(|&i| {
(
self.editor.code_lenses[i].title.clone(),
MenuAction::RunCodeLens(i),
)
})
.collect();
let origin = self.editor.cursor_screen_pos().unwrap_or((
self.editor.last_full_area.x + 1,
self.editor.last_full_area.y + 1,
));
let root = self.tree.root.clone();
self.context_menu = Some(ContextMenu::flat(origin, items, root));
}
}
}
/// Editor: Toggle CodeLens (#608).
fn toggle_code_lens(&mut self) {
self.code_lens_enabled = !self.code_lens_enabled;
self.code_lens_requested.clear();
if !self.code_lens_enabled {
for tab in self.editor.editors.iter_mut() {
tab.code_lenses.clear();
}
for group in self.editor_layout.inactive_groups_mut() {
for tab in group.editors.iter_mut() {
tab.code_lenses.clear();
}
}
}
self.status = format!(
"CodeLens: {}",
if self.code_lens_enabled { "on" } else { "off" }
);
}
/// Scroll sync between split panes (#619): when the focused pane shows a
/// Markdown file and another pane shows the same file the other way
/// (source beside preview), the other one follows. Returns true when it
/// moved anything.
pub fn sync_markdown_scroll(&mut self) -> bool {
let active = &*self.editor;
let Some(path) = active.path.clone() else {
self.md_scroll_synced = None;
return false;
};
// What the focused pane says the position is, in source lines.
let (leads_preview, line) = match active.markdown_preview.as_ref() {
Some(md) => match md.source_line_at_top() {
Some(line) => (true, line),
None => return false,
},
None => (false, active.scroll),
};
let key = (path.clone(), leads_preview, line);
if self.md_scroll_synced.as_ref() == Some(&key) {
return false;
}
let mut moved = false;
for group in self.editor_layout.inactive_groups_mut() {
let idx = group.active_index();
let Some(tab) = group.editors.get_mut(idx) else {
continue;
};
if tab.path.as_deref() != Some(path.as_path()) {
continue;
}
match (leads_preview, tab.markdown_preview.as_mut()) {
(false, Some(md)) if md.source_map.len() > 1 => {
md.scroll_to_source = Some(line);
moved = true;
}
(true, None) => {
tab.scroll = line.min(tab.lines.len().saturating_sub(1));
moved = true;
}
_ => {}
}
}
self.md_scroll_synced = Some(key);
moved
}
/// Arm or disarm Live Run for the active file (Cmd+K V).
pub(crate) fn toggle_live_run(&mut self) {
let Some(path) = self.editor.path.clone() else {
self.status = String::from("Live Run: save the buffer as a .py file first");
return;
};
if !crate::live_run::supports(&path) {
self.status = String::from("Live Run runs Python files (.py)");
return;
}
let name = path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
if self.live_run_files.remove(&path) {
self.live_run_sent.remove(&path);
self.for_each_tab_of(&path, |tab| tab.live_run = None);
self.status = format!("Live Run: off for {name}");
return;
}
self.live_run_files.insert(path);
self.live_run_runner
.get_or_insert_with(crate::live_run::Runner::spawn);
self.status = format!("Live Run: on for {name}, re-running on every pause in typing");
}
/// Apply `f` to every open tab of `path`, in every editor group.
fn for_each_tab_of(
&mut self,
path: &Path,
mut f: impl FnMut(&mut crate::widgets::editor::Editor),
) {
for tab in self.editor.editors.iter_mut() {
if tab.path.as_deref() == Some(path) {
f(tab);
}
}
for group in self.editor_layout.inactive_groups_mut() {
for tab in group.editors.iter_mut() {
if tab.path.as_deref() == Some(path) {
f(tab);
}
}
}
}
/// Live Run's per-tick work: land finished runs on their tabs, then send
/// the active buffer for a re-run once typing has paused. Returns true
/// when anything on screen changed.
pub fn tick_live_run(&mut self) -> bool {
if self.live_run_files.is_empty() {
return false;
}
let mut changed = false;
let mut landed = Vec::new();
if let Some(runner) = &self.live_run_runner {
while let Some(done) = runner.try_recv() {
landed.push(done);
}
}
for done in landed {
// A run that lands after its file was disarmed is dropped: the
// user turned it off and must not see it come back.
if !self.live_run_files.contains(&done.path) {
continue;
}
let active = self.editor.path.as_deref() == Some(done.path.as_path());
match done.outcome {
Ok(report) => {
if active {
self.status = report.summary.clone();
}
let view = crate::live_run::View {
lines: done.lines,
report,
};
self.for_each_tab_of(&done.path, |tab| tab.live_run = Some(view.clone()));
}
Err(msg) => {
if active {
self.status = msg;
}
}
}
changed = true;
}
let tab = &*self.editor;
let Some(path) = tab.path.clone() else {
return changed;
};
if !self.live_run_files.contains(&path)
|| tab.has_non_text_view()
|| tab
.last_edit_at
.is_some_and(|t| t.elapsed() < crate::live_run::DEBOUNCE)
|| self.live_run_sent.get(&path) == Some(&tab.lines)
{
return changed;
}
let lines = tab.lines.clone();
let root = self.roots.primary().to_path_buf();
let dir = path.parent().unwrap_or(Path::new(".")).to_path_buf();
let python = project_python_for(&dir, &root);
self.live_run_sent.insert(path.clone(), lines.clone());
if let Some(runner) = &self.live_run_runner {
runner.submit(crate::live_run::Job {
path,
lines,
python,
});
}
changed
}
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.debug_sessions.focused() 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 and plain `.log` text tab 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);
}
// A plain `.log` open as text wears the same colours (#1537).
ed.refresh_log_highlight();
}
}
}
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) {
self.save_active_tab();
// The saved text is every same-file tab's text: settle them now, so
// none reads as dirty or as changed on disk before the next tick
// (#369). A format-on-save write lands later and settles them in
// `complete_pending_save`.
self.sync_symbol_views();
}
/// Save only the active tab; its same-file siblings are left as they
/// are. Callers go through [`Self::save`].
fn save_active_tab(&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 cell still being typed into is part of the save (#1140): commit
// it the way Enter does, so it reaches the file.
if let Some(view) = self.editor.sheet.as_mut()
&& view.editable()
&& view.commit_edit().is_some()
{
self.editor.dirty = true;
}
// 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() {
// An editable grid or hex view with nothing to write isn't a
// preview (#1140).
let editable = self.editor.sheet.as_ref().is_some_and(|v| v.editable())
|| self.editor.hex.is_some();
self.status = if self
.editor
.hex
.as_ref()
.is_some_and(|v| v.pending_nibble.is_some())
{
String::from("Type the byte's second hex digit, then save")
} else if editable {
String::from("No changes to save")
} else {
String::from("Nothing to save: this tab is a read-only preview")
};
return;
}
// An untitled buffer (#1580) has nowhere to go yet: Save is Save As,
// as in VS Code.
if self.editor.path.is_none() && self.editor.diff.is_none() {
self.open_save_as_prompt();
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. And when
// the owner left (#1147): there is nobody to save for this guest.
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) && !s.owner_gone())
})
{
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;
}
// Saved again while the formatter has still not answered: write now
// rather than wait on it a second time (#1491).
if self.save_after_format.is_some() && self.save_after_format == self.editor.path {
self.save_without_formatting("saved again before the formatter answered");
return;
}
self.format_and_save(self.editor_language_supports_formatting());
}
/// The write at the end of a save: with format on save on and a
/// formatter for the file, defer it until the format reply arrives
/// (`drain_lsp_format`, or `drain_prettier_format`, calls
/// `complete_pending_save`), unless the project names a formatter croft
/// does not run (#1499).
fn format_and_save(&mut self, supports_formatting: bool) {
let prettier = self
.editor
.path
.as_deref()
.and_then(crate::prettier::for_file)
.is_some();
if self.format_on_save_eligible(prettier || supports_formatting) {
if let Some(formatter) = self.foreign_formatter(prettier) {
self.save_for_foreign_formatter(formatter);
return;
}
self.arm_deferred_save();
self.start_format_document();
return;
}
self.write_current_to_disk();
}
/// Apply croft's own config files that changed on disk outside croft
/// (#262): a file that arrived by config sync, or was written by another
/// tool. Returns true when something was reloaded, for a redraw.
pub fn tick_config_watch(&mut self) -> bool {
self.tick_config_watch_at(std::time::Instant::now())
}
fn tick_config_watch_at(&mut self, now: std::time::Instant) -> bool {
let changed = self.config_watch.poll(now);
for path in &changed {
self.reload_config_for_path(path);
}
!changed.is_empty()
}
/// 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);
// The explicit-save path's other follow-up: a save of an agent's
// proposal being edited approves it (#347).
self.approve_saved_edit(&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) {
// Applied now, so the config watch does not reload it a second time.
self.config_watch.note(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 = load_snippets(path);
self.status =
snippets_reload_status(self.snippets.is_broken(), self.snippets.warnings());
} 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 == self.macros_path {
self.macro_registers = crate::macros::load(path);
self.status = format!("Macros reloaded ({} registers)", self.macro_registers.len());
} else if path == crate::triggers::triggers_path() {
self.triggers = load_trigger_set(self.secret_redaction);
self.status = match &self.triggers.problem {
Some(problem) => format!(
"Triggers reloaded ({} of your rules active; {problem})",
self.triggers.user_rules
),
None => format!(
"Triggers reloaded ({} of your rules active)",
self.triggers.user_rules
),
};
} 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();
}
}
/// Flip the Search panel's project exclusions on or off (#1345), VS
/// Code's "Use Exclude Settings and Ignore Files", and search again.
fn toggle_project_excludes(&mut self) {
self.search.use_exclude_settings = !self.search.use_exclude_settings;
self.status = String::from(if self.search.use_exclude_settings {
"Search: project exclusions on"
} else {
"Search: project exclusions off, searching every folder"
});
if !crate::widgets::search::as_typed(&self.search.query).is_empty() {
self.submit_search_query();
}
}
/// Apply the project's `files_exclude` / `search_exclude` globs
/// (#1345): the Explorer hides `files_exclude`, Search and Go to File
/// leave out both. Re-lists the tree and re-runs a live search only
/// when the globs changed.
fn apply_project_excludes(&mut self, p: &crate::prefs::Prefs) {
let mut search = p.files_exclude.clone();
search.extend(p.search_exclude.iter().cloned());
if search != self.search.project_exclude {
self.search.project_exclude = search;
if !crate::widgets::search::as_typed(&self.search.query).is_empty() {
self.submit_search_query();
}
}
if p.files_exclude != self.files_exclude {
self.files_exclude = p.files_exclude.clone();
self.tree.exclude = crate::widgets::search::PathFilter::excluding(&self.files_exclude);
self.tree.refresh_children(0);
}
}
/// The Go to File index without the files the project excludes
/// (#1345): VS Code's file search honours both exclude settings.
fn without_project_excludes(
&self,
entries: std::sync::Arc<Vec<crate::widgets::file_finder::FileEntry>>,
) -> std::sync::Arc<Vec<crate::widgets::file_finder::FileEntry>> {
if self.search.project_exclude.is_empty() {
return entries;
}
let filter = crate::widgets::search::PathFilter::excluding(&self.search.project_exclude);
let kept = entries
.iter()
.filter(|e| {
let root = self
.roots
.iter()
.find(|r| e.path.starts_with(r))
.map_or_else(|| self.roots.primary().to_path_buf(), |r| r.to_path_buf());
!filter.excludes(&root, &e.path)
})
.cloned()
.collect();
std::sync::Arc::new(kept)
}
/// 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 or changes on disk
/// outside croft (#1435); 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;
// The chain follows the primary root and the `extends` targets, so
// the watch follows the chain (#1435).
self.config_watch
.set_paths(config_watch_paths(&self.settings_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.default_formatter = p.default_formatter.clone();
self.language_formatters = p.language_formatters.clone();
self.format_on_type = p.format_on_type;
let old_languages = std::mem::replace(&mut self.language_prefs, p.languages.clone());
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;
self.apply_project_excludes(p);
// 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();
if p.codeql_cli_path != self.codeql_cli_setting {
self.codeql_cli_setting = p.codeql_cli_path.clone();
self.resolve_codeql_cli();
}
// 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();
self.code_scanning = p.code_scanning;
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;
self.paste_reindent = !p.disable_paste_reindent;
self.follow_vim_mode_pref(p.vim_mode);
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;
self.word_suggestions =
crate::word_suggest::WordSuggestions::from_pref(&p.word_based_suggestions);
// A per-language `disable_inlay_hints` change (#1440) moves a file's
// effective setting as surely as the global one does.
let hint_overrides =
|langs: &std::collections::BTreeMap<String, crate::prefs::LanguagePrefs>| {
langs
.iter()
.filter_map(|(k, l)| l.disable_inlay_hints.map(|off| (k.clone(), off)))
.collect::<Vec<_>>()
};
let hints_were_on = self.inlay_hints_enabled;
self.inlay_hints_enabled = !p.disable_inlay_hints;
if hints_were_on != self.inlay_hints_enabled
|| hint_overrides(&old_languages) != hint_overrides(&self.language_prefs)
{
let (langs, global) = (&self.language_prefs, self.inlay_hints_enabled);
if !inlay_hints_on_in(langs, global, editor_scope_id(&self.editor)) {
self.editor.clear_inlay_hints();
}
for group in self.editor_layout.inactive_groups_mut() {
if !inlay_hints_on_in(langs, global, editor_scope_id(group)) {
group.clear_inlay_hints();
}
}
self.request_inlay_hints_for_open_editors();
}
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.save_before_debug = !p.disable_save_before_debug;
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, self.editor.lines.join("\n"));
}
}
/// 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.
///
/// Records the seats 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>>,
) {
// Every save lands here, so this is where a watched test scope
// hears about it (#263). A file git ignores (build output, a `.env`)
// is not source, so its save reruns nothing; git is only asked while
// something is watched.
if self.testing.watch.scope().is_some()
&& path.starts_with(&self.active_test_root)
&& !crate::git::is_ignored(&self.active_test_root, path)
{
self.testing
.watch
.on_saved(path, &self.active_test_root, std::time::Instant::now());
}
self.spawn_history_record(path, seats, described, false);
// Every save passes through here: breakpoints that followed edits in
// the buffer are handed to running sessions now that the file on disk
// has the same lines, or they stay bound to the old line numbers.
self.resend_breakpoints(path);
}
/// Send `path`'s current breakpoints to every debug session.
fn resend_breakpoints(&mut self, path: &Path) {
if self.debug_sessions.is_empty() {
return;
}
let specs = self
.editor
.breakpoints
.get(path)
.map(|lines| self.editor.source_breakpoints(path, lines))
.unwrap_or_default();
for session in self.debug_sessions.iter_mut() {
session.update_breakpoints(path, &specs);
}
}
/// Record each dirty tab of `paths` (any group) in Local History as a
/// kept snapshot, before a reload throws its edits away (#910). The
/// number recorded.
fn keep_unsaved_buffers_in_history(&mut self, paths: &[PathBuf]) -> usize {
let millis = now_millis();
let mut buffers: Vec<(PathBuf, Vec<u8>)> = Vec::new();
let groups = std::iter::once(&self.editor).chain(self.editor_layout.inactive_groups());
for tab in groups.flat_map(|g| g.iter_tabs()) {
let Some(path) = tab.path.as_ref().filter(|p| paths.contains(p)) else {
continue;
};
if tab.dirty
&& !buffers.iter().any(|(p, _)| p == path)
&& let Some(bytes) = tab.bytes_for_disk()
{
buffers.push((path.clone(), bytes));
}
}
buffers
.iter()
.filter(|(path, bytes)| {
crate::history::record_kept_in(&self.history_root, path, bytes, millis).is_ok()
})
.count()
}
/// [`Self::record_history_snapshot_of`] as a kept snapshot (a restore).
fn record_history_snapshot_of_kept(
&mut self,
path: &Path,
seats: crate::provenance::Provenance,
) {
self.spawn_history_record(path, seats, None, true);
}
fn spawn_history_record(
&mut self,
path: &Path,
seats: crate::provenance::Provenance,
described: Option<Vec<u8>>,
keep: bool,
) {
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 _ = if keep {
crate::history::record_kept_with_seats_in(&root, &path, &bytes, millis, &seats)
} else {
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();
let text = editor.lines.join("\n");
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(), text);
}
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();
if chars.is_empty() && self.editor.decode_lossy {
self.status = format!(
"Not saved: this file has bytes that are not valid {}, shown as \u{fffd} - press Cmd+S again to write them as \u{fffd} (irreversible), or Reopen with Encoding via the status bar",
self.editor.encoding.name()
);
return;
}
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(|e| menu_entry_width(e, &self.keymap))
.max()
.unwrap_or(0);
let area = self.last_frame_area;
// Never past the frame: a long menu on a short terminal (or any menu
// under 18 columns) built a rect outside the buffer, which panics.
let fit = |v: u16, max: u16| if max > 0 { v.min(max) } else { v };
let width = fit((widest + 4).max(18) as u16, area.width);
let height = fit((menu.items.len() + 2) as u16, area.height);
// 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(|e| menu_entry_width(e, &self.keymap))
.max()
.unwrap_or(0);
let area = self.last_frame_area;
let fit = |v: u16, max: u16| if max > 0 { v.min(max) } else { v };
let width = fit((widest + 4).max(18) as u16, area.width);
let height = fit((items.len() + 2) as u16, area.height);
// 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 shown = parent.saturating_sub(menu.scroll.get());
let y = (main.y + 1 + shown 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 top = menu.scroll_for(r.height.saturating_sub(2) as usize);
let idx = top + 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 | KeyCode::Right
if self
.context_menu
.as_ref()
.is_some_and(|m| m.crumb.is_some() && m.open_submenu.is_none()) =>
{
// A breadcrumb picker steps to the neighbouring crumb's
// (#1608), VS Code's Left / Right in the focused bar.
let Some(i) = self.context_menu.as_ref().and_then(|m| m.crumb) else {
return;
};
let next = if key.code == KeyCode::Left {
i.checked_sub(1)
} else {
Some(i + 1).filter(|&n| n < self.editor.breadcrumbs.len())
};
if let Some(n) = next {
self.open_breadcrumb_picker(n);
}
}
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");
}
}
/// `root`'s saved agent review queue (#345), less files deleted while
/// croft was closed; an empty one when nothing is saved or there is no
/// store.
fn load_agent_ledger(&self, root: &Path) -> crate::agent_lane::AgentLedger {
let Some(store) = self.agent_ledger_store.as_ref() else {
return crate::agent_lane::AgentLedger::new();
};
let map: std::collections::HashMap<String, crate::agent_lane::AgentLedger> =
std::fs::read_to_string(store)
.ok()
.and_then(|raw| serde_json::from_str(&raw).ok())
.unwrap_or_default();
map.get(&agent_ledger_key(root))
.cloned()
.map(|l| l.restored(Path::exists))
.unwrap_or_default()
}
/// Save the agent review queue under this workspace's key when it has
/// changed since the last save: at most once a second from the frame
/// loop, or at once when `now` (leaving the workspace). An emptied
/// queue removes the key rather than keeping an empty entry.
fn persist_agent_ledger(&mut self, now: bool) {
let Some(store) = self.agent_ledger_store.clone() else {
return;
};
let generation = self.agent_ledger.generation();
let (saved, at) = self.agent_ledger_saved;
if generation == saved || (!now && at.elapsed() < std::time::Duration::from_secs(1)) {
return;
}
let key = agent_ledger_key(self.workspace_root());
let ledger = self.agent_ledger.clone();
let result = crate::workspace::update_json_store::<crate::agent_lane::AgentLedger, _>(
&store,
|map| {
if ledger.is_empty() {
map.remove(&key);
} else {
map.insert(key.clone(), ledger.clone());
}
},
);
if let Err(e) = result {
crate::output::push(
"Agents",
crate::output::OutputLevel::Error,
&format!("Could not save the agent review queue: {e}"),
);
}
self.agent_ledger_saved = (generation, std::time::Instant::now());
}
/// 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) {
// The review queue being left is saved under its own root first.
self.persist_agent_ledger(true);
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;
}
}
// The hot-exit backup is keyed by the workspace: this croft's goes
// with it to the new root at the next tick, rather than staying
// where the old workspace's next launch would restore it (#862).
self.remove_own_hot_exit();
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. The old one's Drop shuts
// its servers down and waits up to 3 s for them, so it is dropped
// off the UI thread, as the build pause does (#737). 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.
//
// Not while a source build of croft has the servers stopped (#694):
// starting them now would put rust-analyzer back beside the compile.
// The manager drops either way, and the end of the build starts one
// at the new root, since the resume reads `workspace_root()`.
if let Some(old) = self.lsp.take() {
fs_watch::offload_drop(old);
}
self.lsp = match self.lsp_paused_for_build {
true => None,
false => match crate::lsp::LspManager::new(new_root.clone()) {
Ok(m) => Some(m),
Err(e) => {
// Not stderr: the TUI owns the screen here, and text written
// around ratatui stays on it (#537's class of leak).
let msg = format!("Language servers could not restart: {e}");
crate::output::push(
"Language Servers",
crate::output::OutputLevel::Error,
&msg,
);
self.status = msg;
None
}
},
};
self.lsp_last_seen.clear();
self.lsp_diagnostics.clear();
self.lsp_progress.clear();
// A new manager numbers semantic replies from 0 again (see the
// build resume, which hits the same thing).
self.semantic_generation_seen.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. The new
// root's own saved queue comes back in its place.
self.agent_ledger = self.load_agent_ledger(&new_root);
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)
}
/// Where the palette's File: New File… / New Folder… create (#852): the
/// Explorer selection while the Explorer has focus, as its own chords
/// do; otherwise beside the active file, falling back to the selection
/// when no file is open.
fn palette_create_target_dir(&self) -> PathBuf {
if !self.is_explorer_focused()
&& let Some(dir) = self.editor.path.as_deref().and_then(Path::parent)
{
return dir.to_path_buf();
}
self.explorer_create_target_dir()
}
/// 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.request_close_tab(idx),
MenuAction::CloseOtherTabs(keep_idx) => self.close_other_tabs(keep_idx),
MenuAction::CloseTabsToRight(from_idx) => self.close_tabs_to_right(from_idx),
MenuAction::CloseAllTabs => self.close_all_tabs(),
MenuAction::CloseSavedTabs => self.close_saved_tabs(),
MenuAction::KeepTabOpen(idx) => self.keep_tab_open(idx),
MenuAction::ToggleTabPin(idx) => self.toggle_tab_pin(idx),
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.open_diff_across_groups(&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::OpenCrumbFile(path) => self.open_crumb_file(&path),
MenuAction::BrowseCrumbFolder { dir, crumb } => {
self.open_crumb_folder_picker(&dir, crumb, None);
}
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::OpenSymbolTab {
path,
name,
first,
last,
} => {
// Go to the symbol first: the tab opens from the file's own
// tab, which may not be the one showing.
self.go_to_definition(path.clone(), first as u32, 0);
if self.editor.path.as_deref() == Some(path.as_path()) {
self.open_symbol_tab_for(name, first, last);
}
}
MenuAction::GoToOutlineSymbol { path, line, col } => {
self.go_to_definition(path, line, col);
}
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.toggle_activity_bar();
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.toggle_status_bar();
self.open_customize_layout_menu_on(&MenuAction::ToggleStatusBar);
}
MenuAction::SetSideBarPosition(pos) => {
self.set_side_bar_position(pos);
self.open_customize_layout_menu_on(&MenuAction::SetSideBarPosition(pos));
}
MenuAction::SetPanelAlignment(al) => {
self.set_panel_alignment(al);
self.open_customize_layout_menu_on(&MenuAction::SetPanelAlignment(al));
}
MenuAction::SetQuickInputPosition(pos) => {
self.set_quick_input_position(pos);
self.open_customize_layout_menu_on(&MenuAction::SetQuickInputPosition(pos));
}
MenuAction::ToggleZenMode => self.toggle_zen_mode(),
MenuAction::ToggleCenteredLayout => {
self.toggle_centered_layout();
self.open_customize_layout_menu_on(&MenuAction::ToggleCenteredLayout);
}
MenuAction::RunCodeLens(idx) => self.run_code_lens(idx),
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::EditorCut => self.cut_editor_selection(),
MenuAction::EditorCopy => self.copy_editor_selection(),
MenuAction::EditorPaste => {
let text = (self.clipboard_reader)();
self.paste_clipboard_into_editor(text.as_deref());
}
MenuAction::ShowCommandPalette => self.open_command_palette(),
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::SplitTerminal => self.split_terminal_reporting(),
MenuAction::KillTerminal(idx) => self.close_terminal_reporting(idx),
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");
}
}
}
}
/// Tab context "Close Others" and View: Close Other Editors in Group
/// (#852): close every tab of the focused group but `keep_idx` and the
/// pinned ones, recording each for Reopen Closed Editor.
fn close_other_tabs(&mut self, keep_idx: usize) {
self.record_closed_tabs_where(|i, ed| i != keep_idx && !ed.pinned);
let removed = self.editor.close_others(keep_idx);
if removed == 0 {
self.status = String::from("No other tabs to close");
return;
}
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();
}
/// Cmd+K →, tab context "Close to the Right" and View: Close Editors to
/// the Right in Group (#852): close the focused group's unpinned tabs
/// right of `from_idx`, recording each for Reopen Closed Editor.
fn close_tabs_to_right(&mut self, from_idx: usize) {
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.status = String::from("No tabs to the right to close");
return;
}
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();
}
/// Cmd+K ⇧P, tab context "Keep Open" and View: Keep Editor (#852):
/// promote the preview tab at `idx` so the next single-click open does
/// not replace it.
fn keep_tab_open(&mut self, idx: usize) {
if self.editor.is_blank_initial() {
self.status = String::from("No editor is open");
} else if self.editor.keep_open(idx) {
self.status = String::from("Kept tab open");
self.poke_cursor();
} else {
self.status = String::from("Tab is already kept open");
}
}
/// Cmd+K P and tab context "Pin" / "Unpin": flip the pin of the tab at
/// `idx`. The welcome screen's placeholder is not a tab to pin.
fn toggle_tab_pin(&mut self, idx: usize) {
if self.editor.is_blank_initial() {
self.status = String::from("No editor is open");
return;
}
let pinned = self.editor.toggle_pin(idx);
self.status = String::from(if pinned { "Pinned tab" } else { "Unpinned tab" });
self.poke_cursor();
}
/// View: Pin Editor (`pin`) / View: Unpin Editor (#852): the active
/// tab's pin, through the tab menu's toggle. Each is a no-op on a tab
/// already in that state, so a key bound to one never does the other.
fn set_active_tab_pinned(&mut self, pin: bool) {
let idx = self.editor.active_index();
if !self.editor.is_blank_initial() && self.editor.is_pinned(idx) == pin {
self.status = String::from(if pin {
"Tab is already pinned"
} else {
"Tab is not pinned"
});
return;
}
self.toggle_tab_pin(idx);
}
/// Cmd+K W / tab context "Close All" / View: Close All Editors (#852):
/// 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.
///
/// Tabs with unsaved changes stay open, in whichever group holds them
/// (#862): a sweep must not decide to throw edits away, and Cmd+W on one
/// of them asks. Only the groups left with nothing fold away then.
fn close_all_tabs(&mut self) {
let mut removed = self.editor.close_all();
let mut kept = self.editor.editors.iter().filter(|e| e.dirty).count();
if self.editor_layout.is_split() {
let mut emptied = Vec::new();
for (g, group) in self
.editor_layout
.inactive_groups_mut()
.into_iter()
.enumerate()
{
removed += group.close_all();
let dirty = group.editors.iter().filter(|e| e.dirty).count();
if dirty == 0 {
emptied.push(g);
}
kept += dirty;
}
if kept == 0 {
self.editor_layout = editor_layout::EditorLayout::single();
} else {
self.editor_layout.prune_inactive_at(&emptied);
self.collapse_split_if_empty();
}
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")
};
if kept > 0 {
self.status
.push_str(&format!("; kept {kept} with unsaved changes open"));
}
self.poke_cursor();
}
/// Close every saved (non-dirty) editor tab, keeping any with unsaved
/// changes. Shared by the tab context menu, the `Cmd+K U` chord and View:
/// Close Saved Editors in Group (#852) so every surface produces 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();
}
/// Go on with `exit`, unless it would drop unsaved changes (#862): then
/// raise the prompt that asks whether to save them first. Every quit and
/// every single-tab close comes through here. The update relaunch alone
/// does not: its session handoff carries unsaved text across the re-exec.
fn guard_unsaved(&mut self, exit: UnsavedExit) {
let at_stake = match &exit {
UnsavedExit::CloseTab { idx, .. } => self.tab_would_lose_edits(*idx),
_ => !self.unsaved_files().is_empty(),
};
if at_stake {
self.pending_unsaved = Some(exit);
} else {
self.finish_unsaved_exit(exit);
}
}
/// Close the focused group's tab at `idx`: at once when it holds nothing
/// unsaved, through the prompt when it does.
fn request_close_tab(&mut self, idx: usize) {
let path = self.editor.tab_path(idx);
self.guard_unsaved(UnsavedExit::CloseTab { idx, path });
}
/// Carry `exit` out, with nothing left to ask.
fn finish_unsaved_exit(&mut self, exit: UnsavedExit) {
match exit {
// A quit that goes ahead kept every edit or was told to drop
// them, so the hot-exit backup goes with it.
UnsavedExit::Quit => {
self.clear_hot_exit();
self.quit = true;
}
UnsavedExit::DropToLocal => {
self.clear_hot_exit();
self.drop_to_local = true;
self.quit = true;
}
UnsavedExit::RemoteLaunch { host, path } => {
// What the answer left unsaved (D) goes without a second
// question at the handoff; anything edited after it does not.
self.remote_handoff_ok = self.unsaved_stamp();
self.start_remote_launch(host, path);
}
UnsavedExit::RemoteHandoff { .. } => {
self.clear_hot_exit();
self.quit = true;
}
UnsavedExit::CloseTab { idx, .. } => self.close_tab_now(idx),
}
}
/// Answer the unsaved-changes prompt (#862). `save` writes the buffers
/// first and goes on only once every one of them is on disk: a file left
/// unsaved keeps croft (or the tab) open and is named in the status
/// line. Otherwise it goes on without saving.
fn answer_unsaved(&mut self, save: bool) {
let Some(exit) = self.pending_unsaved.take() else {
return;
};
if let UnsavedExit::CloseTab { idx, path } = &exit
&& self.editor.tab_path(*idx) != *path
{
self.status = String::from("The tab moved while croft was asking; nothing was closed");
return;
}
if save {
let only = match &exit {
UnsavedExit::CloseTab { idx, .. } => Some(*idx),
_ => None,
};
let left = self.save_tabs_for_exit(only);
if !left.is_empty() {
self.drop_unsaved_exit(&exit);
self.status = format!(
"Did not {}: still unsaved - {}",
exit.verb(),
left.join(", ")
);
return;
}
}
let closing = matches!(exit, UnsavedExit::CloseTab { .. });
self.finish_unsaved_exit(exit);
if closing {
self.status = String::from(if save {
"Saved and closed tab"
} else {
"Closed tab without saving"
});
}
}
fn cancel_unsaved(&mut self) {
if let Some(exit) = self.pending_unsaved.take() {
self.drop_unsaved_exit(&exit);
self.status = format!("Cancelled: did not {}", exit.verb());
}
}
/// Let go of `exit` when the prompt ends without it going ahead. A
/// remote handoff is already armed (the launch waits for the quit), and
/// left armed it would go ahead at the next, unrelated quit.
fn drop_unsaved_exit(&mut self, exit: &UnsavedExit) {
if matches!(exit, UnsavedExit::RemoteHandoff { .. }) {
self.remote_launch = None;
self.tear_down_connect_auth();
}
}
/// Close the focused group's tab at `idx` without asking: the shared end
/// of every single-tab close (Cmd+W, the tab's close button and context
/// menu, View: Close Editor, vim `:q`). The tab is recorded for Reopen
/// Closed Editor first, while it is still in place.
fn close_tab_now(&mut self, idx: usize) {
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();
// Closing the focused group's last tab while split closes the
// group: collapse back to the surviving column.
self.collapse_split_if_empty();
// A tab closed without saving takes its text out of the
// hot-exit backup now (#862 review), not at a later tick: a
// crash in between would bring back what was discarded.
if self.hot_exit_written.is_some() && self.unsaved_stamp() != self.hot_exit_written {
self.write_hot_exit();
}
}
}
/// Whether closing the focused group's tab at `idx` throws unsaved edits
/// away (#862). Not when another open tab holds the very same unsaved
/// text: a symbol tab and its file's tab mirror one buffer (#369), so
/// closing either keeps the edits in the other.
fn tab_would_lose_edits(&self, idx: usize) -> bool {
let Some(ed) = self.editor.editors.get(idx).filter(|e| holds_unsaved(e)) else {
return false;
};
!std::iter::once(&self.editor)
.chain(self.editor_layout.inactive_groups())
.flat_map(|g| g.editors.iter())
.any(|other| {
!std::ptr::eq(other, ed)
&& other.dirty
&& other.path.is_some()
&& other.path == ed.path
&& other.lines == ed.lines
})
}
/// Every file a quit would lose (#862), one label each: the dirty tabs of
/// every editor group, a file open in several tabs (a split, a symbol
/// tab) counted once, and each untitled buffer holding text on its own.
fn unsaved_files(&self) -> Vec<String> {
let mut seen: Vec<&Path> = Vec::new();
let mut labels = Vec::new();
for ed in std::iter::once(&self.editor)
.chain(self.editor_layout.inactive_groups())
.flat_map(|g| g.editors.iter())
.filter(|e| holds_unsaved(e))
{
match ed.path.as_deref() {
Some(p) if seen.contains(&p) => {}
Some(p) => {
seen.push(p);
labels.push(self.status_path(p));
}
None => labels.push(
ed.untitled
.map_or_else(|| String::from("untitled"), |n| format!("Untitled-{n}")),
),
}
}
labels
}
/// A fingerprint of every unsaved buffer as it stands (#862): which tabs
/// hold unsaved text and how far each has been edited, so any edit, save
/// or close changes it. `None` when nothing is unsaved. Cheap enough for
/// every tick: it hashes paths and edit counters, never text.
fn unsaved_stamp(&self) -> Option<u64> {
use std::hash::{Hash, Hasher};
let mut h = std::collections::hash_map::DefaultHasher::new();
let mut any = false;
for ed in std::iter::once(&self.editor)
.chain(self.editor_layout.inactive_groups())
.flat_map(|g| g.editors.iter())
.filter(|e| holds_unsaved(e))
{
any = true;
ed.path.hash(&mut h);
ed.edit_seq.hash(&mut h);
}
any.then(|| h.finish())
}
/// Hot exit's pause after the newest unsaved edit before it backs the
/// buffers up (#862): typing never waits on a write, and a crash loses
/// seconds of it.
const HOT_EXIT_DELAY: std::time::Duration = std::time::Duration::from_secs(5);
/// Keep the hot-exit backup (#862) in step with the unsaved buffers.
/// Runs every tick, but writes only once they changed since the last
/// backup and [`Self::HOT_EXIT_DELAY`] has passed since the newest edit,
/// and removes the backup once nothing is unsaved.
pub fn tick_hot_exit(&mut self, now: std::time::Instant) {
if self.hot_exit_dir.is_none() {
return;
}
let stamp = self.unsaved_stamp();
if stamp == self.hot_exit_written && self.hot_exit_consumed.is_empty() {
return;
}
if self.hot_exit_retry_at.is_some_and(|at| now < at) {
return;
}
let settling = stamp.is_some()
&& self
.newest_unsaved_edit()
.is_some_and(|t| now.saturating_duration_since(t) < Self::HOT_EXIT_DELAY);
if !settling {
self.write_hot_exit();
}
}
/// When the most recently edited unsaved buffer last changed.
fn newest_unsaved_edit(&self) -> Option<std::time::Instant> {
std::iter::once(&self.editor)
.chain(self.editor_layout.inactive_groups())
.flat_map(|g| g.editors.iter())
.filter(|e| holds_unsaved(e))
.filter_map(|e| e.last_edit_at)
.max()
}
/// This croft's hot-exit backup file for its workspace, when it keeps
/// backups at all.
fn hot_exit_path(&self) -> Option<PathBuf> {
let dir = self.hot_exit_dir.as_deref()?;
Some(crate::hot_exit::own_path(dir, self.workspace_root()))
}
/// Write the hot-exit backup now (#862): every unsaved text buffer of
/// every editor group, or no backup at all once there is none. Once it
/// lands, the backups this croft restored from go (never its own file,
/// which may carry the same name). A write that fails says so once, is
/// not counted as written, and is tried again by a later tick. Returns
/// whether it landed.
fn write_hot_exit(&mut self) -> bool {
let Some(path) = self.hot_exit_path() else {
return false;
};
let root = self.workspace_root().to_path_buf();
let stamp = self.unsaved_stamp();
let backup = self.capture_hot_exit();
let result = if backup.buffers.is_empty() {
crate::hot_exit::remove(&path, &root).map_err(|e| {
format!(
"Could not remove the hot-exit backup {} ({e})",
path.display()
)
})
} else {
backup
.save(&path)
.map_err(|e| format!("Could not back up unsaved changes ({e:#})"))
};
match result {
Ok(()) => {
self.hot_exit_written = stamp;
self.hot_exit_retry_at = None;
let mut left = Vec::new();
for consumed in std::mem::take(&mut self.hot_exit_consumed) {
if consumed == path {
continue;
}
if let Err(e) = crate::hot_exit::remove(&consumed, &root) {
left.push(format!("{} ({e})", consumed.display()));
self.hot_exit_unremoved.push(consumed);
}
}
if !left.is_empty() {
self.status = format!(
"Could not remove the hot-exit backup {}: it may still hold unsaved text; delete it by hand",
left.join(", ")
);
}
true
}
Err(note) => {
if self.hot_exit_retry_at.is_none() {
self.status = note;
}
self.hot_exit_retry_at = Some(std::time::Instant::now() + Self::HOT_EXIT_DELAY);
false
}
}
}
/// What a hot-exit backup holds (#862): each unsaved tab as the update
/// relaunch captures it (every group, a file once, untitled buffers
/// that hold text), with the file's stamp from when the buffer last
/// matched it. Hex and sheet tabs carry no text and are left out, as
/// from the relaunch.
fn capture_hot_exit(&self) -> crate::hot_exit::Backup {
let editors: Vec<&Editor> = std::iter::once(&self.editor)
.chain(self.editor_layout.inactive_groups())
.flat_map(|g| g.editors.iter())
.collect();
let buffers = self
.capture_session_state_with(false)
.tabs
.into_iter()
.filter(|t| {
t.dirty
&& t.unsaved_text
.as_deref()
.is_some_and(|text| t.path.is_some() || !text.is_empty())
})
.map(|tab| {
let disk_stamp = tab.path.as_deref().and_then(|p| {
editors
.iter()
.find(|e| e.dirty && e.path.as_deref() == Some(p))
.and_then(|e| e.disk_stamp())
});
crate::hot_exit::Buffer { tab, disk_stamp }
})
.collect();
crate::hot_exit::Backup {
workspace_root: self.workspace_root().to_path_buf(),
buffers,
}
}
/// Remove this croft's hot-exit backup and the ones it restored from
/// (#862): the quit ending it kept every unsaved edit on disk, or was
/// told to drop them. One that cannot be removed is said, in the status
/// line and on stderr after the quit, since it may still hold text the
/// user chose to discard.
fn clear_hot_exit(&mut self) {
let root = self.workspace_root().to_path_buf();
let mut left = Vec::new();
let consumed = std::mem::take(&mut self.hot_exit_consumed);
let unremoved = std::mem::take(&mut self.hot_exit_unremoved);
for path in self
.hot_exit_path()
.into_iter()
.chain(consumed)
.chain(unremoved)
{
if let Err(e) = crate::hot_exit::remove(&path, &root) {
left.push(format!("{} ({e})", path.display()));
}
}
self.hot_exit_written = None;
self.hot_exit_retry_at = None;
if !left.is_empty() {
let note = format!(
"Could not remove the hot-exit backup {}: it may still hold the unsaved text; delete it by hand",
left.join(", ")
);
self.status = note.clone();
self.exit_notes.push(note);
}
}
/// Remove this croft's own hot-exit backup, keyed by the workspace it
/// was written for (#862): a re-root writes it again under the new one
/// at the next tick, and what it restored from stays until then.
fn remove_own_hot_exit(&mut self) {
if let Some(path) = self.hot_exit_path() {
let _ = crate::hot_exit::remove(&path, self.workspace_root());
}
self.hot_exit_written = None;
}
/// Bring back what hot exit kept of this workspace's unsaved buffers
/// (#862) when croft last ended without a clean quit: a kill, a crash,
/// an OOM kill. Each comes back as an unsaved tab with its text and
/// cursor and nothing is written to its file. A file changed on disk
/// since is named in the status line and keeps the stamp its edits were
/// made against, so its first save asks before overwriting the change;
/// a deleted one comes back as a tab for its path. This croft writes its
/// own backup of them at once and removes the consumed ones only after
/// that lands, so a crash straight after the launch, or a write that
/// fails, cannot lose them either. Backups come newest first, and an
/// older one of a file already restored (two crofts on the workspace,
/// both killed) is not restored over the newer: that copy stays in its
/// backup for a later launch.
/// A backup that cannot be read is kept and said so, until it is older
/// than
/// [`crate::hot_exit::UNREADABLE_KEPT_FOR`]. Called once, at a normal
/// launch.
pub fn restore_hot_exit(&mut self) {
let Some(dir) = self.hot_exit_dir.clone() else {
return;
};
let root = self.workspace_root().to_path_buf();
let mut restored = 0usize;
let mut changed: Vec<PathBuf> = Vec::new();
let mut gone: Vec<PathBuf> = Vec::new();
let mut unreadable: Vec<String> = Vec::new();
let mut expired = 0usize;
// The files this launch has filled a tab for. Another backup of one
// of them, older since the newest come first, is a second croft's
// unsaved copy (two crofts on the workspace, both killed), and
// restoring it into that tab would overwrite the newer text. It
// stays in its backup instead, held for a later launch once the
// newer copy is saved or closed.
let mut filled: Vec<PathBuf> = Vec::new();
let mut doubled: Vec<PathBuf> = Vec::new();
let mut trimmed: Vec<(PathBuf, crate::hot_exit::Backup)> = Vec::new();
// A dead croft's backup at this croft's own path (the start time
// could not be read, so the name is the recycled pid alone) would be
// restored from, written over by this croft's backup and cut down,
// all as one file. It is moved aside first; one that cannot be is
// left alone, and this croft keeps no backup rather than write over
// it.
let own = self.hot_exit_path();
let mut orphans = crate::hot_exit::orphaned(&dir, &root);
if let Some(own) = own.as_ref().filter(|own| orphans.contains(own)) {
match crate::hot_exit::move_aside(own) {
Some(aside) => {
for file in orphans.iter_mut().filter(|f| *f == own) {
*file = aside.clone();
}
}
None => {
self.hot_exit_dir = None;
self.status = format!(
"Hot exit is off for this session: a backup is at its own path, {}, and could not be moved aside",
own.display()
);
return;
}
}
}
for file in orphans {
let backup = match crate::hot_exit::Backup::load(&file) {
Ok(backup) if backup.is_of(&root) => backup,
// Another workspace's, under a colliding digest.
Ok(_) => continue,
// Reported for a week already: past recovery by hand.
Err(_) if crate::hot_exit::is_expired(&file) => {
if crate::hot_exit::remove(&file, &root).is_ok() {
expired += 1;
}
continue;
}
Err(_) => {
unreadable.push(file.display().to_string());
continue;
}
};
let before = restored;
let mut held: Vec<crate::hot_exit::Buffer> = Vec::new();
for buffer in &backup.buffers {
if let Some(path) = buffer.tab.path.as_ref().filter(|p| filled.contains(p)) {
doubled.push(path.clone());
held.push(buffer.clone());
continue;
}
let Some(ed) = self.restore_open_tab(&buffer.tab) else {
continue;
};
restored += 1;
let Some(path) = buffer.tab.path.clone() else {
continue;
};
filled.push(path.clone());
match ed.disk_stamp() {
// Kept at the stamp its edits were made against, so a
// file made at the path since is not written over
// without asking.
None => {
ed.set_disk_stamp(buffer.disk_stamp);
gone.push(path);
}
Some(now) if buffer.disk_stamp.is_some_and(|then| then != now) => {
ed.set_disk_stamp(buffer.disk_stamp);
changed.push(path);
}
Some(_) => {}
}
}
if !held.is_empty() {
// Not consumed. Once this croft's own backup holds what was
// restored from it, it is cut down to the held copies, so
// those do not come back a second time.
if restored > before {
trimmed.push((
file,
crate::hot_exit::Backup {
workspace_root: backup.workspace_root,
buffers: held,
},
));
}
} else if restored == before {
// Nothing in it to keep (an emptied backup, left by a
// removal that failed): no write to wait on.
let _ = crate::hot_exit::remove(&file, &root);
} else {
self.hot_exit_consumed.push(file);
}
}
let mut notes = Vec::new();
if restored > 0 {
notes.push(format!(
"Hot exit: restored {restored} unsaved tab{}",
if restored == 1 { "" } else { "s" }
));
let names = |paths: &[PathBuf]| {
paths
.iter()
.map(|p| self.status_path(p))
.collect::<Vec<_>>()
.join(", ")
};
if !changed.is_empty() {
notes.push(format!("{} changed on disk since", names(&changed)));
}
if !gone.is_empty() {
notes.push(format!("{} no longer on disk", names(&gone)));
}
if !doubled.is_empty() {
notes.push(format!(
"{} {} kept in {} backup for a later launch",
names(&doubled),
if doubled.len() == 1 {
"has a second unsaved copy,"
} else {
"have second unsaved copies,"
},
if doubled.len() == 1 { "its" } else { "their" },
));
}
let unremoved = self.hot_exit_unremoved.len();
if self.write_hot_exit() {
if self.hot_exit_unremoved.len() > unremoved {
notes.push(std::mem::take(&mut self.status));
}
// A trim that fails leaves the whole backup, so its other
// files come back again later rather than the held copy
// going.
for (file, held) in trimmed {
let _ = held.save(&file);
}
} else {
notes.push(format!(
"{}; the backup they came from is kept until it can",
std::mem::take(&mut self.status)
));
}
}
if expired > 0 {
notes.push(format!(
"Hot exit: removed {expired} unreadable backup{} older than a week",
if expired == 1 { "" } else { "s" }
));
}
if !unreadable.is_empty() {
notes.push(format!(
"Hot exit: could not read {} (kept for a week)",
unreadable.join(", ")
));
}
if !notes.is_empty() {
self.status = notes.join("; ");
}
}
/// Write what an unsaved-changes prompt (#862) asked about: the focused
/// group's tab at `only`, or every unsaved tab in every group.
///
/// Each write is the explicit save's, done now and unformatted (the tab
/// is about to go, and a formatter's reply would land after it), and it
/// refuses what a first Cmd+S refuses: a file changed on disk, text its
/// encoding cannot hold. A merge with conflicts still open is not written
/// blind either, and an untitled buffer has no file to go to. Returns a
/// line per file still unsaved; empty means everything is on disk.
fn save_tabs_for_exit(&mut self, only: Option<usize>) -> Vec<String> {
use crate::widgets::editor::SaveOutcome;
// The tabs of a file with a symbol tab mirror one text (#369): the
// first write saves them all, and writing a second would read the
// first as a change on disk. The sync afterwards marks them clean.
let mirrored: Vec<PathBuf> = self
.symbol_view_paths()
.into_iter()
.filter(|p| !self.symbol_path_is_live(p))
.collect();
// A collab guest never writes a shared file, and loses nothing by
// leaving it: its edits are already live with the owner, who saves.
let guest = self.is_collab_guest();
let root = self.tree.root.clone();
let collab = &self.collab;
let owner_saves = |p: &Path| {
guest
&& collab_file_key(&root, p)
.is_some_and(|f| collab.as_ref().is_some_and(|s| !s.is_local_only(&f)))
};
// A file open in more than one editor group is a buffer per group.
// The same unsaved text in each is written once and the other copies
// marked saved: a second write would read the first as a change on
// disk. Different texts are not settled by writing whichever group
// comes first, so neither is written. Each path with more than one
// unsaved copy, with how many and whether they hold one text.
let mut copies: Vec<(PathBuf, usize, bool)> = Vec::new();
if only.is_none() {
let mut seen: Vec<(PathBuf, &Editor)> = Vec::new();
for ed in std::iter::once(&self.editor)
.chain(self.editor_layout.inactive_groups())
.flat_map(|g| g.editors.iter())
.filter(|e| holds_unsaved(e) && e.hex.is_none() && e.sheet.is_none())
{
let Some(path) = ed.path.clone() else {
continue;
};
match seen.iter().find(|(p, _)| *p == path) {
Some((_, first)) => {
let same = first.lines == ed.lines
&& first.bytes_for_disk() == ed.bytes_for_disk();
match copies.iter_mut().find(|(p, ..)| *p == path) {
Some((_, n, one_text)) => {
*n += 1;
*one_text &= same;
}
None => copies.push((path, 2, same)),
}
}
None => seen.push((path, ed)),
}
}
}
let mut saved: Vec<(PathBuf, crate::provenance::Provenance, Option<Vec<u8>>)> = Vec::new();
// The saved text of each, for the language server's didSave (#854).
let mut saved_texts: Vec<String> = Vec::new();
let mut left: Vec<(Option<PathBuf>, String)> = Vec::new();
let mut save = |ed: &mut Editor| {
if !holds_unsaved(ed) {
return;
}
let Some(path) = ed.path.clone() else {
left.push((None, String::from("no file to save to")));
return;
};
if owner_saves(&path)
|| (mirrored.contains(&path) && saved.iter().any(|(q, ..)| *q == path))
{
return;
}
let reported = left.iter().any(|(q, _)| q.as_ref() == Some(&path));
match copies.iter().find(|(p, ..)| *p == path) {
Some((_, n, false)) => {
if !reported {
left.push((
Some(path),
format!("open in {n} editor groups with different unsaved text"),
));
}
return;
}
Some((_, _, true)) if saved.iter().any(|(q, ..)| *q == path) => {
ed.mark_clean_like_sibling();
return;
}
// The first copy's save was refused; this one would be too.
Some((_, _, true)) if reported => return,
_ => {}
}
if ed.merge.as_ref().is_some_and(|m| m.unresolved_count() > 0) {
left.push((Some(path), String::from("merge conflicts left")));
return;
}
let outcome = if ed.hex.is_some() {
ed.hex_save(false)
} else if ed.sheet.is_some() {
ed.sheet_save(false, false)
} else {
ed.save_to_disk()
};
let why = match outcome {
Ok(SaveOutcome::Saved) if !ed.dirty => {
saved.push((path, ed.provenance_to_record(), ed.bytes_for_disk()));
saved_texts.push(ed.lines.join("\n"));
return;
}
// A workbook save that held formula cells back names them.
Ok(SaveOutcome::Saved) => ed.status.clone(),
Ok(SaveOutcome::DiskConflict) => String::from("changed on disk"),
Ok(SaveOutcome::EncodingLoss) => {
format!("{} cannot hold every character", ed.encoding.name())
}
Err(e) => e.to_string(),
};
left.push((Some(path), why));
};
match only {
Some(idx) => {
if let Some(ed) = self.editor.editors.get_mut(idx) {
save(ed);
}
}
None => {
self.editor.editors.iter_mut().for_each(&mut save);
for group in self.editor_layout.inactive_groups_mut() {
group.editors.iter_mut().for_each(&mut save);
}
}
}
if only.is_none() && !saved.is_empty() {
self.sync_symbol_views();
}
// The same follow-ups as every other save path.
for (path, ..) in &saved {
self.reload_config_for_path(path);
}
if let Some(lsp) = self.lsp.as_ref() {
for ((path, ..), text) in saved.iter().zip(saved_texts) {
lsp.save_doc(path.clone(), text);
}
}
for (path, seats, described) in saved {
self.record_history_snapshot_of(&path, seats, described);
}
left.into_iter()
.map(|(path, why)| match path {
Some(p) => format!("{} ({why})", self.status_path(&p)),
None => format!("untitled ({why})"),
})
.collect()
}
/// 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();
// A symbol tab's minimap draws only its symbol (#369), so rows
// count from the symbol's first line.
let span = self.editor.minimap_span();
let (first, end) = span;
let top = self.editor.scroll.saturating_sub(first);
let rows = self.editor.visible_rows();
let total = end - first;
let edit_seq = self.editor.edit_seq;
// A selection is only drawn where it meets the drawn lines.
let selection = self
.editor
.selection_rows()
.filter(|&(s, e)| s < end && e >= first)
.map(|(s, e)| (s.max(first) - first, e.min(end - 1) - first));
let doc = {
use std::hash::{Hash, Hasher};
let mut h = std::collections::hash_map::DefaultHasher::new();
self.editor.path.hash(&mut h);
(h.finish(), span)
};
let desired = MinimapLayout {
cell_x: strip.x,
cell_y: strip.y,
cell_w,
cell_h,
top,
rows,
total,
edit_seq,
highlight_generation: self.editor.highlight_generation(),
side: self.minimap_side,
bg,
selection,
doc,
};
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,
)
});
// Typing re-bakes the whole strip image, several kilobytes a key
// over SSH (#682). While only the text changed, the strip catches up
// at most every `MINIMAP_EDIT_REBAKE`; `tick_minimap` redraws once
// the wait is over so the last edit always lands.
let text_only = !placement_moved
&& self.overlays.minimap.layout().is_some_and(|prev| {
(
prev.top,
prev.rows,
prev.side,
prev.bg,
prev.selection,
prev.doc,
) == (
desired.top,
desired.rows,
desired.side,
desired.bg,
desired.selection,
desired.doc,
)
});
if text_only
&& self
.minimap_baked_at
.is_some_and(|t| t.elapsed() < MINIMAP_EDIT_REBAKE)
{
self.minimap_edit_pending = true;
return;
}
self.minimap_edit_pending = false;
self.minimap_baked_at = Some(std::time::Instant::now());
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,
span,
self.editor.highlight_generation(),
);
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);
}
}
/// Swap in every tab's background syntax pass that finished since the
/// last tick (#850), in every editor group. True when any landed, so the
/// frame repaints in the new colors.
pub fn poll_highlights(&mut self) -> bool {
let groups =
std::iter::once(&mut self.editor).chain(self.editor_layout.inactive_groups_mut());
let mut landed = false;
for ed in groups.flat_map(|g| g.editors.iter_mut()) {
landed |= ed.poll_highlights();
}
landed
}
/// True once a deferred minimap bake is due, so the loop redraws and
/// the strip shows the last edit. Consumes the pending flag: that redraw
/// bakes (the wait is over), and if the minimap was hidden meanwhile
/// nothing is left pending to redraw for, forever.
pub fn tick_minimap(&mut self) -> bool {
let due = self.minimap_edit_pending
&& self
.minimap_baked_at
.is_none_or(|t| t.elapsed() >= MINIMAP_EDIT_REBAKE);
if due {
self.minimap_edit_pending = false;
}
due
}
fn disable_minimap_image(&mut self) {
self.overlays.minimap.disable();
self.minimap_img_rect = Rect::default();
self.minimap_text = false;
}
/// Draw the minimap into `strip`: the raster where the terminal draws
/// images, else braille text (#1231), so it shows in tmux, Alacritty,
/// GNOME Terminal and plain xterm too.
fn paint_minimap(&mut self, frame: &mut ratatui::Frame, strip: Rect) {
if self.inline_images_enabled() && self.cell_pixel.is_some() {
self.minimap_text = false;
self.update_minimap_overlay(strip);
} else {
self.overlays.minimap.disable();
self.render_text_minimap(frame.buffer_mut(), strip);
}
}
/// The braille minimap (#1231): the same raster the image path bakes, at
/// one dot row a line (folded to fit a longer file), with the visible
/// lines tinted like the image's viewport box.
fn render_text_minimap(&mut self, buf: &mut ratatui::buffer::Buffer, strip: Rect) {
self.minimap_img_rect = strip;
self.minimap_text = true;
if strip.width == 0 || strip.height == 0 {
return;
}
let (first, end) = self.editor.minimap_span();
let total = end - first;
let w = strip.width as u32 * 2 * MINIMAP_TEXT_CHARS_PER_DOT;
let h = strip.height as u32 * 4;
let content_h = (total as u32).clamp(1, h);
self.minimap_content_h = content_h;
let bg = self.theme.editor_bg_rgb();
let light = 0.299 * bg.0 as f32 + 0.587 * bg.1 as f32 + 0.114 * bg.2 as f32 > 140.0;
let fg = if light {
(0x38, 0x3a, 0x41)
} else {
(0xc5, 0xcd, 0xd9)
};
let sig = (
self.editor.path.clone(),
self.editor.edit_seq,
w,
h,
bg,
(first, end),
self.editor.highlight_generation(),
);
if self.minimap_text_cache.as_ref().map(|(k, _)| k) != Some(&sig) {
let rgba = self.editor.minimap_rgba(w, h, content_h, bg, fg);
let cells = braille_minimap(&rgba, w, h, bg, strip.width, strip.height);
self.minimap_text_cache = Some((sig, cells));
}
let Some((_, cells)) = self.minimap_text_cache.as_ref() else {
return;
};
// The visible lines, in cell rows, get a faint wash of the text colour.
let top = self.editor.scroll.saturating_sub(first);
let rows = self.editor.visible_rows();
let to_cell = |line: usize| line * content_h as usize / total.max(1) / 4;
let (view_top, view_end) = (to_cell(top), to_cell(top + rows.max(1) - 1));
let mix = |a: u8, b: u8| ((a as u16 * 85 + b as u16 * 15) / 100) as u8;
let wash = Color::Rgb(mix(bg.0, fg.0), mix(bg.1, fg.1), mix(bg.2, fg.2));
for (i, cell) in cells.iter().enumerate() {
let (cx, cy) = (i % strip.width as usize, i / strip.width as usize);
let back = if total > 0 && (view_top..=view_end).contains(&cy) {
wash
} else {
Color::Rgb(bg.0, bg.1, bg.2)
};
let Some(out) = buf.cell_mut((strip.x + cx as u16, strip.y + cy as u16)) else {
continue;
};
match cell {
Some((glyph, (r, g, b))) => {
out.set_char(*glyph).set_fg(Color::Rgb(*r, *g, *b));
}
None => {
out.set_char(' ');
}
}
out.set_bg(back);
}
}
/// 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 && !self.minimap_room {
format!(
"Minimap on: it shows once the editor is {} columns wide",
MINIMAP_WIDTH_CELLS + MINIMAP_MIN_EDITOR_WIDTH
)
} else if self.minimap_visible {
String::from("Minimap on")
} else {
String::from("Minimap off")
};
}
/// Carve the minimap strip off `editor_area` (the active group's rect in a
/// split) when the minimap is on and the editor has room. 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(&mut self, editor_area: Rect) -> Option<(Rect, Rect, Rect)> {
self.minimap_room = editor_area.width >= MINIMAP_WIDTH_CELLS + MINIMAP_MIN_EDITOR_WIDTH;
if !self.minimap_visible || !self.minimap_room {
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 (first, end) = self.editor.minimap_span();
let total = end - first;
if r.height == 0 || total == 0 {
return;
}
// The text strip maps four dot rows to a cell (#1231).
let ch_px = if self.minimap_text {
4
} else {
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 = first + (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 {
crumb: None,
scroll: Default::default(),
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 {
crumb: None,
scroll: Default::default(),
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.
/// Go to Next / Previous Change (#1352): in a diff tab its hunks, in a
/// buffer with merge conflicts its conflicts, otherwise the editor's
/// change bars, wrapping at the ends.
fn jump_editor_change(&mut self, forward: bool) {
if self.editor.diff.is_some() {
self.jump_diff_change(forward);
return;
}
if !self.editor.conflicts().is_empty() {
self.jump_conflict(!forward);
return;
}
let row = self.editor.cursor_row;
match self.editor.git_change_from(row, forward) {
Some(line) => {
self.editor.clear_selection();
self.editor.goto_line_centered(line);
self.status = format!("Change at line {}", line + 1);
}
None => self.status = String::from("No changes in this file"),
}
}
/// 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),
_ => {}
}
}
/// Sheet: Sort by Column (#578): sort the open CSV/TSV sheet's rows by
/// the cursor's column, reversing when it is already sorted that way.
/// A reorder is an edit, as in a spreadsheet: it marks the sheet
/// unsaved. xlsx is left out, since its edits are written back by
/// row, and so are the read-only kinds.
fn sort_sheet_by_column(&mut self) {
let Some(sheet) = self.editor.sheet.as_mut() else {
self.status = String::from("Open a CSV or TSV file to sort it");
return;
};
if !matches!(
sheet.kind,
crate::sheet::SheetKind::Csv | crate::sheet::SheetKind::Tsv
) {
self.status = String::from("Sorting is for CSV and TSV sheets");
return;
}
let current = sheet.current_sheet;
let Some(data) = sheet.sheets.get_mut(current) else {
return;
};
let col = data.cur_col;
let name = data
.headers
.get(col)
.filter(|h| !h.is_empty())
.cloned()
.unwrap_or_else(|| format!("column {}", col + 1));
let ascending = data.sort_by_column(col);
sheet.dirty = true;
self.editor.dirty = true;
self.status = format!(
"Sorted by {name}, {}",
if ascending { "ascending" } else { "descending" }
);
}
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 (r, c) = sheet.commit_edit().expect("checked");
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 | KeyCode::End
if sheet.kind == crate::sheet::SheetKind::Sqlite
&& (key.modifiers.contains(KeyModifiers::CONTROL)
|| key.modifiers.contains(KeyModifiers::SUPER)) =>
{
// The table's first or last row, not the loaded batch's
// (#1222).
self.sqlite_jump(key.code == KeyCode::End, visible);
return;
}
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);
}
fn pr_viewed_path() -> PathBuf {
croft_cache_dir().join("pr-viewed.json")
}
/// Open pull request `pr` for review in its own tab (#365), with the
/// viewed marks remembered for `key` (`owner/repo#n`).
pub fn open_pr_review(&mut self, pr: crate::pr_review::PrInfo, key: String) {
let store = crate::pr_review::ViewedStore::load(&Self::pr_viewed_path());
let viewed = store.viewed(&key);
let n = pr.number;
self.editor
.open_pr_review(crate::widgets::pr_review::PrReviewView::new(
pr, key, viewed,
));
self.focus_pane(Pane::Editor);
self.status = format!("Reviewing PR #{n}");
}
/// Ask for a pull request by number or URL (#365).
fn open_pr_number_prompt(&mut self) {
use crate::widgets::input_prompt::{InputPrompt, InputPurpose};
self.open_input_prompt(InputPrompt::new(
InputPurpose::PullRequestNumber,
String::from("Review Pull Request"),
String::from("number, #number, or the PR's URL"),
));
}
/// The Review Pull Request prompt's answer.
fn submit_pr_number(&mut self, input: &str) {
match crate::pr_review::parse_pr_selector(input) {
Some(selector) => self.start_pr_review(selector),
None => {
self.status = format!("{:?} is not a pull request number", input.trim());
}
}
}
/// Fetch the pull request `selector` names (a number, or its URL) with
/// `gh` and open it for review once it arrives.
fn start_pr_review(&mut self, selector: String) {
self.status = format!("Loading PR {selector}…");
let args = crate::pr_review::view_args(&selector);
self.spawn_pr_gh(PrGhJob::View { selector }, args);
}
/// Run one `gh` call for the review tab on a worker (#365): a slow
/// network or a large log never stalls input or redraws, and the call
/// is killed at [`crate::pr_review::GH_TIMEOUT`]. A newer call replaces
/// one still running, whose answer is then dropped.
fn spawn_pr_gh(&mut self, job: PrGhJob, args: Vec<String>) {
let (tx, rx) = std::sync::mpsc::channel();
let gh = self.review_gh.clone();
let root = self.workspace_root().to_path_buf();
std::thread::spawn(move || {
let _ = tx.send(crate::pr_review::run_gh(
&gh,
&args,
&root,
crate::pr_review::GH_TIMEOUT,
));
});
self.pr_gh = Some((job, rx));
}
/// Read GitHub's viewed state for the open review tab on a worker
/// (#365). A PR whose key names no GitHub repository reads nothing, and
/// its marks stay local.
fn start_pr_viewed_fetch(&mut self) {
let Some(view) = self.editor.pr_review.as_ref() else {
return;
};
let key = view.key.clone();
let number = view.pr.number;
let slug = key.split('#').next().unwrap_or_default().to_string();
if crate::pr_review::viewed_query_args(&slug, number, None).is_none() {
return;
}
let (tx, rx) = std::sync::mpsc::channel();
let gh = self.review_gh.clone();
let root = self.workspace_root().to_path_buf();
std::thread::spawn(move || {
let _ = tx.send(crate::pr_review::fetch_viewed(
&gh,
&slug,
number,
&root,
crate::pr_review::GH_TIMEOUT,
));
});
self.pr_viewed_fetch = Some((key, self.pr_viewed_seq, rx));
}
/// Queue a viewed mark for GitHub (#365), stamping its file so a
/// viewed-state read already under way cannot undo it.
fn queue_pr_viewed_write(&mut self, write: PrViewedWrite) {
self.touch_pr_viewed(&write.key, &write.path);
self.pr_viewed_queue.push_back(write);
}
/// Stamp `(key, path)` with the next [`Self::pr_viewed_seq`].
fn touch_pr_viewed(&mut self, key: &str, path: &str) {
self.pr_viewed_seq += 1;
self.pr_viewed_touched
.insert((key.to_string(), path.to_string()), self.pr_viewed_seq);
}
/// Whether GitHub's answer from a read that began at `since` may be
/// older than a viewed write of `path` in the tab keyed `key`: one
/// still queued or in flight, or one that settled after the read began.
fn pr_viewed_fenced(&self, key: &str, path: &str, since: u64) -> bool {
let pending = self
.pr_viewed_queue
.iter()
.any(|w| w.key == key && w.path == path)
|| self
.pr_viewed_write
.as_ref()
.is_some_and(|(k, p, _)| k == key && p == path);
pending
|| self
.pr_viewed_touched
.get(&(key.to_string(), path.to_string()))
.is_some_and(|&stamp| stamp > since)
}
/// Apply GitHub's viewed state when it arrives, report a failed viewed
/// mutation once per tab, and send the next queued one (#365). Returns
/// true when it changed what is on screen.
fn poll_pr_viewed(&mut self) -> bool {
use std::sync::mpsc::TryRecvError;
let mut changed = false;
if let Some((key, since, rx)) = self.pr_viewed_fetch.as_ref() {
let got = rx.try_recv();
if !matches!(got, Err(TryRecvError::Empty)) {
let (key, since) = (key.clone(), *since);
self.pr_viewed_fetch = None;
// gh missing, signed out or refused: the marks stay local,
// exactly as before, and nothing is said about it.
if let Ok(Ok((pr_id, states))) = got {
changed |= self.apply_github_viewed(&key, since, pr_id, states);
}
}
}
if let Some((key, path, rx)) = self.pr_viewed_write.as_ref() {
let got = rx.try_recv();
if !matches!(got, Err(TryRecvError::Empty)) {
let (key, path) = (key.clone(), path.clone());
self.pr_viewed_write = None;
// Settled after any read already under way began: that
// read may predate it.
self.touch_pr_viewed(&key, &path);
let why = match got {
Ok(Ok(_)) => None,
Ok(Err(why)) => Some(why),
Err(_) => Some(String::from("gh stopped without answering")),
};
if let Some(why) = why {
let warned = self
.editor
.pr_review
.as_mut()
.filter(|v| v.key == key)
.is_some_and(|v| std::mem::replace(&mut v.sync_warned, true));
if !warned {
self.status = format!(
"Viewed state saved locally; GitHub could not be updated: {why}"
);
changed = true;
}
}
}
}
if self.pr_viewed_write.is_none()
&& let Some(write) = self.pr_viewed_queue.pop_front()
{
let args = crate::pr_review::mark_viewed_args(&write.pr_id, &write.path, write.viewed);
let (tx, rx) = std::sync::mpsc::channel();
let gh = self.review_gh.clone();
let root = self.workspace_root().to_path_buf();
std::thread::spawn(move || {
let _ = tx.send(crate::pr_review::run_gh(
&gh,
&args,
&root,
crate::pr_review::GH_TIMEOUT,
));
});
self.pr_viewed_write = Some((write.key, write.path, rx));
}
changed
}
/// GitHub's viewed state for the tab keyed `key`, read from `since`,
/// becomes the truth (#365): the checkboxes and the local store follow
/// it, except for a file toggled while the answer was on its way, whose
/// newer mark is sent to GitHub instead, and a file whose write had not
/// settled when the read began, which keeps its mark. Files GitHub did
/// not list keep their local mark.
fn apply_github_viewed(
&mut self,
key: &str,
since: u64,
pr_id: String,
states: std::collections::BTreeMap<String, crate::pr_review::ViewedState>,
) -> bool {
if self.editor.pr_review.as_ref().is_none_or(|v| v.key != key) {
return false;
}
let states: Vec<_> = states
.into_iter()
.filter(|(path, _)| !self.pr_viewed_fenced(key, path, since))
.collect();
let Some(view) = self.editor.pr_review.as_mut() else {
return false;
};
let store_path = Self::pr_viewed_path();
let mut store = crate::pr_review::ViewedStore::load(&store_path);
let unsynced = std::mem::take(&mut view.unsynced);
let mut resend = Vec::new();
for (path, state) in states {
let local = view.viewed.contains(&path);
if unsynced.contains(&path) {
if local != state.is_viewed() {
resend.push(PrViewedWrite {
key: key.to_string(),
pr_id: pr_id.clone(),
path,
viewed: local,
});
}
continue;
}
store.set(key, &path, state.is_viewed());
if state.is_viewed() {
view.viewed.insert(path);
} else {
view.viewed.remove(&path);
}
}
view.github_id = Some(pr_id);
// GitHub holds the marks now; a cache that cannot be written only
// costs the offline copy.
let _ = store.save(&store_path);
for write in resend {
self.queue_pr_viewed_write(write);
}
true
}
/// While the open review tab has checks still running, re-read the PR
/// every [`PR_CHECKS_POLL`] so they turn green or red on their own
/// (#365). Never while another review call is in flight, which it would
/// otherwise replace.
fn refresh_pending_pr_checks(&mut self) {
if self.pr_gh.is_some() {
return;
}
let Some(view) = self.editor.pr_review.as_ref() else {
return;
};
if !view.has_pending_checks() || view.pr.url.is_empty() {
return;
}
let now = std::time::Instant::now();
match self.pr_checks_polled {
Some(at) if now.duration_since(at) < PR_CHECKS_POLL => return,
// The first sight of a pending tab starts the clock.
None => {
self.pr_checks_polled = Some(now);
return;
}
Some(_) => {}
}
self.pr_checks_polled = Some(now);
let url = view.pr.url.clone();
let args = crate::pr_review::view_args(&url);
self.spawn_pr_gh(PrGhJob::Checks { url }, args);
}
/// Apply a finished review `gh` call. Returns true when it changed what
/// is on screen.
fn poll_pr_gh(&mut self) -> bool {
let synced = self.poll_pr_viewed();
self.refresh_pending_pr_checks();
let Some((_, rx)) = self.pr_gh.as_ref() else {
return synced;
};
let result = match rx.try_recv() {
Ok(r) => r,
Err(std::sync::mpsc::TryRecvError::Empty) => return synced,
Err(std::sync::mpsc::TryRecvError::Disconnected) => {
Err(String::from("gh stopped without answering"))
}
};
let Some((job, _)) = self.pr_gh.take() else {
return synced;
};
match job {
PrGhJob::View { selector } => {
match result.and_then(|json| crate::pr_review::parse_pr(&json)) {
Ok(pr) => {
let key = crate::pr_review::review_key(&pr);
self.open_pr_review(pr, key);
self.start_pr_viewed_fetch();
}
Err(why) => self.status = format!("Could not load PR {selector}: {why}"),
}
}
PrGhJob::Diff { path } => match result {
Ok(patch) => {
let Some(view) = self.editor.pr_review.as_mut() else {
return true;
};
view.diff = Some(crate::pr_review::split_diff_by_file(&patch));
self.open_pr_diff_section(&path);
}
Err(why) => self.status = format!("gh pr diff failed: {why}"),
},
PrGhJob::List => {
use crate::widgets::list_picker::{ListPicker, ListPurpose, ListRow, PR_BY_NUMBER};
let items = result.and_then(|json| crate::pr_review::parse_pr_list(&json));
let items = match items {
Ok(items) if !items.is_empty() => items,
other => {
self.open_pr_number_prompt();
if let Err(why) = other {
self.status = format!("Could not list pull requests: {why}");
}
return true;
}
};
let mut rows: Vec<ListRow> = items
.into_iter()
.map(|p| ListRow {
id: p.url,
label: format!(
"#{:<5} {}{} ({})",
p.number,
if p.draft { "[draft] " } else { "" },
p.title,
p.author
),
})
.collect();
rows.push(ListRow {
id: PR_BY_NUMBER.to_string(),
label: String::from("Another pull request by number or URL…"),
});
self.status.clear();
self.list_picker = Some(ListPicker::new(
ListPurpose::ReviewPullRequest,
String::from("Review Pull Request"),
rows,
));
}
PrGhJob::Checks { url } => {
// A failed re-read changes nothing: the next one retries.
let Ok(pr) = result.and_then(|json| crate::pr_review::parse_pr(&json)) else {
return false;
};
let Some(view) = self.editor.pr_review.as_mut().filter(|v| v.pr.url == url) else {
return false;
};
let was_pending = view.has_pending_checks();
view.pr.checks = pr.checks;
view.move_selection(0);
if was_pending && !view.has_pending_checks() {
self.status = format!("PR #{}: every check has finished", view.pr.number);
}
}
PrGhJob::Log { name } => {
let channel = "PR Checks";
crate::output::clear(channel);
// A failed fetch's reason goes where the log would have.
let text = result.unwrap_or_else(|why| why);
for line in text.lines() {
crate::output::push(channel, crate::output::OutputLevel::Info, line);
}
self.status = format!("{name}: log in OUTPUT > {channel}");
}
}
true
}
/// PULL REQUEST tab keys (#365).
fn handle_pr_review_key(&mut self, key: KeyEvent) {
let Some(view) = self.editor.pr_review.as_mut() else {
return;
};
let page = (view.rows_visible as isize).max(1);
match key.code {
KeyCode::Down | KeyCode::Char('j') => view.move_selection(1),
KeyCode::Up | KeyCode::Char('k') => view.move_selection(-1),
KeyCode::PageDown => view.move_selection(page),
KeyCode::PageUp => view.move_selection(-page),
KeyCode::Home => view.selected = 0,
KeyCode::End => view.move_selection(isize::MAX / 2),
KeyCode::Char(' ') => {
let Some(path) = view.selected_file().map(|f| f.path.clone()) else {
return;
};
let store_path = Self::pr_viewed_path();
let mut store = crate::pr_review::ViewedStore::load(&store_path);
let now = store.toggle(&view.key, &path);
if let Err(e) = store.save(&store_path) {
self.status = format!("Could not save the viewed mark: {e}");
}
// The mark flips at once; GitHub hears about it off the UI
// thread, or once its viewed state has loaded.
match view.github_id.clone() {
Some(pr_id) => {
let write = PrViewedWrite {
key: view.key.clone(),
pr_id,
path: path.clone(),
viewed: now,
};
// The fields directly, as `view` still borrows the
// editor: what `queue_pr_viewed_write` does.
self.pr_viewed_seq += 1;
self.pr_viewed_touched
.insert((write.key.clone(), write.path.clone()), self.pr_viewed_seq);
self.pr_viewed_queue.push_back(write);
}
None if self
.pr_viewed_fetch
.as_ref()
.is_some_and(|(k, _, _)| *k == view.key) =>
{
view.unsynced.insert(path.clone());
}
None => {}
}
if now {
view.viewed.insert(path);
} else {
view.viewed.remove(&path);
}
view.move_selection(1);
}
KeyCode::Enter => {
if view.selected_check().is_some() {
self.show_pr_check_log();
} else {
self.open_pr_file_diff();
}
}
KeyCode::Char('l') => self.show_pr_check_log(),
KeyCode::Char('c') => self.checkout_pr_head(),
KeyCode::Char('r') => {
// By URL, so a PR opened from another repository refreshes
// as itself.
let selector = if view.pr.url.is_empty() {
view.pr.number.to_string()
} else {
view.pr.url.clone()
};
self.start_pr_review(selector);
}
KeyCode::Esc | KeyCode::Char('q') => {
let n = view.pr.number;
self.editor.close_active();
self.status = format!("Left review of PR #{n}");
self.leave_pr_checkout();
}
_ => {}
}
}
/// Check the reviewed pull request's head out into a sibling worktree
/// and add it to the workspace (#365), so its code has the language
/// server, go-to-definition and tests. Fetching runs off the UI thread.
fn checkout_pr_head(&mut self) {
let Some(view) = self.editor.pr_review.as_ref() else {
return;
};
if self.pr_checkout_rx.is_some() {
self.status = String::from("A pull request checkout is already fetching");
return;
}
let number = view.pr.number;
let slug = view.key.split('#').next().unwrap_or_default().to_string();
// What review mode last checked out there, the one HEAD a refresh
// may move away from without stranding commits.
let previous = self
.pr_checkout
.as_ref()
.filter(|c| c.number == number)
.map(|c| c.oid.clone());
let repo = self.workspace_root().to_path_buf();
let Some(path) = crate::git::pr_worktree_path(&repo, number) else {
self.status = format!(
"No place beside {} to check PR #{number} out",
repo.display()
);
return;
};
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let remote = crate::git::remote_for_slug(&repo, &slug);
// Canonical, like the workspace roots it is added to and later
// removed from.
let result = crate::git::checkout_pr_worktree(
&repo,
&remote,
number,
&path,
previous.as_deref(),
)
.map(|wt| (path.canonicalize().unwrap_or(path), wt));
let _ = tx.send(result);
});
self.pr_checkout_rx = Some((number, rx));
self.status = format!("Fetching PR #{number}…");
}
/// Apply a finished pull request checkout. Returns true when it changed
/// what is on screen.
fn poll_pr_checkout(&mut self) -> bool {
let Some((number, rx)) = self.pr_checkout_rx.as_ref() else {
return false;
};
let number = *number;
let result = match rx.try_recv() {
Ok(r) => r,
Err(std::sync::mpsc::TryRecvError::Empty) => return false,
Err(std::sync::mpsc::TryRecvError::Disconnected) => {
Err(String::from("the checkout stopped without answering"))
}
};
self.pr_checkout_rx = None;
match result {
Ok((path, wt)) => {
let mut fresh = PrCheckout {
number,
path,
oid: wt.oid,
created: wt.created,
};
// Review closed, or another PR opened, while this fetched:
// no review owns it, so it is settled like a left one.
if self.editor.pr_review.as_ref().map(|v| v.pr.number) != Some(number) {
let outcome = self.settle_pr_checkout(fresh);
self.status = format!(
"PR #{number}'s checkout finished after its review closed; {outcome}"
);
return true;
}
match self.pr_checkout.take() {
// A refresh of the same checkout: still review mode's
// if review mode made it.
Some(old) if old.number == number => fresh.created |= old.created,
// Another PR's: settled before this one replaces it.
Some(old) => {
let _ = self.settle_pr_checkout(old);
}
None => {}
}
if !self.roots.iter().any(|r| r == fresh.path) {
self.add_workspace_folder(fresh.path.clone());
}
let short: String = fresh.oid.chars().take(8).collect();
self.status = if fresh.created {
format!(
"PR #{number} checked out at {short} in {} — leaving review removes it if nothing changed",
fresh.path.display()
)
} else {
format!(
"PR #{number} checked out at {short} in the existing {}, which leaving review keeps",
fresh.path.display()
)
};
self.pr_checkout = Some(fresh);
}
Err(why) => self.status = format!("Could not check out PR #{number}: {why}"),
}
true
}
/// Remove a pull request checkout review mode no longer needs, with its
/// workspace folder and panes, unless something in it is worth keeping:
/// a worktree that existed before review, an unsaved editor tab under
/// it, edits or build output on disk, or new commits. Says which.
fn settle_pr_checkout(&mut self, checkout: PrCheckout) -> String {
let PrCheckout {
path, oid, created, ..
} = checkout;
if !path.exists() {
return String::from("its checkout is already gone");
}
let kept = |why: &str| format!("kept its checkout at {}: {why}", path.display());
if !created {
return kept("it existed before review");
}
let groups = std::iter::once(&self.editor).chain(self.editor_layout.inactive_groups());
let unsaved = groups
.flat_map(|g| g.editors.iter())
.filter(|e| e.dirty)
.find_map(|e| e.path.as_deref().filter(|p| p.starts_with(&path)))
.map(|p| p.strip_prefix(&path).unwrap_or(p).display().to_string());
if let Some(file) = unsaved {
return kept(&format!("{file} has unsaved changes"));
}
if let Some(why) = crate::git::pr_worktree_keep_reason(&path, &oid) {
return kept(&why);
}
match crate::git::remove_worktree_lane(&path) {
Ok(()) => {
self.close_lane_panes(&path);
if self.roots.iter().any(|r| r == path) {
self.remove_workspace_folder(path);
}
String::from("removed its checkout")
}
Err(why) => format!("could not remove {}: {why}", path.display()),
}
}
/// Leaving review mode (#365): remove the pull request's checkout and
/// its workspace folder, unless it holds work — edits, build output or
/// new commits — which stay, with the reason in the status.
fn leave_pr_checkout(&mut self) {
let Some(checkout) = self.pr_checkout.take() else {
return;
};
let number = checkout.number;
let outcome = self.settle_pr_checkout(checkout);
self.status = format!("Left review of PR #{number}; {outcome}");
}
/// SARIF viewer keys (#577). While the filter box has focus, printable
/// keys edit the query; otherwise they drive the list.
fn handle_sarif_key(&mut self, key: KeyEvent) {
use crate::sarif::semantics::{BaselineState, Level, SuppressionState};
use crate::sarif::view::{Column, Tab};
let Some(view) = self.editor.sarif.as_mut() else {
return;
};
if view.editing_query {
match key.code {
KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => {
let mut q = view.query_text.clone();
q.push(c);
view.set_query(&q);
}
KeyCode::Backspace => {
let mut q = view.query_text.clone();
q.pop();
view.set_query(&q);
}
KeyCode::Enter => view.editing_query = false,
KeyCode::Esc => {
view.set_query("");
view.editing_query = false;
}
KeyCode::Up => view.move_selection(-1),
KeyCode::Down => view.move_selection(1),
_ => {}
}
return;
}
let page = (view.rows_visible as isize).max(1);
let toggle = |set: &mut std::collections::HashSet<Level>, l: Level| {
if !set.remove(&l) {
set.insert(l);
}
};
match key.code {
KeyCode::Down | KeyCode::Char('j') => view.move_selection(1),
KeyCode::Up | KeyCode::Char('k') => view.move_selection(-1),
KeyCode::PageDown => view.move_selection(page),
KeyCode::PageUp => view.move_selection(-page),
KeyCode::Home => view.select_first(),
KeyCode::End => view.select_last(),
KeyCode::Left | KeyCode::Char('h') => view.set_fold(true),
KeyCode::Right | KeyCode::Char('l') => view.set_fold(false),
KeyCode::Char('/') => view.editing_query = true,
KeyCode::Esc => view.set_query(""),
KeyCode::Tab | KeyCode::BackTab => {
let order = [Tab::Locations, Tab::Rules, Tab::Logs, Tab::Run];
let i = order.iter().position(|t| *t == view.tab).unwrap_or(0);
let step = if key.code == KeyCode::BackTab { 2 } else { 1 };
view.set_tab(order[(i + step) % order.len()]);
}
KeyCode::Char('s') => {
let order = [
Column::Line,
Column::Level,
Column::Rule,
Column::File,
Column::Message,
];
let i = order.iter().position(|c| *c == view.sort.0).unwrap_or(0);
view.sort_by(order[(i + 1) % order.len()]);
view.sort.1 = true;
}
KeyCode::Char('S') => {
let col = view.sort.0;
view.sort_by(col);
}
KeyCode::Char('c') => view.fold_all(true),
KeyCode::Char('e') => view.fold_all(false),
KeyCode::Char('1') => toggle(&mut view.filters.hidden_levels, Level::Error),
KeyCode::Char('2') => toggle(&mut view.filters.hidden_levels, Level::Warning),
KeyCode::Char('3') => toggle(&mut view.filters.hidden_levels, Level::Note),
KeyCode::Char('4') => toggle(&mut view.filters.hidden_levels, Level::None),
KeyCode::Char('u') => {
let set = &mut view.filters.hidden_suppressions;
if !set.remove(&SuppressionState::Suppressed) {
set.insert(SuppressionState::Suppressed);
}
}
KeyCode::Char('a') => {
let set = &mut view.filters.hidden_baselines;
if !set.remove(&BaselineState::Absent) {
set.insert(BaselineState::Absent);
}
}
KeyCode::Char('x') => view.clear_filters(),
KeyCode::Char('K') => {
self.status = if view.toggle_non_problem_kinds() {
String::from("Hiding pass, not-applicable and informational results")
} else {
String::from("Showing results of every kind")
};
}
KeyCode::Char('W') => {
self.status = match view.close_added_logs() {
0 => String::from("Only the viewer's own log is open"),
n => format!("Closed {n} added log{}", if n == 1 { "" } else { "s" }),
};
}
KeyCode::Char('C') => {
use crate::widgets::input_prompt::{InputPrompt, InputPurpose};
let current = crate::sarif::view::columns_text(&view.columns);
self.open_input_prompt(
InputPrompt::new(
InputPurpose::SarifColumns,
String::from("SARIF Columns"),
String::from(
"rule, level, kind, baseline, suppression, tool, rank (empty for none)",
),
)
.with_value(current),
);
}
KeyCode::Char('f') => self.apply_sarif_fix(0),
KeyCode::Char('o') => {
use crate::widgets::input_prompt::{InputPrompt, InputPurpose};
self.open_input_prompt(InputPrompt::new(
InputPurpose::SarifAddLog,
String::from("Open SARIF Log"),
String::from("path to a .sarif file to add to this view"),
));
}
KeyCode::Char('b') => {
use crate::widgets::input_prompt::{InputPrompt, InputPurpose};
self.open_input_prompt(InputPrompt::new(
InputPurpose::SarifBaseline,
String::from("Compare with Baseline"),
String::from("path to an earlier .sarif log of the same code"),
));
}
KeyCode::Char('X') => self.start_dismiss_code_scanning_alert(),
KeyCode::Char('E') => {
use crate::widgets::input_prompt::{InputPrompt, InputPurpose};
self.open_input_prompt(
InputPrompt::new(
InputPurpose::SarifExport,
String::from("Export Results (CSV, or SARIF for a .sarif name)"),
String::from("file to write the visible results to"),
)
.with_value("sarif-results.csv"),
);
}
KeyCode::Delete | KeyCode::Backspace if view.tab == Tab::Logs => {
match view.selected_log() {
Some(i) if view.remove_log(i) => {
self.sarif_diag_signature.clear();
self.status = String::from("Closed that log");
}
Some(_) => {
self.status = String::from("The last log closes with its tab (Cmd+W)");
}
None => {}
}
}
KeyCode::Char('d') => view.detail_tab = view.detail_tab.step(true),
// Scroll the details pane half a page; the renderer clamps.
KeyCode::Char(']') => {
view.detail_scroll += (view.rows_visible as usize / 2).max(1);
}
KeyCode::Char('[') => {
view.detail_scroll = view
.detail_scroll
.saturating_sub((view.rows_visible as usize / 2).max(1));
}
KeyCode::Char('D') => view.detail_tab = view.detail_tab.step(false),
KeyCode::Char('n') | KeyCode::Char('N') => {
let forward = key.code == KeyCode::Char('n');
match view.step_nav(forward) {
Some(target) => self.open_sarif_loc(&target),
None => self.status = String::from("Nothing to step through on this tab"),
}
}
KeyCode::Char('L') => match view.next_link() {
Some(target) => self.open_sarif_loc(&target),
None => self.status = String::from("This message has no location links"),
},
KeyCode::Char(' ') => view.toggle_preview(),
KeyCode::Enter => {
if view.selected_entry().is_some() {
self.open_selected_sarif_result();
} else {
view.toggle_fold();
}
}
_ => {}
}
}
/// The selected file's section of the PR's patch, side by side. The
/// patch is fetched once per tab with `gh pr diff`, off the UI thread.
fn open_pr_file_diff(&mut self) {
let Some(view) = self.editor.pr_review.as_ref() else {
return;
};
let Some(path) = view.selected_file().map(|f| f.path.clone()) else {
return;
};
if view.diff.is_some() {
self.open_pr_diff_section(&path);
return;
}
let selector = if view.pr.url.is_empty() {
view.pr.number.to_string()
} else {
view.pr.url.clone()
};
self.status = format!("Fetching the diff of PR #{}…", view.pr.number);
self.spawn_pr_gh(
PrGhJob::Diff { path },
vec![String::from("pr"), String::from("diff"), selector],
);
}
/// Open `path`'s section of the fetched patch in a diff tab.
fn open_pr_diff_section(&mut self, path: &str) {
let Some(view) = self.editor.pr_review.as_ref() else {
return;
};
let n = view.pr.number;
let Some(section) = view.diff.as_ref().and_then(|d| d.get(path)).cloned() else {
self.status = format!("{path} has no textual diff (binary or too large)");
return;
};
let label = PathBuf::from(format!("PR #{n}: {path}"));
match self.editor.open_git_diff_side_by_side(&label, §ion) {
Ok(()) => self.status = format!("PR #{n}: {path}"),
Err(e) => self.status = format!("Could not open the diff: {e}"),
}
}
/// Put the selected (or first failing) check's failing-step log in
/// OUTPUT > PR Checks.
fn show_pr_check_log(&mut self) {
let Some(view) = self.editor.pr_review.as_ref() else {
return;
};
let check = view.selected_check().or_else(|| {
view.pr
.checks
.iter()
.find(|c| c.state == crate::pr_review::CheckState::Fail)
});
let Some(check) = check.cloned() else {
self.status = String::from("No failing check");
return;
};
let Some((run, job)) = check.url.as_deref().and_then(crate::pr_review::run_and_job) else {
self.status = format!(
"{} is not a GitHub Actions check; its page: {}",
check.name,
check.url.unwrap_or_default()
);
return;
};
self.status = format!("Fetching the log of {}…", check.name);
self.spawn_pr_gh(
PrGhJob::Log { name: check.name },
crate::pr_review::log_args(run, job),
);
}
/// Open the selected SARIF result's primary location, keeping the viewer
/// tab: it is pinned first, so the preview open lands in a new tab
/// instead of replacing the list the user is working through.
fn open_selected_sarif_result(&mut self) {
use crate::sarif::region::ColumnKind;
let Some((
crate::sarif::view::SelectedPlace {
path,
line,
column,
kind,
uri,
region: place,
embedded,
remote,
..
},
archived,
)) = self.sarif_selected_place_and_origin()
else {
self.status = String::from("This result has no location to open");
return;
};
// Not on this machine, but the log carries the file (#577): open a
// read-only copy, text as text and binary in the hex viewer.
let path = match (path, embedded) {
(Some(p), _) => Some(p),
(None, Some(contents)) => {
// The copy has no buffer yet to convert in, so UTF-16
// columns are turned into characters against its own line.
let column = match (&contents, kind) {
(crate::sarif::resolve::Embedded::Text(t), ColumnKind::Utf16CodeUnits) => {
utf16_col_to_char_in(t.lines().nth(line as usize).unwrap_or(""), column)
}
_ => column as usize,
};
match self.open_sarif_embedded(&uri, &contents, line as usize, column) {
Err(e) => self.status = format!("Could not open the log's copy of {uri}: {e}"),
Ok(()) if archived => {
self.status = format!(
"Opened {uri} from the CodeQL database's source archive (read-only)"
);
}
Ok(()) => {}
}
return;
}
(None, None) => None,
};
let Some(path) = path else {
// VS Code's Locate…: ask where the file is.
let name = uri.rsplit('/').next().unwrap_or(&uri).to_string();
self.sarif_locate_pending = Some((uri.clone(), line + 1, column + 1));
// The run names the repository it scanned: the file can be
// downloaded, once its host is trusted.
if let Some(remote) = remote {
if crate::sarif::resolve::trusted_hosts().contains(&remote.host) {
self.start_sarif_download(&uri, &remote.url);
return;
}
self.open_input_prompt(
crate::widgets::input_prompt::InputPrompt::new(
crate::widgets::input_prompt::InputPurpose::SarifTrustHost {
uri: uri.clone(),
host: remote.host.clone(),
url: remote.url,
},
format!(
"Download {name} from {}? Enter trusts {} for SARIF source",
remote.host, remote.host
),
format!("or type the path to {name} on this machine"),
)
.allowing_blank(),
);
self.status = format!(
"{uri} is not on this machine; {} has it at the scanned commit",
remote.host
);
return;
}
self.open_input_prompt(crate::widgets::input_prompt::InputPrompt::new(
crate::widgets::input_prompt::InputPurpose::SarifLocate { uri: uri.clone() },
format!("Locate {name}"),
format!("path to {name} on this machine"),
));
self.status = format!("Cannot find {uri} on this machine: where is it?");
return;
};
// The region read against the file as it is now: an offset-only
// region gets its line, and a snippet that moved is followed. The
// text is the open buffer's when the file is open (it may be
// edited), else the disk's.
let text = self.sarif_file_text(&path);
let located = place
.zip(text)
.and_then(|((region, context, newlines), text)| {
crate::sarif::region::locate(®ion, context.as_ref(), &text, &newlines, kind)
});
self.editor.pin_active();
let (opened, line, moved) = match located {
// Columns are code points once located.
Some((pos, moved)) => (self.open_at(&path, pos.line, pos.col), pos.line, moved),
None => (
match kind {
ColumnKind::Utf16CodeUnits => {
self.open_at_utf16(&path, line as u32, column as u32)
}
ColumnKind::UnicodeCodePoints => {
self.open_at(&path, line as usize, column as usize)
}
},
line as usize,
false,
),
};
self.status = match opened {
Ok(()) if moved => format!(
"Opened {}:{} (the code moved since the scan; found by its snippet)",
path.display(),
line + 1
),
Ok(()) => format!("Opened {}:{}", path.display(), line + 1),
Err(e) => format!("Open failed: {e}"),
};
}
/// Download `url`, the source of the SARIF location `uri`, off the UI
/// thread; [`App::poll_sarif_download`] opens it (#577). The line and
/// column come from the pending Locate.
fn start_sarif_download(&mut self, uri: &str, url: &str) {
let (line, col) = self
.sarif_locate_pending
.as_ref()
.filter(|(u, _, _)| u == uri)
.map_or((1, 1), |(_, l, c)| (*l, *c));
let (tx, rx) = std::sync::mpsc::channel();
let fetch = self.sarif_fetch;
let (uri, url) = (uri.to_string(), url.to_string());
self.status = format!("Downloading {url}…");
std::thread::spawn(move || {
let body = fetch(&url);
let _ = tx.send(SarifDownload {
uri,
line,
col,
body,
});
});
self.sarif_download = Some(rx);
}
/// Open a finished SARIF source download read-only at its location,
/// or say why it failed.
fn poll_sarif_download(&mut self) {
use std::sync::mpsc::TryRecvError;
let Some(rx) = self.sarif_download.as_ref() else {
return;
};
let done = match rx.try_recv() {
Ok(done) => done,
Err(TryRecvError::Empty) => return,
Err(TryRecvError::Disconnected) => {
self.sarif_download = None;
return;
}
};
self.sarif_download = None;
match done.body {
Ok(bytes) => {
if self
.sarif_locate_pending
.as_ref()
.is_some_and(|(u, _, _)| *u == done.uri)
{
self.sarif_locate_pending = None;
}
let contents = match String::from_utf8(bytes) {
Ok(t) => crate::sarif::resolve::Embedded::Text(t),
Err(e) => crate::sarif::resolve::Embedded::Binary(e.into_bytes()),
};
let (line, col) = (
(done.line.max(1) - 1) as usize,
(done.col.max(1) - 1) as usize,
);
if let Err(e) = self.open_sarif_embedded(&done.uri, &contents, line, col) {
self.status = format!("Could not open the download of {}: {e}", done.uri);
}
}
Err(e) => self.status = format!("Could not download {}: {e}", done.uri),
}
}
/// Where the selected SARIF result points, looked up in the workspace,
/// the learned prefixes, the open files and the log's folder.
/// Also whether its file was read from the source archive of the
/// CodeQL database the log came from (#1369).
fn sarif_selected_place_and_origin(&self) -> Option<(crate::sarif::view::SelectedPlace, bool)> {
let view = self.editor.sarif.as_ref()?;
// A CodeQL run's SARIF says `%SRCROOT%` and leaves its meaning to
// the database (#1369): the folder it was created from.
let database = self.sarif_codeql_database();
let mut base_overrides = std::collections::BTreeMap::new();
if let Some(prefix) = database
.as_deref()
.and_then(crate::codeql_db::source_location_prefix)
.filter(|p| p.is_dir())
{
base_overrides.insert(String::from("%SRCROOT%"), prefix);
}
let resolver = crate::sarif::resolve::Resolver {
roots: vec![self.workspace_root().to_path_buf()],
base_overrides,
learned: crate::sarif::resolve::saved_prefixes(self.workspace_root()),
open: self.open_file_paths(),
..Default::default()
};
let mut place = view.selected_place(resolver, &|p| p.is_file())?;
// Not on this machine: the database keeps a copy of its source.
if place.path.is_none()
&& place.embedded.is_none()
&& let Some(text) = database
.as_deref()
.and_then(|db| crate::codeql_db::archived_source(db, &place.uri))
{
place.embedded = Some(crate::sarif::resolve::Embedded::Text(text));
return Some((place, true));
}
Some((place, false))
}
/// The CodeQL database whose query run wrote the SARIF log in the
/// editor, when it is one (#1369).
/// The log is the one holding the selected result, which may be a log
/// added to the viewer rather than the tab's own.
fn sarif_codeql_database(&self) -> Option<PathBuf> {
let view = self.editor.sarif.as_ref()?;
let log = &view.logs.get(view.selected_entry()?.log)?.path;
let history = crate::codeql_query::History::load(&Self::codeql_history_path());
let entry = history.entries.iter().find(|e| {
e.output == *log
|| e.output
.canonicalize()
.is_ok_and(|o| log.canonicalize().is_ok_and(|l| l == o))
})?;
Self::codeql_run_database(entry)
}
/// `path`'s text as the editor has it when it is open (it may be
/// edited), else as it is on disk.
fn sarif_file_text(&self, path: &Path) -> Option<String> {
self.editor
.iter_tabs()
.find(|t| t.path.as_deref() == Some(path) && !t.has_non_text_view())
.map(|t| t.lines.join("\n"))
.or_else(|| std::fs::read_to_string(path).ok())
}
/// Work out Space's source preview for the selected result when it is
/// on and not yet worked out for this result (#577).
fn refresh_sarif_preview(&mut self) {
use crate::sarif::resolve::Embedded;
use crate::sarif::view::{PREVIEW_RADIUS, SourcePreview, source_window};
let Some(entry) = self.editor.sarif.as_ref().and_then(|v| v.preview_due()) else {
return;
};
let empty = |title: String| SourcePreview {
entry,
title,
first: 1,
target: 0,
lines: Vec::new(),
};
let preview = match self.sarif_selected_place_and_origin() {
None => empty(String::from("This result has no location to preview.")),
Some((p, archived)) => {
let (title, text) = match (&p.path, &p.embedded) {
(Some(path), _) => (path.display().to_string(), self.sarif_file_text(path)),
(None, Some(Embedded::Text(t))) if archived => (
format!("{} (the database's source archive)", p.uri),
Some(t.clone()),
),
(None, Some(Embedded::Text(t))) => {
(format!("{} (the log's copy)", p.uri), Some(t.clone()))
}
(None, Some(Embedded::Binary(_))) => (
format!("{} is binary; Enter opens it in the hex viewer.", p.uri),
None,
),
(None, None) => match &p.remote {
Some(r) => (
format!(
"{} is not on this machine; Enter downloads it from {}.",
p.uri, r.host
),
None,
),
None => (
format!("{} is not on this machine; Enter to locate it.", p.uri),
None,
),
},
};
match text {
None => empty(title),
Some(text) => {
let line = p
.region
.as_ref()
.and_then(|(region, context, newlines)| {
crate::sarif::region::locate(
region,
context.as_ref(),
&text,
newlines,
p.kind,
)
})
.map_or(p.line as usize, |(pos, _)| pos.line);
let (first, lines) = source_window(&text, line, PREVIEW_RADIUS);
let target = if lines.is_empty() {
0
} else {
(line + 1).min(first + lines.len() - 1)
};
SourcePreview {
entry,
title,
first,
target,
lines,
}
}
}
}
};
if let Some(view) = self.editor.sarif.as_mut() {
view.preview = Some(preview);
}
}
/// Every located result of the first open SARIF viewer as
/// `(tab, entry, file, line, column)`, sorted by file then position.
/// Paths are worked out without touching the disk (a relative URI
/// against the workspace root, else the log's folder), so this is cheap
/// enough to run every tick.
fn sarif_targets(&self) -> Vec<(usize, usize, PathBuf, i64, i64)> {
let root = self.workspace_root().to_path_buf();
let Some((tab, view)) = self
.editor
.editors
.iter()
.enumerate()
.find_map(|(i, t)| t.sarif.as_ref().map(|v| (i, v)))
else {
return Vec::new();
};
let mut out = Vec::new();
for (i, e) in view.entries.iter().enumerate() {
if e.uri.is_empty() || e.line <= 0 {
continue;
}
let Some(p) = crate::sarif::resolve::uri_to_path(&e.uri) else {
continue;
};
let path = if p.is_absolute() {
p
} else {
let in_root = root.join(&p);
let log_dir = view
.logs
.get(e.log)
.and_then(|l| l.path.parent())
.map(|d| d.join(&p));
match log_dir {
Some(d) if !in_root.exists() => d,
_ => in_root,
}
};
out.push((tab, i, path, e.line, e.column.max(1)));
}
out.sort_by(|a, b| (&a.2, a.3, a.4).cmp(&(&b.2, b.3, b.4)));
out
}
/// Run `gh` with `args` in the active workspace root. Its stdout, or
/// the first line of what it said went wrong: GitHub's own message when
/// the API sent one, else gh's.
fn run_gh(&self, args: &[String]) -> Result<String, String> {
let mut cmd = std::process::Command::new(&self.gh_program);
cmd.args(args).current_dir(self.active_workspace_root());
let out = crate::review_ops::output_retrying_busy(&mut cmd)
.map_err(|e| format!("could not run gh: {e}"))?;
let stdout = String::from_utf8_lossy(&out.stdout).into_owned();
if out.status.success() {
return Ok(stdout);
}
let api_message = serde_json::from_str::<serde_json::Value>(&stdout)
.ok()
.and_then(|v| v.get("message")?.as_str().map(str::to_string));
let stderr = String::from_utf8_lossy(&out.stderr);
let first = |s: &str| s.trim().lines().next().map(str::to_string);
Err(api_message
.or_else(|| {
let s = stderr.trim();
serde_json::from_str::<serde_json::Value>(s)
.ok()
.and_then(|v| v.get("message")?.as_str().map(str::to_string))
.or_else(|| first(s))
})
.unwrap_or_else(|| String::from("gh failed")))
}
/// List recent code scanning analyses to open one (#577): the current
/// branch's when it has any, else the repository's.
fn open_code_scanning_picker(&mut self) {
use crate::sarif::github;
use crate::widgets::list_picker::{ListPicker, ListPurpose, ListRow};
let fetch = |app: &Self, git_ref: Option<&str>| {
app.run_gh(&github::analyses_args(git_ref))
.and_then(|json| github::parse_analyses(&json))
};
let branch = self.source_control.status.branch.clone();
let on_branch = match &branch {
Some(b) => match fetch(self, Some(&format!("refs/heads/{b}"))) {
Ok(a) => a,
Err(e) => {
self.status = format!("Code scanning: {e}");
return;
}
},
None => Vec::new(),
};
let (analyses, title) = if on_branch.is_empty() {
match fetch(self, None) {
Ok(a) => (a, String::from("Open Code Scanning Analysis")),
Err(e) => {
self.status = format!("Code scanning: {e}");
return;
}
}
} else {
let b = branch.unwrap_or_default();
(on_branch, format!("Open Code Scanning Analysis \u{b7} {b}"))
};
let rows = analyses
.iter()
.map(|a| ListRow {
id: a.id.to_string(),
label: github::label(a),
})
.collect();
self.open_list_picker(
ListPicker::new(ListPurpose::CodeScanningAnalysis, title, rows),
"This repository has no code scanning analyses",
);
}
/// The branch code scanning follows (#577): its name, or `HEAD <oid>`
/// when detached, from the git status the worker keeps current, which
/// reads refs through git itself (packed refs included).
fn code_scan_branch(&self) -> Option<String> {
let st = &self.source_control.status;
if !st.in_repo {
return None;
}
st.branch
.clone()
.or_else(|| st.detached_hash.as_ref().map(|h| format!("HEAD {h}")))
}
/// Look up `branch`'s code scanning analyses off the UI thread: its own
/// ref's (the repository's when detached or when it has none), narrowed
/// to the nearest scanned commit in the local history, one per tool.
fn start_code_scan_lookup(&mut self, branch: String, load: bool) {
use crate::sarif::github;
let gh = self.gh_program.clone();
let root = self.active_workspace_root().to_path_buf();
let git_ref = (!branch.starts_with("HEAD ")).then(|| format!("refs/heads/{branch}"));
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let gh_json = |git_ref: Option<&str>| -> Result<String, String> {
let mut cmd = std::process::Command::new(&gh);
cmd.args(github::analyses_args(git_ref))
.current_dir(&root)
.stdin(std::process::Stdio::null());
let out = crate::review_ops::output_retrying_busy(&mut cmd)
.map_err(|e| format!("could not run gh: {e}"))?;
Ok(String::from_utf8_lossy(&out.stdout).into_owned())
};
let result = (|| {
let mut analyses = match git_ref.as_deref() {
Some(r) => github::parse_analyses(&gh_json(Some(r))?)?,
None => Vec::new(),
};
if analyses.is_empty() {
analyses = github::parse_analyses(&gh_json(None)?)?;
}
let history: Vec<String> = crate::git::branch_history(&root, 200)
.into_iter()
.map(|c| c.hash)
.collect();
Ok(github::nearest_per_tool(&analyses, &history))
})();
let _ = tx.send(result);
});
self.code_scan_list = Some(CodeScanList { branch, load, rx });
}
/// Notice a checkout of another branch and act on the `code_scanning`
/// setting, then drain finished lookups and fetches. Returns true when
/// something on screen changed.
fn poll_code_scanning(&mut self) -> bool {
use crate::sarif::github::CodeScanningMode;
let mut changed = false;
if self.code_scanning != CodeScanningMode::Off
&& self.code_scan_list.is_none()
&& let Some(branch) = self.code_scan_branch()
&& self.code_scan_seen.as_deref() != Some(branch.as_str())
{
self.code_scan_seen = Some(branch.clone());
self.start_code_scan_lookup(branch, self.code_scanning == CodeScanningMode::On);
}
if let Some(list) = self.code_scan_list.as_ref() {
let result = match list.rx.try_recv() {
Ok(r) => Some(r),
Err(std::sync::mpsc::TryRecvError::Empty) => None,
Err(std::sync::mpsc::TryRecvError::Disconnected) => {
Some(Err(String::from("the lookup stopped without answering")))
}
};
if let Some(result) = result
&& let Some(CodeScanList { branch, load, .. }) = self.code_scan_list.take()
{
changed = true;
let shown = branch.strip_prefix("HEAD ").map_or(branch.clone(), |h| {
format!("detached HEAD {}", h.chars().take(8).collect::<String>())
});
match result {
Ok(chosen) if chosen.is_empty() => {
if load {
self.status = format!("Code scanning: no analyses for {shown}");
}
}
Ok(chosen) if load => self.fetch_code_scan_analyses(chosen, &shown),
Ok(chosen) => {
self.status = format!(
"Code scanning has {} analys{} for {shown} (SARIF: Load Code Scanning Results for This Branch)",
chosen.len(),
if chosen.len() == 1 { "is" } else { "es" }
);
}
Err(e) => self.status = format!("Code scanning: {e}"),
}
}
}
if let Some(rx) = self.code_scan_fetch.as_ref()
&& let Ok(files) = rx.try_recv()
{
self.code_scan_fetch = None;
changed = true;
let mut opened = 0;
let mut errors = Vec::new();
for file in files {
match file.and_then(|p| self.editor.open(&p).map_err(|e| e.to_string())) {
Ok(()) => opened += 1,
Err(e) => errors.push(e),
}
}
self.sync_open_file_poll_mtime();
self.status = match errors.first() {
None => format!(
"Loaded {opened} code scanning analys{}",
if opened == 1 { "is" } else { "es" }
),
Some(e) => format!("Loaded {opened} code scanning analyses; {e}"),
};
}
changed
}
/// Download `chosen` as SARIF into croft's cache off the UI thread, to
/// open when they arrive.
fn fetch_code_scan_analyses(
&mut self,
chosen: Vec<crate::sarif::github::Analysis>,
shown: &str,
) {
let gh = self.gh_program.clone();
let root = self.active_workspace_root().to_path_buf();
let dir = croft_cache_dir().join("code-scanning");
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let files = chosen
.iter()
.map(|a| {
let mut cmd = std::process::Command::new(&gh);
cmd.args(crate::sarif::github::sarif_args(a.id))
.current_dir(&root)
.stdin(std::process::Stdio::null());
let out = crate::review_ops::output_retrying_busy(&mut cmd)
.map_err(|e| format!("could not run gh: {e}"))?;
if !out.status.success() {
return Err(format!("analysis #{} could not be downloaded", a.id));
}
let path = dir.join(format!("analysis-{}.sarif", a.id));
std::fs::create_dir_all(&dir)
.and_then(|()| std::fs::write(&path, &out.stdout))
.map_err(|e| format!("{}: {e}", path.display()))?;
Ok(path)
})
.collect();
let _ = tx.send(files);
});
self.code_scan_fetch = Some(rx);
self.status = format!("Loading code scanning results for {shown}…");
}
/// Dismiss the selected result's code scanning alert (#577): the alert
/// number GitHub stamped on the result, or else the open alert with the
/// same rule, path and line; then ask why.
fn start_dismiss_code_scanning_alert(&mut self) {
use crate::sarif::github::{self, DismissReason};
use crate::widgets::list_picker::{ListPicker, ListPurpose, ListRow};
let Some(view) = self.editor.sarif.as_ref() else {
return;
};
let Some(e) = view.selected_entry().cloned() else {
self.status = String::from("Select a result to dismiss its alert");
return;
};
let Some(loaded) = view.logs.get(e.log) else {
return;
};
let log_path = loaded.path.clone();
let Some(run) = loaded.log.runs.get(e.run) else {
return;
};
let Some(result) = run.results.as_ref().and_then(|r| r.get(e.result)) else {
return;
};
let stamped = github::alert_number(result);
// The location as the log wrote it: code scanning paths are
// repository-relative, like the URIs GitHub's own logs carry.
let path = result
.locations
.first()
.and_then(|l| l.physical_location.as_ref())
.and_then(|p| p.artifact_location.as_ref())
.and_then(|a| crate::sarif::resolve::location_parts(run, a))
.map(|(uri, _)| uri)
.unwrap_or_default();
let number = match stamped {
Some(n) => n,
None => {
let alerts = match self
.run_gh(&github::alerts_args(None))
.and_then(|json| github::parse_alerts(&json))
{
Ok(a) => a,
Err(err) => {
self.status = format!("Code scanning alerts: {err}");
return;
}
};
match github::match_alert(&alerts, &e.rule_id, &path, e.line) {
Some(n) => n,
None => {
self.status = String::from("No code scanning alert matches this result");
return;
}
}
}
};
self.dismiss_target = Some((log_path, e.run, e.result));
let rows = DismissReason::ALL
.iter()
.enumerate()
.map(|(i, r)| {
let api = r.api();
let mut label = api[..1].to_uppercase();
label.push_str(&api[1..]);
ListRow {
id: format!("{number}:{i}"),
label,
}
})
.collect();
self.open_list_picker(
ListPicker::new(
ListPurpose::DismissAlert,
format!("Dismiss Alert #{number}"),
rows,
),
"",
);
}
/// Send the dismissal of alert `number` (#577); on success the result
/// it came from is marked suppressed, which the default filter hides.
fn dismiss_code_scanning_alert(&mut self, number: u64, reason: usize, comment: &str) {
use crate::sarif::github::{self, DismissReason};
let reason = DismissReason::ALL
.get(reason)
.copied()
.unwrap_or(DismissReason::FalsePositive);
if let Err(e) = self.run_gh(&github::dismiss_args(number, reason, comment)) {
self.status = format!("Alert #{number} was not dismissed: {e}");
return;
}
if let (Some((log_path, run, result)), Some(view)) =
(self.dismiss_target.take(), self.editor.sarif.as_mut())
{
let log = view.logs.iter().position(|l| l.path == log_path);
for e in &mut view.entries {
if Some(e.log) == log && e.run == run && e.result == result {
e.suppression = crate::sarif::semantics::SuppressionState::Suppressed;
}
}
}
self.status = format!("Dismissed alert #{number} as {}", reason.api());
}
/// Download code scanning analysis `id` as SARIF and open it (#577).
fn open_code_scanning_analysis(&mut self, id: u64) {
let text = match self.run_gh(&crate::sarif::github::sarif_args(id)) {
Ok(t) => t,
Err(e) => {
self.status = format!("Code scanning analysis #{id}: {e}");
return;
}
};
let dir = croft_cache_dir().join("code-scanning");
let path = dir.join(format!("analysis-{id}.sarif"));
if let Err(e) = std::fs::create_dir_all(&dir).and_then(|()| std::fs::write(&path, text)) {
self.status = format!("{}: {e}", path.display());
return;
}
match self.editor.open(&path) {
Ok(()) => {
self.sync_open_file_poll_mtime();
self.focus_pane(Pane::Editor);
self.status = format!("Opened code scanning analysis #{id}");
}
Err(e) => self.status = format!("Code scanning analysis #{id}: {e}"),
}
}
/// Write the SARIF viewer's visible results to a CSV file (#577),
/// relative to the workspace, creating its folder.
pub fn submit_sarif_export(&mut self, value: &str) {
let Some(view) = self.editor.sarif.as_ref() else {
return;
};
let v = value.trim();
// A `.sarif` name gets SARIF, anything else the CSV (#577).
let as_sarif = v.to_ascii_lowercase().ends_with(".sarif");
let count = view.visible().len();
let csv = if as_sarif {
match view.export_sarif() {
Some(text) => text,
None => {
self.status = String::from("Could not reread the log to export it");
return;
}
}
} else {
view.export_csv()
};
let path = if std::path::Path::new(v).is_absolute() {
PathBuf::from(v)
} else {
self.workspace_root().join(v)
};
let written = path
.parent()
.map_or(Ok(()), std::fs::create_dir_all)
.and_then(|()| std::fs::write(&path, csv));
self.status = match written {
Ok(()) => format!(
"Exported {count} result{} to {}",
if count == 1 { "" } else { "s" },
path.display()
),
Err(e) => format!("{}: {e}", path.display()),
};
}
/// Compare the open viewer against a baseline log (#577): results the
/// tool did not mark become new, unchanged or updated, and the
/// baseline's vanished results are listed as absent.
pub fn submit_sarif_baseline(&mut self, value: &str) {
let v = value.trim();
let path = if std::path::Path::new(v).is_absolute() {
PathBuf::from(v)
} else {
self.workspace_root().join(v)
};
let text = match std::fs::read(&path) {
Ok(b) => String::from_utf8_lossy(&b).into_owned(),
Err(e) => {
self.status = format!("{}: {e}", path.display());
return;
}
};
let log = match crate::sarif::load::parse_log(&text) {
Ok(l) => l,
Err(e) => {
self.status = format!("{} is not a usable baseline: {e}", path.display());
return;
}
};
let Some(view) = self.editor.sarif.as_mut() else {
return;
};
self.status = if view.set_baseline(&path, log) {
// The baseline's own results stop publishing.
self.sarif_diag_signature.clear();
let count = |s| view.entries.iter().filter(|e| e.baseline == s).count();
use crate::sarif::semantics::BaselineState as B;
format!(
"Against {}: {} new, {} unchanged, {} updated, {} absent",
path.display(),
count(B::New),
count(B::Unchanged),
count(B::Updated),
count(B::Absent)
)
} else {
String::from("A log cannot be its own baseline")
};
}
/// Merge another SARIF log into the open viewer (#577).
pub fn submit_sarif_add_log(&mut self, value: &str) {
let v = value.trim();
let path = if std::path::Path::new(v).is_absolute() {
PathBuf::from(v)
} else {
self.workspace_root().join(v)
};
let text = match std::fs::read(&path) {
Ok(b) => String::from_utf8_lossy(&b).into_owned(),
Err(e) => {
self.status = format!("{}: {e}", path.display());
return;
}
};
let log = match crate::sarif::load::parse_log(&text) {
Ok(l) => l,
Err(e) => {
self.status = format!("{} was not added: {e}", path.display());
return;
}
};
let Some(view) = self.editor.sarif.as_mut() else {
return;
};
self.status = if view.add_log(&path, log) {
// A new log publishes its results too.
self.sarif_diag_signature.clear();
format!("Added {} · {} results", path.display(), view.entries.len())
} else {
format!("{} is already open here", path.display())
};
}
/// The Locate prompt's answer (#577): the file must carry the name the
/// log gave it; its location teaches a prefix that is saved for this
/// workspace, so the log's other files from the same place resolve too.
pub fn submit_sarif_locate(&mut self, value: &str) {
let Some((uri, line, col)) = self.sarif_locate_pending.clone() else {
return;
};
let v = value.trim();
let typed = match v.strip_prefix("~/") {
Some(rest) => std::env::var_os("HOME")
.map(PathBuf::from)
.unwrap_or_default()
.join(rest),
None => PathBuf::from(v),
};
let path = if typed.is_absolute() {
typed
} else {
self.workspace_root().join(typed)
};
if !path.is_file() {
self.status = format!("{} is not a file", path.display());
return;
}
let want = uri.rsplit('/').next().unwrap_or("").to_string();
let want = crate::sarif::resolve::uri_to_path(&want)
.and_then(|p| p.file_name().map(|n| n.to_string_lossy().into_owned()))
.unwrap_or(want);
let got = path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
if want != got {
self.status = format!("File names must match: \"{want}\" and \"{got}\"");
return;
}
self.sarif_locate_pending = None;
let root = self.workspace_root().to_path_buf();
if let Err(e) = crate::sarif::resolve::save_prefix(&root, &uri, &path) {
self.status = format!("Located, but the mapping was not saved: {e}");
}
self.editor.pin_active();
match self.open_at(
&path,
line.saturating_sub(1) as usize,
col.saturating_sub(1) as usize,
) {
Ok(()) => {
// The learned prefix may change what resolves: republish.
self.sarif_diag_signature.clear();
self.status =
format!("Located {got}; other files from the same place will resolve");
}
Err(e) => self.status = format!("Open failed: {e}"),
}
}
/// Jump to the next (or previous) SARIF result location from the
/// cursor (#577), across files, wrapping at the ends.
fn step_sarif_result(&mut self, forward: bool) {
let targets = self.sarif_targets();
if targets.is_empty() {
self.status = String::from("No SARIF results with a location are open");
return;
}
let here = (
self.editor.path.clone().unwrap_or_default(),
self.editor.cursor_row as i64 + 1,
self.editor.cursor_col as i64 + 1,
);
let key = |t: &(usize, usize, PathBuf, i64, i64)| (t.2.clone(), t.3, t.4);
let pick = if forward {
targets.iter().position(|t| key(t) > here).unwrap_or(0)
} else {
targets
.iter()
.rposition(|t| key(t) < (here.0.clone(), here.1, here.2))
.unwrap_or(targets.len() - 1)
};
let (tab, entry, path, line, col) = targets[pick].clone();
let message = self.editor.editors[tab]
.sarif
.as_ref()
.and_then(|v| v.entries.get(entry))
.map(|e| e.message.clone())
.unwrap_or_default();
if let Some(view) = self.editor.editors[tab].sarif.as_mut()
&& let Some(row) = view
.rows()
.iter()
.position(|r| *r == crate::sarif::view::Row::Item { entry })
{
view.selected = row;
}
if let Err(e) = self.open_at(&path, (line - 1) as usize, (col - 1) as usize) {
self.status = format!("Could not open {}: {e}", path.display());
return;
}
self.status = format!("SARIF {}/{}: {message}", pick + 1, targets.len());
}
/// Select, in an open SARIF viewer, the result on the cursor's line
/// (#577), the way VS Code's panel follows the editor.
pub fn sync_sarif_selection_to_cursor(&mut self) {
let Some(path) = self.editor.path.clone() else {
return;
};
if self.editor.sarif.is_some() {
return;
}
let line = self.editor.cursor_row as i64 + 1;
let Some((tab, entry)) = self
.sarif_targets()
.into_iter()
.find(|t| t.2 == path && t.3 == line)
.map(|t| (t.0, t.1))
else {
return;
};
if let Some(view) = self.editor.editors[tab].sarif.as_mut()
&& let Some(row) = view
.rows()
.iter()
.position(|r| *r == crate::sarif::view::Row::Item { entry })
{
view.selected = row;
}
}
/// Apply fix `index` of the selected SARIF result (#577) to the open
/// buffer of each file it changes (the file on disk when none is open),
/// as one undoable edit that stays unsaved, then mark the result fixed.
fn apply_sarif_fix(&mut self, index: usize) {
let root = self.workspace_root().to_path_buf();
let Some((log_path, run_i, result_i, run, result, what)) =
self.editor.sarif.as_ref().and_then(|v| {
let e = v.selected_entry()?;
let loaded = v.logs.get(e.log)?;
let run = loaded.log.runs.get(e.run)?.clone();
let result = run.results.as_ref()?.get(e.result)?.clone();
let what = crate::sarif::fixes::fix_description(&result, index)?;
Some((loaded.path.clone(), e.run, e.result, run, result, what))
})
else {
self.status = String::from("This result offers no fix");
return;
};
let mut roots = vec![root];
if let Some(dir) = log_path.parent() {
roots.push(dir.to_path_buf());
}
let resolver = crate::sarif::resolve::Resolver {
roots,
learned: crate::sarif::resolve::saved_prefixes(self.workspace_root()),
open: self.open_file_paths(),
..Default::default()
};
let open_text = |p: &std::path::Path| -> Option<String> {
self.editor
.iter_tabs()
.find(|t| t.path.as_deref() == Some(p) && !t.has_non_text_view())
.map(|t| {
let mut s = t.lines.join("\n");
s.push('\n');
s
})
};
let edits = match crate::sarif::fixes::fix_for(&run, &result, index, &resolver, &mut |p| {
open_text(p).or_else(|| std::fs::read_to_string(p).ok())
}) {
Ok(e) => e,
Err(why) => {
self.status = format!("Fix not applied: {why}");
return;
}
};
self.editor.pin_active();
for edit in &edits {
if let Err(e) = self.open_at(&edit.path, 0, 0) {
self.status = format!("Fix not applied: {e}");
return;
}
self.editor
.replace_all_lines(crate::widgets::editor::split_into_lines(&edit.after));
}
let mut store = crate::sarif::view::FixedStore::load();
store.mark(&log_path, run_i, result_i);
let _ = store.save();
for tab in self.editor.editors.iter_mut() {
if let Some(view) = tab.sarif.as_mut() {
for e in view.entries.iter_mut() {
if view.logs.get(e.log).is_some_and(|l| l.path == log_path)
&& e.run == run_i
&& e.result == result_i
{
e.fixed = true;
}
}
}
}
// Republish without the fixed result.
self.sarif_diag_signature.clear();
self.status = format!("Applied \"{what}\" to {} file(s), unsaved", edits.len());
}
/// Open the copy of `uri` a SARIF log embeds (#577), written read-only
/// under croft's cache (named by a hash of the URI and contents, so an
/// unchanged copy is reused): text at `line`/`column`, binary in the hex
/// viewer. Saving it is refused by the file's permissions, since the
/// log, not this copy, is the source.
fn open_sarif_embedded(
&mut self,
uri: &str,
contents: &crate::sarif::resolve::Embedded,
line: usize,
column: usize,
) -> anyhow::Result<()> {
use crate::sarif::resolve::Embedded;
use std::hash::{Hash, Hasher};
let bytes: &[u8] = match contents {
Embedded::Text(t) => t.as_bytes(),
Embedded::Binary(b) => b,
};
let mut h = std::collections::hash_map::DefaultHasher::new();
uri.hash(&mut h);
bytes.hash(&mut h);
let name = uri
.rsplit('/')
.find(|s| !s.is_empty())
.map(crate::sarif::resolve::percent_decode)
.filter(|n| n != "." && n != ".." && !n.contains(['/', '\\']))
.unwrap_or_else(|| String::from("artifact"));
let dir = croft_cache_dir()
.join("sarif-embedded")
.join(format!("{:016x}", h.finish()));
let path = dir.join(&name);
if !path.is_file() {
std::fs::create_dir_all(&dir)?;
std::fs::write(&path, bytes)?;
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o444))?;
}
self.editor.pin_active();
match contents {
Embedded::Text(_) => self.open_at(&path, line, column)?,
Embedded::Binary(_) => {
self.editor.open_hex(&path)?;
self.sync_open_file_poll_mtime();
self.focus_pane(Pane::Editor);
}
}
self.status = format!("Opened the log's own copy of {uri} (read-only)");
Ok(())
}
/// Set the SARIF results list's optional columns from what the user
/// typed, remember them for every viewer, and apply them to each open
/// one (#577).
fn submit_sarif_columns(&mut self, value: &str) {
let cols = match crate::sarif::view::parse_columns(value) {
Ok(c) => c,
Err(why) => {
self.status = why;
return;
}
};
for tab in self.editor.editors.iter_mut() {
if let Some(view) = tab.sarif.as_mut() {
view.columns = cols.clone();
}
}
self.status = match crate::sarif::view::save_columns(&cols) {
Ok(()) if cols.is_empty() => String::from("SARIF columns: position and message only"),
Ok(()) => format!(
"SARIF columns: {}",
crate::sarif::view::columns_text(&cols).replace(',', ", ")
),
Err(e) => format!("Columns set, but not saved: {e}"),
};
}
/// Draw the selected SARIF result's analysis steps in the files they
/// lie in (#577): each step with a location is labelled after its line
/// ("step 2: user input"), in that file's tab and no other. Recomputed
/// when the selection or the set of open files changes.
pub fn sync_sarif_step_marks(&mut self) {
let root = self.workspace_root().to_path_buf();
let open = self.open_file_paths();
let selected = self
.editor
.editors
.iter()
.find_map(|t| t.sarif.as_ref())
.and_then(|v| v.selected_entry().map(|e| (e.log, e.run, e.result)));
let signature = (selected, open.clone());
if self.sarif_step_signature.as_ref() == Some(&signature) {
return;
}
self.sarif_step_signature = Some(signature);
let learned = crate::sarif::resolve::saved_prefixes(self.workspace_root());
let mut by_file: std::collections::HashMap<PathBuf, Vec<(usize, String)>> =
std::collections::HashMap::new();
if let Some(view) = self
.editor
.editors
.iter_mut()
.find_map(|t| t.sarif.as_mut())
&& selected.is_some()
{
let log_dir = view
.selected_entry()
.and_then(|e| view.logs.get(e.log))
.and_then(|l| l.path.parent().map(Path::to_path_buf));
let run = view
.selected_entry()
.and_then(|e| view.logs.get(e.log)?.log.runs.get(e.run).cloned());
let steps: Vec<(String, i64, String)> = view
.details()
.map(|d| {
d.threads
.iter()
.flat_map(|t| &t.steps)
.filter_map(|s| {
let loc = s.location.as_ref()?;
(!loc.uri.is_empty() && loc.line > 0)
.then(|| (loc.uri.clone(), loc.line, s.message.clone()))
})
.collect()
})
.unwrap_or_default();
if let Some(run) = run {
let mut roots = vec![root];
roots.extend(log_dir);
let resolver = crate::sarif::resolve::Resolver {
roots,
learned,
open,
..Default::default()
};
for (n, (uri, line, message)) in steps.into_iter().enumerate() {
let artifact = crate::sarif::model::ArtifactLocation {
uri: Some(uri),
..Default::default()
};
let Some(path) = resolver.resolve(&run, &artifact, &|p| p.is_file()) else {
continue;
};
let message: String = message.chars().take(60).collect();
let label = if message.is_empty() {
format!("step {}", n + 1)
} else {
format!("step {}: {message}", n + 1)
};
by_file
.entry(path)
.or_default()
.push(((line - 1) as usize, label));
}
}
}
for tab in self.editor.editors.iter_mut() {
let marks = tab
.path
.as_ref()
.and_then(|p| by_file.get(p))
.cloned()
.unwrap_or_default();
let path = (!marks.is_empty()).then(|| tab.path.clone()).flatten();
tab.set_step_marks(path, marks);
}
}
/// The paths of the files open in editor tabs, for SARIF resolution.
fn open_file_paths(&self) -> Vec<PathBuf> {
self.editor
.iter_tabs()
.filter_map(|t| t.path.clone())
.collect()
}
/// Open a location from the selected result's details (a step, a frame, a
/// related location), resolving it the way the result's own location is
/// resolved and keeping the viewer tab.
fn open_sarif_loc(&mut self, target: &crate::sarif::details::LocRef) {
use crate::sarif::region::{ColumnKind, column_kind};
if target.uri.is_empty() {
self.status = format!("{} has no file to open", target.label);
return;
}
let root = self.workspace_root().to_path_buf();
let mut on_github = None;
let Some((path, kind)) = self.editor.sarif.as_ref().and_then(|v| {
let e = v.selected_entry()?;
let loaded = v.logs.get(e.log)?;
let run = loaded.log.runs.get(e.run)?;
on_github = crate::sarif::resolve::github_blob_url(run, &target.uri, target.line);
let mut roots = vec![root.clone()];
if let Some(dir) = loaded.path.parent() {
roots.push(dir.to_path_buf());
}
let resolver = crate::sarif::resolve::Resolver {
roots,
learned: crate::sarif::resolve::saved_prefixes(self.workspace_root()),
open: self.open_file_paths(),
..Default::default()
};
let artifact = crate::sarif::model::ArtifactLocation {
uri: Some(target.uri.clone()),
..Default::default()
};
Some((
resolver.resolve(run, &artifact, &|p| p.is_file()),
column_kind(run),
))
}) else {
return;
};
let Some(path) = path else {
// A variant analysis result lives in another repository; its
// run says which, at which commit.
match on_github {
Some(url) => self.open_url_for_user(&url),
None => self.status = format!("Cannot find {} on this machine", target.uri),
}
return;
};
let line = target.line.max(1) - 1;
let column = target.column.max(1) - 1;
self.editor.pin_active();
let opened = match kind {
ColumnKind::Utf16CodeUnits => self.open_at_utf16(&path, line as u32, column as u32),
ColumnKind::UnicodeCodePoints => self.open_at(&path, line as usize, column as usize),
};
self.status = match opened {
Ok(()) => format!("Opened {}:{}", path.display(), line + 1),
Err(e) => format!("Open failed: {e}"),
};
}
/// Rendered log keys (#1189): the arrows move a line, PageUp/PageDown a
/// screen, Home/End (with or without Ctrl) go to the top and the tail.
/// The tab's text side is a one-line stub, so every other key is
/// swallowed: reaching the editor, it pinned the view to line 1 and
/// typing marked the read-only tab modified. Copy, Esc and the
/// tab-number jumps are left to the editor (false), which handles them
/// for a log.
fn handle_log_key(&mut self, key: KeyEvent) -> bool {
if is_editor_copy_key(key) || jump_to_tab_index(key).is_some() || key.code == KeyCode::Esc {
return false;
}
let page = self.editor.visible_rows().saturating_sub(2).max(1);
match key.code {
KeyCode::Down => self.editor.scroll_down(1),
KeyCode::Up => self.editor.scroll_up(1),
KeyCode::PageDown => self.editor.scroll_down(page),
KeyCode::PageUp => self.editor.scroll_up(page),
KeyCode::End => self.editor.scroll_down(usize::MAX / 2),
KeyCode::Home => self.editor.scroll_up(usize::MAX / 2),
_ => {}
}
true
}
/// 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,
};
// Removing the only row that reached the last column shrinks the
// sheet's width too, so the caret column can be past the end (#1137).
let last_col = data.col_count().saturating_sub(1);
data.cur_col = data.cur_col.min(last_col);
data.scroll_col = data.scroll_col.min(data.cur_col);
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(view) = self.editor.sheet.as_ref() else {
return;
};
let idx = view.current_sheet;
let Some(&(_, page)) = view.sqlite_pages.get(idx) 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;
}
self.sqlite_load_page(next, delta < 0);
}
/// Ctrl+Home / Ctrl+End in a SQLite table (#1222): the table's first or
/// last row, loading its page, not the loaded batch's.
fn sqlite_jump(&mut self, to_end: bool, visible: usize) {
let Some(path) = self.editor.path.clone() else {
return;
};
let Some(view) = self.editor.sheet.as_ref() else {
return;
};
let idx = view.current_sheet;
let Some((table, page)) = view.sqlite_pages.get(idx).cloned() else {
return;
};
let target = if to_end {
match crate::sqlite_view::last_page(&path, &table) {
Ok(last) => last,
Err(e) => {
self.status = format!("Page fetch failed: {e}");
return;
}
}
} else {
0
};
if target != page {
self.sqlite_load_page(target, to_end);
}
if let Some(view) = self.editor.sheet.as_mut() {
let data = &mut view.sheets[idx];
(data.cur_row, data.cur_col) = if to_end {
(
data.row_count().saturating_sub(1),
data.col_count().saturating_sub(1),
)
} else {
(0, 0)
};
sheet_follow_cursor(view, idx, visible);
}
}
/// Replace the current SQLite sheet with page `next` of its table, the
/// cursor on its last row when `at_end`.
fn sqlite_load_page(&mut self, next: usize, at_end: bool) {
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, _)) = view.sqlite_pages.get(idx).cloned() else {
return;
};
match crate::sqlite_view::table_page(&path, &table, next) {
Ok((headers, rows, more)) if !rows.is_empty() || next == 0 => {
let got = rows.len();
let label = crate::sqlite_view::page_label(&table, next, got, more);
let mut data = crate::sheet::sheet_data_from_parts(label, headers, rows);
data.row_base = next * crate::sqlite_view::ROW_CAP;
if at_end {
data.cur_row = data.row_count().saturating_sub(1);
}
view.sheets[idx] = data;
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"),
);
}
/// The encoding `path`'s open tab decodes it with, in any group; UTF-8
/// when it isn't open, which is what opening it would pick: a BOM still
/// wins in `decode_blob`, and bytes that are not UTF-8 get the plain
/// open rather than an editable diff of replacement characters.
fn open_tab_encoding(&self, path: &Path) -> &'static encoding_rs::Encoding {
std::iter::once(&self.editor)
.chain(self.editor_layout.inactive_groups())
.flat_map(|g| g.editors.iter())
.find(|e| e.diff.is_none() && e.path.as_deref() == Some(path))
.map_or(encoding_rs::UTF_8, |e| e.encoding)
}
/// Re-point the tabs of a renamed or moved path in every editor group,
/// not just the focused one: a tab in the other split kept the old path,
/// raised a disk conflict, and a save brought the old file back.
fn rename_open_path_everywhere(&mut self, old: &Path, new: &Path) {
self.editor.rename_open_path(old, new);
for group in self.editor_layout.inactive_groups_mut() {
group.rename_open_path(old, new);
}
}
/// 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(()) => {
// Every group's tabs, and files under a deleted folder too.
// A tab with unsaved edits is kept open: closing it threw the
// edits away while the trash only held the saved copy.
let mut kept = 0;
for path in &paths {
kept += self.editor.close_clean_tabs_under(path);
for group in self.editor_layout.inactive_groups_mut() {
kept += group.close_clean_tabs_under(path);
}
}
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")
};
if kept > 0 {
self.status.push_str(&format!(
"; {kept} tab{} with unsaved changes kept open",
if kept == 1 { "" } else { "s" }
));
}
}
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.open_diff_across_groups(&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;
};
let moved = self.move_or_copy_in_explorer(&dest_dir, &clip.paths, clip.mode);
// A cut pasted back where it already is moved nothing, so it stays
// on the clipboard for the paste into the folder it was meant for.
if moved && matches!(clip.mode, ExplorerClipMode::Cut) {
self.tree_clipboard = None;
}
}
/// Explorer paste and drag-drop. A move asks the language servers for
/// their import edits first (#610); a copy renames nothing, so it runs
/// at once.
fn move_or_copy_in_explorer(
&mut self,
dest_dir: &Path,
paths: &[PathBuf],
mode: ExplorerClipMode,
) -> bool {
if matches!(mode, ExplorerClipMode::Copy) {
let _ = self.apply_paste_or_drop(dest_dir, paths, mode);
return true;
}
// An item already in `dest_dir` stays as it is: moving it there is
// no move, and a fresh name for it renamed the file to "<name> copy"
// on disk, retargeting its tabs and the servers' imports (#1174).
let paths: Vec<PathBuf> = paths
.iter()
.filter(|p| !crate::widgets::file_tree::is_directly_in(dest_dir, p))
.cloned()
.collect();
if paths.is_empty() {
self.status = String::from("Already in this folder: nothing to move");
return false;
}
let renames = paths
.iter()
.map(|src| crate::lsp::manager::FileRenameOp {
old: src.clone(),
new: crate::widgets::file_tree::unique_destination_in(dest_dir, src),
is_dir: src.is_dir(),
})
.collect();
let op = FileMove::Paste {
dest_dir: dest_dir.to_path_buf(),
paths,
};
self.start_file_move(op, renames);
true
}
/// Ask the servers about `renames`, then run `op` once they answer (or
/// at once, with no language server running).
fn start_file_move(&mut self, op: FileMove, renames: Vec<crate::lsp::manager::FileRenameOp>) {
// A second move while one is pending runs the first now: two moves
// must not reorder, and the first has waited long enough.
if let Some(prev) = self.pending_file_move.take() {
self.finish_file_move(prev, Vec::new());
}
let Some(lsp) = self
.lsp
.as_mut()
.filter(|l| l.any_server_wants_file_renames())
else {
if self.run_file_move(op)
&& let Some(lsp) = self.lsp.as_mut()
{
lsp.did_rename_files(renames);
}
return;
};
let request_id = lsp.request_will_rename_files(renames.clone());
self.status = String::from("Updating references before the move\u{2026}");
self.pending_file_move = Some(PendingFileMove {
request_id,
op,
renames,
deadline: std::time::Instant::now() + FILE_MOVE_DEADLINE,
baseline: self.edit_seqs_in_every_group(),
});
}
/// Land the servers' answer to a pending Explorer move, or give up on
/// them at the deadline and move anyway. Returns true when the screen
/// changed.
pub fn tick_file_moves(&mut self) -> bool {
let Some(pending) = self.pending_file_move.as_ref() else {
return false;
};
let mut answer = None;
if let Some(lsp) = self.lsp.as_ref() {
while let Some(result) = lsp.drain_will_rename_files() {
if result.request_id == pending.request_id {
answer = Some(result.edits);
}
}
}
if answer.is_none() && std::time::Instant::now() < pending.deadline {
return false;
}
let pending = self.pending_file_move.take().expect("checked above");
self.finish_file_move(pending, answer.unwrap_or_default());
true
}
/// Run the move, then apply the servers' edits and tell the servers it
/// happened. The move goes first: a move that fails (a folder into its
/// own child, a name already taken) must not leave every importer
/// rewritten to a path that does not exist. The edits name files at
/// their old paths, so they are carried to where the move put them.
fn finish_file_move(
&mut self,
pending: PendingFileMove,
edits: Vec<(PathBuf, Vec<crate::widgets::editor::TextSpanEdit>)>,
) {
if !self.run_file_move(pending.op) {
return;
}
let moved_status = self.status.clone();
if !edits.is_empty() {
let edits: Vec<_> = edits
.into_iter()
.map(|(path, e)| (moved_path(&path, &pending.renames), e))
.collect();
// The move carried open tabs to their new paths; so too their
// request-time seqs, for the check below to find them.
let baseline: Vec<_> = pending
.baseline
.iter()
.map(|(path, seq)| (moved_path(path, &pending.renames), *seq))
.collect();
if let Some(file) = self.stale_edit_target(&baseline, &edits) {
self.status = format!(
"{moved_status}; references not updated: {file} changed while the server was working"
);
} else {
match self.apply_rename_edits(&edits) {
Ok((files, _)) => {
self.status =
format!("{moved_status}, references updated in {files} file(s)");
}
Err(e) => {
self.status = format!("{moved_status}; could not update references: {e}")
}
}
}
}
if let Some(lsp) = self.lsp.as_mut() {
lsp.did_rename_files(pending.renames);
}
}
/// Perform an Explorer rename or move. Returns whether anything moved.
fn run_file_move(&mut self, op: FileMove) -> bool {
match op {
FileMove::Paste { dest_dir, paths } => {
self.apply_paste_or_drop(&dest_dir, &paths, ExplorerClipMode::Cut)
}
FileMove::Rename {
parent,
old,
new_name,
} => match crate::widgets::file_tree::rename_in(&parent, &old, &new_name) {
Ok(new_path) => {
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.rename_open_path_everywhere(&old, &new_path);
self.rename_review_boxes_path(&old, &new_path);
crate::history::move_path(&self.history_root, &old, &new_path);
self.sync_open_file_poll_mtime();
true
}
Err(e) => {
self.status = format!("Rename failed: {e}");
false
}
},
}
}
/// Shared implementation for explorer paste and drag-drop. `mode`
/// distinguishes a move (Cut/drag) from a copy (Copy/Alt-drag).
/// Returns whether every item landed.
fn apply_paste_or_drop(
&mut self,
dest_dir: &Path,
paths: &[PathBuf],
mode: ExplorerClipMode,
) -> bool {
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) => {
// Every tab, not just the active one: a background tab of
// a moved file kept the old path and recreated it on save.
if matches!(mode, ExplorerClipMode::Cut) {
self.rename_open_path_everywhere(src, &p);
self.rename_review_boxes_path(src, &p);
crate::history::move_path(&self.history_root, 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)
);
}
errors.is_empty()
}
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()
}
}
/// File: Revert File (#1285): drop the active tab's unsaved edits for
/// the text on disk. One undo step, so Ctrl+Z brings the edits back.
fn revert_file(&mut self) {
let Some(path) = self.editor.path.clone() else {
self.status = String::from("This tab has no file to revert to");
return;
};
let name = self.status_path(&path);
if !self.editor.dirty {
self.status = format!("{name} has no unsaved changes");
return;
}
match self.editor.revert_as_undo_step() {
Ok(()) => {
self.sync_open_file_poll_mtime();
self.status = format!("Reverted {name}");
}
Err(e) => self.status = format!("Revert failed: {e}"),
}
}
/// File: New Untitled Text File (#1580): a scratch tab with no path,
/// focused; saving it asks where to write it.
fn new_untitled_file(&mut self) {
// The lowest number no tab holds in any split group: each group
// numbering its own would give two tabs the same name.
let taken: Vec<usize> = std::iter::once(&self.editor)
.chain(self.editor_layout.inactive_groups())
.flat_map(|group| group.editors.iter().filter_map(|e| e.untitled))
.collect();
let n = (1..).find(|n| !taken.contains(n)).unwrap_or(1);
self.editor.new_untitled(n);
self.focus_pane(Pane::Editor);
self.status = format!("Untitled-{n}: saving asks where to write it");
}
/// File: Save As… (#1203): ask where to write the active tab's buffer.
fn open_save_as_prompt(&mut self) {
if self.editor.has_non_text_view() {
self.status = String::from("Save As works on text tabs; this one is a preview");
return;
}
let buffer = self
.editor
.path
.as_deref()
.map(|p| self.status_path(p))
.unwrap_or_default();
self.prompt = Some(Prompt {
label: String::from("Save As"),
buffer,
kind: PromptKind::SaveAs,
target_dir: self.tree.root.clone(),
error: None,
});
}
/// Write the active tab's buffer to `path` and move the tab there; the
/// error says why not, with the tab left as it was.
fn save_as(&mut self, path: &Path) -> Result<(), String> {
use crate::widgets::editor::SaveOutcome;
match self.editor.save_as(path) {
Ok(SaveOutcome::Saved) => {
self.status = self.editor.status.clone();
let seats = self.editor.provenance_to_record();
let described = self.editor.bytes_for_disk();
self.record_history_snapshot_of(path, seats, described);
self.sync_open_file_poll_mtime();
if let Some(idx) = path.parent().and_then(|d| self.tree.index_of_dir(d)) {
self.tree.refresh_children(idx);
}
Ok(())
}
Ok(SaveOutcome::EncodingLoss) => Err(format!(
"Some characters can't be written as {}",
self.editor.encoding.name()
)),
Ok(SaveOutcome::DiskConflict) => unreachable!("save_as never checks for a conflict"),
Err(e) => Err(format!("Save failed: {e}")),
}
}
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 {
// A tab of its own: `open` reloads the ACTIVE tab
// in place, discarding its unsaved edits.
if let Err(e) = self.editor.open_pinned(&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();
// Validate now, while the prompt can still show the error;
// the rename itself may wait on the servers' edit (#610).
match crate::widgets::file_tree::rename_target(&parent, &old_path, &new_name) {
Ok(target) => {
self.prompt = None;
if target != old_path {
let op = FileMove::Rename {
parent,
old: old_path.clone(),
new_name,
};
let is_dir = old_path.is_dir();
self.start_file_move(
op,
vec![crate::lsp::manager::FileRenameOp {
old: old_path,
new: target,
is_dir,
}],
);
}
}
Err(e) => {
if let Some(p) = self.prompt.as_mut() {
p.error = Some(e.to_string());
}
}
}
}
PromptKind::SaveAs => {
let answer = prompt.buffer.trim().to_string();
let target = prompt.target_dir.join(&answer);
let error = if answer.is_empty() {
Some(String::from("Enter a path to save to"))
} else if self.editor.path.as_deref() != Some(target.as_path()) && target.exists() {
Some(format!("{answer} already exists"))
} else {
self.save_as(&target).err()
};
match error {
Some(e) => {
if let Some(p) = self.prompt.as_mut() {
p.error = Some(e);
}
}
None => self.prompt = None,
}
}
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.rename_baseline = self.edit_seqs_in_every_group();
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::HitCondition { path, line } => {
let hits = prompt.buffer.clone();
self.prompt = None;
self.commit_hit_condition(path, line, &hits);
}
PromptKind::FunctionBreakpoint => {
let name = prompt.buffer.trim().to_string();
self.prompt = None;
self.commit_function_breakpoint(name);
}
PromptKind::DataBreakpoint => {
let name = prompt.buffer.trim().to_string();
self.prompt = None;
self.commit_data_breakpoint(&name);
}
PromptKind::ReviewComment => {
let (body, rel) = (prompt.buffer.trim().to_string(), prompt.target_dir.clone());
self.prompt = None;
self.add_pending_review_comment(&body, rel);
}
PromptKind::StickyNote => {
let body = prompt.buffer.trim().to_string();
self.prompt = None;
self.add_sticky_note(&body);
}
PromptKind::ReviewSummary => {
let summary = prompt.buffer.trim().to_string();
self.prompt = None;
self.submit_review(summary);
}
PromptKind::NewProfile => {
let name = prompt.buffer.trim().to_string();
match crate::profiles::create_from_current(&name) {
Ok(()) => {
self.prompt = None;
self.switch_profile(Some(name));
}
Err(e) => {
if let Some(p) = self.prompt.as_mut() {
p.error = Some(e.to_string());
}
}
}
}
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.
pub(crate) fn takeover_mode_seq() -> Vec<u8> {
let mut seq = Vec::new();
let _ = execute!(
seq,
EnterAlternateScreen,
EnableMouseCapture,
EnableBracketedPaste,
// Focus in/out reports (#1622): auto save "onWindowChange" saves
// when the croft window loses focus, which croft only learns from
// the terminal.
EnableFocusChange,
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` terminal cells 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). Measured in cells, not chars, so a CJK name is not
/// overdrawn by the status bar's right cluster.
fn elide_middle(s: &str, max: usize) -> String {
use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
if s.width() <= max {
return s.to_string();
}
if max < 3 {
let mut out = String::new();
let mut used = 0;
for c in s.chars() {
let w = c.width().unwrap_or(0);
if used + w > max {
break;
}
used += w;
out.push(c);
}
return out;
}
crate::widgets::process_picker::elide_middle_cols(s, max)
}
/// 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())
}
/// [`has_cmd`], or off macOS a `Ctrl`: the command modifier LINUX.md
/// promises there (#843), for the chords whose `Ctrl` spelling is free.
fn has_cmd_or_linux_ctrl(mods: KeyModifiers) -> bool {
has_cmd(mods) || (cfg!(not(target_os = "macos")) && mods.contains(KeyModifiers::CONTROL))
}
/// 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.
pub(crate) 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")
}
/// The host terminal's default colours set to `theme`'s: the portable
/// dynamic colours on every host, then iTerm2's sRGB session background
/// where it has one. Startup, a theme switch and a reattach all send this.
fn theme_host_colors_seq(theme: crate::theme::Theme) -> String {
let mut seq = host_colors_seq(theme);
if crate::iterm2_inline::detect_iterm2_inline_support() {
seq.push_str(&set_session_bg_srgb_seq(theme.editor_bg_rgb()));
}
seq
}
/// What a persistent session's croft sends on every WINCH, which is how a
/// reattach reaches it: every startup mode ([`mode_reassert_seq`]), then the
/// theme's default colours. A terminal attaching for the first time never
/// had those colours, and a `croft remote` client resets them while its
/// connection is down (#1460), so they come back with the modes.
pub(crate) fn reattach_reassert_seq(theme: crate::theme::Theme) -> Vec<u8> {
let mut seq = mode_reassert_seq();
seq.extend_from_slice(theme_host_colors_seq(theme).as_bytes());
seq
}
/// Reset the host terminal's default foreground and background to its own
/// configuration (OSC 110/111), undoing [`host_colors_seq`] on exit.
pub(crate) 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` — doesn't collide with `Ctrl+C` (SIGINT). It is also
/// the host terminal's own Copy in GNOME Terminal and Konsole, which
/// keep it, and without the kitty protocol it arrives as `Ctrl+C`; the
/// pane menu's Copy and "Copy on Selection" reach croft there (#1598).
/// * `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. `ctrl_leads` is
/// [`ctrl_k_leads`] for the focused pane.
fn is_cmd_k_leader_key(key: KeyEvent, ctrl_leads: bool) -> 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;
}
has_cmd(key.modifiers) || (ctrl_leads && key.modifiers.contains(KeyModifiers::CONTROL))
}
/// Whether a bare `Ctrl+K` arms the `Cmd+K` leader (#843). Off macOS it
/// does, as in VS Code's Linux keymap: Super reaches croft only over the
/// kitty keyboard protocol, so in GNOME Terminal, Konsole, xterm or tmux no
/// leader chord was reachable at all. Two places keep `Ctrl+K` for their
/// own job: a focused shell (readline's kill-line) and the editor in vim
/// mode (kill to end of line, also the palette's "Kill to End of Line").
/// On macOS `Ctrl+K` stays kill-line and Cmd leads; on Termux `Ctrl` is
/// the command key outright ([`cmd_active`]), so this is not consulted.
fn ctrl_k_leads(macos: bool, shell_focused: bool, vim_editing: bool) -> bool {
!macos && !shell_focused && !vim_editing
}
/// `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+O`: C/C++: Switch Header/Source (#1360), the clangd extension's
/// chord in VS Code. Rejects Shift and the other modifiers.
fn is_switch_header_source_key(key: KeyEvent) -> bool {
let KeyCode::Char(c) = key.code else {
return false;
};
c.eq_ignore_ascii_case(&'o')
&& key.modifiers.contains(KeyModifiers::ALT)
&& !key.modifiers.contains(KeyModifiers::SHIFT)
&& !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` / `Ctrl+Z` — open the zoxide jump popup.
/// `z` for **z**oxide; the user's shell still uses `j` for the same jump.
/// `Ctrl+Z` counts on every platform, as the Make Root chords do (#1294):
/// xterm, GNOME Terminal, Konsole and tmux never deliver Super, and this
/// predicate only runs while the Explorer is focused, so a `Ctrl+Z` here is
/// never a shell's suspend or the editor's undo. The Explorer has no undo
/// of its own to clash with.
/// 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;
}
key.modifiers.contains(KeyModifiers::CONTROL) || key.modifiers.contains(KeyModifiers::SUPER)
}
/// What Problems: Check Whole Project runs (#256, #1291).
enum ProjectCheck {
/// Each `(program, args)` in turn, with their output merged.
Run(Vec<(std::ffi::OsString, Vec<String>)>),
/// The root tsconfig names no files and no references: tsc would
/// compile nothing and exit clean.
Empty,
}
/// The text terminal find searches: one string per logical line (#1275).
fn find_texts(lines: Vec<crate::widgets::terminal::FindLine>) -> Vec<String> {
lines.into_iter().map(|l| l.text).collect()
}
/// 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)
}
/// File: New Untitled Text File (#1580): `Cmd+N`, and `Ctrl+N` off macOS,
/// as in VS Code. Shift belongs to New Folder.
fn is_new_untitled_file_key(key: KeyEvent) -> bool {
matches!(key.code, KeyCode::Char('n' | 'N'))
&& has_cmd_or_linux_ctrl(key.modifiers)
&& !key
.modifiers
.intersects(KeyModifiers::SHIFT | KeyModifiers::ALT)
}
/// 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.
/// `Ctrl+Shift+S` gets here only when [`is_save_key`] let it go, which needs
/// the kitty keyboard protocol to have reported the Shift (#857).
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')
}
/// `Ctrl/Cmd+Shift+M`: show the PROBLEMS tab from any pane, VS Code's
/// "View: Focus Problems" (#852).
fn is_show_problems_key(key: KeyEvent) -> bool {
is_cmd_shift_letter(key, 'm')
}
/// `Ctrl/Cmd+Shift+U`: show the OUTPUT tab from any pane, VS Code's
/// "View: Toggle Output" chord (#852).
fn is_show_output_key(key: KeyEvent) -> bool {
is_cmd_shift_letter(key, 'u')
}
/// `Ctrl/Cmd+Shift+H`: Search: Replace in Files, VS Code's chord (#860). In
/// the live terminal `Ctrl+Shift+H` stays `is_command_history_key`'s; the
/// dispatcher checks that before this.
fn is_replace_in_files_key(key: KeyEvent) -> bool {
is_cmd_shift_letter(key, 'h')
}
/// The lines the find bar searches, the buffer row the first of them is,
/// and the part of them it searches: with Find in Selection the whole rows
/// the `range` spans and the range relative to them (#1577), so matches
/// are found on the real lines and kept when wholly inside; else a symbol
/// tab's symbol (#369) or the whole buffer.
fn editor_find_lines(
editor: &crate::widgets::editor::Editor,
range: Option<crate::widgets::editor_find::FindRange>,
) -> (
&[String],
usize,
Option<crate::widgets::editor_find::FindRange>,
) {
if let Some(range) = range {
let ((r0, c0), (r1, c1)) = crate::widgets::editor_find::clamp_range(&editor.lines, range);
let lines = editor.lines.get(r0..=r1).unwrap_or(&[]);
return (lines, r0, Some(((0, c0), (r1 - r0, c1))));
}
let (scope, first) = editor.find_scope();
(scope, first, None)
}
/// Buffer position `(row, col)` as a position in the lines
/// [`editor_find_lines`] returned. Outside a selected `window` it goes to
/// the window's nearer edge, so the next match from a caret above the
/// selection is its first, and from below it wraps to it.
fn editor_find_scope_pos(
scope: &[String],
first: usize,
window: Option<crate::widgets::editor_find::FindRange>,
(row, col): (usize, usize),
) -> Option<(usize, usize)> {
let last = scope.len().checked_sub(1)?;
let Some((start, end)) = window else {
return Some((row.saturating_sub(first).min(last), col));
};
let Some(r) = row.checked_sub(first) else {
return Some(start);
};
Some((r, col).clamp(start, end))
}
/// `Alt+C` / `Alt+W` / `Alt+R` / `Alt+P` while a Search side bar input has
/// focus: the `Aa` / `ab` / `.*` / `AB` toggle each flips, VS Code's
/// search-input keys (#860, #1612).
/// Only a bare Alt: a macOS terminal that sends Option+C as `ç` is typing,
/// and taking that glyph would eat it on the keyboards that have it.
fn search_toggle_for_key(key: KeyEvent) -> Option<crate::widgets::search::SearchToggle> {
use crate::widgets::search::SearchToggle;
if key.modifiers != KeyModifiers::ALT {
return None;
}
match key.code {
KeyCode::Char('c' | 'C') => Some(SearchToggle::CaseSensitive),
KeyCode::Char('w' | 'W') => Some(SearchToggle::WholeWord),
KeyCode::Char('r' | 'R') => Some(SearchToggle::UseRegex),
KeyCode::Char('p' | 'P') => Some(SearchToggle::PreserveCase),
_ => None,
}
}
/// `Alt+D` while a Search side bar input has focus: show or hide the "files
/// to include / exclude" rows (#860). VS Code's own chord, `Ctrl+Shift+J`, is
/// croft's maximize-terminal, so D for details.
fn is_search_details_key(key: KeyEvent) -> bool {
key.modifiers == KeyModifiers::ALT && matches!(key.code, KeyCode::Char('d' | 'D'))
}
/// `Cmd+Opt+S` / `Ctrl+Alt+S`: File: Save All (#852). VS Code's macOS chord;
/// its Linux `Ctrl+K S` is croft's Select for Compare. Shift is rejected:
/// `Cmd+Opt+Shift+S` converts indentation to spaces.
fn is_save_all_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) || key.modifiers.contains(KeyModifiers::SHIFT) {
return false;
}
key.modifiers.contains(KeyModifiers::CONTROL) || key.modifiers.contains(KeyModifiers::SUPER)
}
/// 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. Off macOS `Ctrl`+`Enter` too (#843): there it only
/// duplicated `Enter`, and Super reaches croft only over the kitty keyboard
/// protocol. Where a terminal sends `Ctrl`+`Enter` as a bare `Enter`, the
/// palette's "Markdown: Run Code Block at Cursor" runs it.
fn is_run_fence_key(key: KeyEvent) -> bool {
matches!(key.code, KeyCode::Enter)
&& has_cmd_or_linux_ctrl(key.modifiers)
// 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). Any other language
/// is written to a private file under `scripts` and read from it on stdin,
/// `python3 - < 'file'` (#1630): the heredoc it used to be typed as is
/// POSIX shell syntax, so with fish as the pane's shell every python or
/// node block failed. A redirect from a quoted path reads the same in bash,
/// zsh and fish, and the block reaches the interpreter byte for byte, tabs
/// and `!` included. The interpreter still reads stdin, so the block runs
/// with the pane's directory on its import path, as before. Should the file
/// not be written, the heredoc is the fallback.
///
/// A shell block holding a tab or `!` goes as one single-quoted
/// `printf '%b'` argument instead: typed into an interactive shell, a tab
/// is completion and bash expands `!` as history, so what ran was not what
/// the confirm popup showed. Inside single quotes neither happens, and the
/// tab travels as `\t`.
fn fence_command(interpreter: &str, code: &str, scripts: &Path) -> String {
let code = code.trim_end_matches('\n');
if interpreter != "sh" {
if let Ok(file) = stage_block(scripts, interpreter, code) {
return format!("{interpreter} - < '{}'\r", file.display());
}
let mut end = String::from("CROFT_BLOCK");
let mut n = 0u32;
while code.contains(&end) {
n += 1;
end = format!("CROFT_BLOCK_{n}");
}
return format!("{interpreter} - <<'{end}'\n{code}\n{end}\r");
}
if code.contains(['\t', '!']) {
let escaped = format!("{code}\n")
.replace('\\', "\\\\")
.replace('\n', "\\n")
.replace('\t', "\\t")
.replace('\'', "'\\''");
// A shell block runs IN the pane's shell, as a typed one does (a
// `cd` or `export` persists, bash-isms still work): `eval` of the
// decoded text.
return format!("eval \"$(printf '%b' '{escaped}')\"\r");
}
format!("{code}\r")
}
/// Where [`fence_command`] writes the blocks it runs (#1630). Always
/// absolute: the typed command runs in the pane's directory, so a relative
/// cache (HOME unset or relative) would name a file that is not there.
fn block_script_dir() -> PathBuf {
// Never the user's own cache from a test.
let dir = if cfg!(test) {
std::env::temp_dir().join(format!("croft-test-blocks-{}", std::process::id()))
} else {
croft_cache_dir().join("blocks")
};
absolute_block_dir(dir)
}
/// `dir` made absolute against croft's own directory, where it was meant.
fn absolute_block_dir(dir: PathBuf) -> PathBuf {
std::path::absolute(&dir).unwrap_or(dir)
}
/// How long a written block is kept: long enough for its interpreter to
/// have read it, short enough that the directory never grows.
const BLOCK_SCRIPT_TTL: std::time::Duration = std::time::Duration::from_secs(24 * 60 * 60);
/// Write `code` and a final newline to a new file under `dir` that only the
/// user can read, for `interpreter` (#1630). Refuses a path the typed
/// command could not quote in single quotes. Blocks older than
/// [`BLOCK_SCRIPT_TTL`] are cleared first.
fn stage_block(dir: &Path, interpreter: &str, code: &str) -> std::io::Result<PathBuf> {
use std::io::Write;
use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt};
static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
std::fs::DirBuilder::new()
.recursive(true)
.mode(0o700)
.create(dir)?;
if let Ok(entries) = std::fs::read_dir(dir) {
for entry in entries.flatten() {
let old = entry
.metadata()
.and_then(|m| m.modified())
.ok()
.and_then(|t| t.elapsed().ok())
.is_some_and(|age| age > BLOCK_SCRIPT_TTL);
if old && entry.file_name().to_string_lossy().starts_with("block-") {
let _ = std::fs::remove_file(entry.path());
}
}
}
let ext = match interpreter {
"python3" => "py",
"node" => "js",
_ => "txt",
};
let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let path = dir.join(format!(
"block-{}-{seq}-{}.{ext}",
std::process::id(),
now_millis()
));
if path.to_string_lossy().contains(['\'', '\\', '\n', '\r']) {
return Err(std::io::Error::other("the block path cannot be quoted"));
}
let mut file = std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.mode(0o600)
.open(&path)?;
file.write_all(format!("{code}\n").as_bytes())?;
Ok(path)
}
/// 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
}
/// Load the snippets file, writing what could not be read to OUTPUT ·
/// Snippets: one bad entry used to empty the whole set without a word (#1483).
fn load_snippets(path: &std::path::Path) -> crate::snippets::SnippetSet {
let set = crate::snippets::SnippetSet::load(path);
for w in set.warnings() {
crate::output::push("Snippets", crate::output::OutputLevel::Warn, w);
}
set
}
/// The status line shown after a snippets reload, tested the same way. A
/// file that loaded nothing says so, with the detail in OUTPUT (#1191), as
/// keybindings.json does; skipped entries are counted (#1483).
fn snippets_reload_status(broken: bool, warns: &[String]) -> String {
if broken {
return String::from(
"Snippets not loaded: the file does not parse — see OUTPUT · Snippets",
);
}
match warns.len() {
0 => String::from("Snippets reloaded"),
n => format!(
"Snippets reloaded with {n} warning{} — see OUTPUT · Snippets",
if n == 1 { "" } else { "s" }
),
}
}
/// 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)
}
/// `n` with the word for one or for many, as screen reader mode reads a
/// count: "1 error", "3 matches".
fn a11y_count(n: usize, one: &str, many: &str) -> String {
format!("{n} {}", if n == 1 { one } else { many })
}
/// `⌥⌘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+K`: toggle a bookmark on the cursor's line (VS Code's
/// Bookmarks extension binds `Ctrl+Alt+K`; nvim spells it `m<letter>`).
fn is_toggle_bookmark_key(key: KeyEvent) -> bool {
is_cmd_alt_shift_letter(key, 'k')
}
/// `Cmd+Opt+Shift+G`: focus the next member of a compound debug session
/// (#567), so one stopped in the background can be inspected.
fn is_switch_debug_session_key(key: KeyEvent) -> bool {
is_cmd_alt_shift_letter(key, 'g')
}
/// `Cmd+Opt+Shift+B`: clear every bookmark in the open file. `Cmd+Shift+B`
/// (Run Build Task) and `Cmd+Opt+B` (secondary side bar) each exclude the
/// other modifier, so the three chords on `b` never collide.
fn is_clear_bookmarks_key(key: KeyEvent) -> bool {
is_cmd_alt_shift_letter(key, 'b')
}
/// `Cmd+Opt+.`: jump to the next bookmark below the cursor, wrapping to the
/// top of the file. `Cmd+.` alone is Quick Fix, which excludes Alt, so the
/// two never collide.
fn is_next_bookmark_key(key: KeyEvent) -> bool {
matches!(key.code, KeyCode::Char('.') | KeyCode::Char('>'))
&& (key.modifiers.contains(KeyModifiers::SUPER)
|| key.modifiers.contains(KeyModifiers::CONTROL))
&& key.modifiers.contains(KeyModifiers::ALT)
}
/// `Cmd+Opt+,`: mirror of [`is_next_bookmark_key`] walking upwards. The
/// shifted glyph `<` is accepted for terminals that pre-apply the shift.
fn is_prev_bookmark_key(key: KeyEvent) -> bool {
matches!(key.code, KeyCode::Char(',') | KeyCode::Char('<'))
&& (key.modifiers.contains(KeyModifiers::SUPER)
|| key.modifiers.contains(KeyModifiers::CONTROL))
&& key.modifiers.contains(KeyModifiers::ALT)
}
/// `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+=`: Increment the number under the cursor.
///
/// vim's own chord is `Ctrl-A`, which cannot be taken here — it is Select
/// All, and on a terminal it is also the tmux/screen prefix. `Cmd+Opt` with
/// the `=`/`-` pair keeps the two halves adjacent on the keyboard and free
/// of every existing binding. `+` is accepted alongside `=` so a shifted
/// press works on layouts that report it.
fn is_increment_number_key(key: KeyEvent) -> bool {
is_cmd_alt_char(key, &['=', '+'])
}
/// `Cmd+Opt+-`: Decrement the number under the cursor (vim's `Ctrl-X`).
fn is_decrement_number_key(key: KeyEvent) -> bool {
is_cmd_alt_char(key, &['-', '_'])
}
fn is_cmd_alt_char(key: KeyEvent, chars: &[char]) -> bool {
let KeyCode::Char(c) = key.code else {
return false;
};
if !chars.contains(&c) {
return false;
}
let has_alt = key.modifiers.contains(KeyModifiers::ALT);
let has_cmd_or_ctrl = key.modifiers.contains(KeyModifiers::CONTROL)
|| key.modifiers.contains(KeyModifiers::SUPER);
has_alt && has_cmd_or_ctrl
}
/// `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')
}
/// `Cmd+Opt+Shift+E`: Emmet Expand Abbreviation
/// (`editor.emmet.action.expandAbbreviation`). VS Code binds this to Tab,
/// which croft cannot reuse — Tab is indentation here, and an abbreviation
/// that only sometimes expands on Tab is worse than one that always expands
/// on its own chord.
fn is_emmet_expand_key(key: KeyEvent) -> bool {
is_cmd_alt_shift_letter(key, 'e')
}
/// The outline of `lines` as the file at `path` from its own syntax tree,
/// empty for a language croft has no grammar for.
fn syntax_outline_for(
path: &std::path::Path,
lines: &[String],
) -> Vec<crate::lsp::manager::OutlineSymbol> {
crate::outline_syntax::symbols_for_lines(path, lines)
}
/// The largest buffer whose syntax outline is parsed on the UI thread
/// (#1150). A from-scratch parse costs about a quarter of a millisecond per
/// kilobyte, so this keeps it within a frame; larger buffers go to
/// [`App::start_outline_parse`].
const OUTLINE_INLINE_MAX_BYTES: usize = 64 * 1024;
/// Whether `lines` is small enough to parse for the outline inline.
fn outline_parses_inline(lines: &[String]) -> bool {
lines
.iter()
.try_fold(0usize, |bytes, l| {
let bytes = bytes + l.len() + 1;
(bytes <= OUTLINE_INLINE_MAX_BYTES).then_some(bytes)
})
.is_some()
}
/// The breadcrumb scope chain for the caret at (`line`, `col`): the indices
/// of every outline symbol whose range encloses that position, ordered
/// outermost first (the enclosing class before the method inside it).
/// Columns count (#1221): symbols sharing a line, such as a one-line
/// interface's fields or a minified bundle's functions, are siblings, and
/// only the one the caret is in belongs to the chain. Enclosing ranges nest,
/// so the earliest start (then the latest end) is the outermost.
fn breadcrumb_symbol_chain(
symbols: &[crate::lsp::manager::OutlineSymbol],
line: u32,
col: u32,
) -> Vec<usize> {
let start =
|s: &crate::lsp::manager::OutlineSymbol| (s.range_start_line, s.range_start_character);
let end = |s: &crate::lsp::manager::OutlineSymbol| (s.range_end_line, s.range_end_character);
let mut hits: Vec<usize> = symbols
.iter()
.enumerate()
.filter(|(_, s)| start(s) <= (line, col) && (line, col) <= end(s))
.map(|(i, _)| i)
.collect();
hits.sort_by(|&a, &b| {
start(&symbols[a])
.cmp(&start(&symbols[b]))
.then(end(&symbols[b]).cmp(&end(&symbols[a])))
});
hits
}
/// VS Code "Focus and Select Breadcrumbs": `Cmd+Shift+.` / `Ctrl+Shift+.`
/// (#1608). A terminal that applies the shift itself sends `>`.
fn is_focus_breadcrumbs_key(key: KeyEvent) -> bool {
let shifted = match key.code {
KeyCode::Char('.') => key.modifiers.contains(KeyModifiers::SHIFT),
KeyCode::Char('>') => true,
_ => false,
};
shifted
&& (key.modifiers.contains(KeyModifiers::SUPER)
|| key.modifiers.contains(KeyModifiers::CONTROL))
&& !key.modifiers.contains(KeyModifiers::ALT)
}
/// The symbols at `i`'s level under its parent, `i` among them, in outline
/// order (#1608): the outline is a pre-order walk, so they are the symbols
/// of `i`'s depth between the parent and the next symbol shallower than `i`.
fn sibling_symbols(symbols: &[crate::lsp::manager::OutlineSymbol], i: usize) -> Vec<usize> {
let Some(depth) = symbols.get(i).map(|s| s.depth) else {
return Vec::new();
};
let start = (0..i)
.rev()
.find(|&k| symbols[k].depth < depth)
.map_or(0, |parent| parent + 1);
let end = (i + 1..symbols.len())
.find(|&k| symbols[k].depth < depth)
.unwrap_or(symbols.len());
(start..end)
.filter(|&k| symbols[k].depth == depth)
.collect()
}
/// 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 and bringing its
/// TERMINAL tab forward over PROBLEMS / OUTPUT / PORTS / CAPTURES (#852).
/// 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)
}
/// Whitespace rendering for a file in language `scope` (#1440): its
/// language block's `editor.renderWhitespace`, else `global`. A free fn so
/// the render loops can call it while they hold the editors mutably.
fn whitespace_mode_in(
langs: &std::collections::BTreeMap<String, crate::prefs::LanguagePrefs>,
global: crate::widgets::editor::WhitespaceMode,
scope: &str,
) -> crate::widgets::editor::WhitespaceMode {
langs
.get(scope)
.and_then(|l| l.render_whitespace.as_deref())
.map_or(global, crate::widgets::editor::WhitespaceMode::from_pref)
}
/// The VS Code language id of the file at `path`, as its tab would have
/// it (#1440: which `languages` block applies).
fn path_scope_id(path: &Path) -> &'static str {
settings_scope_id(
crate::widgets::editor::language_scope_id(crate::highlight::lang_for_path(path)),
Some(path),
)
}
/// The VS Code language id of `ed`'s buffer for settings lookup (#1440).
fn editor_scope_id(ed: &crate::widgets::editor::Editor) -> &'static str {
settings_scope_id(ed.scope_id(), ed.path.as_deref())
}
/// Refines the highlighter's language id `base` to the VS Code id the
/// file's extension carries where several ids share one grammar (#1440):
/// `.jsx` is `javascriptreact`, `.jsonc` is `jsonc`, `.scss` is `scss`, so
/// their `"[…]"` blocks apply. A buffer switched to another language keeps
/// that language's id.
fn settings_scope_id(base: &'static str, path: Option<&Path>) -> &'static str {
let ext = path
.and_then(|p| p.extension())
.and_then(|e| e.to_str())
.map(str::to_ascii_lowercase);
match (base, ext.as_deref()) {
("javascript", Some("jsx")) => "javascriptreact",
("json", Some("jsonc")) => "jsonc",
("css", Some("scss")) => "scss",
("css", Some("sass")) => "sass",
_ => base,
}
}
/// Inlay hints for a file in language `scope` (#1440): its language
/// block's `disable_inlay_hints`, else `global`. A free fn so callers can
/// use it while they hold the editors mutably.
fn inlay_hints_on_in(
langs: &std::collections::BTreeMap<String, crate::prefs::LanguagePrefs>,
global: bool,
scope: &str,
) -> bool {
langs
.get(scope)
.and_then(|l| l.disable_inlay_hints)
.map_or(global, |off| !off)
}
/// The suite that is the file `path` for `runner` (#1535: Run Tests in
/// Current File), in the runner's own naming: pytest takes the file's path
/// as a node-ID prefix; cargo a source file's module path (`src/a/b.rs` and
/// `src/a/b/mod.rs` are `a::b`); go the
/// file's package directory; CodeQL the test file itself. `None` for a file
/// the runner cannot select alone: a cargo crate root (its tests carry no
/// module prefix to filter on), a binary under `src/bin` or an integration
/// test (each its own test binary, which the name filter cannot pick), any
/// jest or vitest file
/// (their suites are describe titles, not files), and a file outside `root`.
fn file_test_suite(
runner: crate::testing::worker::Runner,
root: &Path,
path: &Path,
) -> Option<String> {
use crate::testing::worker::Runner;
let rel = path.strip_prefix(root).ok()?;
let rel_str = rel.to_str()?.replace('\\', "/");
match runner {
Runner::Pytest | Runner::Codeql => Some(rel_str),
Runner::Go => {
let dir = rel.parent().and_then(Path::to_str).unwrap_or("");
Some(if dir.is_empty() {
String::from(".")
} else {
format!("./{}", dir.replace('\\', "/"))
})
}
Runner::Cargo => {
// Relative to the package the file belongs to: in a workspace,
// `crates/foo/src/parse.rs` is module `parse`.
let in_package = cargo_package_relative(root, path)?;
let in_src = in_package.strip_prefix("src/")?.strip_suffix(".rs")?;
let module = in_src.strip_suffix("/mod").unwrap_or(in_src);
// A crate root's tests have no module prefix to filter on: a
// `tests::` filter is a substring, and would sweep every
// module's `tests` too.
match module {
"main" | "lib" => None,
_ if module.starts_with("bin/") => None,
_ => Some(module.replace('/', "::")),
}
}
Runner::Vitest | Runner::Jest => None,
}
}
/// `path` relative to the nearest package directory above it, up to
/// `root`: the closest ancestor holding a `Cargo.toml` with the file under
/// its `src/`, or `root` itself.
fn cargo_package_relative(root: &Path, path: &Path) -> Option<String> {
let rel_to = |dir: &Path| {
path.strip_prefix(dir)
.ok()
.and_then(Path::to_str)
.map(|s| s.replace('\\', "/"))
};
for dir in path.ancestors().skip(1) {
if dir == root || !dir.starts_with(root) {
break;
}
if let Some(rel) = rel_to(dir)
&& rel.starts_with("src/")
&& dir.join("Cargo.toml").is_file()
{
return Some(rel);
}
}
rel_to(root)
}
/// 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 == '_'
}
/// How long a format-on-save waits for the formatter before writing the
/// file unformatted (#1491).
const FORMAT_ON_SAVE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2);
/// Save All's status line: `before` editors were unsaved, `left` still are,
/// `pending` names the file whose write waits on its formatter, and
/// `active_refusal` is the active tab's own reason it is still unsaved.
fn save_all_summary(
before: usize,
left: usize,
pending: Option<&str>,
active_refusal: String,
) -> String {
let editors = |n: usize| format!("{n} editor{}", if n == 1 { "" } else { "s" });
if left == 0
&& let Some(file) = pending
{
// Its write waits on the formatter (at most FORMAT_ON_SAVE_TIMEOUT):
// not saved yet, so not counted as saved (#1491).
match before.saturating_sub(1) {
0 => format!("Formatting {file} before saving it"),
saved => format!(
"Saved {}; formatting {file} before saving it",
editors(saved)
),
}
} else if left == 0 {
format!("Saved {}", editors(before))
} else if !active_refusal.is_empty() && pending.is_none() {
// The active tab's own refusal names the reason and the key
// that consents; a summary would bury it.
active_refusal
} else {
format!(
"Save All: {left} editor{} still unsaved - open {} and press Cmd+S",
if left == 1 { "" } else { "s" },
if left == 1 { "it" } else { "each" }
)
}
}
/// 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.
}
"#;
/// What Open Settings (JSON) creates when there is no `config.json` yet: an
/// object with no keys, like VS Code's settings.json. Seeding every default
/// made each one a user setting, over an `extends` base and over defaults a
/// later release changes (#1617).
const SETTINGS_TEMPLATE: &str = r#"{
// Your croft settings: add only the keys you want to change, and every
// other setting keeps its default. docs/SETTINGS.md lists the keys and
// explains "extends" and platform blocks.
}
"#;
/// 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,
..Default::default()
}
}
/// 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 })
}
/// Command titles in curly quotes, joined for a status line (#1482):
/// `“A”, “B” and “C”`.
fn quoted_titles(cmds: &[crate::widgets::command_palette::Command]) -> String {
let quoted: Vec<String> = cmds
.iter()
.map(|c| format!("\u{201c}{}\u{201d}", c.title()))
.collect();
match quoted.split_last() {
Some((last, rest)) if !rest.is_empty() => format!("{} and {last}", rest.join(", ")),
_ => quoted.concat(),
}
}
/// 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)
}
/// `Cmd+S` / `Ctrl+S`: save the open file. `kitty_keys` is
/// [`App::kitty_keys`]: whether `Shift` held with `Ctrl` is reported
/// explicitly.
fn is_save_key(key: KeyEvent, kitty_keys: bool) -> 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 the Source Control jump (`is_source_control_jump_key`),
// and so is Ctrl+Shift+S where the kitty keyboard protocol reports the
// Shift explicitly (#857). Without it, a Shift beside Ctrl may be a
// terminal capitalising a plain Ctrl+S, so there Ctrl+Shift+S still
// saves; an uppercase S with Ctrl and no Shift reported saves everywhere.
if has_shift && (has_super || (has_ctrl && kitty_keys)) {
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
}
/// Where `App::copy_where_pasted` put a copy.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum CopyLanding {
/// Queued home over the drop relay, to the machine the user types at.
/// The relay sends no word back on whether that clipboard took it, so
/// the status says it was sent, not that it landed.
Local,
/// This machine's clipboard.
Clipboard,
/// Only an OSC 52 sequence, which the host terminal may ignore.
Osc52,
}
impl CopyLanding {
/// The status line for copying `what`, saying honestly where it went.
fn status(self, what: &str) -> String {
match self {
CopyLanding::Local => format!("Sent {what} to the local clipboard"),
CopyLanding::Clipboard => format!("Copied {what} to clipboard"),
CopyLanding::Osc52 => format!("Copied {what} via OSC 52 (the host terminal decides)"),
}
}
}
/// 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)
}
/// Ctrl+V with no other modifier (or its raw 0x16 form), which the
/// terminal hands to the app rather than pasting (#1290).
fn is_plain_ctrl_v(key: KeyEvent) -> bool {
match key.code {
KeyCode::Char('\u{16}') => true,
KeyCode::Char(c) => c.eq_ignore_ascii_case(&'v') && key.modifiers == KeyModifiers::CONTROL,
_ => false,
}
}
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 Some(lang) = crate::lsp::Language::from_path(path) else {
return false;
};
installed
.iter()
.any(|&i| lsp_server_family(i) == lsp_server_family(lang))
}
/// `Cmd+Shift+L` (`Ctrl+Shift+L` off macOS): Select All Occurrences of Find
/// Match (#1558), VS Code's chord. On a remote session Drop to Local takes
/// it first.
fn is_select_all_occurrences_key(key: KeyEvent) -> bool {
is_cmd_shift_letter(key, 'l')
}
/// `Shift+Alt+I`: Add Cursors to Line Ends (#1558), VS Code's chord.
fn is_add_cursors_to_line_ends_key(key: KeyEvent) -> bool {
matches!(key.code, KeyCode::Char('i' | 'I'))
&& key.modifiers.contains(KeyModifiers::ALT)
&& key.modifiers.contains(KeyModifiers::SHIFT)
&& !key
.modifiers
.intersects(KeyModifiers::CONTROL | KeyModifiers::SUPER)
}
/// 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)
}
/// Debug: Run to Cursor, `Ctrl+F10` (#611), Visual Studio's binding. Checked
/// before the bare F10 step-over, which accepts any modifier.
fn is_run_to_cursor_key(key: KeyEvent) -> bool {
matches!(key.code, KeyCode::F(10))
&& key.modifiers.contains(KeyModifiers::CONTROL)
&& !key.modifiers.contains(KeyModifiers::SHIFT)
}
/// croft's own updater, `Ctrl+Shift+F9` (`Cmd+Shift+F9` too) (#865):
/// relaunch into a landed update, or rebuild a croft older than its source
/// checkout. It once shared bare F9 with Toggle Breakpoint, and won.
fn is_update_croft_key(key: KeyEvent) -> bool {
matches!(key.code, KeyCode::F(9))
&& key.modifiers.contains(KeyModifiers::SHIFT)
&& (key.modifiers.contains(KeyModifiers::CONTROL)
|| key.modifiers.contains(KeyModifiers::SUPER))
&& !key.modifiers.contains(KeyModifiers::ALT)
}
/// How hints name the updater chord: with the modifier each platform's
/// keyboard reaches for, Cmd on macOS and Ctrl elsewhere.
const UPDATE_CROFT_CHORD: &str = if cfg!(target_os = "macos") {
"Cmd+Shift+F9"
} else {
"Ctrl+Shift+F9"
};
/// Editor-pane Peek References: `Alt+Shift+F12` (#616). Alt is croft's
/// "peek" modifier on the F12 family (Alt+F12 peeks the definition), so
/// this must be checked before Go to References, which ignores Alt.
fn is_peek_references_key(key: KeyEvent) -> bool {
matches!(key.code, KeyCode::F(12))
&& key.modifiers.contains(KeyModifiers::SHIFT)
&& key.modifiers.contains(KeyModifiers::ALT)
&& !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. `get`, since a
// caller that shrank the sheet may not have clamped the caret yet.
while data.scroll_col < data.cur_col {
let Some(span) = data.col_widths.get(data.scroll_col..=data.cur_col) else {
break;
};
let used: usize = span.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 enc = old.text_encoding;
let head = crate::git::read_bytes_at_head(root, rel).ok()?;
let head = crate::widgets::editor::decode_blob(&head, enc)?;
let right = std::fs::read(&old.right_path).ok()?;
let right = crate::widgets::editor::decode_blob(&right, enc)?;
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.text_encoding = old.text_encoding;
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,
}
}
}
/// The interpreter that runs Python code in `dir`: the nearest venv up to
/// `workspace_root` ([`find_python_venv`]), else [`project_python`]. Live
/// Run and the debugger's program both use it, so a script debugs against
/// the same installed packages it runs with (#864).
fn project_python_for(dir: &Path, workspace_root: &Path) -> PathBuf {
find_python_venv(dir, workspace_root)
.map(|(py, _)| py)
.unwrap_or_else(|| project_python(workspace_root))
}
/// The interpreter a debugged Python program in `dir` runs under (#864):
/// the one Run would use ([`project_python_for`]) when it exists, a venv or
/// a `python3` on `path_var`. None otherwise, and the launch keeps the debug
/// venv's own python, where the program always ran, rather than a bare
/// `python3` that cannot start.
fn debuggee_python(
dir: &Path,
workspace_root: &Path,
path_var: Option<&std::ffi::OsStr>,
) -> Option<PathBuf> {
find_python_venv(dir, workspace_root)
.map(|(py, _)| py)
.or_else(|| project_python_on(workspace_root, path_var))
}
/// What a Python debug launch says about the interpreter its program runs
/// under (#864). Err is the refusal when debugpy cannot run there at all;
/// Some is the clause naming one older than attach's 3.14 floor, `under
/// Python 3.12 (.venv); attach needs 3.14+`; None is for 3.14+, or a version
/// that cannot be read (the launch then reports for itself).
fn debuggee_python_note(python: &Path) -> Result<Option<String>, String> {
use crate::dap::install::{DEBUGPY_MIN_PYTHON, python_version, pyvenv_cfg};
use crate::dap::remote_attach::MIN_ATTACH_VERSION;
let Some(version) = python_version(python) else {
return Ok(None);
};
let (major, minor) = (version.major, version.minor);
// A venv by its folder name, as the issue's `.venv`; else the path.
let label = pyvenv_cfg(python)
.and_then(|cfg| Some(cfg.parent()?.file_name()?.to_string_lossy().into_owned()))
.unwrap_or_else(|| python.display().to_string());
// Minor versions only: a 3.10.0 debuggee meets debugpy's 3.10 floor.
if (major, minor) < (DEBUGPY_MIN_PYTHON.major, DEBUGPY_MIN_PYTHON.minor) {
return Err(format!(
"Python {major}.{minor} ({label}) is too old to debug: debugpy needs {}.{}+",
DEBUGPY_MIN_PYTHON.major, DEBUGPY_MIN_PYTHON.minor
));
}
if !version.supports_remote_attach() {
return Ok(Some(format!(
"under Python {major}.{minor} ({label}); attach needs {}.{}+",
MIN_ATTACH_VERSION.major, MIN_ATTACH_VERSION.minor
)));
}
Ok(None)
}
/// `lead` followed by the note on the debuggee's interpreter, if any (#864).
fn with_python_note(lead: String, note: Option<&str>) -> String {
match note {
Some(note) => format!("{lead} {note}"),
None => lead,
}
}
/// The interpreter a debugpy `launch` request runs its program under: its
/// `python` (a path, or a command line whose first word is one) or legacy
/// `pythonPath`. A relative path with a folder in it is found where debugpy
/// starts it, so the version check runs the same file (#864 review): the
/// request's `cwd`, else the folder of a `program`, else `adapter_dir`, the
/// folder the adapter runs in. A bare name is left to PATH, as debugpy
/// leaves it.
fn launch_request_python(request: &serde_json::Value, adapter_dir: &Path) -> Option<PathBuf> {
let args = &request["arguments"];
let python = args.get("python").or_else(|| args.get("pythonPath"))?;
let python = PathBuf::from(python.as_str().or_else(|| python.get(0)?.as_str())?);
if python.is_absolute() || python.components().count() < 2 {
return Some(python);
}
let program_dir = args["program"]
.as_str()
.and_then(|p| Path::new(p).parent())
.filter(|dir| !dir.as_os_str().is_empty());
let launch_dir = match args["cwd"].as_str() {
Some(cwd) => adapter_dir.join(cwd),
None => program_dir.map_or_else(|| adapter_dir.to_path_buf(), |d| adapter_dir.join(d)),
};
Some(launch_dir.join(python))
}
/// The interpreter Debug Test's pytest runs under once any debug-test
/// config is applied (#1398): the request's own `python`, a config's
/// included, but not the debug venv's stand-in for a project that has no
/// interpreter of its own, which was never the project's to report on.
fn debug_test_python(
request: &serde_json::Value,
root: &Path,
adapter_py: &Path,
project_found: bool,
) -> Option<PathBuf> {
launch_request_python(request, root).filter(|py| project_found || py != adapter_py)
}
/// The interpreter a launch.json Python config's program runs under when
/// the config names none (#864): resolved from the program's directory,
/// or from `cwd` for a `module` launch, as [`debuggee_python`] does, with
/// `adapter_python` (the debug venv's) only when that finds nothing.
fn config_project_python(
rc: &crate::dap::configs::ResolvedConfig,
cwd: &Path,
workspace_root: &Path,
adapter_python: &Path,
) -> PathBuf {
// A `module` launch drops `program` from the request (debugpy refuses
// both), so the program's directory says nothing about what runs.
let program = rc.program.as_deref().filter(|_| rc.module.is_none());
let dir = program
.map(|p| crate::dap::configs::absolute_in(p, cwd))
.and_then(|p| p.parent().map(Path::to_path_buf))
.unwrap_or_else(|| cwd.to_path_buf());
debuggee_python(&dir, workspace_root, std::env::var_os("PATH").as_deref())
.unwrap_or_else(|| adapter_python.to_path_buf())
}
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 {
crate::remote::running_over_ssh()
}
/// 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);
/// Run `cmd` for at most `budget`, collecting stdout; None when it could not
/// start or ran out of time (it is then killed and reaped). For the few
/// short commands that still run on the UI thread.
fn bounded_output(
cmd: &mut std::process::Command,
budget: std::time::Duration,
) -> Option<(std::process::ExitStatus, Vec<u8>)> {
use std::io::Read;
let deadline = std::time::Instant::now() + budget;
let mut child = cmd
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::null())
.spawn()
.ok()?;
let mut stdout = child.stdout.take()?;
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let mut buf = Vec::new();
let _ = stdout.read_to_end(&mut buf);
let _ = tx.send(buf);
});
let bytes = rx.recv_timeout(budget).ok();
loop {
match child.try_wait() {
Ok(Some(status)) => return bytes.map(|b| (status, b)),
Ok(None) if bytes.is_some() && std::time::Instant::now() < deadline => {
std::thread::sleep(std::time::Duration::from_millis(5));
}
_ => {
let _ = child.kill();
let _ = child.wait();
return 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"),
}
}
/// What the startup status says when the agent hook socket could not be
/// bound (#1368), so a hook that is never answered is not a mystery.
/// `None` when another croft already serves this workspace: that one
/// answers its agents, by design.
fn hook_bind_status(e: &std::io::Error) -> Option<String> {
(e.kind() != std::io::ErrorKind::AddrInUse)
.then(|| format!("Agent edit approvals are unavailable: {e}"))
}
/// 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());
}
}
}
/// The tail of a recorded frame (#356) that leaves a player's cursor where
/// the pane's was: moved to its `(row, col)` and shown, or hidden when the
/// program hid it. Always one or the other, so a frame never inherits the
/// previous frame's cursor state.
fn cursor_suffix(cursor: Option<(u16, u16)>) -> String {
match cursor {
Some((row, col)) => format!("\u{1b}[{};{}H\u{1b}[?25h", row + 1, col + 1),
None => String::from("\u{1b}[?25l"),
}
}
/// 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);
/// The per-workspace agent review queues (#345), keyed by
/// [`agent_ledger_key`].
fn agent_ledger_store_path() -> PathBuf {
croft_cache_dir().join("agent_lane.json")
}
/// A workspace's key in the agent review store: its canonical root, so the
/// save and the load agree however the root was spelled.
fn agent_ledger_key(root: &Path) -> String {
std::fs::canonicalize(root)
.unwrap_or_else(|_| root.to_path_buf())
.display()
.to_string()
}
/// What a CodeQL run evaluates (#578): the whole query, a quick
/// evaluation of part of it, or a published pack named by its reference.
enum CodeqlRunMode {
Whole,
Quick(crate::codeql_qs::QuickEval),
Pack,
}
/// What "CodeQL: Check for CLI Updates" learns (#578): the latest release,
/// or why it could not be read, and the version in use when it runs.
type CodeqlCliCheck = (Result<String, String>, Option<String>);
/// Query help being rendered (#578): where the outcome arrives, the
/// Markdown file to preview, and the query's name.
type CodeqlQueryHelp = (
std::sync::mpsc::Receiver<Result<(), String>>,
PathBuf,
String,
);
/// A `codeql pack` install or download in flight (#578): where its outcome
/// arrives, and the status lines for success and for failure.
type CodeqlPackJob = (
std::sync::mpsc::Receiver<Result<(), String>>,
String,
String,
);
/// A CodeQL document being made (#578): the file it writes, or why not,
/// and the status lines for success and for failure.
type CodeqlDocJob = (
std::sync::mpsc::Receiver<Result<PathBuf, String>>,
String,
String,
);
/// An evaluator log being read for its viewer (#578): the predicates, or
/// why not, and the query whose log it is.
type CodeqlLogViewerJob = (
std::sync::mpsc::Receiver<Result<Vec<crate::codeql_evallog::Predicate>, String>>,
String,
);
/// The rows of the Add CodeQL Database picker and the side-bar action each
/// runs.
const CODEQL_DB_SOURCES: [(crate::widgets::codeql::Action, &str); 4] = [
(
crate::widgets::codeql::Action::AddDatabaseFromFolder,
"From a folder",
),
(
crate::widgets::codeql::Action::AddDatabaseFromArchive,
"From an archive",
),
(
crate::widgets::codeql::Action::AddDatabaseFromUrl,
"From a URL (as a zip file)",
),
(
crate::widgets::codeql::Action::AddDatabaseFromGithub,
"From GitHub",
),
];
/// The Model Editor's endpoints being read (#578): the endpoints, or why
/// not, and the database and language they are for.
type CodeqlModelJob = (
std::sync::mpsc::Receiver<Result<Vec<crate::codeql_model::Endpoint>, String>>,
String,
String,
);
/// A CodeQL database upgrade or cache cleanup in flight (#578): where its
/// outcome arrives, which job it is, and the database's name and folder.
type CodeqlUpgrade = (
std::sync::mpsc::Receiver<Result<(), String>>,
crate::codeql_query::DbJob,
String,
PathBuf,
);
/// What fetching a variant analysis's results made (#578): the combined
/// SARIF log and table, how many repositories they hold, and the
/// repositories whose results could not be fetched, with why.
struct VariantResultFiles {
sarif: Option<PathBuf>,
csv: Option<PathBuf>,
repos: usize,
failed: Vec<(String, String)>,
}
type VariantResults = Result<VariantResultFiles, String>;
/// Where an export of variant analysis results went (#578).
struct VariantExport {
/// The summary file of a folder export.
summary: Option<PathBuf>,
/// The gist a gist export made.
gist: Option<String>,
repos: usize,
failed: Vec<(String, String)>,
}
/// The selected SARIF result (log, run, result) and the open files that
/// step marks were last drawn for (#577).
type SarifStepSignature = (Option<(usize, usize, usize)>, Vec<PathBuf>);
/// One unfinished variant analysis and what reading its progress gave.
type CodeqlRunPoll = (
crate::codeql_submit::Submitted,
Result<crate::codeql_submit::RunProgress, String>,
);
/// How often unfinished variant analyses are read again (#578).
const CODEQL_VARIANT_POLL: std::time::Duration = std::time::Duration::from_secs(30);
/// How long after submitting a variant analysis croft follows it (#578).
const CODEQL_VARIANT_FOLLOW: std::time::Duration = std::time::Duration::from_secs(7 * 24 * 3600);
/// A GitHub Code Search in flight: the variant analysis list its
/// repositories go into, and its outcome: the repositories found, and why
/// a page after the first failed, cutting the results short.
type CodeqlCodeSearch = (
String,
std::sync::mpsc::Receiver<Result<(Vec<String>, Option<String>), String>>,
);
/// The directory this croft keeps hot-exit backups and sticky notes under
/// (#1578): `state`, after moving in what an earlier croft kept under
/// `cache`, which cache cleaners are free to delete. Run at every launch,
/// so a backup an older croft still writes to the cache is taken over too,
/// once that croft is gone (its own exit removes only the cache copy).
/// Notes are merged note by note into the state store, since an older
/// window may still be adding to its cache copy; lock files stay.
pub(crate) fn user_data_dir(cache: &Path, state: &Path) -> PathBuf {
crate::hot_exit::move_tree(
&cache.join("hot-exit"),
&state.join("hot-exit"),
&crate::hot_exit::owned_by_a_running_croft,
);
crate::sticky_notes::merge_stores(&cache.join("notes"), &state.join("notes"));
crate::hot_exit::move_tree(&cache.join("notes"), &state.join("notes"), &|p| {
p.extension().is_some_and(|x| x == "lock")
});
state.to_path_buf()
}
/// The character index in `line` at which `units` UTF-16 code units have
/// passed; past the end it is the line's length.
fn utf16_col_to_char_in(line: &str, units: i64) -> usize {
let mut seen = 0i64;
line.chars()
.take_while(|c| {
seen += c.len_utf16() as i64;
seen <= units
})
.count()
}
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"))
}
/// How long a Keyboard Shortcuts prompt waits for its chord.
const SHORTCUT_RECORD_WINDOW: std::time::Duration = std::time::Duration::from_secs(15);
/// Where `path` is after `renames` ran: under a moved file or folder, its
/// new place; anywhere else, unchanged.
fn moved_path(path: &Path, renames: &[crate::lsp::manager::FileRenameOp]) -> PathBuf {
renames
.iter()
.find_map(|r| path.strip_prefix(&r.old).ok().map(|rest| r.new.join(rest)))
.map(|p| p.components().collect())
.unwrap_or_else(|| path.to_path_buf())
}
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",
SidebarView::CodeQL => "CodeQL",
}
}
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),
"CodeQL" => Some(SidebarView::CodeQL),
_ => 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
));
}
}
}
/// The trust-on-first-use gate on a contributed command's MCP tool: an
/// error naming the recovery when `fingerprint` differs from the one first
/// recorded for `command_id` under `config_dir`.
fn mcp_tool_trust(
config_dir: &Path,
command_id: &str,
tool: &str,
fingerprint: &str,
) -> Result<(), String> {
if crate::prefs::trust_mcp_tool_in(config_dir, command_id, fingerprint) {
return Ok(());
}
Err(format!(
"refusing to run: the '{tool}' tool definition changed since you approved it (possible rug-pull); toggle the extension off and on to re-approve"
))
}
/// File one server's diagnostics batch in the store. An empty batch is the
/// server saying "all clear" for its findings; a path no server reports on
/// any more leaves the store. Files never opened (a workspace pull, a
/// flycheck) and deleted ones used to keep an empty entry each for the rest
/// of the session (#694).
fn store_diagnostics_update(
store: &mut std::collections::HashMap<
PathBuf,
std::collections::HashMap<String, Vec<crate::lsp::manager::Diagnostic>>,
>,
u: crate::lsp::manager::DiagnosticsUpdate,
) {
let key = diagnostics_store_key(&u);
if u.diagnostics.is_empty() {
if let Some(by_server) = store.get_mut(&u.path) {
by_server.remove(&key);
if by_server.is_empty() {
store.remove(&u.path);
}
}
} else {
store.entry(u.path).or_default().insert(key, u.diagnostics);
}
}
/// 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,
config_dir: &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);
mcp_tool_trust(
config_dir,
&resolved.command_id,
&resolved.tool,
&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 shift = key.modifiers.contains(KeyModifiers::SHIFT);
// xterm's modifier parameter: 1 + Shift 1 + Alt 2 + Ctrl 4. A modified
// cursor or editing key carries it (`Ctrl+Left` is `\e[1;5D`); sending
// the plain sequence dropped the modifier, so word motion and selection
// bindings in shells and editors never fired.
let m = 1 + u8::from(shift) + 2 * u8::from(alt) + 4 * u8::from(ctrl);
let cursor = |app: &'static [u8], normal: &'static [u8], fin: char| {
if m > 1 {
format!("\x1b[1;{m}{fin}").into_bytes()
} else if app_cursor {
app.to_vec()
} else {
normal.to_vec()
}
};
let tilde = |n: u8| {
if m > 1 {
format!("\x1b[{n};{m}~").into_bytes()
} else {
format!("\x1b[{n}~").into_bytes()
}
};
let esc_if_alt = |mut v: Vec<u8>| {
if alt && !v.is_empty() {
v.insert(0, 0x1b);
}
v
};
match key.code {
Enter => esc_if_alt(vec![b'\r']),
Tab => vec![b'\t'],
BackTab => b"\x1b[Z".to_vec(),
// Alt+Backspace deletes a word in readline; Ctrl+Backspace sends ^H.
Backspace => esc_if_alt(vec![if ctrl { 0x08 } else { 0x7f }]),
Esc => vec![0x1b],
// Alt alone on Left/Right keeps readline's word motion (`\eb`/`\ef`),
// which every shell binds; other modifiers use the xterm form.
Right if alt && !ctrl && !shift => b"\x1bf".to_vec(),
Left if alt && !ctrl && !shift => b"\x1bb".to_vec(),
Up => cursor(b"\x1bOA", b"\x1b[A", 'A'),
Down => cursor(b"\x1bOB", b"\x1b[B", 'B'),
Right => cursor(b"\x1bOC", b"\x1b[C", 'C'),
Left => cursor(b"\x1bOD", b"\x1b[D", 'D'),
Home => cursor(b"\x1bOH", b"\x1b[H", 'H'),
End => cursor(b"\x1bOF", b"\x1b[F", 'F'),
PageUp => tilde(5),
PageDown => tilde(6),
Insert => tilde(2),
Delete => tilde(3),
F(n) => match n {
1..=4 => {
let fin = b"PQRS"[usize::from(n - 1)] as char;
if m > 1 {
format!("\x1b[1;{m}{fin}").into_bytes()
} else {
format!("\x1bO{fin}").into_bytes()
}
}
5 => tilde(15),
6 => tilde(17),
7 => tilde(18),
8 => tilde(19),
9 => tilde(20),
10 => tilde(21),
11 => tilde(23),
12 => tilde(24),
_ => Vec::new(),
},
Char(c) => {
if ctrl {
let lc = c.to_ascii_lowercase();
let byte = if lc.is_ascii_lowercase() {
Some((lc as u8) - b'a' + 1)
} else {
match c {
' ' | '@' | '2' => Some(0x00),
'[' | '3' => Some(0x1b),
'\\' | '4' => Some(0x1c),
']' | '5' => Some(0x1d),
'^' | '6' => Some(0x1e),
'/' | '_' | '7' => Some(0x1f),
'8' | '?' => Some(0x7f),
_ => None,
}
};
// Ctrl+Alt+letter is ESC then the control byte.
byte.map_or_else(Vec::new, |b| esc_if_alt(vec![b]))
} else {
let mut buf = [0u8; 4];
esc_if_alt(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 undo group the stream's edits share (#1207), so the whole
/// stream undoes in one step.
undo_group: u64,
}
/// A fresh remote undo group id (#1207), unique for the process.
fn next_remote_undo_group() -> u64 {
use std::sync::atomic::{AtomicU64, Ordering};
static NEXT: AtomicU64 = AtomicU64::new(1);
NEXT.fetch_add(1, Ordering::Relaxed)
}
/// 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 tree-sitter grammar for `path`, by extension: what symbol tabs
/// (#369) parse to re-find a renamed or displaced symbol.
fn syntax_kind_of(path: &Path) -> Option<crate::highlight::LangKind> {
crate::highlight::lang_for_path(path)
}
/// `path` relative to `repo_root` with forward slashes, as GitHub names it.
fn repo_relative(repo_root: &Path, path: &Path) -> Option<String> {
let rel = path.strip_prefix(repo_root).ok()?;
Some(
rel.components()
.map(|c| c.as_os_str().to_string_lossy())
.collect::<Vec<_>>()
.join("/"),
)
}
/// 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>>;
/// The status a run gesture gets while another run is in flight (#1534).
const TEST_RUN_IN_PROGRESS: &str = "A test run is in progress (s in Testing stops it)";
pub fn run(
root: PathBuf,
restore_session: Option<PathBuf>,
open_file: Option<PathBuf>,
open_at: Option<(usize, usize)>,
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);
// Hand the heap a large file's parse passes freed back to the OS
// (#1707), so croft doesn't stay resident at the parse's peak.
crate::mem_relief::start();
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 hosted default pane (#694) is recorded at once, restored or not.
app.save_terminal_session_if_hosted();
// 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() {
match crate::session_state::SessionState::load(session_path) {
Ok(state) => {
app.apply_session_state(&state);
let _ = std::fs::remove_file(session_path);
// The hot-exit backup follows what the relaunch brought
// back (#862), at once rather than after the first edit.
let _ = app.write_hot_exit();
}
// Kept: it may hold the only copy of unsaved text.
Err(e) => {
app.status = format!(
"Could not restore the session ({e:#}); it is kept at {}",
session_path.display()
);
}
}
} else {
// A normal launch brings back what hot exit kept of this workspace
// when croft last ended without a clean quit (#862).
app.restore_hot_exit();
}
// `--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() {
// `croft file:line[:col]` (#1606).
if app.open_file_at_launch(file)
&& let Some((row, col)) = open_at
{
app.without_auto_hide(|app| app.place_caret_at(row, col));
}
}
// A `croft://` link (#359) names what to land on.
match std::env::var("CROFT_FOCUS").as_deref() {
Ok("terminal") => app.focus_pane(Pane::Terminal),
Ok("editor") => app.focus_pane(Pane::Editor),
// The approval popup is modal and opens by itself for a waiting
// edit, so landing on it needs no focus change; say so when there
// is nothing to land on (answered or expired on the way here).
Ok("approval") => {
app.drain_hook_requests();
if app.approvals.is_empty() {
app.status = String::from("No agent edit is waiting for approval");
}
}
_ => {}
}
app.start_update_watch_if_remote();
app.start_drift_probe_if_local();
app.start_update_check_if_local();
// `croft pr <n>` (#365): open the review once the app is up.
if let Some(selector) = crate::pr_review::take_startup_pr() {
app.start_pr_review(selector);
}
// `croft demo` (#377): start the tour once the app is up.
if crate::tour::take_startup_demo() {
app.start_demo();
}
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();
crate::widgets::terminal::SIXEL_HOST
.store(app.sixel_supported, std::sync::atomic::Ordering::Relaxed);
}
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();
app.kitty_keys = kbd_enhanced;
{
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(theme_host_colors_seq(theme).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);
// An owner's goodbye goes out now (#1147): the drop-to-local and
// self-update exits below never drop the App.
drop(app.collab.take());
// 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();
// A test run still in flight ends with croft (#1534): its runner was
// left running under PID 1.
if app.testing.is_busy() {
app.test_worker.cancel();
}
// Quitting mid-debug ends the program as Stop Debugging does (#1536):
// nothing sent `disconnect` here, and the debuggee outlived croft.
// The teardowns run while the terminal is restored and are joined
// below, before any exit path.
if !app.debug_sessions.is_empty() {
app.debug_stop();
}
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,
DisableFocusChange,
)
.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();
crate::dap::transport::join_teardowns();
// What croft could not do on the way out, said once the shell is the
// user's again (#862).
for note in app.exit_notes.drain(..) {
eprintln!("croft: {note}");
}
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();
// Saved once already when the relaunch was armed; this refresh is
// best-effort, and a failure leaves that copy in place.
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, 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) and focus reports (1004), 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[?1004l\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,
DisableFocusChange,
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(())
}
/// Fingerprints of the text cells under each large post-frame image this
/// frame (see [`overlay::ImageOverlay::needs_emit`]).
struct ImageUnderlays {
/// Around each activity-bar and toolbar icon, for iTerm2's keepalive.
activity: Vec<u64>,
editor: [u64; 2],
terminal: u64,
markdown: u64,
minimap: u64,
}
/// A fingerprint of the cells of `buf` in the given rectangle: symbols,
/// colours and modifiers, so any write ratatui makes there changes it.
fn cells_fingerprint(buf: &ratatui::buffer::Buffer, x: u16, y: u16, w: u16, h: u16) -> u64 {
use std::hash::{Hash, Hasher};
let mut hasher = std::collections::hash_map::DefaultHasher::new();
let area = buf.area;
let (x0, y0) = (x.max(area.x), y.max(area.y));
let x1 = x.saturating_add(w).min(area.x + area.width);
let y1 = y.saturating_add(h).min(area.y + area.height);
(x0, y0, x1, y1).hash(&mut hasher);
for row in y0..y1 {
for col in x0..x1 {
let cell = &buf[(col, row)];
cell.symbol().hash(&mut hasher);
(cell.fg, cell.bg, cell.modifier).hash(&mut hasher);
}
}
hasher.finish()
}
impl App {
/// This frame's [`ImageUnderlays`], read from the buffer just drawn.
fn image_underlays(&self, buf: &ratatui::buffer::Buffer) -> ImageUnderlays {
// A one-cell ring around each icon's block (the widest is 4x2).
let activity: Vec<u64> = self
.overlays
.activity
.last_positions()
.iter()
.map(|&(x, y)| cells_fingerprint(buf, x.saturating_sub(1), y.saturating_sub(1), 6, 4))
.collect();
// Kitty keeps pictures on their own layer: text written into the
// cells never deletes a placement (only a delete command or a screen
// clear does, and both forget what was sent). So on Kitty the cells
// beneath do not matter, and streaming output beside an image sends
// nothing.
if self.inline_protocol == crate::iterm2_inline::InlineImageProtocol::Kitty {
return ImageUnderlays {
activity,
editor: [0, 0],
terminal: 0,
markdown: 0,
minimap: 0,
};
}
let o = &self.overlays;
let editor = |side: usize| {
o.editor[side].layout().map_or(0, |l| {
cells_fingerprint(buf, l.cell_x, l.cell_y, l.cell_w, l.cell_h)
})
};
ImageUnderlays {
activity,
editor: [editor(0), editor(1)],
terminal: o.terminal_image.layout().map_or(0, |l| {
cells_fingerprint(buf, l.cell_x, l.cell_y, l.cell_w, l.cell_h)
}),
markdown: o.markdown_image.layout().map_or(0, |l| {
cells_fingerprint(buf, l.cell_x, l.cell_y, l.cell_w, l.cell_h)
}),
minimap: o.minimap.layout().map_or(0, |l| {
cells_fingerprint(buf, l.cell_x, l.cell_y, l.cell_w, l.cell_h)
}),
}
}
/// Whether a small chrome image must be sent this frame (#682). These
/// used to go out after every redraw, so a keystroke re-sent each one
/// over SSH. Now one goes out when it is new, changed or moved, and on
/// iTerm2 and Sixel also when the cells around it were repainted (iTerm2
/// evicts an image under neighbouring traffic, and a cell-buffer picture
/// is erased by writes into it). Kitty keeps images on their own layer.
fn chrome_image_due(&mut self, key: &'static str, image: &str, at: Rect) -> bool {
use std::hash::{Hash, Hasher};
let mut h = std::collections::hash_map::DefaultHasher::new();
image.hash(&mut h);
(at.x, at.y, at.width, at.height).hash(&mut h);
if self.inline_protocol != crate::iterm2_inline::InlineImageProtocol::Kitty
&& let Some(buf) = &self.drawn_buffer
{
cells_fingerprint(
buf,
at.x.saturating_sub(1),
at.y.saturating_sub(1),
at.width.saturating_add(2),
at.height.saturating_add(2),
)
.hash(&mut h);
}
let sig = h.finish();
self.chrome_seen.insert(key);
self.chrome_sent.insert(key, sig) != Some(sig)
}
/// Drop the record of chrome images that were not on screen this frame,
/// so they are sent again when they come back.
fn end_chrome_flush(&mut self) {
let seen = std::mem::take(&mut self.chrome_seen);
self.chrome_sent.retain(|k, _| seen.contains(k));
}
/// The screen was wiped or its images evicted: every large image is
/// sent again on the next flush.
fn forget_sent_images(&mut self) {
self.chrome_sent.clear();
self.overlays.activity.forget_sent();
for side in 0..2 {
self.overlays.editor[side].forget_sent();
}
self.overlays.terminal_image.forget_sent();
self.overlays.markdown_image.forget_sent();
self.overlays.minimap.forget_sent();
}
}
/// 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;
}
// Same-file tabs agree before the watcher is read: a save from one
// symbol tab leaves its siblings holding the saved text, so the
// change event reads as their own write, not a conflict (#369).
let symbol_views_settled = app.sync_symbol_views();
// 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 codeql_changed = app.drain_codeql_run()
| app.drain_codeql_ast()
| app.drain_codeql_model()
| app.drain_codeql_doc()
| app.drain_codeql_upgrade()
| app.drain_codeql_version()
| app.drain_codeql_log_summary()
| app.drain_codeql_log_viewer()
| app.drain_codeql_perf_compare()
| app.drain_codeql_query_help()
| app.drain_codeql_pack_job()
| app.drain_codeql_db_job()
| app.drain_codeql_cli_download()
| app.drain_codeql_cli_check()
| app.drain_codeql_code_search()
| app.drain_codeql_variant_submit()
| app.poll_codeql_variant_runs()
| app.drain_codeql_variant_results()
| app.drain_codeql_variant_export()
| app.drain_codeql_queries();
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 hook_changed = app.drain_hook_requests()
| app.poll_pr_gh()
| app.poll_pr_checkout()
| app.poll_code_scanning();
app.sync_approval_check();
app.persist_agent_ledger(false);
let kernel_changed = app.poll_notebook_kernels();
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 symbol_views_changed = app.sync_symbol_views() | symbol_views_settled;
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();
app.tick_hot_exit(std::time::Instant::now());
let highlights_changed = app.poll_highlights();
let live_run_changed =
app.tick_live_run() | app.sync_markdown_scroll() | app.tick_minimap();
app.tick_code_lens();
let code_lens_changed = app.tick_config_watch()
| app.drain_lsp_code_lens()
| app.drain_search_editor()
| app.tick_inline_complete()
| app.drain_review_ops();
let connect_changed = app.poll_connect_dialog() | app.drain_scrub_views();
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.send_due_completion_reask();
let markdown_lint_changed = app.sync_markdown_lint();
let sarif_diagnostics_changed = app.sync_sarif_diagnostics();
app.sync_sarif_selection_to_cursor();
app.sync_sarif_step_marks();
app.refresh_sarif_preview();
app.poll_sarif_download();
app.sync_git_gutters();
app.sync_blame();
app.sync_provenance();
let blame_changed = app.drain_blame() | app.drain_git_net() | app.drain_git_view();
// 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() | app.tick_file_moves();
let format_changed = app.drain_lsp_format() | app.drain_prettier_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()
| app.drain_pending_cargo_launch();
// 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);
}
if app.testing.take_cancelled() {
app.status = String::from("Test run cancelled");
}
// One notification per red run (#358), from the latch the panel
// sets when a run ends, never per test case.
let coverage_changed = app.sync_coverage();
let watch_changed = app.tick_test_watch();
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();
let zen_hint_changed = app.expire_zen_hint(std::time::Instant::now());
// 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
|| zen_hint_changed
|| fs_changed
|| mcp_changed
|| pair_changed
|| tests_changed
|| coverage_changed
|| watch_changed
|| blink_changed
|| spinner_changed
|| ext_index_changed
|| codeql_changed
|| search_changed
|| log_index_changed
|| remote_changed
|| pulls_changed
|| view_changed
|| hook_changed
|| kernel_changed
|| ports_changed
|| session_presence_changed
|| session_typing_changed
|| collab_changed
|| symbol_views_changed
|| bells_changed
|| captures_changed
|| labels_changed
|| auto_save_changed
|| highlights_changed
|| live_run_changed
|| code_lens_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
|| markdown_lint_changed
|| sarif_diagnostics_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();
app.forget_sent_images();
}
let draw_start = std::time::Instant::now();
let drawn = terminal.draw(|f| app.render_for_terminal(f))?;
let mut underlays = app.image_underlays(drawn.buffer);
app.drawn_buffer = Some(drawn.buffer.clone());
// 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();
app.forget_sent_images();
let drawn = terminal.draw(|f| app.render_for_terminal(f))?;
underlays = app.image_underlays(drawn.buffer);
app.drawn_buffer = Some(drawn.buffer.clone());
}
// 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(&underlays.activity);
// Active editor image preview: baked once, and sent after
// ratatui's diff only when it could be missing from the screen
// (`ImageOverlay::needs_emit`), never on every frame: a picture
// is megabytes, and over SSH resending it per keystroke stalls
// the session (#682). One slot per editor split column (0 =
// left, 1 = right); when not split only slot 0 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,
)
{
if !app.overlays.editor[side].needs_emit(underlays.editor[side]) {
continue;
}
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);
app.overlays.editor[side].mark_sent_over(underlays.editor[side]);
} else {
app.overlays.editor[side].forget_sent();
}
}
// Terminal-pane inline image (captured imgcat output): same
// bake-once / send-when-missing 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,
)
{
if app.overlays.terminal_image.needs_emit(underlays.terminal) {
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();
app.overlays
.terminal_image
.mark_sent_over(underlays.terminal);
}
} else {
app.overlays.terminal_image.forget_sent();
}
// Markdown-preview inline image (#176): same bake-once /
// send-when-missing 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,
)
{
if app.overlays.markdown_image.needs_emit(underlays.markdown) {
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();
app.overlays
.markdown_image
.mark_sent_over(underlays.markdown);
}
} else {
app.overlays.markdown_image.forget_sent();
}
// Editor minimap: same bake-once / send-when-missing overlay,
// painted after ratatui's diff so the raster lands on the strip.
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,
)
{
if app.overlays.minimap.needs_emit(underlays.minimap) {
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();
app.overlays.minimap.mark_sent_over(underlays.minimap);
}
} else {
app.overlays.minimap.forget_sent();
}
// 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();
app.end_chrome_flush();
// 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::FocusLost => {
app.on_window_focus_lost();
}
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
// updater relaunch 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(&reattach_reassert_seq(app.theme));
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(())
}