pub(super) mod config_hosts;
pub(super) mod picker;
pub(super) mod session;
pub(super) mod sftp;
pub(super) mod transfer;
use std::num::NonZeroU32;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
use lune_terminal::{Palette, PixelPosition, PixelSize};
use winit::dpi::{PhysicalPosition, PhysicalSize};
use crate::PixelRect;
use super::PaneId;
pub(super) use config_hosts::{SshConfigHost, SshLaunchSpec, load_ssh_config_hosts};
pub(super) use picker::{SshUploadPicked, open_upload_picker};
pub(super) use session::{SshSession, detect_pane_ssh, ensure_socket_dir};
pub(super) use sftp::{
EntryKind, RemoteEntry, SftpWorker, SshBrowserUpdate, SshOpKind, SshOpResult,
};
pub(super) use transfer::{
TransferDirection, TransferItem, TransferState, TransferUpdate, TransferWorker,
};
const DOUBLE_CLICK_TIMEOUT: Duration = Duration::from_millis(420);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum BrowserStatus {
NoSession,
Loading,
Ready,
Error,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum BrowserAction {
Up,
Refresh,
ToggleHidden,
ToggleFollowCwd,
Upload,
NewFolder,
Rename,
NewSshTab,
ConnectSsh,
Close,
Breadcrumb(usize),
PromptInput,
Row(usize),
TransferButton(u64),
Retry,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) enum InlinePromptKind {
CreateDir,
Rename {
old_path: String,
original_name: String,
},
}
#[derive(Clone, Debug)]
pub(super) struct InlinePrompt {
pub(super) kind: InlinePromptKind,
pub(super) text: String,
pub(super) cursor: usize,
pub(super) anchor: Option<usize>,
pub(super) preedit: String,
}
impl InlinePrompt {
pub(super) fn create_dir() -> Self {
Self {
kind: InlinePromptKind::CreateDir,
text: String::new(),
cursor: 0,
anchor: None,
preedit: String::new(),
}
}
pub(super) fn rename(old_path: String, original_name: String) -> Self {
let len = original_name.len();
Self {
text: original_name.clone(),
cursor: len,
anchor: None,
kind: InlinePromptKind::Rename {
old_path,
original_name,
},
preedit: String::new(),
}
}
pub(super) fn selection_range(&self) -> Option<std::ops::Range<usize>> {
let anchor = self.anchor?;
let a = anchor.min(self.text.len());
let b = self.cursor.min(self.text.len());
(a != b).then(|| a.min(b)..a.max(b))
}
fn delete_selection(&mut self) -> bool {
let Some(range) = self.selection_range() else {
self.anchor = None;
return false;
};
self.text.drain(range.clone());
self.cursor = range.start;
self.anchor = None;
true
}
pub(super) fn push_text(&mut self, input: &str) -> bool {
let mut filtered = String::new();
for ch in input.chars() {
if !ch.is_control() && ch != '/' {
filtered.push(ch);
}
}
if filtered.is_empty() {
return false;
}
self.delete_selection();
let remaining = 255usize.saturating_sub(self.text.len());
if remaining == 0 {
return false;
}
let mut insert_end = 0;
for ch in filtered.chars() {
if insert_end + ch.len_utf8() > remaining {
break;
}
insert_end += ch.len_utf8();
}
if insert_end == 0 {
return false;
}
let pos = self.cursor.min(self.text.len());
self.text.insert_str(pos, &filtered[..insert_end]);
self.cursor = pos + insert_end;
self.anchor = None;
true
}
pub(super) fn backspace(&mut self) -> bool {
if self.delete_selection() {
return true;
}
let pos = self.cursor.min(self.text.len());
if pos == 0 {
return false;
}
let prev = prev_char_boundary(&self.text, pos);
self.text.drain(prev..pos);
self.cursor = prev;
true
}
pub(super) fn delete_forward(&mut self) -> bool {
if self.delete_selection() {
return true;
}
let pos = self.cursor.min(self.text.len());
if pos >= self.text.len() {
return false;
}
let next = next_char_boundary(&self.text, pos);
self.text.drain(pos..next);
true
}
pub(super) fn delete_word(&mut self) -> bool {
if self.delete_selection() {
return true;
}
let pos = self.cursor.min(self.text.len());
if pos == 0 {
return false;
}
let prev = prev_word_boundary(&self.text, pos);
self.text.drain(prev..pos);
self.cursor = prev;
true
}
pub(super) fn delete_word_forward(&mut self) -> bool {
if self.delete_selection() {
return true;
}
let pos = self.cursor.min(self.text.len());
if pos >= self.text.len() {
return false;
}
let next = next_word_boundary(&self.text, pos);
self.text.drain(pos..next);
true
}
pub(super) fn delete_to_start(&mut self) -> bool {
if self.delete_selection() {
return true;
}
let pos = self.cursor.min(self.text.len());
if pos == 0 {
return false;
}
self.text.drain(0..pos);
self.cursor = 0;
true
}
pub(super) fn delete_to_end(&mut self) -> bool {
if self.delete_selection() {
return true;
}
let pos = self.cursor.min(self.text.len());
if pos >= self.text.len() {
return false;
}
self.text.truncate(pos);
true
}
pub(super) fn move_left(&mut self, extend: bool, word: bool) -> bool {
let prev_cursor = self.cursor;
let prev_anchor = self.anchor;
if !extend && let Some(range) = self.selection_range() {
self.cursor = range.start;
self.anchor = None;
return true;
}
if extend && self.anchor.is_none() {
self.anchor = Some(self.cursor);
}
self.cursor = if word {
prev_word_boundary(&self.text, self.cursor)
} else {
prev_char_boundary(&self.text, self.cursor)
};
if !extend {
self.anchor = None;
}
self.cursor != prev_cursor || self.anchor != prev_anchor
}
pub(super) fn move_right(&mut self, extend: bool, word: bool) -> bool {
let prev_cursor = self.cursor;
let prev_anchor = self.anchor;
if !extend && let Some(range) = self.selection_range() {
self.cursor = range.end;
self.anchor = None;
return true;
}
if extend && self.anchor.is_none() {
self.anchor = Some(self.cursor);
}
self.cursor = if word {
next_word_boundary(&self.text, self.cursor)
} else {
next_char_boundary(&self.text, self.cursor)
};
if !extend {
self.anchor = None;
}
self.cursor != prev_cursor || self.anchor != prev_anchor
}
pub(super) fn move_home(&mut self, extend: bool) -> bool {
let prev_cursor = self.cursor;
let prev_anchor = self.anchor;
if extend && self.anchor.is_none() {
self.anchor = Some(self.cursor);
}
self.cursor = 0;
if !extend {
self.anchor = None;
}
self.cursor != prev_cursor || self.anchor != prev_anchor
}
pub(super) fn move_end(&mut self, extend: bool) -> bool {
let prev_cursor = self.cursor;
let prev_anchor = self.anchor;
if extend && self.anchor.is_none() {
self.anchor = Some(self.cursor);
}
self.cursor = self.text.len();
if !extend {
self.anchor = None;
}
self.cursor != prev_cursor || self.anchor != prev_anchor
}
pub(super) fn select_all(&mut self) -> bool {
if self.text.is_empty() {
return false;
}
let changed = self.anchor != Some(0) || self.cursor != self.text.len();
self.anchor = Some(0);
self.cursor = self.text.len();
changed
}
pub(super) fn set_cursor(&mut self, byte_pos: usize) -> bool {
let clamped = snap_char_boundary(&self.text, byte_pos);
let changed = self.cursor != clamped || self.anchor.is_some();
self.cursor = clamped;
self.anchor = None;
changed
}
}
fn is_word_sep(ch: char) -> bool {
ch.is_whitespace() || matches!(ch, '-' | '_' | '.')
}
fn snap_char_boundary(s: &str, pos: usize) -> usize {
let mut p = pos.min(s.len());
while p > 0 && !s.is_char_boundary(p) {
p -= 1;
}
p
}
fn prev_char_boundary(s: &str, pos: usize) -> usize {
let pos = snap_char_boundary(s, pos);
s[..pos]
.char_indices()
.next_back()
.map_or(0, |(idx, _)| idx)
}
fn next_char_boundary(s: &str, pos: usize) -> usize {
let pos = snap_char_boundary(s, pos);
s[pos..]
.chars()
.next()
.map_or(s.len(), |ch| pos + ch.len_utf8())
}
fn prev_word_boundary(s: &str, pos: usize) -> usize {
let mut p = snap_char_boundary(s, pos);
while p > 0 {
let prev = prev_char_boundary(s, p);
let ch = s[prev..p].chars().next().unwrap();
if !is_word_sep(ch) {
break;
}
p = prev;
}
while p > 0 {
let prev = prev_char_boundary(s, p);
let ch = s[prev..p].chars().next().unwrap();
if is_word_sep(ch) {
break;
}
p = prev;
}
p
}
fn next_word_boundary(s: &str, pos: usize) -> usize {
let mut p = snap_char_boundary(s, pos);
while p < s.len() {
let next = next_char_boundary(s, p);
let ch = s[p..next].chars().next().unwrap();
if !is_word_sep(ch) {
break;
}
p = next;
}
while p < s.len() {
let next = next_char_boundary(s, p);
let ch = s[p..next].chars().next().unwrap();
if is_word_sep(ch) {
break;
}
p = next;
}
p
}
#[derive(Clone, Copy, Debug)]
pub(super) struct TransferSlot {
pub(super) id: u64,
pub(super) rect: PixelRect,
pub(super) button_rect: PixelRect,
}
#[derive(Clone, Debug)]
pub(super) struct BreadcrumbSlot {
pub(super) label: String,
pub(super) path: String,
pub(super) rect: PixelRect,
}
#[derive(Clone, Copy, Debug)]
pub(super) struct ToolbarButton {
pub(super) action: BrowserAction,
pub(super) rect: PixelRect,
pub(super) active: bool,
pub(super) enabled: bool,
}
#[derive(Clone, Copy, Debug)]
pub(super) struct RowSlot {
pub(super) visible_idx: usize,
pub(super) entry_idx: usize,
pub(super) rect: PixelRect,
}
#[derive(Clone, Copy, Debug)]
pub(super) struct DrawerResizeDrag {
pub(super) start_x: f64,
pub(super) start_width_px: f64,
}
#[derive(Clone, Copy, Debug)]
pub(super) struct ClickRecord {
pub(super) entry_idx: usize,
pub(super) at: Instant,
}
#[derive(Default)]
pub(super) struct BrowserLayout {
pub(super) rect: Option<PixelRect>,
pub(super) header_rect: Option<PixelRect>,
pub(super) toolbar_rect: Option<PixelRect>,
pub(super) toolbar_sep_x: Option<u32>,
pub(super) path_rect: Option<PixelRect>,
pub(super) prompt_rect: Option<PixelRect>,
pub(super) list_top: u32,
pub(super) list_bottom: u32,
pub(super) row_height: u32,
pub(super) row_gap: u32,
pub(super) visible_rows: usize,
pub(super) pad_x: u32,
pub(super) item_gap: u32,
pub(super) icon_size: u32,
pub(super) row_radius: u32,
pub(super) toolbar_buttons: Vec<ToolbarButton>,
pub(super) breadcrumbs: Vec<BreadcrumbSlot>,
pub(super) rows: Vec<RowSlot>,
pub(super) transfers_top: Option<u32>,
pub(super) transfers: Vec<TransferSlot>,
pub(super) retry_rect: Option<PixelRect>,
pub(super) connect_rect: Option<PixelRect>,
}
impl BrowserLayout {
pub(super) fn width(&self) -> u32 {
self.rect.map_or(0, |r| r.size.width.get())
}
pub(super) fn contains(&self, pos: PhysicalPosition<f64>) -> bool {
let Some(rect) = self.rect else {
return false;
};
rect_contains(rect, pos)
}
pub(super) fn hit_divider(&self, pos: PhysicalPosition<f64>, scale: f64) -> bool {
let Some(rect) = self.rect else {
return false;
};
if !pos.x.is_finite() || !pos.y.is_finite() {
return false;
}
let grab = (5.0 * scale.max(1.0)).max(4.0);
let edge = f64::from(rect.origin.x);
(pos.x - edge).abs() <= grab
&& pos.y >= f64::from(rect.origin.y)
&& pos.y < f64::from(rect.origin.y + rect.size.height.get())
}
pub(super) fn hit(&self, pos: PhysicalPosition<f64>) -> Option<BrowserAction> {
if !self.contains(pos) {
return None;
}
for button in &self.toolbar_buttons {
if button.enabled && rect_contains(button.rect, pos) {
return Some(button.action);
}
}
for (idx, crumb) in self.breadcrumbs.iter().enumerate() {
if rect_contains(crumb.rect, pos) {
return Some(BrowserAction::Breadcrumb(idx));
}
}
if let Some(prompt) = self.prompt_rect
&& rect_contains(prompt, pos)
{
return Some(BrowserAction::PromptInput);
}
if let Some(retry) = self.retry_rect
&& rect_contains(retry, pos)
{
return Some(BrowserAction::Retry);
}
if let Some(connect) = self.connect_rect
&& rect_contains(connect, pos)
{
return Some(BrowserAction::ConnectSsh);
}
for row in &self.rows {
if rect_contains(row.rect, pos) {
return Some(BrowserAction::Row(row.visible_idx));
}
}
for slot in &self.transfers {
if rect_contains(slot.button_rect, pos) {
return Some(BrowserAction::TransferButton(slot.id));
}
}
None
}
}
pub(super) struct SshBrowser {
pub(super) open: bool,
pub(super) focused: bool,
pub(super) width_cells: Option<f64>,
pub(super) show_hidden: bool,
pub(super) follow_cwd: bool,
pub(super) active_pane: Option<PaneId>,
pub(super) session: Option<SshSession>,
pub(super) status: BrowserStatus,
pub(super) path: String,
pub(super) entries: Vec<RemoteEntry>,
pub(super) visible_indices: Vec<usize>,
pub(super) error: Option<String>,
pub(super) selected: Option<usize>,
pub(super) scroll: usize,
pub(super) hovered: Option<BrowserAction>,
pub(super) generation: u64,
pub(super) next_transfer_id: u64,
pub(super) transfers: Vec<TransferItem>,
pub(super) last_followed_uri: Option<String>,
pub(super) last_click: Option<ClickRecord>,
pub(super) prompt: Option<InlinePrompt>,
pub(super) layout: BrowserLayout,
}
impl Default for SshBrowser {
fn default() -> Self {
Self {
open: false,
focused: false,
width_cells: None,
show_hidden: false,
follow_cwd: true,
active_pane: None,
session: None,
status: BrowserStatus::NoSession,
path: String::new(),
entries: Vec::new(),
visible_indices: Vec::new(),
error: None,
selected: None,
scroll: 0,
hovered: None,
generation: 0,
next_transfer_id: 0,
transfers: Vec::new(),
last_followed_uri: None,
last_click: None,
prompt: None,
layout: BrowserLayout::default(),
}
}
}
impl SshBrowser {
pub(super) fn compute_width(
size: PhysicalSize<u32>,
cell: PixelSize,
scale: f64,
open: bool,
left_bar_width: u32,
custom_cells: Option<f64>,
) -> u32 {
if !open || size.width == 0 || size.height == 0 {
return 0;
}
let scale = scale.max(1.0);
let floor = |logical: f64| (logical * scale).round().max(1.0) as u32;
let cell_w = cell.width.get().max(1);
let pad_x = (cell_w.saturating_mul(4) / 5).max(floor(8.0));
let min_w = cell_w
.saturating_mul(20)
.saturating_add(pad_x * 2)
.max(floor(180.0));
let remaining = size.width.saturating_sub(left_bar_width);
let max_by_window = (remaining.saturating_mul(45) / 100)
.min(remaining.saturating_sub(cell_w.saturating_mul(20)));
let max_w = cell_w
.saturating_mul(52)
.saturating_add(pad_x * 2)
.min(max_by_window);
if max_w < min_w {
return 0;
}
let default_w = cell_w
.saturating_mul(30)
.saturating_add(pad_x * 2)
.clamp(min_w, max_w);
let desired = match custom_cells {
Some(cells) => (cells * f64::from(cell_w)).round() as u32,
None => default_w,
};
desired.clamp(min_w, max_w)
}
pub(super) fn next_generation(&mut self) -> u64 {
self.generation = self.generation.wrapping_add(1).max(1);
self.generation
}
pub(super) fn enqueue_transfer(
&mut self,
pane_id: PaneId,
session_key: String,
direction: TransferDirection,
name: String,
remote_dir: String,
) -> (u64, Arc<AtomicBool>) {
self.next_transfer_id = self.next_transfer_id.wrapping_add(1).max(1);
let id = self.next_transfer_id;
let cancel = Arc::new(AtomicBool::new(false));
self.transfers.push(TransferItem {
id,
pane_id,
session_key,
direction,
name,
remote_dir,
done_bytes: 0,
total_bytes: 0,
state: TransferState::Queued,
cancel: cancel.clone(),
});
while self.transfers.len() > 4 {
if let Some(done_idx) = self.transfers.iter().position(|item| {
matches!(
item.state,
TransferState::Finished(_)
| TransferState::Failed(_)
| TransferState::Cancelled
)
}) {
self.transfers.remove(done_idx);
} else {
break;
}
}
(id, cancel)
}
pub(super) fn apply_transfer_update(&mut self, update: TransferUpdate) -> Option<TransferItem> {
let item = self
.transfers
.iter_mut()
.find(|item| item.id == update.id)?;
item.done_bytes = update.done_bytes;
item.total_bytes = update.total_bytes;
item.state = update.state;
Some(item.clone())
}
pub(super) fn cancel_or_dismiss_transfer(&mut self, id: u64) -> bool {
let Some(pos) = self.transfers.iter().position(|item| item.id == id) else {
return false;
};
let active = matches!(
self.transfers[pos].state,
TransferState::Queued | TransferState::Running
);
if active {
self.transfers[pos].cancel.store(true, Ordering::Release);
self.transfers[pos].state = TransferState::Cancelled;
} else {
self.transfers.remove(pos);
}
true
}
pub(super) fn clear_session(&mut self) {
self.session = None;
self.status = BrowserStatus::NoSession;
self.path.clear();
self.entries.clear();
self.visible_indices.clear();
self.error = None;
self.selected = None;
self.scroll = 0;
self.last_followed_uri = None;
self.last_click = None;
self.prompt = None;
}
pub(super) fn rebuild_visible(&mut self) {
self.visible_indices.clear();
for (idx, entry) in self.entries.iter().enumerate() {
if !self.show_hidden && entry.name.starts_with('.') {
continue;
}
self.visible_indices.push(idx);
}
if let Some(sel) = self.selected
&& sel >= self.visible_indices.len()
{
self.selected = self.visible_indices.len().checked_sub(1);
}
self.clamp_scroll();
}
pub(super) fn apply_update(&mut self, update: SshBrowserUpdate) -> bool {
if update.generation != self.generation || self.active_pane != Some(update.pane_id) {
return false;
}
if self
.session
.as_ref()
.is_none_or(|session| session.key() != update.session_key)
{
return false;
}
match update.result {
Ok(listing) => {
self.status = BrowserStatus::Ready;
self.path = listing.path;
self.entries = listing.entries;
self.error = None;
self.scroll = 0;
self.rebuild_visible();
self.selected = (!self.visible_indices.is_empty()).then_some(0);
}
Err(message) => {
self.status = BrowserStatus::Error;
self.error = Some(message);
}
}
true
}
pub(super) fn selected_entry(&self) -> Option<&RemoteEntry> {
let vis = self.selected?;
let idx = *self.visible_indices.get(vis)?;
self.entries.get(idx)
}
pub(super) fn entry_at_visible(&self, visible_idx: usize) -> Option<&RemoteEntry> {
let idx = *self.visible_indices.get(visible_idx)?;
self.entries.get(idx)
}
pub(super) fn full_path_for(&self, entry_name: &str) -> String {
join_remote_path(&self.path, entry_name)
}
pub(super) fn parent_path(&self) -> Option<String> {
parent_remote_path(&self.path)
}
pub(super) fn record_row_click(&mut self, visible_idx: usize, now: Instant) -> bool {
let Some(&entry_idx) = self.visible_indices.get(visible_idx) else {
return false;
};
self.selected = Some(visible_idx);
self.ensure_selected_visible();
let is_double = self.last_click.is_some_and(|prev| {
prev.entry_idx == entry_idx
&& now.saturating_duration_since(prev.at) <= DOUBLE_CLICK_TIMEOUT
});
if is_double {
self.last_click = None;
} else {
self.last_click = Some(ClickRecord { entry_idx, at: now });
}
is_double
}
pub(super) fn move_selection(&mut self, delta: isize) -> bool {
let total = self.visible_indices.len();
if total == 0 {
return false;
}
let next = match self.selected {
Some(current) => (current as isize + delta).clamp(0, (total - 1) as isize) as usize,
None => {
if delta >= 0 {
0
} else {
total - 1
}
}
};
if self.selected == Some(next) {
return false;
}
self.selected = Some(next);
self.ensure_selected_visible();
true
}
pub(super) fn scroll_by(&mut self, delta: isize) -> bool {
let visible = self.layout.visible_rows.max(1);
let max_scroll = self.visible_indices.len().saturating_sub(visible);
let next = (self.scroll as isize + delta).clamp(0, max_scroll as isize) as usize;
if next == self.scroll {
return false;
}
self.scroll = next;
true
}
fn clamp_scroll(&mut self) {
let visible = self.layout.visible_rows.max(1);
let max_scroll = self.visible_indices.len().saturating_sub(visible);
self.scroll = self.scroll.min(max_scroll);
}
fn ensure_selected_visible(&mut self) {
let Some(selected) = self.selected else {
return;
};
let visible = self.layout.visible_rows.max(1);
if selected < self.scroll {
self.scroll = selected;
} else if selected >= self.scroll + visible {
self.scroll = selected + 1 - visible;
}
self.clamp_scroll();
}
pub(super) fn reflow(
&mut self,
size: PhysicalSize<u32>,
cell: PixelSize,
scale: f64,
top_inset: u32,
bottom_inset: u32,
left_bar_width: u32,
) {
self.layout.toolbar_buttons.clear();
self.layout.breadcrumbs.clear();
self.layout.rows.clear();
self.layout.transfers_top = None;
self.layout.transfers.clear();
self.layout.retry_rect = None;
self.layout.connect_rect = None;
self.layout.header_rect = None;
self.layout.toolbar_rect = None;
self.layout.toolbar_sep_x = None;
self.layout.path_rect = None;
self.layout.prompt_rect = None;
let width = Self::compute_width(
size,
cell,
scale,
self.open,
left_bar_width,
self.width_cells,
);
let height = size
.height
.saturating_sub(top_inset)
.saturating_sub(bottom_inset);
let (Some(w_nz), Some(h_nz)) = (NonZeroU32::new(width), NonZeroU32::new(height)) else {
self.layout.rect = None;
return;
};
let origin_x = size.width.saturating_sub(width);
let rect = PixelRect {
origin: PixelPosition {
x: origin_x,
y: top_inset,
},
size: PixelSize {
width: w_nz,
height: h_nz,
},
};
self.layout.rect = Some(rect);
let scale = scale.max(1.0);
let floor = |logical: f64| (logical * scale).round().max(1.0) as u32;
let cell_w = cell.width.get().max(1);
let cell_h = cell.height.get().max(1);
let pad_x = (cell_w.saturating_mul(4) / 5).max(floor(8.0));
let item_gap = (pad_x.saturating_mul(2) / 3).max(floor(5.0));
let row_height = cell_h
.saturating_add((cell_h / 2).max(floor(10.0)))
.max(floor(28.0));
let row_gap = (row_height / 10).max(floor(2.0));
let row_radius = (row_height / 4).max(floor(6.0));
let icon_size = (cell_h.saturating_mul(75) / 100)
.max(floor(13.0))
.min(row_height.saturating_sub(6).max(12));
let btn_size = cell_h
.saturating_add(floor(6.0))
.max(floor(22.0))
.min(row_height);
self.layout.pad_x = pad_x;
self.layout.item_gap = item_gap;
self.layout.row_height = row_height;
self.layout.row_gap = row_gap;
self.layout.icon_size = icon_size;
self.layout.row_radius = row_radius;
let inner_x = origin_x.saturating_add(1).saturating_add(pad_x);
let inner_w = width.saturating_sub(pad_x * 2 + 1);
if inner_w == 0 {
return;
}
let header_h = btn_size.max(cell_h.saturating_add(floor(4.0)));
let header_y = top_inset.saturating_add(pad_x);
if let (Some(hw), Some(hh)) = (NonZeroU32::new(inner_w), NonZeroU32::new(header_h)) {
self.layout.header_rect = Some(PixelRect {
origin: PixelPosition {
x: inner_x,
y: header_y,
},
size: PixelSize {
width: hw,
height: hh,
},
});
}
let close_x = inner_x.saturating_add(inner_w).saturating_sub(btn_size);
let close_y = header_y + header_h.saturating_sub(btn_size) / 2;
let btn_gap = (item_gap / 2).max(floor(3.0));
if let Some(side) = NonZeroU32::new(btn_size) {
self.layout.toolbar_buttons.push(ToolbarButton {
action: BrowserAction::Close,
rect: PixelRect {
origin: PixelPosition {
x: close_x,
y: close_y,
},
size: PixelSize {
width: side,
height: side,
},
},
active: false,
enabled: true,
});
let plus_x = close_x.saturating_sub(btn_gap).saturating_sub(btn_size);
if plus_x >= inner_x.saturating_add(cell_w.saturating_mul(6)) {
self.layout.toolbar_buttons.push(ToolbarButton {
action: BrowserAction::NewSshTab,
rect: PixelRect {
origin: PixelPosition {
x: plus_x,
y: close_y,
},
size: PixelSize {
width: side,
height: side,
},
},
active: false,
enabled: true,
});
}
}
let toolbar_h = btn_size;
let toolbar_y = header_y.saturating_add(header_h).saturating_add(floor(4.0));
if let (Some(tw), Some(th)) = (NonZeroU32::new(inner_w), NonZeroU32::new(toolbar_h)) {
self.layout.toolbar_rect = Some(PixelRect {
origin: PixelPosition {
x: inner_x,
y: toolbar_y,
},
size: PixelSize {
width: tw,
height: th,
},
});
}
let is_ready = self.status == BrowserStatus::Ready && !self.path.is_empty();
let can_up = is_ready && self.parent_path().is_some();
let can_rename = is_ready && self.selected_entry().is_some();
let creating_dir = matches!(
self.prompt.as_ref().map(|p| &p.kind),
Some(InlinePromptKind::CreateDir)
);
let renaming = matches!(
self.prompt.as_ref().map(|p| &p.kind),
Some(InlinePromptKind::Rename { .. })
);
let nav_specs = [
(BrowserAction::Up, false, can_up),
(BrowserAction::Refresh, false, self.session.is_some()),
(BrowserAction::ToggleHidden, self.show_hidden, true),
(BrowserAction::ToggleFollowCwd, self.follow_cwd, true),
];
let op_specs = [
(BrowserAction::Upload, false, is_ready),
(BrowserAction::NewFolder, creating_dir, is_ready),
(BrowserAction::Rename, renaming, can_rename || renaming),
];
let right_edge = inner_x.saturating_add(inner_w);
let mut tx = inner_x;
if let Some(side) = NonZeroU32::new(btn_size) {
for (action, active, enabled) in nav_specs {
if tx.saturating_add(btn_size) > right_edge {
break;
}
self.layout.toolbar_buttons.push(ToolbarButton {
action,
rect: PixelRect {
origin: PixelPosition {
x: tx,
y: toolbar_y,
},
size: PixelSize {
width: side,
height: side,
},
},
active,
enabled,
});
tx = tx.saturating_add(btn_size).saturating_add(btn_gap);
}
let sep_pad = floor(3.0);
if tx.saturating_add(sep_pad * 2 + btn_size) <= right_edge {
self.layout.toolbar_sep_x = Some(tx.saturating_add(sep_pad));
tx = tx.saturating_add(sep_pad * 2 + 1 + btn_gap);
for (action, active, enabled) in op_specs {
if tx.saturating_add(btn_size) > right_edge {
break;
}
self.layout.toolbar_buttons.push(ToolbarButton {
action,
rect: PixelRect {
origin: PixelPosition {
x: tx,
y: toolbar_y,
},
size: PixelSize {
width: side,
height: side,
},
},
active,
enabled,
});
tx = tx.saturating_add(btn_size).saturating_add(btn_gap);
}
}
}
let path_h = cell_h.saturating_add(floor(8.0)).max(floor(24.0));
let path_y = toolbar_y.saturating_add(toolbar_h).saturating_add(item_gap);
if let (Some(pw), Some(ph)) = (NonZeroU32::new(inner_w), NonZeroU32::new(path_h)) {
self.layout.path_rect = Some(PixelRect {
origin: PixelPosition {
x: inner_x,
y: path_y,
},
size: PixelSize {
width: pw,
height: ph,
},
});
if !self.path.is_empty() {
let segments = build_breadcrumbs(&self.path);
let mut bx = inner_x.saturating_add(item_gap);
let right_limit = inner_x.saturating_add(inner_w).saturating_sub(item_gap);
let sep_w = cell_w.saturating_add(floor(4.0));
let root_gap = floor(2.0);
let widths: Vec<u32> = segments
.iter()
.map(|(label, _)| {
let chars = label.chars().count().max(1) as u32;
chars.saturating_mul(cell_w).saturating_add(floor(8.0))
})
.collect();
let mut start_idx = 0usize;
let avail_crumb_w = right_limit.saturating_sub(bx);
while start_idx + 1 < segments.len() {
let mut needed = 0u32;
for i in start_idx..segments.len() {
needed = needed.saturating_add(widths[i]);
if i + 1 < segments.len() {
let gap = if segments[i].0 == "/" {
root_gap
} else {
sep_w
};
needed = needed.saturating_add(gap);
}
}
if needed <= avail_crumb_w {
break;
}
start_idx += 1;
}
for (i, (label, path)) in segments.into_iter().enumerate().skip(start_idx) {
if bx >= right_limit {
break;
}
let is_root = label == "/";
let cw = widths[i].min(right_limit.saturating_sub(bx));
if let Some(cw_nz) = NonZeroU32::new(cw) {
self.layout.breadcrumbs.push(BreadcrumbSlot {
label,
path,
rect: PixelRect {
origin: PixelPosition { x: bx, y: path_y },
size: PixelSize {
width: cw_nz,
height: ph,
},
},
});
}
bx = bx.saturating_add(cw).saturating_add(if is_root {
root_gap
} else {
sep_w
});
}
}
}
let mut list_top = path_y.saturating_add(path_h).saturating_add(item_gap);
if self.prompt.is_some() {
let prompt_h = cell_h.saturating_add(floor(10.0)).max(floor(26.0));
if let (Some(pw), Some(ph)) = (NonZeroU32::new(inner_w), NonZeroU32::new(prompt_h)) {
self.layout.prompt_rect = Some(PixelRect {
origin: PixelPosition {
x: inner_x,
y: list_top,
},
size: PixelSize {
width: pw,
height: ph,
},
});
list_top = list_top.saturating_add(prompt_h).saturating_add(item_gap);
}
}
let drawer_bottom = top_inset.saturating_add(height).saturating_sub(pad_x);
let shown_transfers = self.transfers.len().min(3);
let xfer_row_h = cell_h.saturating_add(floor(14.0)).max(floor(32.0));
let xfer_gap = floor(4.0);
let xfer_block_h = if shown_transfers > 0 {
xfer_row_h
.saturating_mul(shown_transfers as u32)
.saturating_add(xfer_gap.saturating_mul(shown_transfers.saturating_sub(1) as u32))
.saturating_add(item_gap.saturating_mul(2))
} else {
0
};
let list_bottom = if shown_transfers > 0
&& drawer_bottom
> list_top
.saturating_add(row_height.saturating_mul(2))
.saturating_add(xfer_block_h)
{
let xfer_top = drawer_bottom.saturating_sub(xfer_block_h);
self.layout.transfers_top = Some(xfer_top);
let start_idx = self.transfers.len().saturating_sub(shown_transfers);
let close_side = btn_size.min(xfer_row_h.saturating_sub(6).max(16));
if let (Some(tw), Some(th), Some(bs)) = (
NonZeroU32::new(inner_w),
NonZeroU32::new(xfer_row_h),
NonZeroU32::new(close_side),
) {
for (slot_i, item) in self.transfers[start_idx..].iter().enumerate() {
let y = xfer_top
.saturating_add(item_gap)
.saturating_add((xfer_row_h + xfer_gap).saturating_mul(slot_i as u32));
let bx = inner_x + inner_w.saturating_sub(close_side + floor(4.0));
let by = y + xfer_row_h.saturating_sub(close_side) / 2;
self.layout.transfers.push(TransferSlot {
id: item.id,
rect: PixelRect {
origin: PixelPosition { x: inner_x, y },
size: PixelSize {
width: tw,
height: th,
},
},
button_rect: PixelRect {
origin: PixelPosition { x: bx, y: by },
size: PixelSize {
width: bs,
height: bs,
},
},
});
}
}
xfer_top.saturating_sub(item_gap)
} else {
drawer_bottom
};
self.layout.list_top = list_top;
self.layout.list_bottom = list_bottom;
let step = row_height.saturating_add(row_gap).max(1);
let avail_h = list_bottom.saturating_sub(list_top);
let visible = ((avail_h.saturating_add(row_gap)) / step).max(1) as usize;
self.layout.visible_rows = visible;
self.clamp_scroll();
if self.status == BrowserStatus::NoSession && avail_h >= row_height.saturating_mul(2) {
let btn_w = cell_w.saturating_mul(16).min(inner_w).max(floor(116.0));
let btn_h = row_height;
let btn_x = inner_x + inner_w.saturating_sub(btn_w) / 2;
let btn_y = (list_top + avail_h / 2 + cell_h.saturating_add(floor(14.0)))
.min(list_bottom.saturating_sub(btn_h));
if btn_y >= list_top
&& btn_y + btn_h <= list_bottom
&& let (Some(bw), Some(bh)) = (NonZeroU32::new(btn_w), NonZeroU32::new(btn_h))
{
self.layout.connect_rect = Some(PixelRect {
origin: PixelPosition { x: btn_x, y: btn_y },
size: PixelSize {
width: bw,
height: bh,
},
});
}
return;
}
if self.status == BrowserStatus::Error && avail_h >= row_height.saturating_mul(2) {
let retry_w = cell_w.saturating_mul(10).min(inner_w).max(floor(76.0));
let retry_h = row_height;
let retry_x = inner_x + inner_w.saturating_sub(retry_w) / 2;
let retry_y = (list_top + avail_h / 2 + cell_h.saturating_mul(2))
.min(list_bottom.saturating_sub(retry_h));
if retry_y >= list_top
&& retry_y + retry_h <= list_bottom
&& let (Some(rw), Some(rh)) = (NonZeroU32::new(retry_w), NonZeroU32::new(retry_h))
{
self.layout.retry_rect = Some(PixelRect {
origin: PixelPosition {
x: retry_x,
y: retry_y,
},
size: PixelSize {
width: rw,
height: rh,
},
});
}
return;
}
if let (Some(rw), Some(rh)) = (NonZeroU32::new(inner_w), NonZeroU32::new(row_height)) {
for (slot_idx, visible_idx) in (self.scroll..self.visible_indices.len())
.take(visible)
.enumerate()
{
let y = list_top.saturating_add(step.saturating_mul(slot_idx as u32));
if y + row_height > list_bottom.saturating_add(row_gap) {
break;
}
self.layout.rows.push(RowSlot {
visible_idx,
entry_idx: self.visible_indices[visible_idx],
rect: PixelRect {
origin: PixelPosition { x: inner_x, y },
size: PixelSize {
width: rw,
height: rh,
},
},
});
}
}
}
}
pub(super) struct BrowserView<'a> {
pub(super) browser: &'a SshBrowser,
pub(super) palette: &'a Palette,
pub(super) background_opacity: f32,
pub(super) scale: f64,
}
pub(super) fn join_remote_path(base: &str, name: &str) -> String {
if name.starts_with('/') {
return name.to_owned();
}
if base.is_empty() || base == "/" {
format!("/{name}")
} else {
format!("{}/{name}", base.trim_end_matches('/'))
}
}
pub(super) fn parent_remote_path(path: &str) -> Option<String> {
let trimmed = path.trim_end_matches('/');
if trimmed.is_empty() {
return None;
}
match trimmed.rfind('/') {
Some(0) => Some("/".to_owned()),
Some(idx) => Some(trimmed[..idx].to_owned()),
None => Some("/".to_owned()),
}
}
pub(super) fn build_breadcrumbs(path: &str) -> Vec<(String, String)> {
if path.is_empty() || path == "/" {
return vec![("/".to_owned(), "/".to_owned())];
}
let mut out = Vec::new();
let mut current = String::new();
if path.starts_with('/') {
out.push(("/".to_owned(), "/".to_owned()));
}
for part in path.split('/').filter(|part| !part.is_empty()) {
current.push('/');
current.push_str(part);
out.push((part.to_owned(), current.clone()));
}
out
}
pub(super) fn format_size(size: u64) -> String {
const UNITS: &[&str] = &["B", "KB", "MB", "GB", "TB"];
let mut value = size as f64;
let mut unit = 0usize;
while value >= 1024.0 && unit + 1 < UNITS.len() {
value /= 1024.0;
unit += 1;
}
if unit == 0 {
format!("{size} B")
} else if value >= 100.0 {
format!("{value:.0} {}", UNITS[unit])
} else {
format!("{value:.1} {}", UNITS[unit])
}
}
pub(super) fn posix_shell_quote(text: &str) -> String {
if !text.is_empty()
&& text.bytes().all(|b| {
b.is_ascii_alphanumeric()
|| matches!(b, b'/' | b'.' | b'_' | b'-' | b'+' | b':' | b'@' | b',')
})
{
return text.to_owned();
}
let mut out = String::with_capacity(text.len() + 2);
out.push('\'');
for ch in text.chars() {
if ch == '\'' {
out.push_str("'\\''");
} else {
out.push(ch);
}
}
out.push('\'');
out
}
fn rect_contains(rect: PixelRect, pos: PhysicalPosition<f64>) -> bool {
let x = f64::from(rect.origin.x);
let y = f64::from(rect.origin.y);
pos.x >= x
&& pos.x < x + f64::from(rect.size.width.get())
&& pos.y >= y
&& pos.y < y + f64::from(rect.size.height.get())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn remote_path_helpers_join_parent_breadcrumbs_and_quote_safely() {
assert_eq!(join_remote_path("/", "etc"), "/etc");
assert_eq!(
join_remote_path("/srv/app", "config.toml"),
"/srv/app/config.toml"
);
assert_eq!(join_remote_path("/srv/app/", "logs"), "/srv/app/logs");
assert_eq!(parent_remote_path("/"), None);
assert_eq!(parent_remote_path("/srv"), Some("/".to_owned()));
assert_eq!(
parent_remote_path("/srv/app/logs"),
Some("/srv/app".to_owned())
);
assert_eq!(
build_breadcrumbs("/srv/app"),
vec![
("/".to_owned(), "/".to_owned()),
("srv".to_owned(), "/srv".to_owned()),
("app".to_owned(), "/srv/app".to_owned()),
]
);
assert_eq!(posix_shell_quote("/srv/app/file.rs"), "/srv/app/file.rs");
assert_eq!(
posix_shell_quote("/srv/my dir/a'b"),
"'/srv/my dir/a'\\''b'"
);
assert_eq!(format_size(512), "512 B");
assert_eq!(format_size(1536), "1.5 KB");
assert_eq!(format_size(5 * 1024 * 1024), "5.0 MB");
}
#[test]
fn inline_prompt_moves_cursor_deletes_and_replaces_selection_safely() {
let mut p = InlinePrompt::rename("/srv/文档_v1.txt".into(), "文档_v1.txt".into());
assert_eq!(p.cursor, p.text.len());
for _ in 0..4 {
assert!(p.move_left(false, false));
}
assert!(p.backspace());
assert_eq!(p.text, "文档_v.txt");
assert!(p.push_text("2"));
assert_eq!(p.text, "文档_v2.txt");
assert!(p.delete_forward());
assert_eq!(p.text, "文档_v2txt");
assert!(p.move_home(false));
assert!(p.delete_forward());
assert_eq!(p.text, "档_v2txt");
assert!(p.select_all());
assert!(p.push_text("clean.md"));
assert_eq!(p.text, "clean.md");
assert_eq!(p.cursor, "clean.md".len());
assert!(p.delete_word());
assert_eq!(p.text, "clean.");
assert!(p.delete_to_start());
assert!(p.text.is_empty());
}
}