use super::*;
use crate::widgets::confirm_frame::{ConfirmFrame, Inset, draw_confirm};
pub(super) fn manual_update_check_refusal(remote: bool, disabled: bool) -> Option<&'static str> {
if remote {
Some("No croft update is waiting: this croft is updated by the croft that launched it")
} else if disabled {
Some("No croft update is waiting, and update checks are off (CROFT_NO_UPDATE_CHECK)")
} else {
None
}
}
impl UpdateToast {
pub(super) fn offer(release: crate::update_check::Release) -> Self {
UpdateToast {
release,
ready: false,
failed: None,
open: true,
buttons: Vec::new(),
painted: Vec::new(),
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(super) enum UpdateToastAction {
Update,
Skip,
Later,
Relaunch,
CopyCommand,
ReleaseNotes,
InstallLog,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(super) enum UpdateSource {
Watch,
SelfInstall,
Staged,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(super) enum UpdateStatus {
Idle,
InProgress,
Ready,
}
impl App {
pub(super) fn answer_view_client(
&mut self,
mut stream: std::os::unix::net::UnixStream,
deadline: std::time::Instant,
) -> (crate::view_ipc::ViewReply, bool) {
let _ = stream.set_nonblocking(false);
let reply = match crate::view_ipc::read_request(&stream, deadline) {
Ok(req) if req.probe => self.probe_view_path(&req.to_path()),
Ok(req) => {
let reply = self.apply_view_request(&req.to_path());
if let (crate::view_ipc::ViewReply::Ok, Some((row, col))) = (&reply, req.at) {
self.place_caret_at(row, col);
}
reply
}
Err(e) => crate::view_ipc::ViewReply::Err {
message: format!("unreadable request: {e}"),
},
};
let left = deadline
.saturating_duration_since(std::time::Instant::now())
.max(std::time::Duration::from_millis(1));
let _ = stream.set_write_timeout(Some(left));
let opened = matches!(reply, crate::view_ipc::ViewReply::Ok);
let _ = crate::view_ipc::write_reply(&mut stream, &reply);
(reply, opened)
}
pub(super) fn render_terminal_warning(&self, frame: &mut ratatui::Frame) {
if !self.pending_terminal_warning {
return;
}
let frame_spec = ConfirmFrame {
title: " UNSUPPORTED TERMINAL ",
accent: self.theme.ui(Color::Rgb(0xff, 0xa5, 0x00)),
title_fg: Color::Black,
height: 11,
inset: Inset::Wide,
};
draw_confirm(frame, self.theme, frame_spec, |frame, inner| {
let accent = self.theme.ui(Color::Rgb(0x4e, 0x9a, 0xff));
let current = std::env::var("TERM_PROGRAM")
.ok()
.filter(|s| !s.is_empty())
.or_else(|| std::env::var("TERM").ok().filter(|s| !s.is_empty()))
.unwrap_or_else(|| String::from("this terminal"));
let text = Style::default().fg(self.theme.ui(Color::White));
let name = Style::default().fg(accent).add_modifier(Modifier::BOLD);
let key = Style::default()
.fg(Color::Green)
.add_modifier(Modifier::BOLD);
let body = ratatui::text::Text::from(vec![
Line::from(Span::styled(
"Croft draws its icons and images with inline-image protocols",
text,
)),
Line::from(Span::styled(
format!("that {current} does not support, so the activity bar and"),
text,
)),
Line::from(Span::styled(
"file icons stay blank. Croft still runs; for the full UI use:",
text,
)),
Line::from(""),
Line::from(vec![
Span::raw(" macOS: "),
Span::styled("iTerm2", name),
Span::raw(" or "),
Span::styled("Ghostty", name),
]),
Line::from(vec![Span::raw(" Linux: "), Span::styled("Ghostty", name)]),
Line::from(""),
Line::from(vec![
Span::styled("[any key]", key),
Span::raw(" dismiss "),
Span::styled("[D]", key),
Span::raw("on't show again"),
]),
]);
frame.render_widget(ratatui::widgets::Paragraph::new(body), inner);
});
}
pub(super) fn render_update_toast(&mut self, frame: &mut ratatui::Frame) {
let rect = self.paint_update_toast(frame);
if rect != self.update_card_rect {
self.update_card_rect = rect;
self.overlays.activity.mark_dirty();
}
}
pub(super) fn paint_update_toast(&mut self, frame: &mut ratatui::Frame) -> Option<Rect> {
let Some(toast) = self.update_toast.as_ref().filter(|t| t.open) else {
if let Some(t) = self.update_toast.as_mut() {
t.buttons.clear();
}
return None;
};
let mut card = self.update_card(toast);
let area = frame.area();
let width = crate::widgets::update_popup::WIDTH.min(area.width.saturating_sub(2));
let status_h: u16 = if self.status_bar_visible { 1 } else { 0 };
let stack: u16 = if self.port_toast.is_some() {
PORT_TOAST_HEIGHT
} else {
0
};
let room = area.height.saturating_sub(status_h + 1 + stack);
if card.height(width) > room {
card.link = None;
card.rows.truncate(1);
}
let height = card.height(width);
if width < crate::widgets::update_popup::MIN_WIDTH || height > room {
if let Some(t) = self.update_toast.as_mut() {
t.buttons.clear();
}
return None;
}
let rect = Rect {
x: area.x + 1,
y: area.y + room - height,
width,
height,
};
let hits = card.render(frame.buffer_mut(), rect, self.theme, self.pointer_cell);
let painted = hits
.iter()
.map(|(r, _)| cells_in(frame.buffer_mut(), *r))
.collect();
if let Some(t) = self.update_toast.as_mut() {
t.buttons = hits;
t.painted = painted;
}
Some(rect)
}
pub(super) fn update_card_covers(&self, at: Rect) -> bool {
self.update_card_rect
.is_some_and(|card| card.intersects(at))
}
pub(super) fn drop_covered_update_controls(&mut self, buf: &ratatui::buffer::Buffer) {
let Some(t) = self.update_toast.as_mut() else {
return;
};
let painted = std::mem::take(&mut t.painted);
let buttons = std::mem::take(&mut t.buttons);
t.buttons = buttons
.into_iter()
.zip(painted)
.filter(|((r, _), cells)| cells_in(buf, *r) == *cells)
.map(|(hit, _)| hit)
.collect();
}
pub(super) fn update_card(
&self,
toast: &UpdateToast,
) -> crate::widgets::update_popup::Card<UpdateToastAction> {
use crate::widgets::update_popup::{
Card, ERROR_GLYPH, LOG_GLYPH, NOTES_GLYPH, PACKAGE_GLYPH, READY_GLYPH,
};
let release = &toast.release;
let brew = self.install_source == crate::update_check::InstallSource::Homebrew;
let installed = format!("v{}", env!("CARGO_PKG_VERSION"));
let mut rows = vec![
("Version", format!("v{}", release.version)),
(
"Installed",
if brew {
format!("{installed} (Homebrew)")
} else {
installed
},
),
];
if let Some(date) = release
.published
.as_deref()
.and_then(crate::update_check::date_label)
{
rows.push(("Released", date));
}
if let Some(size) = release.size {
rows.push(("Size", crate::widgets::editor::format_bytes_human(size)));
}
let button = |label: &str, action| (String::from(label), action);
let skip = button("Skip", UpdateToastAction::Skip);
let later = button("Later", UpdateToastAction::Later);
let accent = self.theme.accent();
let (glyph, glyph_color, title, message, buttons) = if toast.ready {
(
READY_GLYPH,
self.theme.ui(Color::Rgb(0x89, 0xd1, 0x85)),
"Update Ready",
Some(String::from(
"Relaunching keeps open files and unsaved edits; terminals restart.",
)),
vec![later, button("Relaunch", UpdateToastAction::Relaunch)],
)
} else if let Some(reason) = toast.failed {
(
ERROR_GLYPH,
self.theme.ui(Color::Rgb(0xf1, 0x4c, 0x4c)),
"Update Failed",
Some(format!("Not installed: {reason}.")),
vec![skip, later, button("Retry", UpdateToastAction::Update)],
)
} else if brew {
(
PACKAGE_GLYPH,
accent,
"Update Available",
Some(format!(
"Homebrew manages this install. Update it with `{}`.",
crate::update_check::BREW_UPGRADE
)),
vec![
skip,
later,
button("Copy Command", UpdateToastAction::CopyCommand),
],
)
} else {
(
PACKAGE_GLYPH,
accent,
"Update Available",
None,
vec![skip, later, button("Update", UpdateToastAction::Update)],
)
};
let link = if toast.failed.is_some() {
(
LOG_GLYPH,
String::from("View the Install Log"),
UpdateToastAction::InstallLog,
)
} else {
(
NOTES_GLYPH,
format!("What's New in v{}", release.version),
UpdateToastAction::ReleaseNotes,
)
};
Card {
glyph,
glyph_color,
title: String::from(title),
rows,
message,
buttons,
link: Some(link),
}
}
pub(super) fn arm_terminal_warning(&mut self) {
if crate::prefs::Prefs::load_or_default().suppress_terminal_warning {
return;
}
self.pending_terminal_warning = crate::iterm2_inline::terminal_warrants_switch_warning(
self.inline_protocol,
crate::iterm2_inline::detect_termux(),
);
}
pub(super) fn dismiss_terminal_warning(&mut self, dont_show_again: bool) {
self.pending_terminal_warning = false;
if dont_show_again {
self.report_unsaved_setting(crate::prefs::save_suppress_terminal_warning(true));
}
}
pub(super) fn start_update_watch_if_remote(&mut self) {
if !self.session.remote_autoupdate {
return;
}
let cache_dir = croft_cache_dir();
let launch_stamp = std::fs::read_to_string(cache_dir.join("install-stamp"))
.map(|s| s.trim().to_string())
.unwrap_or_default();
self.update_watch = Some(crate::update_watch::UpdateWatch::start(
cache_dir,
launch_stamp,
));
}
pub(super) fn poll_source_build_marker(&mut self) -> bool {
if self.update_watch.is_none() {
return false;
}
let now = std::time::Instant::now();
if self
.build_marker_checked
.is_some_and(|t| now.duration_since(t) < std::time::Duration::from_secs(1))
{
return false;
}
self.build_marker_checked = Some(now);
let building = crate::update_watch::source_build_running(
&croft_cache_dir(),
crate::update_watch::boot_id,
crate::update_watch::boot_time,
process_is_alive,
);
self.apply_source_build_state(building)
}
pub(super) fn apply_source_build_state(&mut self, building: bool) -> bool {
match (building, self.lsp.paused_for_build) {
(true, false) => {
if self.lsp.manager.is_none() {
return false;
}
if let Some(old) = self.lsp.manager.take() {
fs_watch::offload_drop(old);
}
self.lsp.paused_for_build = true;
if self.format_request_id.take().is_some() {
self.complete_pending_save();
}
self.lsp.last_seen.clear();
self.lsp.progress.clear();
let msg = "Language servers stopped while croft builds its update on this host";
crate::output::push("Language Servers", crate::output::OutputLevel::Info, msg);
self.status = String::from(msg);
true
}
(false, true) => {
self.lsp.paused_for_build = false;
self.lsp.manager =
match crate::lsp::LspManager::new(self.workspace_root().to_path_buf()) {
Ok(m) => {
m.set_extra_roots(
self.roots.iter().skip(1).map(Path::to_path_buf).collect(),
);
crate::output::push(
"Language Servers",
crate::output::OutputLevel::Info,
"Update build finished; language servers restarted",
);
Some(m)
}
Err(e) => {
let msg = format!("Language servers could not restart: {e}");
crate::output::push(
"Language Servers",
crate::output::OutputLevel::Error,
&msg,
);
self.status = msg;
None
}
};
self.lsp.last_seen.clear();
self.lsp.progress.clear();
self.lsp.semantic_generation_seen.clear();
let open = self.open_buffer_paths();
self.lsp.diagnostics.retain(|p, _| open.contains(p));
self.rebuild_problems();
true
}
_ => false,
}
}
pub(super) fn start_drift_probe_if_local(&mut self) {
if self.session.remote_autoupdate {
return;
}
self.drift_probe = Some(crate::update_watch::DriftProbe::start(
String::from(env!("CARGO_MANIFEST_DIR")),
String::from(env!("CROFT_GIT_HASH_FULL")),
));
}
pub(super) fn start_update_check_if_local(&mut self) {
if self.session.remote_autoupdate || self.session.no_update_check {
return;
}
self.update_check = Some(crate::update_check::UpdateCheck::start(
croft_cache_dir(),
String::from(env!("CARGO_PKG_VERSION")),
));
}
pub(super) fn poll_update_check(&mut self) -> bool {
let Some(check) = self.update_check.as_ref() else {
return false;
};
let Some(verdict) = check.take() else {
return false;
};
self.update_check = None;
let Some(release) = verdict else {
return false;
};
self.update_toast = Some(UpdateToast::offer(release));
true
}
pub(super) fn start_staged_update(&mut self, version: String) {
if self.install_source == crate::update_check::InstallSource::Homebrew {
self.status = format!(
"croft v{version} is available - this install is managed by Homebrew: run `{}`",
crate::update_check::BREW_UPGRADE
);
return;
}
self.staged_status = UpdateStatus::Idle;
#[cfg(test)]
let staging = std::io::Result::Ok(crate::update_check::StagedInstall::preloaded(
&[],
PathBuf::new(),
&version,
));
#[cfg(not(test))]
let staging = crate::update_check::StagedInstall::start(
croft_cache_dir(),
version.clone(),
staged_install_log_path(),
);
match staging {
Ok(install) => {
self.update_toast = None;
self.staged_install = Some(install);
}
Err(e) => self.status = format!("croft v{version} could not be installed: {e}"),
}
}
pub(super) fn dismiss_update_offer(&mut self, version: &str) {
if let Err(e) = crate::update_check::dismiss(&croft_cache_dir(), version) {
self.status = format!("Could not remember the dismissed update: {e}");
}
}
pub(super) fn staged_update_binary(&self) -> Option<PathBuf> {
let install = self.staged_install.as_ref()?;
(self.staged_status == UpdateStatus::Ready).then(|| install.binary().to_path_buf())
}
pub(super) fn any_update_ready(&self) -> bool {
self.update_status == UpdateStatus::Ready || self.staged_status == UpdateStatus::Ready
}
pub(super) fn any_update_in_progress(&self) -> bool {
self.update_status == UpdateStatus::InProgress
|| self.staged_status == UpdateStatus::InProgress
}
pub(super) fn poll_drift_probe(&mut self) -> bool {
let Some(probe) = self.drift_probe.as_ref() else {
return false;
};
let Some(verdict) = probe.take() else {
return false;
};
self.drift_probe = None;
let Some(current) = verdict else {
return false;
};
self.status = format!(
"This croft was built at {}, but its repo is now at {current} - press {UPDATE_CROFT_CHORD} to rebuild & reinstall in the background",
env!("CROFT_GIT_HASH"),
);
self.local_drift = Some(current);
true
}
pub(super) fn start_local_reinstall(&mut self) {
#[cfg(test)]
{
self.self_install = Some(crate::update_watch::SelfInstall::preloaded(&[]));
}
#[cfg(not(test))]
match crate::update_watch::SelfInstall::start(
String::from(env!("CARGO_MANIFEST_DIR")),
self_install_log_path(),
) {
Ok(install) => self.self_install = Some(install),
Err(e) => self.status = format!("croft could not start its rebuild: {e}"),
}
}
pub(super) fn update_armed(&self) -> bool {
self.any_update_ready()
|| (self.local_drift.is_some()
&& self.update_status == UpdateStatus::Idle
&& self.staged_status != UpdateStatus::InProgress
&& self.self_install.is_none()
&& self.staged_install.is_none())
}
pub(super) fn update_croft(&mut self) {
if self.any_update_ready() {
self.arm_reexec();
} else if self.update_armed() {
self.start_local_reinstall();
} else if self.self_install.is_some()
|| self.staged_install.is_some()
|| self.any_update_in_progress()
{
self.status = String::from("croft is already updating in the background");
} else if let Some(version) = self
.update_toast
.as_ref()
.filter(|t| !t.ready)
.map(|t| t.release.version.clone())
{
self.start_staged_update(version);
} else if self.manual_update_check.is_some() {
self.status = String::from("Already checking for croft updates");
} else if let Some(why) = manual_update_check_refusal(
self.session.remote_autoupdate,
self.session.no_update_check,
) {
self.status = String::from(why);
} else {
match crate::update_check::ManualCheck::start_with(
croft_cache_dir(),
String::from(env!("CARGO_PKG_VERSION")),
self.update_fetch,
) {
Ok(check) => {
self.status = String::from("Checking for croft updates\u{2026}");
self.manual_update_check = Some(check);
}
Err(e) => self.status = format!("Could not check for croft updates: {e}"),
}
}
}
pub(super) fn poll_manual_update_check(&mut self) -> bool {
let verdict = match self.manual_update_check.as_ref().map(|c| c.poll()) {
None | Some(crate::jobs::Poll::Pending) => return false,
Some(crate::jobs::Poll::Done(verdict)) => verdict,
Some(crate::jobs::Poll::Died) => {
self.manual_update_check = None;
return true;
}
};
self.manual_update_check = None;
self.status = match verdict {
Ok(Some(release)) => {
let status = format!("croft v{} is available", release.version);
self.update_toast = Some(UpdateToast::offer(release));
status
}
Ok(None) => format!("croft v{} is up to date", env!("CARGO_PKG_VERSION")),
Err(reason) => format!("Could not check for croft updates: {reason}"),
};
true
}
pub fn poll_update_watch(&mut self) -> bool {
let mut changed = self.poll_drift_probe();
changed |= self.poll_source_build_marker();
changed |= self.poll_update_check();
changed |= self.poll_manual_update_check();
let mut events: Vec<(UpdateSource, crate::update_watch::UpdateEvent)> = Vec::new();
if let Some(watch) = self.update_watch.as_ref() {
events.extend(watch.drain().into_iter().map(|e| (UpdateSource::Watch, e)));
}
if let Some(install) = self.self_install.as_mut() {
events.extend(
install
.drain()
.into_iter()
.map(|e| (UpdateSource::SelfInstall, e)),
);
}
if let Some(staged) = self.staged_install.as_mut() {
events.extend(
staged
.drain()
.into_iter()
.map(|e| (UpdateSource::Staged, e)),
);
}
for (source, ev) in events {
changed = true;
let staged = source == UpdateSource::Staged;
match ev {
crate::update_watch::UpdateEvent::InProgress => {
if staged {
self.staged_status = UpdateStatus::InProgress;
} else {
self.update_status = UpdateStatus::InProgress;
}
self.update_spinner_start = Some(std::time::Instant::now());
self.status.clear();
}
crate::update_watch::UpdateEvent::Failed => {
if staged {
self.staged_status = UpdateStatus::Idle;
} else {
self.update_status = UpdateStatus::Idle;
}
if !self.any_update_in_progress() {
self.update_spinner_start = None;
}
let status = match source {
UpdateSource::Staged => {
let staging = self.staged_install.take();
let reason = staging
.as_ref()
.and_then(|s| s.failure_reason())
.unwrap_or("the build failed");
let version = staging.map(|s| s.version).unwrap_or_default();
self.update_toast = Some(UpdateToast {
failed: Some(reason),
..UpdateToast::offer(version.as_str().into())
});
(reason != crate::update_check::CRASHED_REASON).then(|| {
format!(
"croft v{version} was not installed: {reason} - see {} (still on v{})",
staged_install_log_path().display(),
env!("CARGO_PKG_VERSION")
)
})
}
UpdateSource::SelfInstall => {
(!self.self_install.take().is_some_and(|i| i.crashed())).then(|| {
format!(
"croft rebuild failed - see {} (still on the old binary)",
self_install_log_path().display()
)
})
}
UpdateSource::Watch => Some(String::from(
"Background croft update failed; staying on current version",
)),
};
if let Some(status) = status {
self.status = status;
}
}
crate::update_watch::UpdateEvent::Ready => {
if staged {
self.staged_status = UpdateStatus::Ready;
} else {
self.update_status = UpdateStatus::Ready;
}
if !self.any_update_in_progress() {
self.update_spinner_start = None;
}
self.status = format!(
"Update ready - press {UPDATE_CROFT_CHORD} to relaunch croft (terminals will reset)"
);
if staged && let Some(install) = self.staged_install.as_ref() {
self.update_toast = Some(UpdateToast {
ready: true,
..UpdateToast::offer(install.version.as_str().into())
});
}
}
}
}
changed
}
pub(super) fn update_spinner_glyph(&self) -> &'static str {
match self.update_spinner_start {
Some(t) => update_spinner_frame(t.elapsed().as_millis()),
None => UPDATE_SPINNER_FRAMES[0],
}
}
pub(super) fn update_spinner_phase(&self) -> u128 {
match self.update_spinner_start {
Some(t) => t.elapsed().as_millis() / UPDATE_SPINNER_FRAME_MS,
None => 0,
}
}
pub(super) fn arm_reexec(&mut self) {
let path = if cfg!(test) {
std::env::temp_dir().join(format!(
"croft-test-session-{}-{:?}.json",
std::process::id(),
std::thread::current().id()
))
} else {
crate::session_state::handoff_path()
};
if let Err(e) = self.capture_session_state().save(&path) {
self.status = format!("Relaunch cancelled: could not save the session ({e:#})");
return;
}
self.pending_reexec = true;
self.quit = true;
}
pub(super) fn bind_view_socket() -> Option<std::os::unix::net::UnixListener> {
if cfg!(test) {
return None;
}
let dir = croft_cache_dir();
if let Err(e) = std::fs::create_dir_all(&dir) {
*VIEW_BIND_ERROR.lock().unwrap() = Some(format!("{e}"));
return None;
}
let path = crate::view_ipc::socket_path(&dir, std::process::id());
let path = std::path::absolute(&path).unwrap_or(path);
sweep_dead_view_sockets(&dir);
let listener = prepare_view_listener(&path)
.map_err(|e| {
*VIEW_BIND_ERROR.lock().unwrap() = Some(format!("{e}"));
})
.ok()?;
let _ = crate::view_ipc::SOCK_PATH.set(path);
Some(listener)
}
pub fn drain_view_requests(&mut self) -> bool {
if self.view_listener.is_none() {
return false;
}
let deadline = std::time::Instant::now() + self.view_drain_budget;
let mut changed = false;
loop {
if deadline.saturating_duration_since(std::time::Instant::now())
< std::time::Duration::from_millis(3)
{
return changed;
}
let Some(listener) = self.view_listener.as_ref() else {
return changed;
};
match listener.accept() {
Ok((stream, _)) => {
let (_, opened) = self.answer_view_client(stream, deadline);
changed |= opened;
}
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => return changed,
Err(_) => return changed,
}
}
}
pub(super) fn apply_view_request(&mut self, path: &Path) -> crate::view_ipc::ViewReply {
use crate::view_ipc::ViewReply;
if !path.is_absolute() {
return ViewReply::Err {
message: format!(
"the request must carry an absolute path, got {}",
path.display()
),
};
}
let meta = match std::fs::metadata(path) {
Ok(m) => m,
Err(e) => {
return ViewReply::Err {
message: format!("cannot read {}: {e}", path.display()),
};
}
};
if meta.is_dir() {
return ViewReply::Err {
message: format!("{} is a directory", path.display()),
};
}
if !meta.is_file() {
return ViewReply::Err {
message: format!("{} is not a regular file", path.display()),
};
}
let claimed = crate::view_ipc::claim_staged(path, std::process::id());
let path = claimed.as_deref().unwrap_or(path);
match self.editor.open_pinned(path) {
Ok(()) => {
self.focus_pane(Pane::Editor);
self.sync_open_file_poll_mtime();
self.status = if crate::rebase_todo::is_todo(path) {
String::from(crate::rebase_todo::HINT)
} else if let Some(why) = self.editor.hex_routed_because() {
format!("Opened {} in the hex viewer: {why}", path.display())
} else {
format!("Opened {}", path.display())
};
ViewReply::Ok
}
Err(e) => ViewReply::Err {
message: format!("could not open {}: {e}", path.display()),
},
}
}
pub(super) fn handle_update_toast_click(&mut self, x: u16, y: u16) -> bool {
let Some(toast) = self.update_toast.as_ref().filter(|t| t.open) else {
return false;
};
let Some(action) = toast
.buttons
.iter()
.find(|(r, _)| rect_contains(*r, x, y))
.map(|(_, a)| *a)
else {
return false;
};
let version = toast.release.version.clone();
match action {
UpdateToastAction::Update => {
if self.staged_install.is_none() && self.self_install.is_none() {
self.start_staged_update(version);
} else {
self.status = String::from("croft is already updating in the background");
}
}
UpdateToastAction::Skip => {
self.update_toast = None;
self.dismiss_update_offer(&version);
}
UpdateToastAction::Later => {
if let Some(t) = self.update_toast.as_mut() {
t.open = false;
}
}
UpdateToastAction::CopyCommand => {
let command = crate::update_check::BREW_UPGRADE;
self.status = self
.copy_where_pasted(command)
.status(&format!("`{command}`"));
}
UpdateToastAction::ReleaseNotes => {
self.open_url_for_user(&crate::update_check::release_notes_url(&version));
}
UpdateToastAction::InstallLog => {
let log = staged_install_log_path();
if let Err(e) = self.open_at(&log, 0, 0) {
self.status = format!("Could not open {}: {e:#}", log.display());
}
}
UpdateToastAction::Relaunch => {
self.update_toast = None;
if self.staged_update_binary().is_some() {
self.arm_reexec();
}
}
}
true
}
pub(super) fn probe_view_path(&self, path: &Path) -> crate::view_ipc::ViewReply {
let canon = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
let is_it = |p: &Path| p == path || p.canonicalize().is_ok_and(|c| c == canon);
let open = self
.editor_layout
.all_groups(&self.editor)
.flat_map(|g| g.editors.iter())
.any(|t| t.path.as_deref().is_some_and(is_it));
if open {
crate::view_ipc::ViewReply::Err {
message: String::from(crate::view_ipc::PROBE_OPEN),
}
} else {
crate::view_ipc::ViewReply::Err {
message: String::from(crate::view_ipc::PROBE_CLOSED),
}
}
}
pub(super) fn rebase_todo_key(&mut self, key: KeyEvent) -> bool {
let KeyCode::Char(c) = key.code else {
return false;
};
if !key.modifiers.is_empty()
|| self.vim.enabled
|| !self
.editor
.path
.as_deref()
.is_some_and(crate::rebase_todo::is_todo)
{
return false;
}
let Some(action) = crate::rebase_todo::action_for_key(c) else {
return false;
};
let row = self.editor.cursor_row;
let Some(line) = self.editor.lines.get(row).cloned() else {
return false;
};
if line.trim().is_empty() {
self.status = String::from(crate::rebase_todo::HINT);
return true;
}
let Some(new_line) = crate::rebase_todo::set_action(&line, action) else {
return false;
};
if matches!(action, "squash" | "fixup")
&& !crate::rebase_todo::has_kept_commit_above(&self.editor.lines, row)
{
self.status = format!("Can't {action} the first commit: no commit above it");
return true;
}
self.editor
.apply_span_edits(&[crate::widgets::editor::TextSpanEdit {
start: (row, 0),
end: (row, line.chars().count()),
new_text: new_line,
utf16: false,
}]);
if let Some(next) = self.editor.lines[row + 1..]
.iter()
.position(|l| crate::rebase_todo::is_commit_line(l))
{
self.editor.cursor_row = row + 1 + next;
}
self.editor.cursor_col = 0;
self.status = String::from(crate::rebase_todo::HINT);
true
}
pub(super) fn abort_rebase_todo(&mut self) {
if !self
.editor
.path
.as_deref()
.is_some_and(crate::rebase_todo::is_todo)
{
if matches!(
crate::git::repo_operation(&self.scm_root()),
Some(crate::git::RepoOp::Rebase { .. })
) {
self.abort_git_operation();
return;
}
self.status = String::from("Rebase: Abort works in a git-rebase-todo tab");
return;
}
let end = self.editor.lines.len().saturating_sub(1);
let end_col = self
.editor
.lines
.last()
.map(|l| l.chars().count())
.unwrap_or(0);
self.editor
.apply_span_edits(&[crate::widgets::editor::TextSpanEdit {
start: (0, 0),
end: (end, end_col),
new_text: String::new(),
utf16: false,
}]);
self.save();
self.run_command(crate::widgets::command_palette::Command::CloseEditor);
self.status = String::from("Rebase aborted");
}
}
pub(super) fn keyboard_enhancement_flags() -> KeyboardEnhancementFlags {
KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES
| KeyboardEnhancementFlags::REPORT_EVENT_TYPES
}
pub(crate) fn takeover_mode_seq() -> Vec<u8> {
let mut seq = Vec::new();
let _ = execute!(
seq,
EnterAlternateScreen,
EnableMouseCapture,
EnableBracketedPaste,
EnableFocusChange,
crossterm::cursor::SetCursorStyle::SteadyBar,
);
seq
}
pub(super) fn mode_reassert_seq() -> Vec<u8> {
use std::io::Write;
let mut seq = takeover_mode_seq();
let _ = write!(seq, "\x1b[={};1u", keyboard_enhancement_flags().bits());
seq
}
pub(super) fn set_title_seq(title: &str) -> Vec<u8> {
let mut out = Vec::with_capacity(title.len() + 5);
out.extend_from_slice(b"\x1b]0;");
for byte in title.as_bytes() {
match *byte {
0x00..=0x1f | 0x7f => continue,
b => out.push(b),
}
}
out.push(0x07);
out
}
pub(super) fn set_session_bg_srgb_seq(rgb: (u8, u8, u8)) -> String {
format!(
"\x1b]1337;SetColors=bg=srgb:{:02x}{:02x}{:02x}\x07",
rgb.0, rgb.1, rgb.2,
)
}
pub(crate) fn reset_session_bg_seq() -> String {
String::from("\x1b]1337;SetColors=bg=default\x07")
}
pub(super) fn host_colors_seq(theme: crate::theme::Theme) -> String {
let (br, bg, bb) = theme.editor_bg_rgb();
let (fr, fg, fb) = theme.syntax().fg;
format!("\x1b]11;rgb:{br:02x}/{bg:02x}/{bb:02x}\x07\x1b]10;rgb:{fr:02x}/{fg:02x}/{fb:02x}\x07")
}
pub(super) fn theme_host_colors_seq(theme: crate::theme::Theme) -> String {
let mut seq = host_colors_seq(theme);
if crate::iterm2_inline::detect_iterm2_inline_support() {
seq.push_str(&set_session_bg_srgb_seq(theme.editor_bg_rgb()));
}
seq
}
pub(crate) fn reattach_reassert_seq(theme: crate::theme::Theme) -> Vec<u8> {
let mut seq = mode_reassert_seq();
seq.extend_from_slice(theme_host_colors_seq(theme).as_bytes());
seq
}
pub(crate) fn reset_host_colors_seq() -> &'static str {
"\x1b]110\x07\x1b]111\x07"
}
pub(super) fn build_title(workspace: &std::path::Path) -> String {
let name = workspace
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.filter(|s| !s.is_empty())
.unwrap_or_else(|| workspace.display().to_string());
format!("{APP_NAME} {name}")
}
pub(super) const UPDATE_CROFT_CHORD: &str = if cfg!(target_os = "macos") {
"Cmd+Shift+F9"
} else {
"Ctrl+Shift+F9"
};
pub(super) fn prepare_view_listener(
path: &Path,
) -> std::io::Result<std::os::unix::net::UnixListener> {
let listener = crate::session::bind_socket_0600(path)?;
listener.set_nonblocking(true)?;
Ok(listener)
}
pub(super) static VIEW_BIND_ERROR: std::sync::Mutex<Option<String>> = std::sync::Mutex::new(None);
pub(super) fn view_status(view_bind_error: Option<&str>) -> String {
match view_bind_error {
Some(e) => format!("croft view is unavailable: {e}"),
None => String::from("Ready"),
}
}
pub(super) fn settings_not_loaded_status(error: &str) -> String {
format!("Settings not loaded: {error}")
}
pub(super) fn hook_bind_status(e: &std::io::Error) -> Option<String> {
(e.kind() != std::io::ErrorKind::AddrInUse)
.then(|| format!("Agent edit approvals are unavailable: {e}"))
}
pub(crate) fn sweep_dead_view_sockets(dir: &Path) {
let Ok(entries) = std::fs::read_dir(dir) else {
return;
};
let names: Vec<(String, PathBuf)> = entries
.flatten()
.filter_map(|e| Some((e.file_name().to_str()?.to_string(), e.path())))
.collect();
let me = std::process::id();
for (name, entry_path) in &names {
let sock_name = match name.as_str().strip_suffix(".bind.lock") {
Some(stem) => std::borrow::Cow::Owned(format!("{stem}.sock")),
None => std::borrow::Cow::Borrowed(name),
};
let Some(pid) = crate::view_ipc::pid_of_socket(&sock_name) else {
continue;
};
let gone = pid != me
&& unsafe { libc::kill(pid as libc::pid_t, 0) } != 0
&& std::io::Error::last_os_error().raw_os_error() == Some(libc::ESRCH);
if gone {
let _ = std::fs::remove_file(entry_path);
sweep_dead_bind_stages(&names, pid);
let _ = std::fs::remove_file(dir.join(sock_name.as_ref()).with_extension("bind.lock"));
}
}
sweep_staged_stdin(dir);
}
pub(super) fn sweep_dead_bind_stages(names: &[(String, PathBuf)], pid: u32) {
let prefix = format!(".s{pid}-");
for (name, path) in names {
if name.starts_with(&prefix) && name[prefix.len()..].parse::<u64>().is_ok() {
let _ = std::fs::remove_dir_all(path);
}
}
}
pub(super) const STAGED_STDIN_RETENTION: std::time::Duration =
std::time::Duration::from_secs(60 * 60 * 24);
pub(super) fn sweep_staged_stdin(dir: &Path) {
let staged = dir.join("view-stdin");
let Ok(entries) = std::fs::read_dir(&staged) else {
return;
};
for entry in entries.flatten() {
let name = entry.file_name();
let Some(name) = name.to_str() else { continue };
if !name.starts_with("stdin-") && !name.starts_with(crate::view_ipc::HELD_PREFIX) {
continue;
}
if let Some(holder) = crate::view_ipc::holder_of_staged(name) {
let alive = holder == std::process::id()
|| unsafe { libc::kill(holder as libc::pid_t, 0) } == 0
|| std::io::Error::last_os_error().raw_os_error() != Some(libc::ESRCH);
if alive {
continue;
}
}
let too_old = entry
.metadata()
.and_then(|m| m.modified())
.and_then(|t| t.elapsed().map_err(std::io::Error::other))
.is_ok_and(|age| age > STAGED_STDIN_RETENTION);
if too_old {
let _ = std::fs::remove_file(entry.path());
}
}
}
pub(super) fn self_install_log_path() -> PathBuf {
croft_cache_dir().join(format!("self-install-{}.log", std::process::id()))
}
pub(super) fn staged_install_log_path() -> PathBuf {
croft_cache_dir().join(format!("staged-install-{}.log", std::process::id()))
}
pub(super) fn reexec_binary_path(
local_install: Option<&crate::update_watch::SelfInstall>,
) -> PathBuf {
let installed = if let Some(install) = local_install {
install
.installed_path()
.or_else(crate::update_watch::cargo_install_bin)
} else {
std::env::var_os("HOME")
.map(|home| PathBuf::from(home).join(".cargo").join("bin").join("croft"))
};
if let Some(p) = installed
&& p.exists()
{
return p;
}
std::env::current_exe().unwrap_or_else(|_| PathBuf::from("croft"))
}
pub(super) fn restore_host_terminal_state() {
use std::io::Write;
let mut out = stdout();
let _ = out.write_all(TERMINAL_RESTORE_SEQ);
let _ = out.flush();
}
pub(super) const TERMINAL_RESTORE_SEQ: &[u8] =
b"\x1b[?2026l\x1b[?1000l\x1b[?1002l\x1b[?1003l\x1b[?1006l\x1b[?1015l\x1b[?2004l\x1b[?1004l\x1b[?1049l\x1b[ q\x1b]110\x07\x1b]111\x07";
impl App {
pub(super) fn poll_background_panic(&mut self) -> bool {
let crashes = take_background_panics();
if crashes.is_empty() {
return false;
}
let recovered = crashes.iter().all(|c| c.recovered);
let threads = crashes
.iter()
.map(|c| c.thread.as_str())
.collect::<Vec<_>>()
.join(", ");
self.status = if recovered {
format!(
"A background task crashed ({threads}); croft carried on without it. \
Details in ~/.cache/croft/panic.log"
)
} else {
format!(
"A background task crashed ({threads}). Save your work and restart croft; \
details in ~/.cache/croft/panic.log"
)
};
true
}
}
pub(super) struct BackgroundPanic {
pub(super) thread: String,
pub(super) recovered: bool,
}
static BACKGROUND_PANIC: std::sync::Mutex<Vec<BackgroundPanic>> = std::sync::Mutex::new(Vec::new());
pub(super) fn panic_ends_croft(
panicking: std::thread::ThreadId,
ui: std::thread::ThreadId,
) -> bool {
panicking == ui
}
pub(super) fn note_background_panic(thread: &str, recovered: bool) {
BACKGROUND_PANIC
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.push(BackgroundPanic {
thread: thread.to_string(),
recovered,
});
}
pub(super) fn take_background_panics() -> Vec<BackgroundPanic> {
std::mem::take(
&mut *BACKGROUND_PANIC
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner),
)
}
pub(super) fn claim_background_panic(thread: &str) {
BACKGROUND_PANIC
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.retain(|crash| crash.thread != thread);
}
pub(super) fn install_terminal_restore_panic_hook() {
static HOOK: std::sync::Once = std::sync::Once::new();
HOOK.call_once(|| {
let ui = std::thread::current().id();
let original = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
use std::io::Write;
log_panic_to_file(info);
let current = std::thread::current();
if !panic_ends_croft(current.id(), ui) {
note_background_panic(
current.name().unwrap_or("<unnamed>"),
crate::jobs::on_supervised_thread(),
);
return;
}
let _ = disable_raw_mode();
let mut out = stdout();
let _ = out.write_all(TERMINAL_RESTORE_SEQ);
let _ = out.write_all(b"\x1b[?25h");
let _ = out.flush();
original(info);
}));
});
}
pub(super) fn log_panic_to_file(info: &std::panic::PanicHookInfo<'_>) {
use std::io::Write;
let Some(home) = std::env::var_os("HOME") else {
return;
};
let dir = std::path::PathBuf::from(home).join(".cache").join("croft");
let _ = std::fs::create_dir_all(&dir);
let Ok(mut f) = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(dir.join("panic.log"))
else {
return;
};
let payload = info.payload();
let message = payload
.downcast_ref::<&str>()
.map(|s| s.to_string())
.or_else(|| payload.downcast_ref::<String>().cloned())
.unwrap_or_else(|| String::from("<non-string panic payload>"));
let location = info
.location()
.map(|l| format!("{}:{}:{}", l.file(), l.line(), l.column()))
.unwrap_or_else(|| String::from("<unknown>"));
let thread = std::thread::current()
.name()
.unwrap_or("<unnamed>")
.to_string();
let backtrace = std::backtrace::Backtrace::force_capture();
let _ = writeln!(
f,
"=== croft {} panicked ===\nthread: {thread}\nlocation: {location}\nmessage: {message}\nbacktrace:\n{backtrace}\n",
env!("CARGO_PKG_VERSION"),
);
}