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 agents_collab;
mod bottom_panel;
mod click;
mod code_scanning;
mod codeql;
mod commands;
mod completion;
mod cursor_blink;
mod debugger;
mod diff_merge;
mod editor_input;
mod editor_layout;
mod editor_tabs;
mod explorer;
mod frame;
mod fs_watch;
mod git_worker;
mod host_integration;
mod hover;
mod inline_images;
mod key_input;
mod language_servers;
mod memory_report;
mod menus;
mod message_card;
mod mouse_input;
mod nav;
mod overlay;
mod perf_hud;
mod popups;
mod prompts;
mod remote_sessions;
mod review;
mod right_click;
mod runners;
mod save_restore;
mod scm;
mod screencast;
mod search;
mod settings;
pub(crate) mod sidebar_dwell;
mod terminal_panes;
mod terminal_tools;
mod tick;
mod viewers;
mod welcome;
mod welcome_screen;
mod workbench;
use agents_collab::*;
use bottom_panel::*;
use click::{ClickTracker, ModifiedClickTracker};
use code_scanning::*;
use codeql::*;
#[cfg(test)]
use commands::*;
use completion::*;
use cursor_blink::CursorBlink;
use debugger::*;
use editor_input::*;
use editor_tabs::*;
use explorer::*;
use frame::*;
use fs_watch::FsWatch;
use git_worker::GitWorker;
pub(crate) use host_integration::reattach_reassert_seq;
pub(crate) use host_integration::reset_host_colors_seq;
pub(crate) use host_integration::reset_session_bg_seq;
pub(crate) use host_integration::takeover_mode_seq;
use host_integration::*;
use hover::{HOVER_DELAY, HoverDwell};
use inline_images::*;
use key_input::*;
use language_servers::*;
use menus::*;
use nav::{NavHistory, NavLoc};
use overlay::OverlayManager;
use perf_hud::PerfHud;
use prompts::*;
use remote_sessions::*;
use review::*;
use runners::*;
use save_restore::*;
use scm::*;
use screencast::Screencast;
use search::*;
use settings::*;
use sidebar_dwell::{AUTO_HIDE_DWELL, SidebarDwell};
use terminal_panes::*;
#[cfg(test)]
use terminal_tools::*;
use tick::*;
use viewers::*;
use welcome::WelcomeState;
#[cfg(test)]
use welcome_screen::*;
pub(crate) use workbench::PanelAlignment;
pub(crate) use workbench::QuickInputPosition;
pub(crate) use workbench::SideBarPosition;
use workbench::*;
use crate::lsp::manager::CompletionTrigger;
use crate::lsp::manager::{diagnostics_by_source, diagnostics_source, diagnostics_store_key};
use crate::paths::croft_cache_dir;
use crate::proc::info::cwd_of_pid;
use crate::theme::BRAND_ORANGE;
use crate::dependencies::{Dependency, Ecosystem};
use crate::search::SearchRequest;
use crate::widgets::{
dependencies::DependenciesPanel,
editor::{Editor, EditorTabs},
file_tree::FileTree,
open_editors::{OpenEditorItem, OpenEditorsPanel},
outline::OutlinePanel,
remote::RemotePanel,
run_debug::RunDebugPanel,
search::{SearchPanel, SearchProgress},
source_control::SourceControlPanel,
terminal::{MouseAction, MouseButtonKind, MouseMods, PtyTerminal},
timeline::TimelinePanel,
};
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum SidebarView {
Explorer,
Search,
SourceControl,
Remote,
RunDebug,
Extensions,
Testing,
CodeQL,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub struct ExplorerViewVisibility {
flags: crate::prefs::ExplorerViewsPrefs,
}
struct PendingSelectionRanges {
id: u64,
path: PathBuf,
seq: u64,
presses: usize,
positions: Vec<(u32, u32)>,
}
#[derive(Clone, Debug)]
struct BookmarkTarget {
group: usize,
tab: usize,
path: PathBuf,
line: usize,
}
#[derive(Clone, Debug)]
enum ShortcutCapture {
Recording {
cmd: crate::widgets::command_palette::Command,
since: std::time::Instant,
},
Confirming {
cmd: crate::widgets::command_palette::Command,
chord: KeyEvent,
owners: Vec<crate::widgets::command_palette::Command>,
},
}
#[derive(Clone, Copy, Debug, Default)]
struct PreZenLayout {
activity_bar: bool,
status_bar: bool,
side_bar: bool,
secondary_side_bar: bool,
panel: bool,
}
#[derive(Clone, Copy, Default)]
struct LayoutIconAreas {
toggle_side_bar: Rect,
toggle_panel: Rect,
customize: Rect,
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
struct StatusHitAreas {
message: Rect,
diagnostics: Rect,
codeql: Rect,
update: Rect,
offer: Rect,
position: Rect,
indent: Rect,
encoding: Rect,
eol: Rect,
language: Rect,
agents: Rect,
}
#[derive(Debug, Default, PartialEq)]
struct PanelHitAreas {
problems_tab: Rect,
output_tab: Rect,
ports_tab: Rect,
captures_tab: Rect,
terminal_tab: Rect,
maximize_button: Rect,
focus_button: Rect,
add_buttons: Vec<Rect>,
profile_buttons: Vec<Rect>,
close_buttons: Vec<Rect>,
pane_labels: Vec<Rect>,
collapse_buttons: Vec<Rect>,
collapsed_strips: Vec<Rect>,
rail_rows: Vec<Rect>,
rail: Rect,
}
impl PanelHitAreas {
fn reset(&mut self) {
let Self {
problems_tab,
output_tab,
ports_tab,
captures_tab,
terminal_tab,
maximize_button,
focus_button,
add_buttons,
profile_buttons,
close_buttons,
pane_labels,
collapse_buttons,
collapsed_strips,
rail_rows,
rail,
} = self;
for area in [
problems_tab,
output_tab,
ports_tab,
captures_tab,
terminal_tab,
maximize_button,
focus_button,
rail,
] {
*area = Rect::default();
}
for list in [
add_buttons,
profile_buttons,
close_buttons,
pane_labels,
collapse_buttons,
collapsed_strips,
rail_rows,
] {
list.clear();
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
struct ChromeLayout {
activity: Option<Rect>,
primary_side: Option<Rect>,
secondary_side: Option<Rect>,
right: Rect,
sidebar_splitter_x: Option<u16>,
}
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,
}
}
#[derive(Default, Clone, Copy)]
struct SidebarAreas {
activity_icons: ActivityBlocks,
}
#[cfg_attr(test, derive(Default))]
pub struct ActivityIconImages {
active: Option<String>,
inactive: String,
hovered: String,
}
#[cfg_attr(test, derive(Default))]
pub struct ActivityBarImages {
icons: [ActivityIconImages; ActivityIcon::ALL.len()],
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,
}
#[derive(Clone, Copy)]
struct ChromeBakeInput {
protocol: crate::iterm2_inline::InlineImageProtocol,
cell: (u32, u32),
is_tmux: bool,
icon_bg: ::image::Rgba<u8>,
icon_ink: crate::iterm2_inline::IconInk,
sponsor_ink: crate::iterm2_inline::IconInk,
}
struct ChromeImages {
activity: Option<ActivityBarImages>,
run_debug: Option<String>,
ssh: Option<String>,
}
#[derive(Clone, Copy, PartialEq)]
struct WelcomeBakeKey {
layout: WelcomeLayout,
cell: (u32, u32),
bg: ::image::Rgba<u8>,
light: bool,
protocol: crate::iterm2_inline::InlineImageProtocol,
}
pub const APP_NAME: &str = "croft";
#[derive(Clone, Copy)]
struct StatusTones {
text: Color,
muted: Color,
dim: Color,
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Pane {
Tree,
Editor,
Terminal,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum BottomPanelTab {
Terminal,
Problems,
Output,
Ports,
Captures,
}
impl BottomPanelTab {
const ALL: [BottomPanelTab; 5] = [
BottomPanelTab::Problems,
BottomPanelTab::Output,
BottomPanelTab::Terminal,
BottomPanelTab::Ports,
BottomPanelTab::Captures,
];
fn label(self) -> &'static str {
match self {
BottomPanelTab::Problems => "PROBLEMS",
BottomPanelTab::Output => "OUTPUT",
BottomPanelTab::Terminal => "TERMINAL",
BottomPanelTab::Ports => "PORTS",
BottomPanelTab::Captures => "CAPTURES",
}
}
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,
}
}
}
struct PortToast {
port: u16,
process: Option<String>,
origin_remote: bool,
shown_at: std::time::Instant,
buttons: Vec<(Rect, PortToastAction)>,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum CreateKind {
File,
Folder,
}
struct UpdateToast {
release: crate::update_check::Release,
ready: bool,
failed: Option<&'static str>,
open: bool,
buttons: Vec<(Rect, UpdateToastAction)>,
painted: Vec<Vec<ratatui::buffer::Cell>>,
}
#[derive(Clone, Debug)]
struct PendingRunBlock {
pane_name: String,
cwd: PathBuf,
command: String,
code: String,
destructive: bool,
doc: Option<PathBuf>,
block_line: usize,
persist: bool,
capture_timeout: Option<std::time::Duration>,
}
struct PendingCapture {
pane_name: String,
doc: Option<PathBuf>,
block_line: usize,
after: Option<u64>,
started: std::time::Instant,
timeout: Option<std::time::Duration>,
persist: bool,
}
#[derive(Clone, PartialEq, Eq, Debug)]
enum MenuAction {
Scm(crate::widgets::scm_menu::ScmAction),
Commit(crate::widgets::source_control::CommitMenuItem),
Create(CreateKind),
RunCommand(crate::widgets::command_palette::Command),
Delete {
paths: Vec<PathBuf>,
},
Rename(PathBuf),
Cut(Vec<PathBuf>),
Copy(Vec<PathBuf>),
Paste(PathBuf),
SelectForCompare(PathBuf),
CompareWithSelected {
anchor: PathBuf,
other: PathBuf,
},
MakeRoot(PathBuf),
AddWorkspaceFolder,
RemoveWorkspaceFolder(PathBuf),
CopyTabPath(PathBuf),
CopyTabRelativePath(PathBuf),
RevealInExplorer(PathBuf),
RevealInFinder(PathBuf),
OpenInViewer(String, PathBuf),
CloseTab(usize),
CloseOtherTabs(usize),
CloseTabsToRight(usize),
CloseAllTabs,
CloseSavedTabs,
KeepTabOpen(usize),
ToggleTabPin(usize),
SplitEditor,
SplitEditorLeft,
SplitEditorUp,
SplitEditorDown,
MoveEditorUp,
MoveEditorDown,
MoveEditorLeft,
MoveEditorRight,
SplitInGroup,
FocusGroupLeft,
FocusGroupRight,
MoveIntoNewWindow(usize),
CopyIntoNewWindow(usize),
RenameSymbolAt {
row: usize,
col: usize,
},
CopyPermalink,
OpenOnRemote,
ChangeAllOccurrencesAt {
row: usize,
col: usize,
},
GoToDefinitionAt {
row: usize,
col: usize,
},
GoToDeclarationAt {
row: usize,
col: usize,
},
GoToTypeDefinitionAt {
row: usize,
col: usize,
},
GoToImplementationAt {
row: usize,
col: usize,
},
GoToReferencesAt {
row: usize,
col: usize,
},
NavigateBack,
NavigateForward,
QuickFixAt {
row: usize,
col: usize,
},
OpenCrumbFile(PathBuf),
BrowseCrumbFolder {
dir: PathBuf,
crumb: usize,
},
GoToLocation {
path: PathBuf,
line: u32,
col: u32,
},
ToggleBookmarkAt {
line: usize,
},
NextBookmark,
PreviousBookmark,
ToggleBreakpointAt {
line: usize,
},
EditBreakpointConditionAt {
line: usize,
},
EditLogpointAt {
line: usize,
},
AskNavigatorAt {
line: usize,
},
AskNavigatorSelection {
start: usize,
end: usize,
},
AskNavigatorAboutCapture,
CopyDebugValue {
expression: Option<String>,
value: String,
},
CopyDebugExpression(String),
AddDebugWatch(String),
RemoveDebugWatch(usize),
CopyCallStack,
FixProblemWithNavigator {
path: PathBuf,
item: crate::widgets::problems::ProblemItem,
},
OpenSymbolTab {
path: PathBuf,
name: String,
first: usize,
last: usize,
},
GoToOutlineSymbol {
path: PathBuf,
line: u32,
col: u32,
},
ShowCallsAt {
row: usize,
col: usize,
incoming: bool,
},
OpenThemePicker,
SetTheme(crate::theme::Theme),
ToggleExplorerView(ExplorerView),
OpenCustomizeLayout,
ToggleActivityBar,
ToggleSideBar,
ToggleAutoHideSideBar,
ToggleSecondarySideBar,
TogglePanel,
ToggleStatusBar,
SetSideBarPosition(SideBarPosition),
SetPanelAlignment(PanelAlignment),
SetQuickInputPosition(QuickInputPosition),
ToggleZenMode,
ToggleCenteredLayout,
RunCodeLens(usize),
RenameTerminal(usize),
ClearTerminal(usize),
ToggleMaximizeTerminal(usize),
ToggleCollapseTerminal(usize),
TerminalCopySelection,
TerminalPaste,
EditorCut,
EditorCopy,
EditorPaste,
ShowCommandPalette,
TerminalQuickSelect,
TerminalCopyMode,
TerminalCommandHistory,
OpenScrollbackInEditor,
ToggleBroadcastInput,
ToggleBroadcastExclusion,
UndoCloseTerminal,
SplitTerminal,
KillTerminal(usize),
CopyCommandOutput(usize, crate::widgets::terminal::CommandDecoration),
SelectCommandOutput(usize, crate::widgets::terminal::CommandDecoration),
RerunCommand(usize, crate::widgets::terminal::CommandDecoration),
NewTerminalWithProfile(String),
ToggleMinimap,
SetMinimapSide(MinimapSide),
SetLanguage(Option<crate::highlight::LangKind>),
SetLineEnding(crate::widgets::editor::LineEnding),
SetEncoding(&'static encoding_rs::Encoding),
SetIndentStyle(crate::widgets::editor::IndentStyle),
ConvertIndentation(bool),
CommitAction {
action: CommitAction,
hash: String,
short: String,
},
}
struct CompoundLaunch {
members: Vec<crate::dap::configs::DebugConfig>,
compound: String,
stop_all: bool,
}
struct PrViewedWrite {
key: String,
pr_id: String,
path: String,
viewed: bool,
}
struct CodeScanList {
branch: String,
load: bool,
rx: std::sync::mpsc::Receiver<Result<Vec<crate::sarif::github::Analysis>, String>>,
}
struct PrCheckout {
number: u64,
path: PathBuf,
oid: String,
created: bool,
}
struct InputRun {
ask: Vec<crate::dap::configs::LaunchInput>,
answers: std::collections::BTreeMap<String, String>,
then: InputThen,
}
struct PendingDebugLaunch {
pane: u64,
command: String,
step: PendingLaunchStep,
started: std::time::Instant,
watch: bool,
}
#[derive(Clone, Debug)]
struct ExplorerClipboard {
mode: ExplorerClipMode,
paths: Vec<PathBuf>,
}
#[derive(Clone, Debug)]
struct PendingFileMove {
request_id: u64,
op: FileMove,
renames: Vec<crate::lsp::manager::FileRenameOp>,
deadline: std::time::Instant,
baseline: Vec<(PathBuf, u64)>,
}
static TEST_KEYBINDINGS_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
#[derive(Clone, Debug)]
struct TreeTypeahead {
prefix: String,
last: std::time::Instant,
}
struct ContextMenu {
origin: (u16, u16),
items: Vec<MenuEntry>,
selected: usize,
open_submenu: Option<usize>,
submenu_selected: usize,
target_dir: PathBuf,
crumb: Option<usize>,
scroll: std::cell::Cell<usize>,
submenu_scroll: std::cell::Cell<usize>,
look: MenuLook,
keyed: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum MenuLook {
Panel,
ScmActions { op: Option<crate::git::RepoOp> },
CommitActions,
}
#[derive(Clone, PartialEq, Eq, Debug)]
enum PromptKind {
Create(CreateKind),
Rename(PathBuf),
SaveAs,
RenameSymbol {
path: PathBuf,
row: usize,
col: usize,
},
BreakpointCondition {
path: PathBuf,
line: usize,
},
Logpoint {
path: PathBuf,
line: usize,
},
HitCondition {
path: PathBuf,
line: usize,
},
FunctionBreakpoint,
DataBreakpoint,
NewProfile,
ReviewComment,
ReviewSummary,
StickyNote,
RenameTerminal(usize),
AnnotateTerminal {
pane: usize,
line: i32,
clock: i64,
start: u16,
len: u16,
existing: Option<usize>,
},
}
struct Prompt {
label: String,
buffer: String,
caret: usize,
kind: PromptKind,
target_dir: PathBuf,
error: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct PendingUnsavedScm {
op: ScmWrite,
root: PathBuf,
files: Vec<PathBuf>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct PendingStashDrop {
root: PathBuf,
oid: String,
label: String,
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct PendingDiscard {
root: PathBuf,
rel_path: String,
untracked: bool,
staged: bool,
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct PendingRevertHunk {
rel_path: String,
patch: String,
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct LossySave {
path: Option<PathBuf>,
encoding: &'static str,
chars: Vec<char>,
}
pub struct TourRun {
pub tour: crate::tour::Tour,
pub scratch: PathBuf,
pub previous_root: PathBuf,
pub step_opened_modal: bool,
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct SshOffer {
pane: u64,
host: String,
since: std::time::Instant,
cwd_at_offer: Option<crate::remote::CwdReport>,
}
pub struct QuickSelectState {
pane: usize,
clock: i64,
hints: Vec<QuickHint>,
typed: String,
shifted: bool,
}
#[derive(Clone)]
struct QuickHint {
line: i32,
start: usize,
len: usize,
text: String,
label: String,
tail: Vec<(i32, usize, usize)>,
}
pub struct CopyModeState {
pane: usize,
line: i32,
col: u16,
anchor: Option<(i32, u16)>,
kind: CopySelKind,
clock: i64,
}
pub struct ClosedTab {
pub path: PathBuf,
pub pinned: bool,
pub cursor: (usize, usize),
pub scroll: usize,
}
pub struct ClosedTerminal {
pub term: crate::widgets::terminal::PtyTerminal,
pub idx: usize,
pub closed_at: std::time::Instant,
}
struct RunningStatus {
shown: String,
label: String,
started: std::time::Instant,
}
pub struct App {
pub tree: FileTree,
pub search: SearchPanel,
pub remote: RemotePanel,
pub source_control: SourceControlPanel,
pub commit_graph: crate::widgets::commit_graph::CommitGraphPanel,
graph_fetch: Option<crate::jobs::Job<GraphReply>>,
graph_revspec: Option<String>,
graph_refetch_queued: bool,
pub run_debug: RunDebugPanel,
pub testing: crate::widgets::testing::TestingPanel,
pub codeql: crate::widgets::codeql::CodeqlPanel,
test_worker: crate::testing::worker::TestWorker,
test_run_status: Option<RunningStatus>,
last_test_run: Option<LastTestRun>,
pane_run_statuses: Vec<(u64, RunningStatus)>,
pub extensions: crate::widgets::extensions::ExtensionsPanel,
pub vscode_listed: Vec<String>,
pub open_editors: OpenEditorsPanel,
pub outline: OutlinePanel,
pub timeline: TimelinePanel,
pub agent_lane_panel: crate::widgets::agent_lane::AgentLanePanel,
lane_change_counts: std::collections::HashMap<PathBuf, (LaneCountKey, Option<(usize, usize)>)>,
pub dependencies: DependenciesPanel,
dep_ecosystems: Vec<Ecosystem>,
pub explorer_views: ExplorerViewVisibility,
settings_chain: Vec<PathBuf>,
settings_provenance: std::collections::BTreeMap<String, crate::config_layers::LayerKind>,
applied_settings: crate::prefs::Prefs,
disabled_extensions: std::collections::BTreeSet<String>,
installed_extensions: std::collections::BTreeSet<String>,
keymap: crate::keymap::Keymap,
macro_recording: Option<crate::macros::Recording>,
macro_last: Option<crate::macros::Macro>,
macro_registers: std::collections::HashMap<String, crate::macros::Macro>,
macro_replaying: bool,
macros_path: std::path::PathBuf,
config_watch: crate::config_sync::ConfigWatch,
last_mouse_pos: Option<(u16, u16)>,
tab_click_target: Option<usize>,
snippets: crate::snippets::SnippetSet,
format_on_save: bool,
default_formatter: Option<String>,
language_formatters: std::collections::BTreeMap<String, String>,
foreign_formatters_noted: std::collections::BTreeSet<String>,
language_prefs: std::collections::BTreeMap<String, crate::prefs::LanguagePrefs>,
copy_on_select: bool,
multi_cursor_persist: bool,
files_exclude: Vec<String>,
files_associations: std::collections::BTreeMap<String, String>,
files_associations_roots: Vec<PathBuf>,
files_encoding: Option<crate::file_encoding::Charset>,
log_highlight: bool,
secret_redaction: bool,
redaction_reveal_until: Option<std::time::Instant>,
auto_save: bool,
pub auto_save_on_focus_change: bool,
last_focus_signature: Option<(usize, usize, Option<PathBuf>)>,
save_after_format: Option<PathBuf>,
prettier_job: Option<crate::prettier::Job>,
format_save_deadline: Option<std::time::Instant>,
timeline_fetch: Option<crate::jobs::Job<(PathBuf, Vec<crate::git::FileHistoryEntry>)>>,
codeql_jobs: codeql::CodeqlJobs,
timeline_fetched: Option<PathBuf>,
nested_repo_scan: Option<(PathBuf, std::time::Instant)>,
blame_rx: std::sync::mpsc::Receiver<(PathBuf, crate::git::Blame)>,
blame_tx: std::sync::mpsc::Sender<(PathBuf, crate::git::Blame)>,
blame_fetched: Option<PathBuf>,
blame_hover: Option<(String, std::sync::mpsc::Receiver<Result<String, String>>)>,
git_net_job: Option<(String, PathBuf, std::sync::mpsc::Receiver<GitNetDone>)>,
git_view_job: Option<std::sync::mpsc::Receiver<GitNetDone>>,
git_file_lookup: Option<scm::GitFileLookup>,
git_file_queue: std::collections::VecDeque<(scm::GitFileCommand, PathBuf, PathBuf)>,
vim_mode_pref: bool,
inline_blame_enabled: bool,
provenance_overlay: bool,
indent_guides_enabled: bool,
home_walks_rows: bool,
bracket_colors_enabled: bool,
whitespace_mode: crate::widgets::editor::WhitespaceMode,
rulers: Vec<u16>,
line_numbers: crate::widgets::editor::LineNumbers,
diff_ws_default: crate::widgets::diff::DiffWhitespace,
inline_values_enabled: bool,
save_before_debug: bool,
auto_close_pairs: bool,
paste_reindent: bool,
save_cleanup: crate::widgets::editor::SaveCleanup,
inlay_hints_enabled: bool,
history_root: PathBuf,
history_restore: Option<(PathBuf, u64, Vec<u8>)>,
history_done_rx: std::sync::mpsc::Receiver<PathBuf>,
history_done_tx: std::sync::mpsc::Sender<PathBuf>,
#[allow(clippy::type_complexity)]
project_check: Option<crate::jobs::Job<(PathBuf, std::io::Result<std::process::Output>)>>,
project_check_rows: usize,
problems_project_scope: String,
build_column_unit: crate::build_matchers::ColumnUnit,
last_problem_jump: Option<(PathBuf, u32, u32, usize, usize, usize)>,
project_hint_rx: std::sync::mpsc::Receiver<()>,
project_hint_tx: std::sync::mpsc::Sender<()>,
project_check_hinted: bool,
#[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)>)>,
deps_fetch: Option<crate::jobs::Job<Vec<Dependency>>>,
deps_fetched: Option<PathBuf>,
voice_handle: Option<crate::voice::VoiceHandle>,
voice_canceling: bool,
voice_ready: Option<String>,
pub editor: EditorTabs,
pub editor_layout: editor_layout::EditorLayout,
force_save_armed: bool,
sudo_save_armed: Option<PathBuf>,
pending_sudo_saves: Vec<(PathBuf, Vec<u8>, Option<i32>)>,
pub terminals: Vec<PtyTerminal>,
pub active_terminal: usize,
perf: PerfHud,
screencast: Screencast,
roots: crate::workspace::WorkspaceRoots,
sidebar_view: SidebarView,
sidebar_areas: SidebarAreas,
theme: crate::theme::Theme,
focus: Pane,
show_tree: bool,
show_terminal: bool,
terminal_maximized: bool,
activity_bar_visible: bool,
status_bar_visible: bool,
side_bar_position: SideBarPosition,
secondary_side_bar_visible: bool,
panel_alignment: PanelAlignment,
quick_input_position: QuickInputPosition,
centered_layout: bool,
zen_center_layout: bool,
zen_centered: bool,
centered_layout_width: u16,
zen_esc_at: Option<std::time::Instant>,
zen_hint_until: Option<std::time::Instant>,
sidebar_auto_hide: bool,
sidebar_auto_hide_suspended: bool,
sidebar_pinned_open: bool,
sidebar_dwell: SidebarDwell,
pre_zen: Option<PreZenLayout>,
layout_icon_areas: LayoutIconAreas,
status: String,
persistence_warning: Option<&'static str>,
quit: bool,
drop_to_local: bool,
session: HostSession,
context_menu: Option<ContextMenu>,
crumb_filter: (String, Vec<MenuEntry>),
prompt: Option<Prompt>,
fs_watch: FsWatch,
fs_watch_extra: Vec<FsWatch>,
git_extra: Vec<(PathBuf, GitWorker)>,
active_scm_root: PathBuf,
scm_pin: Option<PathBuf>,
scm_follow_root: PathBuf,
active_test_root: PathBuf,
test_root_follow: Option<((PathBuf, Option<PathBuf>), PathBuf)>,
test_root_pending: Option<PendingTestRoot>,
pending_workspace_folders: Option<Vec<PathBuf>>,
git_head_oids: std::collections::BTreeMap<PathBuf, Option<String>>,
git: GitWorker,
cursor_blink: CursorBlink,
overwrite_mode: bool,
caret_block_sent: bool,
editor_click: ClickTracker,
tree_click: ClickTracker,
terminal_click: ClickTracker,
modified_click: ModifiedClickTracker,
ports_click: ClickTracker,
gesture: Option<Gesture>,
secondary_outline: crate::widgets::outline::OutlineView,
welcome: WelcomeState,
ext_index_refresh: Option<std::sync::mpsc::Receiver<bool>>,
ext_index_manual_refresh: bool,
search_query_tx: std::sync::mpsc::Sender<crate::search::SearchRequest>,
search_results_rx: std::sync::mpsc::Receiver<crate::search::SearchEvent>,
cell_pixel: Option<(u32, u32)>,
chrome_bake: Option<std::sync::mpsc::Receiver<(ChromeBakeInput, ChromeImages)>>,
chrome_shown: Option<ChromeBakeInput>,
chrome_bake_next: Option<ChromeBakeInput>,
welcome_bake: Option<(WelcomeBakeKey, std::sync::mpsc::Receiver<Option<String>>)>,
last_pdf_wheel: Option<(std::time::Instant, i32, Option<PathBuf>)>,
formula_overwrite_armed: bool,
activity_badges: [CountBadge; ActivityIcon::ALL.len()],
problems_badge_count: usize,
problems_badge_cell: Option<(u16, u16)>,
inline_protocol: crate::iterm2_inline::InlineImageProtocol,
sixel_supported: bool,
resize_repaint_needed: bool,
minimap: inline_images::MinimapState,
picture_cover: popups::PictureCover,
chrome_sent: std::collections::HashMap<&'static str, u64>,
chrome_seen: std::collections::HashSet<&'static str>,
clipboard_reader: fn() -> Option<String>,
remote_launch: Option<RemoteLaunch>,
pending_remote_launch_host: Option<String>,
pending_remote_launch_path: Option<String>,
ssh_offer: Option<SshOffer>,
ssh_offer_seen: std::collections::BTreeMap<u64, Option<String>>,
remote_offer_disabled: bool,
remote_offer_excluded: Vec<String>,
fleet_groups: std::collections::BTreeMap<String, Vec<String>>,
code_scanning: crate::sarif::github::CodeScanningMode,
code_scan_seen: Option<String>,
code_scan_list: Option<CodeScanList>,
code_scan_fetch: Option<std::sync::mpsc::Receiver<Vec<Result<PathBuf, String>>>>,
remote_offer_refused: crate::remote::RefusedHosts,
lane_agent: Option<String>,
pub(crate) color_depth: crate::color_depth::ColorDepth,
pub(crate) underline_colors: bool,
lane_panes: std::collections::BTreeMap<u64, crate::terminal_session::LaneRecord>,
tree_clipboard: Option<ExplorerClipboard>,
tree_typeahead: Option<TreeTypeahead>,
compare_anchor: Option<PathBuf>,
last_frame_area: Rect,
last_sidebar_area: Option<Rect>,
pending_scp_uploads: Vec<ScpUpload>,
pending_remote_pulls: Vec<PendingRemotePull>,
pending_relay_copies: Vec<PendingRelayCopy>,
view_listener: Option<std::os::unix::net::UnixListener>,
hook_listener: Option<std::os::unix::net::UnixListener>,
hook_root: PathBuf,
approvals: std::collections::VecDeque<crate::agent_approval::Pending>,
approval_ui: Option<crate::agent_approval::ApprovalUi>,
approval_check: Option<crate::agent_approval::ProposalCheck>,
approval_edit: Option<(String, PathBuf)>,
approval_merge_into: Option<PathBuf>,
notebook_kernels: std::collections::HashMap<PathBuf, crate::notebook_kernel::NotebookRun>,
kernel_listing: Option<(PathBuf, crate::notebook_kernel::KernelSession)>,
kernel_choice: Option<(
PathBuf,
Vec<crate::notebook_kernel::KernelSpec>,
Option<String>,
)>,
coverage_at: Option<std::time::SystemTime>,
coverage_lens_path: Option<PathBuf>,
coverage_install: Option<String>,
view_drain_budget: std::time::Duration,
pending_local_open: Option<String>,
pending_discard: Option<PendingDiscard>,
pending_unsaved_scm: Option<PendingUnsavedScm>,
remote_tag_root: Option<PathBuf>,
scm_unsaved_cleared: bool,
scm_after_format_save: Option<(ScmWrite, PathBuf)>,
pending_revert_hunk: Option<PendingRevertHunk>,
pending_unsaved: Option<UnsavedExit>,
pending_lossy_save: Option<LossySave>,
remote_handoff_ok: Option<u64>,
pub hot_exit_dir: Option<PathBuf>,
hot_exit_written: Option<u64>,
hot_exit_retry_at: Option<std::time::Instant>,
hot_exit_consumed: Vec<PathBuf>,
hot_exit_unremoved: Vec<PathBuf>,
exit_notes: Vec<String>,
pub session_dir: Option<PathBuf>,
saved_session: Option<(
std::sync::mpsc::Receiver<crate::session_state::SessionState>,
bool,
)>,
closed_bookmarks: std::collections::HashMap<PathBuf, std::collections::BTreeSet<usize>>,
run_tasks: Vec<crate::tasks::Task>,
last_task: Option<crate::tasks::Task>,
pending_terminal_warning: bool,
message_card: Option<crate::widgets::message_card::MessageCard>,
default_branch_label: Option<String>,
default_branch_ask: Option<(PathBuf, std::sync::mpsc::Receiver<Option<String>>)>,
trust_local_browser: bool,
sidebar_width: u16,
terminal_height: Option<u16>,
sidebar_splitter_x: Option<u16>,
terminal_splitter_y: Option<u16>,
editor_seams: Vec<editor_layout::Seam>,
editor_layout_area: Rect,
terminal_rail_scroll: usize,
terminal_rail_revealed: Option<usize>,
consented_extensions: std::collections::BTreeSet<String>,
config_dir: PathBuf,
settings_profile: Option<String>,
scrollback_dir: PathBuf,
terminal_pane_maximized: bool,
bottom_panel_tab: BottomPanelTab,
problems: crate::widgets::problems::ProblemsPanel,
output: crate::widgets::output::OutputPanel,
ports: crate::widgets::ports::PortsPanel,
pub captures: crate::widgets::captures::CapturesPanel,
port_toast: Option<PortToast>,
last_port_poll: std::time::Instant,
port_poll: Option<crate::jobs::Job<PortPoll>>,
fleet_run: Option<crate::jobs::Job<Vec<crate::fleet::HostResult>>>,
fleet_command: String,
last_label_refresh: std::time::Instant,
label_pass: Option<crate::jobs::Job<terminal_panes::LabelPass>>,
panel_hits: PanelHitAreas,
pointer_cell: Option<(u16, u16)>,
hovered_activity_icon: Option<ActivityIcon>,
hovered_layout_icon: Option<usize>,
osk: Option<crate::widgets::osk::Osk>,
osk_auto: bool,
last_content_width: u16,
last_content_height: u16,
lsp: language_servers::LspState,
shell_lint_notice_shown: bool,
tool_search_path: Option<std::ffi::OsString>,
problems_open_set: std::collections::BTreeSet<PathBuf>,
markdown_lint_last_seen: std::collections::HashMap<PathBuf, (u64, Vec<String>)>,
live_run_files: std::collections::HashSet<PathBuf>,
live_run_sent: std::collections::HashMap<PathBuf, Vec<String>>,
live_run_runner: Option<crate::live_run::Runner>,
md_scroll_synced: Option<(PathBuf, bool, usize)>,
code_lens_enabled: bool,
code_lens_requested: std::collections::HashMap<PathBuf, u64>,
function_breakpoints: Vec<String>,
screen_reader: bool,
screen_reader_command: Option<String>,
announcer: crate::a11y::Announcer,
announce_pos: Option<(u16, u16)>,
a11y_event: Option<(u64, String)>,
debug: debugger::DebugState,
term_suggest_enabled: bool,
term_suggestion: Option<(usize, String, String)>,
shortcut_capture: Option<ShortcutCapture>,
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_lsp: Option<(u64, PathBuf, u64, usize, usize)>,
inline_asked: Option<(PathBuf, u64, usize, usize)>,
inline_next_id: u64,
keybindings_file: PathBuf,
search_editor_job: Option<(
PathBuf,
crate::search_editor::Header,
std::sync::mpsc::Receiver<Vec<crate::search::SearchHit>>,
)>,
sarif_diag_signature: Vec<(PathBuf, Option<(std::time::SystemTime, u64)>)>,
sarif_added_polled: Option<std::time::Instant>,
sarif_step_signature: Option<SarifStepSignature>,
sarif_published: Vec<(PathBuf, String)>,
completion: completion::CompletionState,
quick_suggestions: bool,
pub word_suggestions: crate::word_suggest::WordSuggestions,
pub signature_help_popup: Option<crate::widgets::signature_help_popup::SignatureHelpPopup>,
signature_help_request_id: Option<u64>,
signature_help_anchor: Option<(usize, usize, u64)>,
hover: mouse_input::HoverState,
rust_analyzer_request: Option<(u64, crate::lsp::rust_analyzer::RaRequest)>,
tab_hover: HoverDwell,
tab_tooltip: Option<crate::widgets::hover_popup::HoverPopup>,
tab_hover_idx: Option<usize>,
ui_hover: HoverDwell,
ui_tooltip: Option<crate::widgets::hover_popup::HoverPopup>,
ui_tooltip_label: Option<std::borrow::Cow<'static, str>>,
search_hint_view: (usize, usize, bool),
ui_tooltip_area: Option<Rect>,
update_card_rect: Option<Rect>,
definition_request_id: Option<u64>,
peek_definition_request_id: Option<u64>,
peek_popup: Option<crate::widgets::hover_popup::HoverPopup>,
peek_target: Option<(PathBuf, u32, u32)>,
peek_refs: Option<(Vec<PeekLocation>, usize)>,
references_want_peek: bool,
declaration_request_id: Option<u64>,
type_definition_request_id: Option<u64>,
outline_synced: Option<(PathBuf, Option<u64>)>,
outline_parse: Option<(OutlineKey, OutlineParse)>,
outline_parsed_for: Option<(PathBuf, Option<u64>)>,
outline_lsp_landed: Option<(PathBuf, u64)>,
implementation_request_id: Option<u64>,
references_request_id: Option<u64>,
call_hierarchy_request_id: Option<u64>,
occurrences_request: Option<CaretRequest>,
linked_request: Option<FileRequest>,
linked_observed: Option<CaretSpot>,
linked_observed_at: std::time::Instant,
linked_asked: bool,
selection_range_request: Option<PendingSelectionRanges>,
occ_observed: Option<CaretSpot>,
occ_observed_at: std::time::Instant,
rename_request_id: Option<u64>,
rename_baseline: Vec<(PathBuf, u64)>,
pending_file_move: Option<PendingFileMove>,
prepare_rename_request: Option<CaretRequest>,
format_request_id: Option<u64>,
format_request_selection: bool,
format_request_seq: Option<u64>,
format_on_type: bool,
on_type_request: Option<FileRequest>,
code_action_request_id: Option<u64>,
code_action_pending_resolve: bool,
code_action_baseline: Vec<(PathBuf, u64)>,
pending_code_actions: Vec<crate::lsp::manager::CodeActionItem>,
review: review::ReviewState,
notes: crate::sticky_notes::Notes,
notes_path: Option<PathBuf>,
note_box_ids: std::collections::HashMap<u64, String>,
notes_shown_gen: u64,
recording: Option<(
crate::asciicast::Recorder,
std::fs::File,
std::time::Instant,
)>,
recorded_size: (u16, u16),
scrub: diff_merge::ScrubState,
auto_approve: Option<(String, std::time::Instant)>,
pub tour: Option<TourRun>,
pub tour_done: bool,
pub welcome_tour_button: Rect,
gh_program: PathBuf,
gh_limit: std::time::Duration,
code_scan_asks: Vec<crate::jobs::Job<code_scanning::CodeScanAnswer>>,
dismiss_target: Option<code_scanning::DismissTarget>,
code_scan_picker_root: Option<PathBuf>,
sarif_locate_pending: Option<(String, i64, i64)>,
sarif_download: Option<std::sync::mpsc::Receiver<SarifDownload>>,
sarif_fetch: fn(&str) -> Result<Vec<u8>, String>,
pub agent_ledger: crate::agent_lane::AgentLedger,
agent_ledger_store: Option<PathBuf>,
agent_ledger_saved: (u64, std::time::Instant),
pending_lane_picks: Vec<(String, PathBuf)>,
pending_bookmarks: Vec<BookmarkTarget>,
problems_fix_started: Option<std::time::Instant>,
http_run: Option<std::sync::mpsc::Receiver<HttpRunOutcome>>,
http_environment: Option<String>,
pending_color_presentations: Vec<(String, Vec<crate::widgets::editor::TextSpanEdit>)>,
pending_color_context: Option<(PathBuf, u64)>,
color_presentations_request: Option<(u64, PathBuf, u64)>,
nav: NavHistory,
editor_vim_chord: EditorVimChord,
cmd_k_leader: Option<CmdKLeader>,
cmd_k_miss_note: Option<(std::time::Instant, String)>,
kitty_keys: bool,
legacy_ctrl_punct: bool,
vim: crate::vim::VimState,
vim_last_find: Option<(crate::vim::FindKind, char)>,
vim_visual_line: bool,
shortcuts_modal: Option<crate::widgets::shortcuts::ShortcutsModal>,
settings_editor: Option<crate::widgets::settings_editor::SettingsEditor>,
status_hits: StatusHitAreas,
status_logged: String,
status_wide: bool,
connect_dialog: Option<crate::widgets::connect_dialog::ConnectDialog>,
connect_auth: Option<crate::remote_connect::SshAuth>,
install_session: Option<crate::install_session::InstallSession>,
update_watch: Option<crate::update_watch::UpdateWatch>,
build_marker_checked: Option<std::time::Instant>,
drift_probe: Option<crate::update_watch::DriftProbe>,
local_drift: Option<String>,
self_install: Option<crate::update_watch::SelfInstall>,
update_check: Option<crate::update_check::UpdateCheck>,
manual_update_check: Option<crate::update_check::ManualCheck>,
update_fetch: fn() -> Result<Option<crate::update_check::Release>, String>,
update_toast: Option<UpdateToast>,
install_source: crate::update_check::InstallSource,
staged_install: Option<crate::update_check::StagedInstall>,
staged_status: UpdateStatus,
update_status: UpdateStatus,
update_spinner_start: Option<std::time::Instant>,
pending_reexec: bool,
overlays: OverlayManager,
pub editor_find: Option<crate::widgets::editor_find::EditorFind>,
pub terminal_find: Option<crate::widgets::editor_find::EditorFind>,
terminal_find_pane: usize,
terminal_find_match: Option<(i64, i32, usize, usize)>,
pub terminal_quick_select: Option<QuickSelectState>,
pub command_history: crate::command_history::CommandHistory,
pub command_history_popup: Option<crate::widgets::history_popup::HistoryPopup>,
pub terminal_session_path: PathBuf,
pub terminal_restore_respawns: bool,
terminal_store_error: Option<String>,
pub workspace_folders_path: PathBuf,
pub terminal_session_dirty: bool,
pub terminal_copy_mode: Option<CopyModeState>,
pub triggers: std::sync::Arc<crate::triggers::TriggerSet>,
agents: crate::agents::AgentTable,
agent_events: std::collections::VecDeque<crate::agents::AgentEvent>,
pub matchers: std::sync::Arc<crate::problem_matchers::MatcherSet>,
pub watch_set: std::sync::Arc<crate::problem_matchers::WatchSet>,
task_matcher_by_pane:
std::collections::HashMap<u64, std::sync::Arc<crate::problem_matchers::CompiledMatcher>>,
watch_published_panes: std::collections::HashSet<u64>,
pub broadcast_input: bool,
pub pending_broadcast_enable: bool,
pub pending_terminal_paste: Option<Vec<u8>>,
pending_terminal_paste_target: Option<u64>,
pub multiline_paste_warning: crate::prefs::MultilinePasteWarning,
pending_run_block: Option<PendingRunBlock>,
pending_captures: Vec<PendingCapture>,
block_outputs: std::collections::HashMap<(String, usize), crate::markdown::BlockOutput>,
pub show_terminal_timestamps: bool,
notifier: crate::notifications::Notifier,
host_accents: Vec<HostAccent>,
pub closed_terminals: Vec<ClosedTerminal>,
ending_terminals: Vec<crate::jobs::Job<()>>,
pub closed_tabs: Vec<ClosedTab>,
pub file_finder: Option<crate::widgets::file_finder::FileFinder>,
quick_open_range: Option<(PathBuf, crate::widgets::editor::EditorSelection)>,
pub command_palette: Option<crate::widgets::command_palette::CommandPalette>,
pub go_to_symbol: Option<crate::widgets::symbol_picker::SymbolPicker>,
pub workspace_symbols: Option<crate::widgets::workspace_symbols::WorkspaceSymbolPicker>,
ws_symbols_request_id: Option<u64>,
ws_symbols_pending: Option<std::time::Instant>,
mcp_rx: Option<std::sync::mpsc::Receiver<crate::mcp::McpOutcome>>,
mcp_started: Option<std::time::Instant>,
mcp_busy_label: Option<String>,
pub process_picker: Option<crate::widgets::process_picker::ProcessPicker>,
selected_debug_config: Option<String>,
selected_debug_compound: Option<String>,
pending_debug_launch: Option<PendingDebugLaunch>,
input_run: Option<InputRun>,
pending_attach: Option<(crate::dap::configs::ResolvedConfig, LaunchSlot)>,
pending_test_debug: Option<PendingTestDebug>,
pending_cargo_launches: Vec<PendingCargoLaunch>,
pub watch_exprs: Vec<String>,
pub watch_vals: std::collections::HashMap<String, (String, bool)>,
watch_prev: std::collections::HashMap<String, String>,
watch_baseline_pending: bool,
pub zoxide_jump: Option<crate::widgets::zoxide_jump::ZoxideJump>,
pub zoxide_add_folder: bool,
pub branch_picker: Option<crate::widgets::branch_picker::BranchPicker>,
pub branch_purpose: BranchPurpose,
blocked_switch: Option<(
PathBuf,
Option<String>,
crate::widgets::branch_picker::BranchAction,
)>,
pub input_prompt: Option<crate::widgets::input_prompt::InputPrompt>,
pub list_picker: Option<crate::widgets::list_picker::ListPicker>,
pub session_channel: Option<crate::session_host::InnerChannel>,
pub session_participants: Vec<crate::session_host::Participant>,
session_host_stale_seen: bool,
session_stale_notice: Option<String>,
session_typist: Option<u64>,
session_carets: std::collections::HashMap<u64, SessionCaret>,
session_presence_mtime: Option<std::time::SystemTime>,
last_session_presence_poll: std::time::Instant,
collab: agents_collab::CollabState,
pair: agents_collab::PairState,
#[cfg(test)]
#[allow(clippy::type_complexity)]
kernel_start_override: Option<Box<dyn Fn(&str) -> crate::notebook_kernel::KernelSession>>,
pub git_output_log: Vec<String>,
build_diagnostics:
std::collections::HashMap<PathBuf, Vec<(u64, crate::widgets::problems::ProblemItem)>>,
build_diag_files_by_pane: std::collections::HashMap<u64, Vec<PathBuf>>,
undo_pushed_commit_armed: Option<String>,
reset_hard_armed: Option<(PathBuf, String, String)>,
pub pending_discard_all: bool,
pending_stash_drop: Option<PendingStashDrop>,
pending_replace_all: Option<(usize, usize, usize)>,
file_finder_index: Option<std::sync::Arc<Vec<crate::file_index::FileEntry>>>,
file_finder_index_job: Option<crate::jobs::Job<Vec<crate::file_index::FileEntry>>>,
file_finder_index_dirty: bool,
}
#[derive(Clone, Copy, Debug, Default)]
struct EditorVimChord {
op: VimOp,
count: usize,
}
#[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,
pub page: u32,
pub generation: u64,
}
#[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,
}
#[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,
}
struct MinimapBase {
rgba: Vec<u8>,
w: u32,
h: u32,
sig: MinimapSig,
}
#[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,
highlight_generation: u64,
side: MinimapSide,
bg: (u8, u8, u8),
selection: Option<(usize, usize)>,
doc: (u64, (usize, usize)),
}
struct PortPoll {
hits: Vec<crate::port_detect::PortHit>,
listening: Option<std::collections::HashSet<u16>>,
}
struct MinimapOverlay {
top: usize,
rows: usize,
total: usize,
light: bool,
selection: Option<(usize, usize)>,
sel_rgb: (u8, u8, u8),
content_h: u32,
}
#[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,
pub open_after_forward: Option<String>,
pub remote_ipv6: bool,
}
struct RemoteLaunch {
host: String,
path: Option<String>,
adopted: Option<crate::remote::AdoptedMaster>,
}
struct SarifDownload {
uri: String,
line: i64,
col: i64,
body: Result<Vec<u8>, String>,
}
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
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct LochWelcomePlan {
logo_y: u16,
logo_h: u16,
tagline_y: u16,
start_y: Option<u16>,
chip_y: Option<u16>,
card_y: u16,
card_h: u16,
notes: usize,
}
use crate::gradient::{GRAD_TL, GRAD_TR, POPUP_SEL_BG, paint_gradient_box, rgb_color};
struct LspQuestion {
server: String,
text: String,
actions: Vec<lsp_types::MessageActionItem>,
reply: tokio::sync::oneshot::Sender<Option<lsp_types::MessageActionItem>>,
}
struct PendingCompletionResolve {
request_id: u64,
path: PathBuf,
start: (usize, usize),
upto: (usize, usize),
text_hash: u64,
undo: ImportUndo,
}
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
};
cmd.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null());
cmd.spawn().with_context(|| format!("opening {url}"))?;
Ok(())
}
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()
}
impl App {
pub fn new(root: PathBuf) -> Result<Self> {
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();
let dep_ecosystems = crate::dependencies::detect_ecosystems(&root);
dependencies.set_header(crate::widgets::dependencies::header_label(&dep_ecosystems));
if !cfg!(test) {
crate::profiles::activate_for_workspace(&root);
}
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 built = settings_to_build_with(&loaded_prefs);
crate::widgets::terminal::publish_pane_settings(&loaded_prefs);
let data_dir =
(!cfg!(test)).then(|| user_data_dir(&croft_cache_dir(), &crate::paths::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_log_highlight_default_at_startup(!built.disable_log_highlight);
let loaded_keymap = if cfg!(test) {
crate::keymap::Keymap::default()
} else {
crate::keymap::Keymap::load(&crate::keymap::keybindings_path())
};
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());
crate::startup_trace::mark("settings, keymap and matchers loaded");
let explorer_views = ExplorerViewVisibility::from_prefs(built.explorer_views);
let disabled_extensions = loaded_prefs.disabled_extensions.clone();
let installed_extensions = if cfg!(test) {
crate::mcp::catalog::bundled_ids()
} else {
crate::mcp::catalog::installed_ids(&crate::lsp::manifest::user_extensions_dir())
};
let (history_done_tx, history_done_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 (blame_tx, blame_rx) = std::sync::mpsc::channel();
let editor = EditorTabs::new();
let view_listener = Self::bind_view_socket();
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();
crate::startup_trace::mark("sockets bound");
let term = PtyTerminal::new(&root).context("spawning terminal")?;
crate::startup_trace::mark("terminal shell spawned");
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 search_root = root.clone();
std::thread::spawn(move || {
crate::search::search_worker_loop(search_root, search_query_rx, search_results_tx);
});
let index_root = root.clone();
let file_finder_index_job = crate::jobs::Job::spawn(
FILE_INDEX_THREAD,
crate::jobs::Start::AfterFirstFrame,
move || crate::file_index::build_file_index(&index_root),
)
.ok();
let fs_watch = FsWatch::spawn(&root, &tree);
crate::startup_trace::mark("file watcher started");
let layout_prefs = if cfg!(test) {
crate::prefs::LayoutPrefs::default()
} else {
loaded_prefs.layout
};
let session = HostSession::from_env();
let persistence_warning = remote_persistence_status(session.is_remote, session.persistent);
let terminal_restore_respawns = session.is_remote;
let mut app = Self {
tree,
search,
remote,
source_control,
commit_graph: crate::widgets::commit_graph::CommitGraphPanel::new(),
graph_revspec: None,
graph_fetch: None,
graph_refetch_queued: false,
run_debug,
testing: crate::widgets::testing::TestingPanel::new(),
codeql: crate::widgets::codeql::CodeqlPanel::new(),
test_worker: crate::startup_trace::after(
"test runner started",
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,
installed_extensions,
keymap: loaded_keymap,
last_mouse_pos: None,
tab_click_target: None,
macro_recording: None,
macro_last: None,
macro_registers: crate::startup_trace::after(
"macros loaded",
crate::macros::load(&crate::macros::macros_path()),
),
macro_replaying: false,
macros_path: crate::macros::macros_path(),
config_watch: crate::startup_trace::after(
"settings watcher set up",
crate::config_sync::ConfigWatch::new(config_watch_paths(&merged_settings.chain)),
),
snippets: crate::startup_trace::after(
"snippets loaded",
load_all_snippets([root.as_path()]),
),
format_on_save: built.format_on_save,
default_formatter: built.default_formatter.clone(),
language_formatters: built.language_formatters.clone(),
foreign_formatters_noted: std::collections::BTreeSet::new(),
language_prefs: built.languages.clone(),
copy_on_select: built.copy_on_select,
multi_cursor_persist: built.multi_cursor_persist,
files_exclude: Vec::new(),
files_associations: std::collections::BTreeMap::new(),
files_associations_roots: Vec::new(),
files_encoding: None,
log_highlight: !built.disable_log_highlight,
secret_redaction: !built.disable_secret_redaction,
redaction_reveal_until: None,
auto_save: built.auto_save,
auto_save_on_focus_change: built.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,
applied_settings: built.clone(),
timeline_fetch: None,
codeql_jobs: codeql::CodeqlJobs::new(built.codeql_cli_path.clone()),
history_done_rx,
history_done_tx,
project_check: None,
project_check_rows: 0,
project_hint_rx,
project_hint_tx,
project_check_hinted: false,
problems_project_scope: if built.problems_project_scope.is_empty() {
String::from("auto")
} else {
built.problems_project_scope.clone()
},
build_column_unit: crate::build_matchers::ColumnUnit::from_pref(
&built.build_column_unit,
),
last_problem_jump: None,
test_jump_rx,
test_jump_tx,
timeline_fetched: None,
nested_repo_scan: None,
blame_rx,
blame_tx,
blame_fetched: None,
blame_hover: None,
git_net_job: None,
git_view_job: None,
git_file_lookup: None,
git_file_queue: std::collections::VecDeque::new(),
vim_mode_pref: false,
inline_blame_enabled: !built.disable_inline_blame,
provenance_overlay: false,
indent_guides_enabled: !built.disable_indent_guides,
home_walks_rows: built.home_walks_wrapped_rows,
bracket_colors_enabled: !built.disable_bracket_colors,
whitespace_mode: crate::widgets::editor::WhitespaceMode::from_pref(
&built.render_whitespace,
),
rulers: crate::widgets::editor::normalize_rulers(&built.rulers),
line_numbers: crate::widgets::editor::LineNumbers::from_pref(&built.line_numbers),
diff_ws_default: crate::widgets::diff::DiffWhitespace::from_config(
&built.diff_ignore_whitespace,
),
inline_values_enabled: !built.disable_inline_values,
save_before_debug: !built.disable_save_before_debug,
auto_close_pairs: !built.disable_auto_close_pairs,
paste_reindent: !built.disable_paste_reindent,
save_cleanup: crate::widgets::editor::SaveCleanup::from_prefs(&built),
inlay_hints_enabled: !built.disable_inlay_hints,
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_fetch: None,
deps_fetched: None,
voice_handle: None,
voice_canceling: false,
voice_ready: None,
editor,
editor_layout: editor_layout::EditorLayout::single(),
force_save_armed: false,
sudo_save_armed: None,
pending_sudo_saves: Vec::new(),
terminals: vec![term],
active_terminal: 0,
perf: PerfHud::default(),
screencast: Screencast::default(),
roots: crate::workspace::WorkspaceRoots::single(root.clone()),
sidebar_view: SidebarView::Explorer,
sidebar_areas: SidebarAreas::default(),
theme: if cfg!(test) {
crate::theme::Theme::default()
} else {
built.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,
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: built.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 (
merged_settings.user_config_error.as_deref(),
hook_bind_error,
) {
(Some(error), _) => settings_not_loaded_status(error),
(None, Some(hook)) if view_bind_error.is_none() => hook,
_ => view_status(view_bind_error.as_deref()),
},
persistence_warning,
quit: false,
drop_to_local: false,
session,
context_menu: None,
crumb_filter: (String::new(), Vec::new()),
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(),
test_root_follow: None,
test_root_pending: None,
pending_workspace_folders: None,
git_head_oids: std::collections::BTreeMap::new(),
git,
cursor_blink: CursorBlink::new(),
overwrite_mode: false,
caret_block_sent: false,
editor_click: ClickTracker::default(),
tree_click: ClickTracker::default(),
terminal_click: ClickTracker::default(),
modified_click: ModifiedClickTracker::default(),
ports_click: ClickTracker::default(),
gesture: None,
secondary_outline: Default::default(),
welcome,
ext_index_refresh,
ext_index_manual_refresh: false,
search_query_tx,
search_results_rx,
cell_pixel: None,
chrome_bake: None,
chrome_shown: None,
chrome_bake_next: None,
welcome_bake: None,
last_pdf_wheel: None,
formula_overwrite_armed: false,
activity_badges: Default::default(),
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: inline_images::MinimapState::new(layout_prefs.minimap),
picture_cover: popups::PictureCover::default(),
chrome_sent: std::collections::HashMap::new(),
chrome_seen: std::collections::HashSet::new(),
clipboard_reader: read_system_clipboard,
remote_launch: None,
pending_remote_launch_host: None,
pending_remote_launch_path: None,
ssh_offer: None,
ssh_offer_seen: std::collections::BTreeMap::new(),
remote_offer_disabled: built.disable_remote_offer,
remote_offer_excluded: built.remote_offer_excluded_hosts.clone(),
fleet_groups: built.fleet_groups.clone(),
code_scanning: built.code_scanning,
code_scan_seen: None,
code_scan_list: None,
code_scan_fetch: None,
remote_offer_refused: crate::startup_trace::after(
"refused remote hosts read",
crate::remote::load_refused_hosts(
&crate::remote::refused_hosts_path(&croft_cache_dir()),
std::time::SystemTime::now(),
),
),
lane_agent: built.lane_agent.clone(),
color_depth: built
.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())
}),
underline_colors: crate::color_depth::underline_colors_supported(|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,
pending_scp_uploads: Vec::new(),
pending_remote_pulls: Vec::new(),
pending_relay_copies: 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,
pending_lossy_save: 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(),
session_dir: data_dir.as_deref().map(|dir| dir.join("sessions")),
saved_session: None,
closed_bookmarks: std::collections::HashMap::new(),
run_tasks: Vec::new(),
last_task: None,
pending_terminal_warning: false,
message_card: None,
default_branch_label: None,
default_branch_ask: None,
trust_local_browser: false,
sidebar_width: SIDEBAR_WIDTH_DEFAULT,
terminal_height: None,
editor_seams: Vec::new(),
editor_layout_area: Rect::default(),
sidebar_splitter_x: None,
terminal_splitter_y: None,
consented_extensions: built.mcp_consented.clone(),
config_dir: crate::paths::config_dir(),
settings_profile: if cfg!(test) {
None
} else {
crate::profiles::active()
},
scrollback_dir: crate::session_state::dirs_cache_croft().join("scrollback"),
terminal_rail_scroll: 0,
terminal_rail_revealed: 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: None,
fleet_run: None,
fleet_command: String::new(),
last_label_refresh: std::time::Instant::now(),
label_pass: None,
panel_hits: PanelHitAreas::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: language_servers::LspState::new(crate::startup_trace::after(
"language server manager built",
match crate::lsp::LspManager::new(root.clone()) {
Ok(m) => Some(m),
Err(e) => {
eprintln!("lsp manager init failed: {e}");
None
}
},
)),
shell_lint_notice_shown: false,
tool_search_path: std::env::var_os("PATH"),
problems_open_set: std::collections::BTreeSet::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: built.screen_reader,
screen_reader_command: built.screen_reader_command.clone(),
announcer: crate::a11y::Announcer::default(),
announce_pos: None,
a11y_event: None,
debug: debugger::DebugState::new(),
term_suggest_enabled: true,
term_suggestion: None,
shortcut_capture: None,
inline_enabled: false,
inline_worker: None,
inline_config: None,
inline_job: None,
inline_lsp: 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(),
completion: completion::CompletionState::new(),
editor_vim_chord: EditorVimChord::default(),
cmd_k_leader: None,
cmd_k_miss_note: None,
kitty_keys: false,
legacy_ctrl_punct: false,
vim: crate::vim::VimState::new(),
vim_last_find: None,
vim_visual_line: false,
shortcuts_modal: None,
settings_editor: None,
status_hits: StatusHitAreas::default(),
status_logged: String::new(),
status_wide: false,
connect_dialog: None,
connect_auth: None,
install_session: None,
update_watch: None,
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,
command_history: crate::startup_trace::after(
"command history read",
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,
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: crate::startup_trace::after(
"triggers loaded",
load_trigger_set(!built.disable_secret_redaction),
),
agents: crate::startup_trace::after(
"agents loaded",
crate::agents::AgentTable::load(&crate::agents::agents_path()),
),
agent_events: std::collections::VecDeque::new(),
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_terminal_paste: None,
pending_terminal_paste_target: None,
multiline_paste_warning: built.terminal_multiline_paste_warning,
pending_run_block: None,
pending_captures: Vec::new(),
block_outputs: std::collections::HashMap::new(),
show_terminal_timestamps: false,
notifier: crate::notifications::Notifier::new(&built.notifications),
host_accents: compile_host_accents(&built.host_accents),
closed_terminals: Vec::new(),
ending_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,
selected_debug_config: None,
selected_debug_compound: None,
pending_debug_launch: None,
input_run: None,
pending_attach: None,
pending_test_debug: None,
pending_cargo_launches: Vec::new(),
watch_exprs: Vec::new(),
watch_vals: std::collections::HashMap::new(),
watch_prev: std::collections::HashMap::new(),
watch_baseline_pending: false,
zoxide_jump: None,
zoxide_add_folder: false,
branch_picker: None,
branch_purpose: BranchPurpose::Checkout,
blocked_switch: None,
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: agents_collab::CollabState::new(),
pair: agents_collab::PairState::new(&root, !built.disable_proactive_navigator),
#[cfg(test)]
kernel_start_override: None,
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,
reset_hard_armed: None,
pending_discard_all: false,
pending_stash_drop: None,
pending_replace_all: None,
file_finder_index: None,
file_finder_index_job,
file_finder_index_dirty: false,
quick_suggestions: !built.disable_quick_suggestions,
word_suggestions: crate::word_suggest::WordSuggestions::from_pref(
&built.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: built.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: review::ReviewState::new(
built
.review_ai_prefix
.clone()
.unwrap_or_else(|| String::from(crate::review_threads::DEFAULT_AI_PREFIX)),
),
notes: crate::startup_trace::after(
"sticky notes read",
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,
recording: None,
recorded_size: (0, 0),
scrub: diff_merge::ScrubState::new(),
auto_approve: None,
tour: None,
tour_done: loaded_prefs.tour_done,
welcome_tour_button: Rect::default(),
gh_program: PathBuf::from("gh"),
gh_limit: code_scanning::CODE_SCAN_GH_LIMIT,
code_scan_asks: Vec::new(),
dismiss_target: None,
code_scan_picker_root: None,
sarif_locate_pending: None,
sarif_download: None,
sarif_fetch: fetch_sarif_source,
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(),
pending_bookmarks: Vec::new(),
problems_fix_started: None,
http_run: None,
http_environment: None,
pending_color_presentations: Vec::new(),
pending_color_context: None,
color_presentations_request: None,
hover: mouse_input::HoverState::new(),
rust_analyzer_request: None,
tab_hover: HoverDwell::default(),
tab_tooltip: None,
tab_hover_idx: None,
ui_hover: HoverDwell::default(),
ui_tooltip: None,
ui_tooltip_label: None,
search_hint_view: (0, 0, false),
ui_tooltip_area: None,
update_card_rect: 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(),
};
crate::startup_trace::mark("editor state built");
app.apply_merged_settings(&loaded_prefs);
if cfg!(test) {
app.test_worker
.set_codeql_program(app.codeql_jobs.program.clone());
} else {
app.resolve_codeql_cli();
}
app.test_worker.set_extensions_dir(app.extensions_dir());
app.sync_focus_flags();
crate::highlight::set_syntax_palette(app.theme.syntax());
let root = app.workspace_root().to_path_buf();
app.watch_project_snippets();
app.agent_ledger = app.load_agent_ledger(&root);
app.sync_agent_lane_decorations();
Ok(app)
}
pub fn flush_activity_image_overlays(&mut self, around: &[u64]) {
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();
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;
}
if overlays.is_empty() {
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();
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 cursor_on = self.cursor_should_be_visible();
let on_screen = overlays
.iter()
.filter(|((x, y), _)| {
self.overlay_fits_on_screen(*x, *y, 1, 1)
})
.map(|((x, y), seq)| (*x, *y, seq.as_bytes()));
write_inline_images(&mut stdout(), on_screen, cursor_on);
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);
}
fn poke_cursor(&mut self) {
self.cursor_blink.poke();
}
fn sync_open_file_poll_mtime(&mut self) {
let paths = self.polled_open_file_paths();
self.fs_watch.sync_open_file_mtime(&paths);
self.sync_run_debug_if_file_changed();
}
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)
}
fn active_workspace_root(&self) -> PathBuf {
self.active_workspace_root_path().to_path_buf()
}
fn active_workspace_root_path(&self) -> &Path {
self.editor
.path
.as_deref()
.and_then(|p| self.roots.owning_root(p))
.unwrap_or_else(|| self.roots.primary())
}
fn workspace_folders(&self) -> Vec<(String, PathBuf)> {
crate::dap::configs::workspace_folders(self.roots.iter())
}
fn open_text_line_counts(&self) -> std::collections::HashMap<PathBuf, usize> {
self.editor
.editors
.iter()
.filter(|e| !e.has_non_text_view())
.filter_map(|e| Some((e.path.clone()?, e.lines.len())))
.collect()
}
pub(super) fn sync_file_finder_open_lines(&mut self) -> bool {
if self.file_finder.is_none() {
return false;
}
let open = self.open_text_line_counts();
self.file_finder
.as_mut()
.is_some_and(|f| f.set_open_lines(open))
}
fn open_buffer_paths(&self) -> std::collections::BTreeSet<PathBuf> {
self.buffer_paths().map(Path::to_path_buf).collect()
}
fn buffer_paths(&self) -> impl Iterator<Item = &Path> + '_ {
self.editor_layout
.all_groups(&self.editor)
.flat_map(|g| g.editors.iter())
.filter_map(|e| e.path.as_deref())
}
fn cycle_focus(&mut self) {
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;
}
}
self.focus_pane(next);
}
fn pane_visible(&self, p: Pane) -> bool {
match p {
Pane::Tree => self.show_tree,
Pane::Terminal => self.show_terminal,
Pane::Editor => true,
}
}
pub fn terminal(&self) -> &PtyTerminal {
&self.terminals[self.active_terminal]
}
pub fn terminal_mut(&mut self) -> &mut PtyTerminal {
&mut self.terminals[self.active_terminal]
}
fn focus_pane(&mut self, p: Pane) {
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();
}
if p == Pane::Editor && self.terminal_maximized {
self.terminal_maximized = false;
}
match p {
Pane::Tree => {
self.sidebar_pinned_open = false;
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();
}
}
pub(super) fn apply_view_prefs(&mut self) {
let (langs, ws_global) = (&self.language_prefs, self.whitespace_mode);
for group in self.editor_layout.all_groups_mut(&mut self.editor) {
for ed in &mut group.editors {
ed.show_indent_guides = self.indent_guides_enabled;
ed.show_bracket_colors = self.bracket_colors_enabled;
ed.whitespace_mode = whitespace_mode_in(langs, ws_global, editor_scope_id(ed));
ed.home_walks_rows = self.home_walks_rows;
ed.rulers.clone_from(&self.rulers);
ed.line_numbers = self.line_numbers;
}
}
}
fn sync_focus_flags(&mut self) {
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;
}
if self
.terminal_quick_select
.as_ref()
.is_some_and(|st| st.pane != self.active_terminal)
{
self.close_terminal_quick_select();
}
if self.terminal_find.is_some() && self.terminal_find_pane != self.active_terminal {
self.close_terminal_find();
}
self.editor.focused = self.focus == Pane::Editor;
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;
}
let gradient = self.theme.gradient();
let pdf_on = self.is_extension_enabled("pdf");
let csv_on = self.is_extension_enabled("csv");
for ed in self
.editor_layout
.all_groups_mut(&mut self.editor)
.flat_map(|g| g.editors.iter_mut())
{
ed.focus_gradient = gradient;
ed.theme = self.theme;
ed.pdf_viewer_enabled = pdf_on;
ed.csv_viewer_enabled = csv_on;
ed.provenance_overlay = self.provenance_overlay;
ed.diff_ws_default = self.diff_ws_default;
}
self.apply_view_prefs();
self.refresh_scm_repositories();
self.problems.fix_glyph = match self.problems_fix_started {
Some(t) => update_spinner_frame(t.elapsed().as_millis()),
None => "",
};
self.output.sync();
for t in self.terminals.iter_mut() {
t.show_timestamps = self.show_terminal_timestamps;
}
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();
}
fn popup_gradient(&self) -> bool {
self.theme.gradient()
}
fn open_url_for_user(&mut self, url: &str) {
self.try_open_url_for_user(url);
}
fn try_open_url_for_user(&mut self, url: &str) -> bool {
self.open_web_url(
url,
WebOpenOpts {
inert_in_tests: true,
..WebOpenOpts::default()
},
)
}
fn typed_path(&self, value: &str) -> PathBuf {
self.typed_path_checked(value).unwrap_or_else(|| {
let v = value.trim();
self.workspace_root()
.join(v.strip_prefix("~/").unwrap_or(v))
})
}
fn typed_path_checked(&self, value: &str) -> Option<PathBuf> {
resolve_typed_path(
value,
std::env::var_os("HOME").map(PathBuf::from).as_deref(),
self.workspace_root(),
)
}
fn editor_is_text(&self) -> bool {
!self.editor.has_non_text_view() && self.editor.markdown_preview.is_none()
}
fn status_path(&self, path: &Path) -> String {
let rel = self
.roots
.owning_root(path)
.and_then(|r| path.strip_prefix(r).ok())
.unwrap_or(path);
if rel.as_os_str().is_empty() {
String::from(".")
} else {
rel.display().to_string()
}
}
}
fn 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)
}
fn one_line<'a>(text: std::borrow::Cow<'a, str>) -> std::borrow::Cow<'a, str> {
if !text.contains(char::is_control) {
return text;
}
let pieces = text.split(char::is_control).map(str::trim);
std::borrow::Cow::Owned(
pieces
.filter(|p| !p.is_empty())
.collect::<Vec<_>>()
.join(" "),
)
}
fn workspace_relative<'a>(text: &'a str, root: &Path) -> std::borrow::Cow<'a, str> {
use std::borrow::Cow;
let root = root.to_string_lossy();
let root = root.trim_end_matches('/');
if root.is_empty() || !text.contains(root) {
return Cow::Borrowed(text);
}
let needle = format!("{root}/");
if !text.contains(&needle) {
return Cow::Borrowed(text);
}
let mut out = String::with_capacity(text.len());
let mut rest = text;
while let Some(i) = rest.find(&needle) {
let starts_word = rest[..i]
.chars()
.next_back()
.or_else(|| out.chars().next_back())
.is_none_or(|c| c.is_whitespace() || "'\"`([{<".contains(c));
out.push_str(&rest[..i]);
if !starts_word {
out.push_str(&needle);
}
rest = &rest[i + needle.len()..];
}
out.push_str(rest);
Cow::Owned(out)
}
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 a11y_count(n: usize, one: &str, many: &str) -> String {
format!("{n} {}", if n == 1 { one } else { many })
}
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)
}
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),
)
}
fn editor_scope_id(ed: &crate::widgets::editor::Editor) -> &'static str {
settings_scope_id(ed.scope_id(), ed.path.as_deref())
}
fn settings_scope_id(base: &'static str, path: Option<&Path>) -> &'static str {
let ext_is = |want: &str| {
path.and_then(|p| p.extension())
.and_then(|e| e.to_str())
.is_some_and(|e| e.eq_ignore_ascii_case(want))
};
match base {
"javascript" if ext_is("jsx") => "javascriptreact",
"json" if ext_is("jsonc") => "jsonc",
"css" if ext_is("scss") => "scss",
"css" if ext_is("sass") => "sass",
_ => base,
}
}
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)
}
use crate::proc::info::cwd_is_observable;
fn cells_in(buf: &ratatui::buffer::Buffer, r: Rect) -> Vec<ratatui::buffer::Cell> {
let r = r.intersection(buf.area);
r.positions().map(|p| buf[p].clone()).collect()
}
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()
}
#[cfg(unix)]
fn process_is_alive(pid: u32) -> bool {
let Ok(pid) = libc::pid_t::try_from(pid) else {
return true;
};
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
}
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
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RunSpec {
pub program: String,
pub args: Vec<String>,
pub cwd: PathBuf,
}
struct HttpRunOutcome {
file: PathBuf,
raw_line: String,
result: Result<crate::http_file::HttpResponse, String>,
}
struct VariantResultFiles {
sarif: Option<PathBuf>,
csv: Option<PathBuf>,
repos: usize,
failed: Vec<(String, String)>,
}
struct VariantExport {
summary: Option<PathBuf>,
gist: Option<String>,
repos: usize,
failed: Vec<(String, String)>,
}
#[derive(Default)]
struct TerminalPaneButtons {
add: Option<Rect>,
profile: Option<Rect>,
close: Option<Rect>,
collapse: Option<Rect>,
}
#[cfg(test)]
mod tests;
#[derive(Clone, Debug, PartialEq, Eq)]
struct SessionCaret {
path: PathBuf,
row: usize,
col: usize,
}
struct CollabCaret {
file: String,
row: usize,
col: usize,
name: String,
last_moved: std::time::Instant,
}
struct CollabStreamInfo {
file: String,
name: String,
site: u64,
undo_group: u64,
}
struct CountingWriter {
inner: Stdout,
pending: Vec<u8>,
bytes: std::sync::Arc<std::sync::atomic::AtomicUsize>,
}
impl CountingWriter {
fn new(inner: Stdout, bytes: std::sync::Arc<std::sync::atomic::AtomicUsize>) -> Self {
Self {
inner,
pending: Vec::with_capacity(64 * 1024),
bytes,
}
}
}
impl std::io::Write for CountingWriter {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.pending.extend_from_slice(buf);
self.bytes
.fetch_add(buf.len(), std::sync::atomic::Ordering::Relaxed);
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
if !self.pending.is_empty() {
let sent = self.inner.write_all(&self.pending);
self.pending.clear();
sent?;
}
self.inner.flush()
}
}
const BEGIN_SYNCHRONIZED_UPDATE: &[u8] = b"\x1b[?2026h";
const END_SYNCHRONIZED_UPDATE: &[u8] = b"\x1b[?2026l";
type CroftTerminal = Terminal<CrosstermBackend<CountingWriter>>;
#[cfg(all(test, target_os = "linux"))]
pub(crate) fn run_scp_uploads_for_record(
workspace: PathBuf,
alias: &str,
sources: &[PathBuf],
) -> Result<()> {
let mut app = App::new(workspace)?;
app.remote.targets = vec![crate::remote::RemoteTarget {
alias: alias.to_string(),
host_name: None,
user: None,
}];
app.remote.selected = 0;
app.import_paths_into_remote(sources);
let backend = CrosstermBackend::new(CountingWriter::new(stdout(), Default::default()));
let mut terminal: CroftTerminal = Terminal::with_options(
backend,
ratatui::TerminalOptions {
viewport: ratatui::Viewport::Fixed(Rect::new(0, 0, 80, 24)),
},
)?;
remote_sessions::run_pending_scp_uploads(&mut app, &mut terminal)
}
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<()> {
std::thread::spawn(crate::lsp::manifest::prewarm_bundled);
std::thread::spawn(crate::triggers::prewarm_builtin_redactions);
crate::startup_gate::arm();
crate::startup_gate::spawn_after_first_frame(crate::agents::prewarm_builtin);
crate::termux::ensure_codicon_font_in_background();
crate::startup_gate::spawn_after_first_frame(crate::highlight::prewarm_configs);
crate::mem_relief::start();
let title = build_title(&root);
crate::startup_trace::mark("background work started");
enable_raw_mode().context("enable raw mode")?;
#[cfg(unix)]
let host_probe = StartupProbe(Some(crate::iterm2_inline::ask_host()));
let mut app = App::new(root.clone())?;
crate::startup_trace::mark("editor built");
app.restore_terminal_session();
app.save_terminal_session_if_hosted();
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);
}
}
if let Some(session_path) = restore_session.as_ref() {
match crate::session_state::SessionState::load(session_path) {
Ok(state) => {
let left = app.apply_session_state(&state);
if app.hold_unrestored_tabs(left) {
let _ = std::fs::remove_file(session_path);
} else {
app.status = format!(
"Some unsaved xlsx cells could not be restored; the session is kept at {}",
session_path.display()
);
}
let _ = app.write_hot_exit();
}
Err(e) => {
app.status = format!(
"Could not restore the session ({e:#}); it is kept at {}",
session_path.display()
);
}
}
} else {
let restored = app.restore_hot_exit();
app.read_saved_session(!restored);
}
crate::startup_trace::mark("session restored");
if zen {
app.show_tree = false;
app.show_terminal = false;
}
if let Some(file) = open_file.as_ref() {
if app.open_file_at_launch(file)
&& let Some((row, col)) = open_at
{
app.without_auto_hide(|app| app.place_caret_at(row, col));
}
}
match std::env::var("CROFT_FOCUS").as_deref() {
Ok("terminal") => app.focus_pane(Pane::Terminal),
Ok("editor") => app.focus_pane(Pane::Editor),
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();
if let Some(selector) = crate::pr_review::take_startup_pr() {
app.start_pr_review(selector);
}
if crate::tour::take_startup_demo() {
app.start_demo();
}
#[cfg(unix)]
{
let host = host_probe.answer();
if app.inline_protocol == crate::iterm2_inline::InlineImageProtocol::None {
app.sixel_supported = host.sixel && !crate::iterm2_inline::detect_tmux();
crate::widgets::terminal::SIXEL_HOST
.store(app.sixel_supported, std::sync::atomic::Ordering::Relaxed);
}
app.legacy_ctrl_punct = host.answered && !host.kitty_keyboard;
}
crate::startup_trace::mark("host terminal answered");
let mut out = stdout();
{
use std::io::Write;
out.write_all(&takeover_mode_seq())
.and_then(|()| out.flush())
.context("enter alt screen")?;
}
install_terminal_restore_panic_hook();
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();
let theme = crate::prefs::Prefs::load_or_default().theme();
out.write_all(theme_host_colors_seq(theme).as_bytes()).ok();
out.flush().ok();
}
app.init_graphics();
app.arm_terminal_warning();
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::new(out, perf_bytes));
let mut terminal: CroftTerminal = Terminal::new(backend).context("create terminal")?;
crate::startup_trace::mark("screen set up");
let result = main_loop(&mut app, &mut terminal);
drop(app.collab.session.take());
app.save_terminal_session();
if app.testing.is_busy() {
app.test_worker.cancel();
}
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();
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();
}
{
use std::io::Write;
let backend = terminal.backend_mut();
let _ = backend.write_all(END_SYNCHRONIZED_UPDATE);
let _ = backend.flush();
}
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();
if let Some(host) = app.pair.host.take() {
host.shutdown_blocking();
}
crate::pair_host::join_teardowns();
crate::dap::transport::join_teardowns();
for note in app.exit_notes.drain(..) {
eprintln!("croft: {note}");
}
result?;
if app.drop_to_local {
crate::widgets::editor::delete_own_gunzip_copies();
app.wait_for_ending_terminals();
std::process::exit(crate::remote::DROP_TO_LOCAL_EXIT_CODE);
}
if app.pending_reexec {
let state = app.capture_session_state();
let session_path = crate::session_state::handoff_path();
let _ = state.save(&session_path);
use std::os::unix::process::CommandExt;
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)
{
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);
crate::widgets::editor::delete_own_gunzip_copies();
app.wait_for_ending_terminals();
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(()),
}
}
if let Err(e) = app.save_session_for_next_launch() {
eprintln!("croft: could not save the session: {e:#}");
}
Ok(())
}
#[cfg(unix)]
struct StartupProbe(Option<crate::iterm2_inline::PendingHostProbe>);
#[cfg(unix)]
impl StartupProbe {
fn answer(mut self) -> crate::iterm2_inline::HostProbe {
self.0
.take()
.map(crate::iterm2_inline::PendingHostProbe::answer)
.unwrap_or_default()
}
}
#[cfg(unix)]
impl Drop for StartupProbe {
fn drop(&mut self) {
if let Some(pending) = self.0.take() {
let _ = pending.answer();
disable_raw_mode().ok();
}
}
}
struct ImageUnderlays {
activity: Vec<u64>,
editor: [u64; 2],
terminal: u64,
markdown: u64,
minimap: u64,
}
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_popup_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<()> {
let mut needs_redraw = true;
let mut first_frame = true;
let mut last_blink_visible = app.cursor_visible_phase();
let mut last_spinner_phase = app.update_spinner_phase();
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;
let pty_min_interval = if app.session.is_remote {
Duration::from_millis(50)
} else {
Duration::from_millis(33)
};
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 !app.pending_scp_uploads.is_empty() {
run_pending_scp_uploads(app, terminal)?;
needs_redraw = true;
}
let pass = tick_background(app);
let pty_pending = pass.pty_pending;
let blink_visible = pass.blink_visible;
let blink_changed = blink_visible != last_blink_visible;
let spinner_phase = pass.spinner_phase;
let spinner_changed = spinner_phase != last_spinner_phase;
let non_pty_dirty = needs_redraw || pass.changed || blink_changed || spinner_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;
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();
}
{
use std::io::Write;
let _ = terminal.backend_mut().write_all(BEGIN_SYNCHRONIZED_UPDATE);
}
let resize_repaint = app.consume_resize_repaint();
if consume_any_image_clear(app) || resize_repaint {
if resize_repaint || 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();
}
crate::startup_trace::mark("loop work done");
let draw_start = std::time::Instant::now();
let mut drawn = terminal.draw(|f| app.render_for_terminal(f))?.buffer;
crate::startup_trace::mark("frame drawn");
app.sync_caret_style();
let mut underlays = app.image_underlays(drawn);
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();
drawn = terminal.draw(|f| app.render_for_terminal(f))?.buffer;
underlays = app.image_underlays(drawn);
}
app.flush_activity_image_overlays(&underlays.activity);
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;
}
write_inline_image(
&mut stdout(),
layout.cell_x,
layout.cell_y,
osc.as_bytes(),
app.cursor_should_be_visible(),
);
app.mark_editor_image_displayed(side);
app.overlays.editor[side].mark_sent_over(underlays.editor[side]);
} else {
app.overlays.editor[side].forget_sent();
}
}
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) {
write_inline_image(
&mut stdout(),
layout.cell_x,
layout.cell_y,
osc.as_bytes(),
app.cursor_should_be_visible(),
);
app.mark_terminal_image_displayed();
app.overlays
.terminal_image
.mark_sent_over(underlays.terminal);
}
} else {
app.overlays.terminal_image.forget_sent();
}
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) {
write_inline_image(
&mut stdout(),
layout.cell_x,
layout.cell_y,
osc.as_bytes(),
app.cursor_should_be_visible(),
);
app.mark_markdown_image_displayed();
app.overlays
.markdown_image
.mark_sent_over(underlays.markdown);
}
} else {
app.overlays.markdown_image.forget_sent();
}
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) {
write_inline_image(
&mut stdout(),
layout.cell_x,
layout.cell_y,
osc.as_bytes(),
app.cursor_should_be_visible(),
);
app.mark_minimap_image_displayed();
app.overlays.minimap.mark_sent_over(underlays.minimap);
}
} else {
app.overlays.minimap.forget_sent();
}
app.flush_chrome_images(drawn);
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,
)
{
write_inline_image(
&mut stdout(),
layout.cell_x,
layout.cell_y,
img.as_bytes(),
app.cursor_should_be_visible(),
);
app.mark_welcome_image_emitted();
}
app.flush_tooltip_over_image();
{
use std::io::Write;
let backend = terminal.backend_mut();
let _ = backend.write_all(END_SYNCHRONIZED_UPDATE);
let _ = backend.flush();
}
if std::mem::take(&mut first_frame) {
crate::startup_trace::mark("first frame on screen");
crate::startup_gate::open();
if let Some(lsp) = app.lsp.manager.as_ref() {
lsp.prewarm_workspace();
}
crate::startup_trace::finish();
crate::gui_path::refresh_in_background();
}
needs_redraw = false;
last_blink_visible = blink_visible;
last_spinner_phase = spinner_phase;
}
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))? {
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(_, _) => {
app.on_resize();
if app.session.persistent {
use std::io::Write;
let out = terminal.backend_mut();
let _ = out.write_all(&reattach_reassert_seq(app.theme));
let _ = out.flush();
app.caret_block_sent = false;
}
}
_ => {}
}
if !event::poll(Duration::ZERO)? {
break;
}
}
needs_redraw = true;
}
poll_max_us = poll_max_us.max(poll_start.elapsed().as_micros());
if app.tick_terminal_autoscroll() {
needs_redraw = true;
}
}
Ok(())
}