rcom/src/ui/render.rs

1470 lines
46 KiB
Rust

//! Pure Ratatui rendering for application state and transient overlays.
use std::path::Path;
use std::time::SystemTime;
use chrono::{DateTime, Utc};
use ratatui::Frame;
use ratatui::layout::{Alignment, Rect, Size};
use ratatui::style::Style;
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, Clear, Paragraph};
use unicode_width::UnicodeWidthStr;
use crate::app::{AppState, Clipboard, Overlay, PaneId, PaneMode, PaneState};
use crate::domain::{Entry, EntryKind, Location, SourceId};
use crate::image_preview::ImageRenderContext;
use crate::operations::{OperationKind, WorkKind};
use crate::preview::{EntryPreview, Preview, PreviewKind, TRUNCATION_MARKER};
use crate::ssh::HostPickerState;
use super::help::{HelpTabs, help_view_model};
use super::layout::{ColumnRole, centered, frame_layout_with_filter, pane_rows_area};
use super::text::{fit, sanitize, truncate_filename, truncate_middle, wrap};
use super::{IconMode, ResolvedIcon, Theme, ThemeId};
/// Draws a complete frame without mutating application or picker state.
pub fn render(
frame: &mut Frame,
app: &AppState,
host_picker: Option<&HostPickerState>,
theme: &Theme,
) {
render_with_context(frame, app, host_picker, theme, None);
}
/// Production rendering with optional fixed prepared images; no resize/encode occurs in Frame.
pub fn render_with_context(
frame: &mut Frame,
app: &AppState,
host_picker: Option<&HostPickerState>,
theme: &Theme,
image_context: Option<ImageRenderContext<'_>>,
) {
let area = frame.area();
if area.is_empty() {
return;
}
frame.render_widget(Block::new().style(theme.base()), area);
let layout =
frame_layout_with_filter(area, app.mode, app.active, app.overlay == Overlay::Filter);
if layout.too_small {
render_too_small(frame, area, theme);
return;
}
if let Some(header) = layout.header {
render_header(frame, header, app, theme);
}
for column in &layout.columns {
match column.role {
ColumnRole::Parent => render_parent(frame, column.area, app.active_pane(), theme),
ColumnRole::Pane(id) => render_pane(
frame,
column.area,
app.pane(id),
!app.filter_query(id).is_empty(),
app.clipboard.as_ref(),
id,
id == app.active,
app.mode,
theme,
),
ColumnRole::Preview => {
render_preview(
frame,
column.area,
app.active_pane(),
app.active,
theme,
false,
image_context,
app.terminal_epoch,
);
}
}
}
if let Some(editor) = layout.filter_editor {
render_filter_editor(frame, editor, app, theme);
}
if let Some(status) = layout.status {
render_status(frame, status, app, theme);
}
match app.overlay {
Overlay::None | Overlay::Filter => {}
Overlay::Help => render_help(frame, area, app, theme),
Overlay::HostPicker => render_host_picker(frame, area, host_picker, theme),
Overlay::Preview => render_preview_overlay(
frame,
area,
app.active_pane(),
app.active,
theme,
image_context,
app.terminal_epoch,
),
Overlay::ThemePicker => render_theme_picker(frame, area, app, theme),
Overlay::Message => render_message_overlay(frame, area, app, theme),
Overlay::EntryPrompt | Overlay::ConfirmEntryAction | Overlay::Undo | Overlay::Edit => {
super::actions::render_action_overlay(frame, area, app, theme)
}
Overlay::Tasks | Overlay::TaskDetails
if app
.task_manager
.tasks()
.any(|task| task.plan().work_kind() != WorkKind::CopyMove) =>
{
super::actions::render_task_overlay(
frame,
area,
app,
theme,
app.overlay == Overlay::TaskDetails,
);
}
Overlay::DestinationPrompt
| Overlay::ConfirmOperation
| Overlay::Collision
| Overlay::Tasks
| Overlay::TaskDetails
| Overlay::Quit => super::operations::render_operation_overlay(frame, area, app, theme),
}
}
fn render_header(frame: &mut Frame, area: Rect, app: &AppState, theme: &Theme) {
const BRAND: &str = " RCOM ";
const SUBTITLE: &str = "dual-pane file manager";
const HELP: &str = "? Help";
let mode = match app.mode {
PaneMode::Single => "SINGLE",
PaneMode::Dual if app.active == PaneId::Left => "DUAL PANE 1/2",
PaneMode::Dual => "DUAL PANE 2/2",
};
let width = usize::from(area.width);
let brand_width = UnicodeWidthStr::width(BRAND);
let mode_width = UnicodeWidthStr::width(mode);
let help_width = UnicodeWidthStr::width(HELP);
let show_mode = brand_width + mode_width + 2 + help_width <= width;
let reserved_right = if show_mode { mode_width + 2 } else { 0 } + help_width;
let show_subtitle =
brand_width + UnicodeWidthStr::width(SUBTITLE) + 2 + reserved_right <= width;
let mut left = vec![Span::styled(
BRAND,
Style::new()
.fg(theme.color(theme.palette.active))
.bg(theme.color(theme.palette.background))
.add_modifier(ratatui::style::Modifier::BOLD),
)];
if show_subtitle {
left.push(Span::styled(SUBTITLE, theme.base()));
}
frame.render_widget(Paragraph::new(Line::from(left)).style(theme.base()), area);
let mut right = Vec::new();
if show_mode {
right.push(Span::styled(format!("{mode} "), theme.base()));
}
right.push(Span::styled(HELP, theme.active()));
frame.render_widget(
Paragraph::new(Line::from(right))
.alignment(Alignment::Right)
.style(theme.base()),
area,
);
}
fn render_too_small(frame: &mut Frame, area: Rect, theme: &Theme) {
let separator = theme.separator();
let message = format!(
"Current {}x{}{}Required 40x8",
area.width, area.height, separator
);
let lines = vec![
Line::from("TERMINAL TOO SMALL").style(theme.error()),
Line::from(message).style(theme.muted()),
];
let height = lines.len().min(usize::from(area.height)) as u16;
let centered = Rect::new(
area.x,
area.y + area.height.saturating_sub(height) / 2,
area.width,
height,
);
frame.render_widget(
Paragraph::new(lines)
.alignment(Alignment::Center)
.style(theme.panel()),
centered,
);
}
#[allow(clippy::too_many_arguments)]
fn render_pane(
frame: &mut Frame,
area: Rect,
pane: &PaneState,
filtering: bool,
clipboard: Option<&Clipboard>,
id: PaneId,
active: bool,
mode: PaneMode,
theme: &Theme,
) {
let full_state = match (mode, active) {
(PaneMode::Dual, true) => format!(
"{} ACTIVE{}PANE {}/2",
theme.active_marker(),
theme.separator(),
id.index() + 1
),
(PaneMode::Dual, false) => format!(" PANE {}/2", id.index() + 1),
(_, true) => format!("{} ACTIVE", theme.active_marker()),
(_, false) => format!(" PANE {}", id.index() + 1),
};
let source = source_badge(&pane.location);
let title_width = usize::from(area.width.saturating_sub(2));
let full_prefix = format!(
"{full_state}{}{source}{}",
theme.separator(),
theme.separator()
);
let full_prefix_width = UnicodeWidthStr::width(full_prefix.as_str());
let compact = active
&& full_prefix_width.saturating_add(4) > title_width
&& matches!(pane.location.source, SourceId::Ssh(_));
let join_separator = if compact {
if theme.is_ascii() { "|" } else { "·" }
} else {
theme.separator()
};
let prefix = if compact {
let compact_state = match (mode, active) {
(PaneMode::Dual, true) => {
format!("{} ACTIVE {}/2", theme.active_marker(), id.index() + 1)
}
(PaneMode::Dual, false) => format!(" {}/2", id.index() + 1),
_ => full_state,
};
format!("{compact_state}{join_separator}{source}{join_separator}")
} else {
full_prefix
};
let source_with_separator = format!("{source}{join_separator}");
let state_with_separator = prefix
.strip_suffix(&source_with_separator)
.unwrap_or(&prefix);
let path_separator = join_separator;
let path_reserve = 4;
let source_width = title_width
.saturating_sub(UnicodeWidthStr::width(state_with_separator))
.saturating_sub(UnicodeWidthStr::width(path_separator) + path_reserve);
let source = truncate_source_badge(&source, source_width, theme.is_ascii());
let prefix = format!("{state_with_separator}{source}{path_separator}");
let path_width = title_width.saturating_sub(UnicodeWidthStr::width(prefix.as_str()));
let path = truncate_middle(&display_path(&pane.location), path_width, theme.is_ascii());
let title = format!("{prefix}{path}");
let border_style = if active {
theme.active()
} else {
theme.muted()
};
let mut block = Block::new()
.borders(Borders::ALL)
.border_type(theme.border_type())
.border_style(border_style)
.title(title)
.style(theme.panel());
let foreground_loading = pane.loading && !pane.background_refresh;
if foreground_loading {
block = block.title_bottom(
Line::from(format!(" {} LOADING ", theme.loading_marker()))
.alignment(Alignment::Right)
.style(theme.active()),
);
}
let inner = block.inner(area);
frame.render_widget(block, area);
if inner.is_empty() {
return;
}
if let Some(error) = &pane.error {
render_message(
frame,
inner,
"LISTING ERROR",
&[
error.user_message(),
["m Details", "h Parent", "Ctrl-r Retry", "s Reconnect"].join(theme.separator()),
],
theme.error(),
theme,
);
} else if foreground_loading && pane.entries.is_empty() {
let target = pane.pending_target.as_ref().unwrap_or(&pane.location);
let message = match &target.source {
SourceId::Ssh(host) if target.path == Path::new(".") => {
format!("Connect SSH {}", sanitize(host.as_str()))
}
_ => format!("Reading {}", display_path(target)),
};
render_message(
frame,
inner,
&format!("{} LOADING", theme.loading_marker()),
&[message],
theme.active(),
theme,
);
} else if pane.entries.is_empty() {
let (heading, messages) = if filtering {
(
"NO MATCHES",
vec![
"No entries match the current filter.".to_owned(),
["/ Edit filter", "Esc Close/Clear"].join(theme.separator()),
],
)
} else {
(
"EMPTY DIRECTORY",
vec![
"No visible entries.".to_owned(),
[". Show hidden", "Ctrl-r Refresh"].join(theme.separator()),
],
)
};
render_message(frame, inner, heading, &messages, theme.muted(), theme);
} else {
render_entries(frame, area, inner, pane, clipboard, active, theme);
}
}
fn render_entries(
frame: &mut Frame,
pane_area: Rect,
inner: Rect,
pane: &PaneState,
clipboard: Option<&Clipboard>,
active: bool,
theme: &Theme,
) {
let rows_area = pane_rows_area(pane_area);
if rows_area.y > inner.y {
let header = entry_row(
" ",
"TYPE",
None,
"NAME",
"SIZE",
"MODIFIED",
inner.width,
theme,
false,
);
frame.render_widget(
Paragraph::new(header).style(theme.secondary()),
Rect::new(inner.x, inner.y, inner.width, 1),
);
}
let visible = usize::from(rows_area.height);
if visible == 0 {
return;
}
let selected = pane.selection.index();
let offset = selected
.map(|index| index.saturating_sub(visible / 2))
.unwrap_or(0)
.min(pane.entries.len().saturating_sub(visible));
let end = offset.saturating_add(visible).min(pane.entries.len());
let normal_style = if active { theme.text() } else { theme.muted() };
for (row, index) in (offset..end).enumerate() {
let entry = &pane.entries[index];
let is_selected = selected == Some(index);
let id = pane.location.entry_id(&entry.name);
let marked = pane.selection_set.contains(&id);
let clipboard_kind = clipboard
.filter(|clipboard| clipboard.sources.contains(&id))
.map(|clipboard| clipboard.kind);
let marker = format!(
"{}{}",
if is_selected {
theme.selected_marker()
} else {
" "
},
match (marked, clipboard_kind) {
(true, Some(OperationKind::Copy)) if theme.is_ascii() => "C",
(true, Some(OperationKind::Move)) if theme.is_ascii() => "X",
(true, Some(OperationKind::Copy)) => "±",
(true, Some(OperationKind::Move)) => "∓",
(true, None) => "*",
(false, Some(OperationKind::Copy)) => "+",
(false, Some(OperationKind::Move)) => "-",
(false, None) => " ",
}
);
let name = entry_display_name(entry);
let line = entry_row(
&marker,
entry_kind(entry.kind),
Some(theme.icon_resolver().resolve(entry)),
&name,
&format_size(entry.size, theme),
&format_modified(entry.modified),
rows_area.width,
theme,
is_selected,
);
let style = if is_selected {
theme.selection()
} else {
normal_style
};
let row_area = Rect::new(
rows_area.x,
rows_area.y.saturating_add(row as u16),
rows_area.width,
1,
);
frame.render_widget(Paragraph::new(line).style(style), row_area);
// Raw spans used as spacing do not necessarily touch their cells in the Buffer. Apply the
// effective selected style afterwards so selection has no Reset-colored gaps around icons.
if is_selected {
frame.buffer_mut().set_style(row_area, style);
}
}
}
#[allow(clippy::too_many_arguments)]
fn entry_row(
marker: &str,
kind: &str,
icon: Option<ResolvedIcon>,
name: &str,
size: &str,
modified: &str,
width: u16,
theme: &Theme,
selected: bool,
) -> Line<'static> {
let width = usize::from(width);
let marker_width = UnicodeWidthStr::width(marker);
let show_size = width >= 30;
let show_modified = width >= 46;
let size_width = if show_size { 9 } else { 0 };
let modified_width = if show_modified { 17 } else { 0 };
let show_text_kind = theme.icon_resolver().mode() == IconMode::None;
let text_kind_width = if show_text_kind { 5 } else { 1 };
let glyph_width = icon
.as_ref()
.map_or(0, |icon| UnicodeWidthStr::width(icon.glyph));
let icon_width = if glyph_width == 0 { 0 } else { glyph_width + 1 };
let name_width = width
.saturating_sub(marker_width + text_kind_width + icon_width + size_width + modified_width);
let name = if name.ends_with('/') {
truncate_middle(name, name_width, theme.is_ascii())
} else {
truncate_filename(name, name_width, theme.is_ascii())
};
let mut spans = vec![Span::raw(fit(marker, marker_width, theme.is_ascii()))];
if show_text_kind {
spans.push(Span::raw(fit(kind, 4, theme.is_ascii())));
}
spans.push(Span::raw(" "));
if let Some(icon) = icon.filter(|_| glyph_width > 0) {
let style = if selected {
Style::new()
} else {
theme.icon_style(&icon)
};
spans.push(Span::styled(
fit(icon.glyph, glyph_width, theme.is_ascii()),
style,
));
spans.push(Span::raw(" "));
}
let name_style = match (selected, icon) {
(false, Some(icon)) => theme.filename_style(icon.class),
_ => Style::new(),
};
spans.push(Span::styled(
fit(&name, name_width, theme.is_ascii()),
name_style,
));
if show_size {
spans.push(Span::raw(format!(" {size:>8}")));
}
if show_modified {
spans.push(Span::raw(format!(" {modified}")));
}
let used: usize = spans
.iter()
.map(|span| UnicodeWidthStr::width(span.content.as_ref()))
.sum();
if used < width {
spans.push(Span::raw(" ".repeat(width - used)));
}
if selected {
for span in &mut spans {
span.style = theme.selection();
}
}
Line::from(spans)
}
fn render_parent(frame: &mut Frame, area: Rect, pane: &PaneState, theme: &Theme) {
let parent = pane
.location
.parent()
.unwrap_or_else(|| pane.location.clone());
let title = format!("PARENT{}{}", theme.separator(), display_path(&parent));
let title = truncate_middle(
&title,
usize::from(area.width.saturating_sub(2)),
theme.is_ascii(),
);
let block = Block::new()
.borders(Borders::ALL)
.border_type(theme.border_type())
.border_style(theme.muted())
.title(title)
.style(theme.panel());
let inner = block.inner(area);
frame.render_widget(block, area);
if inner.is_empty() {
return;
}
let mut ancestors: Vec<&Path> = pane.location.path.ancestors().collect();
ancestors.reverse();
let skip = ancestors.len().saturating_sub(usize::from(inner.height));
let lines = ancestors.into_iter().skip(skip).map(|path| {
let current = path == pane.location.path;
let marker = if current {
theme.selected_marker()
} else {
" "
};
let label = if path.file_name().is_none() {
path.display().to_string()
} else {
format!(
"{}/",
path.file_name().unwrap_or_default().to_string_lossy()
)
};
let label = sanitize(&label);
let text = fit(
&format!("{marker} {label}"),
usize::from(inner.width),
theme.is_ascii(),
);
Line::from(text).style(if current {
theme.selection()
} else {
theme.muted()
})
});
frame.render_widget(
Paragraph::new(lines.collect::<Vec<_>>()).style(theme.panel()),
inner,
);
}
#[allow(clippy::too_many_arguments)]
fn render_preview(
frame: &mut Frame,
area: Rect,
pane: &PaneState,
pane_id: PaneId,
theme: &Theme,
overlay: bool,
image_context: Option<ImageRenderContext<'_>>,
terminal_epoch: u64,
) {
let title_width = usize::from(area.width.saturating_sub(2));
let title = if let Some(entry) = pane.selected_entry() {
let icon = theme.icon_resolver().resolve(entry);
let prefix = format!("PREVIEW{}", theme.separator());
let mut spans = vec![Span::raw(prefix.clone())];
let mut used = UnicodeWidthStr::width(prefix.as_str());
if !icon.glyph.is_empty() {
let width = UnicodeWidthStr::width(icon.glyph);
spans.push(Span::styled(icon.glyph, theme.icon_style(&icon)));
spans.push(Span::raw(" "));
used += width + 1;
}
let name = entry_display_name(entry);
let name = truncate_middle(&name, title_width.saturating_sub(used), theme.is_ascii());
spans.push(Span::styled(name, theme.filename_style(icon.class)));
Line::from(spans)
} else {
Line::from("PREVIEW")
};
let block = Block::new()
.borders(Borders::ALL)
.border_type(theme.border_type())
.border_style(if overlay {
theme.active()
} else {
theme.muted()
})
.title(title)
.style(theme.panel());
let inner = block.inner(area);
if overlay {
frame.render_widget(Clear, area);
}
frame.render_widget(block, area);
if inner.is_empty() {
return;
}
if pane.preview.debouncing || (pane.preview.loading && pane.preview.selection_recovery) {
frame.render_widget(Paragraph::new("").style(theme.panel()), inner);
} else if pane.selected_entry().is_none() {
render_message(
frame,
inner,
"NO PREVIEW",
&["Select a file or directory to inspect it.".to_owned()],
theme.muted(),
theme,
);
} else if pane.preview.loading && !pane.preview.background_refresh {
render_message(
frame,
inner,
&format!("{} LOADING PREVIEW", theme.loading_marker()),
&[if theme.is_ascii() {
"Reading a bounded, safe preview...".to_owned()
} else {
"Reading a bounded, safe preview…".to_owned()
}],
theme.active(),
theme,
);
} else if let Some(error) = &pane.preview.error {
render_message(
frame,
inner,
"PREVIEW ERROR",
&[error.user_message()],
theme.error(),
theme,
);
} else if let Some(preview) = &pane.preview.content {
let rendered_image = preview.kind == crate::preview::PreviewKind::Image
&& render_prepared_image(frame, inner, pane, pane_id, terminal_epoch, image_context);
if !rendered_image {
render_preview_content(frame, inner, preview, theme);
}
} else {
render_message(
frame,
inner,
"NO PREVIEW",
&["Preview is unavailable for this entry.".to_owned()],
theme.muted(),
theme,
);
}
}
fn directory_preview_line(
entry: &EntryPreview,
display_name: &str,
width: u16,
theme: &Theme,
) -> Line<'static> {
let kind = if entry.is_dir {
EntryKind::Directory
} else {
EntryKind::File
};
let domain_entry = Entry::new(entry.name.clone(), kind);
let icon = theme.icon_resolver().resolve(&domain_entry);
let name = display_name;
let width = usize::from(width);
let glyph_width = UnicodeWidthStr::width(icon.glyph);
if glyph_width == 0 {
return Line::from(fit(name, width, theme.is_ascii())).style(theme.text());
}
let name_width = width.saturating_sub(glyph_width + 1);
let name = if entry.is_dir {
truncate_middle(name, name_width, theme.is_ascii())
} else {
truncate_filename(name, name_width, theme.is_ascii())
};
Line::from(vec![
Span::styled(icon.glyph, theme.icon_style(&icon)),
Span::raw(" "),
Span::styled(name, theme.filename_style(icon.class)),
])
}
fn render_prepared_image(
frame: &mut Frame,
area: Rect,
pane: &PaneState,
pane_id: PaneId,
terminal_epoch: u64,
context: Option<ImageRenderContext<'_>>,
) -> bool {
let Some(context) = context else {
return false;
};
let Some(target) = pane.preview.target.clone() else {
return false;
};
let identity = context.identity(
pane_id,
pane.preview.image_generation,
target,
pane.session_epoch,
Size::new(area.width, area.height),
terminal_epoch,
);
let Some(protocol) = context.cache.current(&identity) else {
return false;
};
if protocol.needs_placeholder(area).is_some() {
return false;
}
frame.render_widget(ratatui_image::Image::new(protocol), area);
true
}
fn render_preview_content(frame: &mut Frame, area: Rect, preview: &Preview, theme: &Theme) {
let footer_height = u16::from(preview.truncated);
let body = Rect::new(
area.x,
area.y,
area.width,
area.height.saturating_sub(footer_height),
);
let lines: Vec<Line<'static>> =
if preview.kind == PreviewKind::Directory && !preview.directory_entries.is_empty() {
preview
.directory_entries
.iter()
.zip(preview.lines.iter())
.take(usize::from(body.height))
.map(|(entry, line)| directory_preview_line(entry, line, body.width, theme))
.collect()
} else {
preview
.lines
.iter()
.filter(|line| !preview.truncated || line.as_str() != TRUNCATION_MARKER)
.take(usize::from(body.height))
.map(|line| {
let safe = sanitize(line);
Line::from(fit(&safe, usize::from(body.width), theme.is_ascii()))
.style(theme.text())
})
.collect()
};
frame.render_widget(Paragraph::new(lines).style(theme.panel()), body);
if footer_height > 0 {
let footer = Rect::new(
area.x,
area.y.saturating_add(body.height),
area.width,
footer_height,
);
let marker = fit(
TRUNCATION_MARKER,
usize::from(footer.width),
theme.is_ascii(),
);
frame.render_widget(
Paragraph::new(Line::from(marker).style(theme.secondary())).style(theme.panel()),
footer,
);
}
}
fn render_message(
frame: &mut Frame,
area: Rect,
heading: &str,
messages: &[String],
heading_style: Style,
theme: &Theme,
) {
let mut lines = vec![
Line::from(sanitize(heading)).style(heading_style),
Line::from(""),
];
lines.extend(messages.iter().map(|message| {
Line::from(fit(
&sanitize(message),
usize::from(area.width),
theme.is_ascii(),
))
.style(theme.text())
}));
frame.render_widget(Paragraph::new(lines).style(theme.panel()), area);
}
fn render_filter_editor(frame: &mut Frame, area: Rect, app: &AppState, theme: &Theme) {
let query = app
.filter_editor
.as_ref()
.map(|editor| editor.draft.as_str())
.unwrap_or("");
let input = format!(
"FILTER> {}",
crate::preview::sanitize_text(query.as_bytes())
);
frame.render_widget(
Paragraph::new(fit(&input, usize::from(area.width), theme.is_ascii()))
.style(theme.active()),
Rect::new(area.x, area.y, area.width, 1),
);
if area.height > 1 {
frame.render_widget(
Paragraph::new(fit(
"Enter Apply | Esc Cancel | Ctrl-u Clear",
usize::from(area.width),
theme.is_ascii(),
))
.alignment(Alignment::Center)
.style(theme.secondary()),
Rect::new(area.x, area.y + 1, area.width, 1),
);
}
}
fn render_status(frame: &mut Frame, area: Rect, app: &AppState, theme: &Theme) {
let pane = app.active_pane();
let filter = app.filter_stats(app.active);
let (message, style) = if let Some(error) = &pane.error {
(
format!("ERROR {}{}", theme.separator(), error.user_message()),
theme.error(),
)
} else if pane.loading && !pane.background_refresh {
let warning = if pane.entries.is_empty() {
"Reading directory".to_owned()
} else {
format!(
"{} Refreshing; previous listing may be stale",
theme.warning_marker()
)
};
(
format!(
"{} LOADING{}{}",
theme.loading_marker(),
theme.separator(),
warning
),
theme.active(),
)
} else if !filter.query.is_empty() {
let query = crate::preview::sanitize_text(filter.query.as_bytes());
let marked = if filter.hidden_marked > 0 {
format!(
"{}Hidden marked {}",
theme.separator(),
filter.hidden_marked
)
} else {
String::new()
};
let counts = format!(
"{}{}/{}{}",
theme.separator(),
filter.visible,
filter.total,
marked
);
let prefix = "FILTER ";
let query_width = usize::from(area.width)
.saturating_sub(UnicodeWidthStr::width(prefix))
.saturating_sub(UnicodeWidthStr::width(counts.as_str()));
let query = if query_width == 0 {
String::new()
} else {
truncate_middle(&query, query_width, theme.is_ascii())
};
(format!("{prefix}{query}{counts}"), theme.secondary())
} else if let Some(notice) = filter.notice {
(notice, theme.secondary())
} else {
let selected = pane.selection.index().map_or(0, |index| index + 1);
let hidden = if pane.show_hidden { "shown" } else { "hidden" };
let marked = if pane.selection_set.is_empty() {
String::new()
} else {
format!("{}Marked {}", theme.separator(), pane.selection_set.len())
};
(
format!(
"{} entries{}Selected {}/{}{}Dotfiles {}{}",
pane.entries.len(),
theme.separator(),
selected,
pane.entries.len(),
theme.separator(),
hidden,
marked
),
theme.base(),
)
};
let message = fit(
&sanitize(&message),
usize::from(area.width),
theme.is_ascii(),
);
frame.render_widget(Paragraph::new(message).style(style), area);
}
fn render_theme_picker(frame: &mut Frame, area: Rect, app: &AppState, theme: &Theme) {
let Some(picker) = &app.theme_picker else {
return;
};
let overlay = centered(area, 64, 24);
let block = Block::new()
.borders(Borders::ALL)
.border_type(theme.border_type())
.border_style(theme.active())
.title("THEMES")
.style(theme.panel());
let inner = block.inner(overlay);
frame.render_widget(Clear, overlay);
frame.render_widget(block, overlay);
if inner.is_empty() {
return;
}
let footer_height = u16::from(inner.height >= 2);
let error_height = u16::from(picker.error.is_some() && inner.height >= 4);
let list_height = inner
.height
.saturating_sub(footer_height)
.saturating_sub(error_height);
let visible = usize::from(list_height).max(1);
let selected = picker.selected_index();
let mut offset = effective_scroll(picker.scroll, visible, ThemeId::ALL.len());
if selected < offset {
offset = selected;
} else if selected >= offset + visible {
offset = selected + 1 - visible;
}
offset = offset.min(ThemeId::ALL.len().saturating_sub(visible));
let lines = ThemeId::ALL
.iter()
.enumerate()
.skip(offset)
.take(visible)
.map(|(index, id)| {
let marker = if index == selected { ">" } else { " " };
let row = format!(
"{marker} {} {} {}/20",
id.display_name(),
id.mode().as_str(),
index + 1
);
Line::from(fit(&row, usize::from(inner.width), theme.is_ascii())).style(
if index == selected {
theme.selection()
} else {
theme.text()
},
)
})
.collect::<Vec<_>>();
frame.render_widget(
Paragraph::new(lines).style(theme.panel()),
Rect::new(inner.x, inner.y, inner.width, list_height),
);
if error_height > 0 {
let error = picker.error.as_deref().unwrap_or("Theme save failed");
frame.render_widget(
Paragraph::new(fit(
&format!("ERROR: {}", sanitize(error)),
usize::from(inner.width),
theme.is_ascii(),
))
.style(theme.error()),
Rect::new(inner.x, inner.y + list_height, inner.width, error_height),
);
}
if footer_height > 0 {
frame.render_widget(
Paragraph::new(fit(
"Enter Save | Esc Cancel",
usize::from(inner.width),
theme.is_ascii(),
))
.alignment(Alignment::Center)
.style(theme.secondary()),
Rect::new(inner.x, inner.y + inner.height - 1, inner.width, 1),
);
}
}
fn render_help(frame: &mut Frame, area: Rect, app: &AppState, theme: &Theme) {
let model = help_view_model(area, &app.help);
let block = Block::new()
.borders(Borders::ALL)
.border_type(theme.border_type())
.border_style(theme.active())
.title("HELP")
.style(theme.panel());
frame.render_widget(Clear, model.overlay);
frame.render_widget(block, model.overlay);
if model.inner.is_empty() {
return;
}
if let Some(tabs_area) = model.tabs_area {
match model.tabs {
HelpTabs::Full => {
let mut spans = Vec::new();
for (index, category) in crate::app::HelpCategory::ALL.iter().enumerate() {
if index > 0 {
spans.push(Span::raw(" "));
}
let active = *category == app.help.category;
let label = if active {
format!("[{}]", category.label())
} else {
category.label().to_owned()
};
spans.push(Span::styled(
label,
if active {
theme.active()
} else {
theme.muted()
},
));
}
frame.render_widget(
Paragraph::new(Line::from(spans)).style(theme.panel()),
tabs_area,
);
}
HelpTabs::Compact { .. } => {
let label = model.compact_label().unwrap_or_default();
frame.render_widget(
Paragraph::new(label)
.alignment(Alignment::Center)
.style(theme.active()),
tabs_area,
);
}
}
}
frame.render_widget(
Paragraph::new(
model
.lines
.iter()
.skip(model.offset)
.map(|line| Line::from(line.clone()).style(theme.text()))
.collect::<Vec<_>>(),
)
.style(theme.panel()),
model.body,
);
if let Some(footer) = model.footer {
frame.render_widget(
Paragraph::new(fit(
&model.footer_text,
usize::from(footer.width),
theme.is_ascii(),
))
.alignment(Alignment::Right)
.style(theme.secondary()),
footer,
);
}
}
fn render_message_overlay(frame: &mut Frame, area: Rect, app: &AppState, theme: &Theme) {
let overlay = centered(area, 100, 32);
let block = Block::new()
.borders(Borders::ALL)
.border_type(theme.border_type())
.border_style(theme.active())
.title("ERROR DETAILS")
.style(theme.panel());
let inner = block.inner(overlay);
frame.render_widget(Clear, overlay);
frame.render_widget(block, overlay);
if inner.is_empty() {
return;
}
let footer_height = u16::from(inner.height >= 3);
let body = Rect::new(
inner.x,
inner.y,
inner.width,
inner.height.saturating_sub(footer_height),
);
let pane = app.active_pane();
let mut lines = Vec::new();
if let Some(error) = &pane.error {
lines.push(Line::from("TARGET").style(theme.active()));
let target = format!(
"{}{}{}",
source_badge(&pane.location),
theme.separator(),
display_path(&pane.location)
);
lines.extend(
wrap(&target, usize::from(body.width))
.into_iter()
.map(|line| Line::from(line).style(theme.text())),
);
lines.push(Line::from(""));
lines.push(Line::from("MESSAGE").style(theme.error()));
let message = sanitize(&error.user_message());
lines.extend(
wrap(&message, usize::from(body.width))
.into_iter()
.map(|line| Line::from(line).style(theme.text())),
);
} else {
lines.push(Line::from("No error in the active pane.").style(theme.muted()));
}
let visible = usize::from(body.height);
let offset = effective_scroll(app.overlay_scroll, visible, lines.len());
let total = lines.len();
frame.render_widget(
Paragraph::new(
lines
.into_iter()
.skip(offset)
.collect::<Vec<Line<'static>>>(),
)
.style(theme.panel()),
body,
);
if footer_height > 0 {
let navigation = if inner.width >= 55 {
"j/k PgUp/PgDn Ctrl-u/d"
} else {
"j/k PgUp/Dn"
};
let footer = format!(
"{}{}{navigation}{}Esc Close",
scroll_position(offset, visible, total),
theme.separator(),
theme.separator()
);
frame.render_widget(
Paragraph::new(fit(&footer, usize::from(inner.width), theme.is_ascii()))
.alignment(Alignment::Right)
.style(theme.secondary()),
Rect::new(
inner.x,
inner.y.saturating_add(inner.height.saturating_sub(1)),
inner.width,
1,
),
);
}
}
fn effective_scroll(scroll: usize, visible: usize, total: usize) -> usize {
scroll.min(total.saturating_sub(visible))
}
fn scroll_position(offset: usize, visible: usize, total: usize) -> String {
if total == 0 {
return "0/0".to_owned();
}
if visible == 0 {
return format!("0-0/{total}");
}
let start = offset.saturating_add(1).min(total);
let end = offset.saturating_add(visible).min(total);
format!("{start}-{end}/{total}")
}
fn render_host_picker(
frame: &mut Frame,
area: Rect,
picker: Option<&HostPickerState>,
theme: &Theme,
) {
let overlay = centered(area, 76, 24);
let block = Block::new()
.borders(Borders::ALL)
.border_type(theme.border_type())
.border_style(theme.active())
.title(format!("SSH HOSTS{}type to filter", theme.separator()))
.style(theme.panel());
let inner = block.inner(overlay);
frame.render_widget(Clear, overlay);
frame.render_widget(block, overlay);
if inner.is_empty() {
return;
}
let Some(picker) = picker else {
render_message(
frame,
inner,
"HOST DISCOVERY UNAVAILABLE",
&["Esc Close".to_owned()],
theme.error(),
theme,
);
return;
};
let query = format!(
"Filter: {}{}",
sanitize(picker.query()),
if theme.is_ascii() { "_" } else { "▏" }
);
frame.render_widget(
Paragraph::new(fit(&query, usize::from(inner.width), theme.is_ascii())).style(theme.text()),
Rect::new(inner.x, inner.y, inner.width, 1),
);
let hints_height = u16::from(inner.height >= 3);
let content = Rect::new(
inner.x,
inner.y.saturating_add(1),
inner.width,
inner.height.saturating_sub(1 + hints_height),
);
let warning_count = picker.warnings().len().min(usize::from(content.height / 3));
for (index, warning) in picker.warnings().iter().take(warning_count).enumerate() {
let warning = format!(
"{} WARNING{}{}",
theme.warning_marker(),
theme.separator(),
warning
);
frame.render_widget(
Paragraph::new(fit(
&sanitize(&warning),
usize::from(content.width),
theme.is_ascii(),
))
.style(theme.secondary()),
Rect::new(
content.x,
content.y.saturating_add(index as u16),
content.width,
1,
),
);
}
let list = Rect::new(
content.x,
content.y.saturating_add(warning_count as u16),
content.width,
content.height.saturating_sub(warning_count as u16),
);
render_hosts(frame, list, picker, theme);
if hints_height > 0 {
let hints = if theme.is_ascii() {
"Up/Down Select | Enter Connect | Esc Close"
} else {
"↑/↓ Select · Enter Connect · Esc Close"
};
frame.render_widget(
Paragraph::new(fit(hints, usize::from(inner.width), theme.is_ascii()))
.style(theme.secondary()),
Rect::new(
inner.x,
inner.y.saturating_add(inner.height.saturating_sub(1)),
inner.width,
1,
),
);
}
}
fn render_hosts(frame: &mut Frame, area: Rect, picker: &HostPickerState, theme: &Theme) {
if area.is_empty() {
return;
}
if picker.is_empty() {
let message = if picker.hosts().is_empty() {
"No SSH hosts found in ~/.ssh/config"
} else {
"No hosts match the current filter"
};
frame.render_widget(
Paragraph::new(message)
.alignment(Alignment::Center)
.style(theme.muted()),
area,
);
return;
}
let visible = usize::from(area.height);
let selected = picker.selection().index();
let offset = selected
.map(|index| index.saturating_sub(visible / 2))
.unwrap_or(0)
.min(picker.filtered().len().saturating_sub(visible));
let end = offset.saturating_add(visible).min(picker.filtered().len());
for (row, index) in (offset..end).enumerate() {
let is_selected = selected == Some(index);
let marker = if is_selected {
theme.selected_marker()
} else {
" "
};
let host = sanitize(picker.filtered()[index].as_str());
let line = fit(
&format!("{marker} {host}"),
usize::from(area.width),
theme.is_ascii(),
);
frame.render_widget(
Paragraph::new(line).style(if is_selected {
theme.selection()
} else {
theme.text()
}),
Rect::new(area.x, area.y.saturating_add(row as u16), area.width, 1),
);
}
}
fn render_preview_overlay(
frame: &mut Frame,
area: Rect,
pane: &PaneState,
pane_id: PaneId,
theme: &Theme,
image_context: Option<ImageRenderContext<'_>>,
terminal_epoch: u64,
) {
let overlay = centered(area, 120, 34);
render_preview(
frame,
overlay,
pane,
pane_id,
theme,
true,
image_context,
terminal_epoch,
);
if overlay.height >= 3 {
let hints = "F3 / Esc / q Close";
let area = Rect::new(
overlay.x.saturating_add(2),
overlay.y.saturating_add(overlay.height.saturating_sub(1)),
overlay.width.saturating_sub(4),
1,
);
frame.render_widget(
Paragraph::new(hints)
.alignment(Alignment::Right)
.style(theme.secondary()),
area,
);
}
}
fn truncate_source_badge(source: &str, width: usize, ascii: bool) -> String {
if UnicodeWidthStr::width(source) <= width {
return source.to_owned();
}
if let Some(alias) = source.strip_prefix("SSH ") {
if width == 3 {
return "SSH".to_owned();
}
if width > 3 {
let alias = truncate_middle(alias, width.saturating_sub(4), ascii);
return format!("SSH {alias}");
}
}
truncate_middle(source, width, ascii)
}
fn source_badge(location: &Location) -> String {
match &location.source {
SourceId::Local => "LOCAL".to_owned(),
SourceId::Ssh(host) => format!("SSH {}", sanitize(host.as_str())),
}
}
fn display_path(location: &Location) -> String {
sanitize(&location.path.to_string_lossy())
}
fn entry_display_name(entry: &Entry) -> String {
let suffix = match entry.kind {
EntryKind::Directory => "/",
EntryKind::Symlink => "@",
EntryKind::File
if entry
.permissions
.is_some_and(|permissions| permissions & 0o111 != 0) =>
{
"*"
}
EntryKind::File | EntryKind::Other => "",
};
format!("{}{suffix}", sanitize(&entry.name.to_string_lossy()))
}
fn entry_kind(kind: EntryKind) -> &'static str {
match kind {
EntryKind::Directory => "DIR",
EntryKind::File => "FILE",
EntryKind::Symlink => "LINK",
EntryKind::Other => "OTH",
}
}
fn format_size(size: Option<u64>, theme: &Theme) -> String {
let Some(size) = size else {
return theme.unknown().to_owned();
};
const UNITS: [&str; 5] = ["B", "KiB", "MiB", "GiB", "TiB"];
let mut value = size as f64;
let mut unit = 0;
while value >= 1024.0 && unit < UNITS.len() - 1 {
value /= 1024.0;
unit += 1;
}
if unit == 0 {
format!("{size} B")
} else if value >= 10.0 {
format!("{value:.0} {}", UNITS[unit])
} else {
format!("{value:.1} {}", UNITS[unit])
}
}
fn format_modified(modified: Option<SystemTime>) -> String {
match modified {
Some(time) => {
let datetime: DateTime<Utc> = time.into();
datetime.format("%Y-%m-%d %H:%M").to_string()
}
None => "-".repeat(16),
}
}