minor changes in scrolling
This commit is contained in:
156
src/app.rs
156
src/app.rs
@@ -37,6 +37,7 @@ pub struct App {
|
|||||||
pub error: Option<String>,
|
pub error: Option<String>,
|
||||||
pub breadcrumbs: Vec<usize>,
|
pub breadcrumbs: Vec<usize>,
|
||||||
pub selected_index: usize,
|
pub selected_index: usize,
|
||||||
|
pub menu_scroll_offset: usize,
|
||||||
pub popup: Option<Popup>,
|
pub popup: Option<Popup>,
|
||||||
pub event_tx: UnboundedSender<Event>,
|
pub event_tx: UnboundedSender<Event>,
|
||||||
/// When set, main loop suspends ratatui, runs the command, then restores.
|
/// When set, main loop suspends ratatui, runs the command, then restores.
|
||||||
@@ -54,11 +55,8 @@ pub enum Popup {
|
|||||||
ExecutingBashTerminal { child: tokio::process::Child },
|
ExecutingBashTerminal { child: tokio::process::Child },
|
||||||
ExecutingStructured {
|
ExecutingStructured {
|
||||||
reply_tx: tokio::sync::mpsc::UnboundedSender<String>,
|
reply_tx: tokio::sync::mpsc::UnboundedSender<String>,
|
||||||
script_pid: Option<u32>,
|
/// Fires SIGTERM to the script's process group on Esc.
|
||||||
kill_tx: Option<tokio::sync::oneshot::Sender<()>>,
|
kill_tx: Option<tokio::sync::oneshot::Sender<()>>,
|
||||||
/// Background tokio tasks — aborted when popup closes to prevent
|
|
||||||
/// stale output from leaking into a subsequent popup.
|
|
||||||
task_handles: Vec<tokio::task::JoinHandle<()>>,
|
|
||||||
log_buffer: Vec<String>,
|
log_buffer: Vec<String>,
|
||||||
current_command: Option<executor::StructuredCommand>,
|
current_command: Option<executor::StructuredCommand>,
|
||||||
input_buffer: String,
|
input_buffer: String,
|
||||||
@@ -70,6 +68,8 @@ pub enum Popup {
|
|||||||
form_values: Vec<bool>,
|
form_values: Vec<bool>,
|
||||||
/// Index of the first visible line in log_buffer (0 = top of output).
|
/// Index of the first visible line in log_buffer (0 = top of output).
|
||||||
log_scroll_pos: usize,
|
log_scroll_pos: usize,
|
||||||
|
/// Horizontal scroll offset in chars (0 = leftmost column).
|
||||||
|
log_scroll_x: usize,
|
||||||
/// When true, keep position pinned to the bottom as new output arrives.
|
/// When true, keep position pinned to the bottom as new output arrives.
|
||||||
log_follow_bottom: bool,
|
log_follow_bottom: bool,
|
||||||
/// Set when the process has exited; popup stays open until Esc.
|
/// Set when the process has exited; popup stays open until Esc.
|
||||||
@@ -110,6 +110,7 @@ impl App {
|
|||||||
error: None,
|
error: None,
|
||||||
breadcrumbs: Vec::new(),
|
breadcrumbs: Vec::new(),
|
||||||
selected_index: 0,
|
selected_index: 0,
|
||||||
|
menu_scroll_offset: 0,
|
||||||
popup: None,
|
popup: None,
|
||||||
event_tx,
|
event_tx,
|
||||||
pending_exec: None,
|
pending_exec: None,
|
||||||
@@ -310,15 +311,14 @@ impl App {
|
|||||||
|
|
||||||
Popup::ExecutingStructured {
|
Popup::ExecutingStructured {
|
||||||
reply_tx,
|
reply_tx,
|
||||||
script_pid,
|
|
||||||
kill_tx,
|
kill_tx,
|
||||||
task_handles,
|
|
||||||
input_buffer,
|
input_buffer,
|
||||||
current_command,
|
current_command,
|
||||||
menu_selected_index,
|
menu_selected_index,
|
||||||
form_cursor,
|
form_cursor,
|
||||||
form_values,
|
form_values,
|
||||||
log_scroll_pos,
|
log_scroll_pos,
|
||||||
|
log_scroll_x,
|
||||||
log_follow_bottom,
|
log_follow_bottom,
|
||||||
log_buffer,
|
log_buffer,
|
||||||
finished: _,
|
finished: _,
|
||||||
@@ -438,6 +438,12 @@ impl App {
|
|||||||
*log_follow_bottom =
|
*log_follow_bottom =
|
||||||
*log_scroll_pos + 1 >= log_buffer.len();
|
*log_scroll_pos + 1 >= log_buffer.len();
|
||||||
}
|
}
|
||||||
|
KeyCode::Left if !is_text_input && !is_menu && !is_form => {
|
||||||
|
*log_scroll_x = log_scroll_x.saturating_sub(4);
|
||||||
|
}
|
||||||
|
KeyCode::Right if !is_text_input && !is_menu && !is_form => {
|
||||||
|
*log_scroll_x = log_scroll_x.saturating_add(4);
|
||||||
|
}
|
||||||
|
|
||||||
// ── Confirm shortcuts (immediate, no Enter needed) ─
|
// ── Confirm shortcuts (immediate, no Enter needed) ─
|
||||||
KeyCode::Char('y') | KeyCode::Char('Y') if is_confirm => {
|
KeyCode::Char('y') | KeyCode::Char('Y') if is_confirm => {
|
||||||
@@ -518,10 +524,9 @@ impl App {
|
|||||||
let _ = current_command.take();
|
let _ = current_command.take();
|
||||||
let _ = reply_tx.send("n".to_string());
|
let _ = reply_tx.send("n".to_string());
|
||||||
} else {
|
} else {
|
||||||
debug_kill(format!("Esc pressed, pid={:?}", script_pid));
|
if let Some(kx) = kill_tx.take() {
|
||||||
kill_process(*script_pid);
|
let _ = kx.send(());
|
||||||
if let Some(tx) = kill_tx.take() { let _ = tx.send(()); }
|
}
|
||||||
for h in task_handles.drain(..) { h.abort(); }
|
|
||||||
self.popup = None;
|
self.popup = None;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -588,20 +593,27 @@ impl App {
|
|||||||
let _ = reply_tx.send(response);
|
let _ = reply_tx.send(response);
|
||||||
input_buffer.clear();
|
input_buffer.clear();
|
||||||
*menu_selected_index = 0;
|
*menu_selected_index = 0;
|
||||||
|
} else {
|
||||||
|
*log_scroll_x = log_scroll_x.saturating_add(4);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
KeyCode::Char('h') if !is_text_input => {
|
KeyCode::Char('h') if !is_text_input => {
|
||||||
if is_confirm {
|
if is_confirm {
|
||||||
let _ = current_command.take();
|
let _ = current_command.take();
|
||||||
let _ = reply_tx.send("n".to_string());
|
let _ = reply_tx.send("n".to_string());
|
||||||
} else {
|
} else if !is_menu && !is_form {
|
||||||
kill_process(*script_pid);
|
*log_scroll_x = log_scroll_x.saturating_sub(4);
|
||||||
if let Some(tx) = kill_tx.take() { let _ = tx.send(()); }
|
|
||||||
for h in task_handles.drain(..) { h.abort(); }
|
|
||||||
self.popup = None;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── H / L = start / end of line (horizontal) ───
|
||||||
|
KeyCode::Char('H') if !is_text_input && !is_menu && !is_form => {
|
||||||
|
*log_scroll_x = 0;
|
||||||
|
}
|
||||||
|
KeyCode::Char('L') if !is_text_input && !is_menu && !is_form => {
|
||||||
|
*log_scroll_x = usize::MAX;
|
||||||
|
}
|
||||||
|
|
||||||
// ── d / u = PgDn / PgUp (vim half-page scroll) ──
|
// ── d / u = PgDn / PgUp (vim half-page scroll) ──
|
||||||
KeyCode::Char('d') if !is_text_input && !is_form => {
|
KeyCode::Char('d') if !is_text_input && !is_form => {
|
||||||
*log_scroll_pos = log_scroll_pos.saturating_add(10);
|
*log_scroll_pos = log_scroll_pos.saturating_add(10);
|
||||||
@@ -699,24 +711,25 @@ impl App {
|
|||||||
KeyCode::Up | KeyCode::Char('k') => {
|
KeyCode::Up | KeyCode::Char('k') => {
|
||||||
let len = self.current_items().len();
|
let len = self.current_items().len();
|
||||||
if len > 0 {
|
if len > 0 {
|
||||||
self.selected_index = (self.selected_index + len - 1) % len;
|
self.selected_index = self.selected_index.saturating_sub(1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
KeyCode::Down | KeyCode::Char('j') => {
|
KeyCode::Down | KeyCode::Char('j') => {
|
||||||
let len = self.current_items().len();
|
let len = self.current_items().len();
|
||||||
if len > 0 {
|
if len > 0 && self.selected_index + 1 < len {
|
||||||
self.selected_index = (self.selected_index + 1) % len;
|
self.selected_index += 1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
KeyCode::Enter | KeyCode::Char('l') => {
|
KeyCode::Enter | KeyCode::Char('l') | KeyCode::Right => {
|
||||||
if let Some(item) = self.selected_item().cloned() {
|
if let Some(item) = self.selected_item().cloned() {
|
||||||
self.activate_item(item).await?;
|
self.activate_item(item).await?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
KeyCode::Esc | KeyCode::Char('h') => {
|
KeyCode::Esc | KeyCode::Char('h') | KeyCode::Left => {
|
||||||
if !self.breadcrumbs.is_empty() {
|
if !self.breadcrumbs.is_empty() {
|
||||||
self.breadcrumbs.pop();
|
self.breadcrumbs.pop();
|
||||||
self.selected_index = 0;
|
self.selected_index = 0;
|
||||||
|
self.menu_scroll_offset = 0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
KeyCode::Char('r') | KeyCode::Char('R') => {
|
KeyCode::Char('r') | KeyCode::Char('R') => {
|
||||||
@@ -832,11 +845,11 @@ impl App {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async fn run_bash_structured(&mut self, script: &str) -> Result<()> {
|
async fn run_bash_structured(&mut self, script: &str) -> Result<()> {
|
||||||
let (output_rx, command_rx, finished_rx, reply_tx, kill_tx, pid) =
|
let (output_rx, command_rx, finished_rx, reply_tx, kill_tx) =
|
||||||
executor::structured::spawn(script)?;
|
executor::structured::spawn(script)?;
|
||||||
|
|
||||||
let tx_output = self.event_tx.clone();
|
let tx_output = self.event_tx.clone();
|
||||||
let h_output = tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
let mut rx = output_rx;
|
let mut rx = output_rx;
|
||||||
while let Some(line) = rx.recv().await {
|
while let Some(line) = rx.recv().await {
|
||||||
if tx_output.send(Event::StructuredOutput(line)).is_err() {
|
if tx_output.send(Event::StructuredOutput(line)).is_err() {
|
||||||
@@ -846,7 +859,7 @@ impl App {
|
|||||||
});
|
});
|
||||||
|
|
||||||
let tx_cmd = self.event_tx.clone();
|
let tx_cmd = self.event_tx.clone();
|
||||||
let h_cmd = tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
let mut rx = command_rx;
|
let mut rx = command_rx;
|
||||||
while let Some(cmd) = rx.recv().await {
|
while let Some(cmd) = rx.recv().await {
|
||||||
if tx_cmd.send(Event::StructuredCommand(cmd)).is_err() {
|
if tx_cmd.send(Event::StructuredCommand(cmd)).is_err() {
|
||||||
@@ -856,16 +869,14 @@ impl App {
|
|||||||
});
|
});
|
||||||
|
|
||||||
let tx_finished = self.event_tx.clone();
|
let tx_finished = self.event_tx.clone();
|
||||||
let h_finished = tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
let code = finished_rx.await.unwrap_or(1);
|
let code = finished_rx.await.unwrap_or(1);
|
||||||
let _ = tx_finished.send(Event::StructuredFinished(code));
|
let _ = tx_finished.send(Event::StructuredFinished(code));
|
||||||
});
|
});
|
||||||
|
|
||||||
self.popup = Some(Popup::ExecutingStructured {
|
self.popup = Some(Popup::ExecutingStructured {
|
||||||
reply_tx,
|
reply_tx,
|
||||||
script_pid: pid,
|
|
||||||
kill_tx: Some(kill_tx),
|
kill_tx: Some(kill_tx),
|
||||||
task_handles: vec![h_output, h_cmd, h_finished],
|
|
||||||
log_buffer: Vec::new(),
|
log_buffer: Vec::new(),
|
||||||
current_command: None,
|
current_command: None,
|
||||||
input_buffer: String::new(),
|
input_buffer: String::new(),
|
||||||
@@ -873,6 +884,7 @@ impl App {
|
|||||||
form_cursor: 0,
|
form_cursor: 0,
|
||||||
form_values: Vec::new(),
|
form_values: Vec::new(),
|
||||||
log_scroll_pos: 0,
|
log_scroll_pos: 0,
|
||||||
|
log_scroll_x: 0,
|
||||||
log_follow_bottom: false,
|
log_follow_bottom: false,
|
||||||
finished: None,
|
finished: None,
|
||||||
});
|
});
|
||||||
@@ -881,95 +893,3 @@ impl App {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Find all descendant PIDs of `root_pid` by scanning /proc/*/status for PPid.
|
|
||||||
/// Works on any Linux including musl; no external tools needed.
|
|
||||||
#[cfg(target_os = "linux")]
|
|
||||||
fn find_descendants(root_pid: u32) -> Vec<u32> {
|
|
||||||
let mut result = Vec::new();
|
|
||||||
let mut frontier = vec![root_pid];
|
|
||||||
|
|
||||||
// BFS: each round finds the next generation of children.
|
|
||||||
while !frontier.is_empty() {
|
|
||||||
let mut next = Vec::new();
|
|
||||||
if let Ok(entries) = std::fs::read_dir("/proc") {
|
|
||||||
for entry in entries.flatten() {
|
|
||||||
let Ok(proc_pid) = entry.file_name().to_string_lossy().parse::<u32>()
|
|
||||||
else { continue };
|
|
||||||
if result.contains(&proc_pid) || proc_pid == root_pid {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let path = format!("/proc/{}/status", proc_pid);
|
|
||||||
let Ok(status) = std::fs::read_to_string(&path) else { continue };
|
|
||||||
let ppid: u32 = status
|
|
||||||
.lines()
|
|
||||||
.find(|l| l.starts_with("PPid:"))
|
|
||||||
.and_then(|l| l.split_whitespace().nth(1))
|
|
||||||
.and_then(|s| s.parse().ok())
|
|
||||||
.unwrap_or(0);
|
|
||||||
if frontier.contains(&ppid) {
|
|
||||||
result.push(proc_pid);
|
|
||||||
next.push(proc_pid);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
frontier = next;
|
|
||||||
}
|
|
||||||
result
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Kill a process and ALL its descendants (grep, php, mysql, …).
|
|
||||||
///
|
|
||||||
/// Linux: scan /proc for every process whose PPid chain leads back to
|
|
||||||
/// `root_pid`, kill descendants first, then the root itself.
|
|
||||||
/// macOS: bash was spawned with process_group(0), so PGID == bash PID;
|
|
||||||
/// kill(-PGID, SIGKILL) terminates the whole group atomically.
|
|
||||||
fn kill_process(pid: Option<u32>) {
|
|
||||||
debug_kill(format!("kill_process pid={:?}", pid));
|
|
||||||
let Some(pid) = pid else { return };
|
|
||||||
|
|
||||||
// ── Kill descendants BEFORE bash so the kernel can't reparent them ────────
|
|
||||||
//
|
|
||||||
// On Linux: walk /proc/*/status PPid chain to collect all descendants.
|
|
||||||
#[cfg(target_os = "linux")]
|
|
||||||
{
|
|
||||||
let descendants = find_descendants(pid);
|
|
||||||
debug_kill(format!(" /proc descendants: {:?}", descendants));
|
|
||||||
for &child in &descendants {
|
|
||||||
unsafe { libc::kill(child as libc::pid_t, libc::SIGKILL); }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Use pgrep to find and log direct children by parent-PID, then kill each.
|
|
||||||
// pgrep -lP lists "<pid> <command>" lines — gives us names for the log.
|
|
||||||
if let Ok(out) = std::process::Command::new("pgrep")
|
|
||||||
.args(["-lP", &pid.to_string()])
|
|
||||||
.output()
|
|
||||||
{
|
|
||||||
let text = String::from_utf8_lossy(&out.stdout);
|
|
||||||
debug_kill(format!(" pgrep -lP {pid}: [{text}]"));
|
|
||||||
for line in text.lines() {
|
|
||||||
if let Some(child_pid) = line.split_whitespace().next()
|
|
||||||
.and_then(|s| s.parse::<u32>().ok())
|
|
||||||
{
|
|
||||||
let r = unsafe { libc::kill(child_pid as libc::pid_t, libc::SIGKILL) };
|
|
||||||
debug_kill(format!(" kill({child_pid})={r}"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── Kill bash itself (direct + whole process group) ───────────────────────
|
|
||||||
#[cfg(unix)]
|
|
||||||
{
|
|
||||||
let r1 = unsafe { libc::kill(-(pid as libc::pid_t), libc::SIGKILL) };
|
|
||||||
let r2 = unsafe { libc::kill(pid as libc::pid_t, libc::SIGKILL) };
|
|
||||||
debug_kill(format!(" kill(-{pid})={r1} kill({pid})={r2}"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn debug_kill(msg: String) {
|
|
||||||
use std::io::Write;
|
|
||||||
if let Ok(mut f) = std::fs::OpenOptions::new()
|
|
||||||
.create(true).append(true).open("/tmp/ostiary-kill.log")
|
|
||||||
{
|
|
||||||
let _ = writeln!(f, "{}", msg);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -88,7 +88,6 @@ pub fn spawn(
|
|||||||
tokio::sync::oneshot::Receiver<i32>,
|
tokio::sync::oneshot::Receiver<i32>,
|
||||||
UnboundedSender<String>,
|
UnboundedSender<String>,
|
||||||
tokio::sync::oneshot::Sender<()>, // kill signal
|
tokio::sync::oneshot::Sender<()>, // kill signal
|
||||||
Option<u32>, // bash PID for direct kill
|
|
||||||
)> {
|
)> {
|
||||||
let mut child = Command::new("bash")
|
let mut child = Command::new("bash")
|
||||||
.arg("-c")
|
.arg("-c")
|
||||||
@@ -96,22 +95,10 @@ pub fn spawn(
|
|||||||
.stdin(Stdio::piped())
|
.stdin(Stdio::piped())
|
||||||
.stdout(Stdio::piped())
|
.stdout(Stdio::piped())
|
||||||
.stderr(Stdio::piped())
|
.stderr(Stdio::piped())
|
||||||
// Create a new process group (PGID = bash PID) so that
|
|
||||||
// kill(-pid, SIGKILL) kills bash AND all its children
|
|
||||||
// (grep, php, mysql, etc.) without touching the parent ostiary.
|
|
||||||
.process_group(0)
|
|
||||||
.spawn()?;
|
.spawn()?;
|
||||||
|
|
||||||
// Capture the PID before moving child into tasks (needed for kill).
|
// Capture the PID before moving child into tasks (needed for kill).
|
||||||
let pid = child.id();
|
let pid = child.id();
|
||||||
dbg_kill(format!("spawn: bash pid={:?}", pid));
|
|
||||||
// Log the actual process group bash landed in.
|
|
||||||
#[cfg(unix)]
|
|
||||||
if let Some(p) = pid {
|
|
||||||
let pgid = unsafe { libc::getpgid(p as libc::pid_t) };
|
|
||||||
let my_pgid = unsafe { libc::getpgid(0) };
|
|
||||||
dbg_kill(format!(" bash pgid={pgid} ostiary pgid={my_pgid}"));
|
|
||||||
}
|
|
||||||
|
|
||||||
let stdin = child.stdin.take().unwrap();
|
let stdin = child.stdin.take().unwrap();
|
||||||
let stdout = child.stdout.take().unwrap();
|
let stdout = child.stdout.take().unwrap();
|
||||||
@@ -175,33 +162,20 @@ pub fn spawn(
|
|||||||
let _ = finished_tx.send(code);
|
let _ = finished_tx.send(code);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Kill-watcher: when kill_tx fires, send SIGKILL to the entire process
|
// Kill-watcher: when kill_tx fires, send SIGTERM to the entire process
|
||||||
// group so bash AND all its children are unconditionally terminated.
|
// group so bash AND all its children (mysqldump, php, etc.) are killed.
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
let recv = kill_rx.await;
|
if kill_rx.await.is_ok() {
|
||||||
dbg_kill(format!("kill-watcher: recv={:?} pid={:?}", recv.is_ok(), pid));
|
|
||||||
if recv.is_ok() {
|
|
||||||
if let Some(pid) = pid {
|
if let Some(pid) = pid {
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
{
|
unsafe {
|
||||||
let r1 = unsafe { libc::kill(-(pid as libc::pid_t), libc::SIGKILL) };
|
libc::kill(-(pid as libc::pid_t), libc::SIGTERM);
|
||||||
let r2 = unsafe { libc::kill(pid as libc::pid_t, libc::SIGKILL) };
|
|
||||||
dbg_kill(format!(" kill-watcher kill(-{pid})={r1}, kill({pid})={r2}"));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
Ok((output_rx, cmd_rx, finished_rx, reply_tx, kill_tx, pid))
|
Ok((output_rx, cmd_rx, finished_rx, reply_tx, kill_tx))
|
||||||
}
|
|
||||||
|
|
||||||
fn dbg_kill(msg: String) {
|
|
||||||
use std::io::Write;
|
|
||||||
if let Ok(mut f) = std::fs::OpenOptions::new()
|
|
||||||
.create(true).append(true).open("/tmp/ostiary-kill.log")
|
|
||||||
{
|
|
||||||
let _ = writeln!(f, "{}", msg);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn parse_command(json_str: &str, cmd_tx: UnboundedSender<StructuredCommand>) -> Result<()> {
|
fn parse_command(json_str: &str, cmd_tx: UnboundedSender<StructuredCommand>) -> Result<()> {
|
||||||
|
|||||||
226
src/ui.rs
226
src/ui.rs
@@ -28,40 +28,115 @@ pub fn render(f: &mut Frame, app: &mut App) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn render_menu(f: &mut Frame, app: &App, area: Rect) {
|
fn render_menu(f: &mut Frame, app: &mut App, area: Rect) {
|
||||||
|
const SCROLLOFF: usize = 1;
|
||||||
|
|
||||||
let items = app.current_items();
|
let items = app.current_items();
|
||||||
let list_items: Vec<ListItem> = items
|
let total = items.len();
|
||||||
|
let inner_w = area.width.saturating_sub(2) as usize;
|
||||||
|
let inner_h = area.height.saturating_sub(2) as usize;
|
||||||
|
let sel = if total > 0 { app.selected_index.min(total - 1) } else { 0 };
|
||||||
|
|
||||||
|
// Wrap each item title into visual lines
|
||||||
|
let item_lines: Vec<Vec<String>> = items.iter().map(|item| {
|
||||||
|
let prefix = match &item.kind {
|
||||||
|
crate::menu::MenuItemKind::Category { .. } => "📁 ",
|
||||||
|
crate::menu::MenuItemKind::Action { .. } => "⚡ ",
|
||||||
|
};
|
||||||
|
wrap_to_lines(&format!("{}{}", prefix, item.title), inner_w)
|
||||||
|
}).collect();
|
||||||
|
|
||||||
|
// How many items fit starting from offset
|
||||||
|
let vis_from = |off: usize| -> usize {
|
||||||
|
let mut rows = 0usize;
|
||||||
|
let mut n = 0usize;
|
||||||
|
for lines in item_lines.get(off..).unwrap_or(&[]) {
|
||||||
|
let h = lines.len().max(1);
|
||||||
|
if rows + h > inner_h { break; }
|
||||||
|
rows += h;
|
||||||
|
n += 1;
|
||||||
|
}
|
||||||
|
n
|
||||||
|
};
|
||||||
|
|
||||||
|
// Clamp scroll offset for scrolloff margin
|
||||||
|
let offset = &mut app.menu_scroll_offset;
|
||||||
|
if total == 0 {
|
||||||
|
*offset = 0;
|
||||||
|
} else {
|
||||||
|
// Ensure sel is not before offset
|
||||||
|
if *offset > sel {
|
||||||
|
*offset = sel;
|
||||||
|
}
|
||||||
|
// Scroll up: sel must not be within top SCROLLOFF items
|
||||||
|
if sel < offset.saturating_add(SCROLLOFF) && *offset > 0 {
|
||||||
|
*offset = sel.saturating_sub(SCROLLOFF);
|
||||||
|
}
|
||||||
|
// Scroll down: sel must not be within bottom SCROLLOFF items
|
||||||
|
loop {
|
||||||
|
let vis = vis_from(*offset);
|
||||||
|
if vis == 0 { break; }
|
||||||
|
let trigger = offset.saturating_add(vis).saturating_sub(SCROLLOFF);
|
||||||
|
if sel >= trigger && *offset + vis < total {
|
||||||
|
*offset += 1;
|
||||||
|
} else {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Clamp to valid range
|
||||||
|
let max_off = total.saturating_sub(1);
|
||||||
|
*offset = (*offset).min(max_off);
|
||||||
|
}
|
||||||
|
|
||||||
|
let start = *offset;
|
||||||
|
let vis = vis_from(start);
|
||||||
|
let end = (start + vis).min(total);
|
||||||
|
|
||||||
|
let list_items: Vec<ListItem> = item_lines[start..end]
|
||||||
.iter()
|
.iter()
|
||||||
.enumerate()
|
.enumerate()
|
||||||
.map(|(i, item)| {
|
.map(|(i, lines)| {
|
||||||
let prefix = match &item.kind {
|
let abs = start + i;
|
||||||
crate::menu::MenuItemKind::Category { .. } => "📁 ",
|
let text: Vec<Line> = lines.iter().map(|l| Line::from(l.clone())).collect();
|
||||||
crate::menu::MenuItemKind::Action { .. } => "⚡ ",
|
let li = ListItem::new(ratatui::text::Text::from(text));
|
||||||
};
|
if abs == sel {
|
||||||
let content = Line::from(Span::raw(format!("{}{}", prefix, item.title)));
|
li.style(Style::default().bg(Color::Blue).add_modifier(Modifier::BOLD))
|
||||||
if i == app.selected_index {
|
|
||||||
ListItem::new(content).style(Style::default().bg(Color::Blue))
|
|
||||||
} else {
|
} else {
|
||||||
ListItem::new(content)
|
li
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
let list = List::new(list_items)
|
let list = List::new(list_items).block(
|
||||||
.block(
|
Block::default()
|
||||||
Block::default()
|
.borders(Borders::ALL)
|
||||||
.borders(Borders::ALL)
|
.title(" Меню ")
|
||||||
.title(" Меню ")
|
.title(
|
||||||
.title(
|
Line::from(Span::styled(
|
||||||
Line::from(Span::styled(
|
format!(" v{} ", env!("CARGO_PKG_VERSION")),
|
||||||
format!(" v{} ", env!("CARGO_PKG_VERSION")),
|
Style::default().fg(Color::DarkGray),
|
||||||
Style::default().fg(Color::DarkGray),
|
))
|
||||||
))
|
.alignment(Alignment::Right),
|
||||||
.alignment(Alignment::Right),
|
),
|
||||||
),
|
);
|
||||||
)
|
|
||||||
.highlight_style(Style::default().add_modifier(Modifier::BOLD));
|
|
||||||
f.render_widget(list, area);
|
f.render_widget(list, area);
|
||||||
|
|
||||||
|
if total > vis {
|
||||||
|
let max_off = total.saturating_sub(vis);
|
||||||
|
let scrollbar = Scrollbar::default()
|
||||||
|
.orientation(ScrollbarOrientation::VerticalRight)
|
||||||
|
.begin_symbol(Some("▲"))
|
||||||
|
.end_symbol(Some("▼"))
|
||||||
|
.thumb_symbol("█");
|
||||||
|
let mut sb_state = ScrollbarState::new(max_off).position(start);
|
||||||
|
let sb_area = Rect {
|
||||||
|
x: area.x + area.width.saturating_sub(1),
|
||||||
|
y: area.y + 1,
|
||||||
|
width: 1,
|
||||||
|
height: area.height.saturating_sub(2),
|
||||||
|
};
|
||||||
|
f.render_stateful_widget(scrollbar, sb_area, &mut sb_state);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn render_description(f: &mut Frame, app: &App, area: Rect) {
|
fn render_description(f: &mut Frame, app: &App, area: Rect) {
|
||||||
@@ -127,9 +202,7 @@ fn render_popup(f: &mut Frame, popup: &mut Popup) {
|
|||||||
|
|
||||||
Popup::ExecutingStructured {
|
Popup::ExecutingStructured {
|
||||||
reply_tx: _,
|
reply_tx: _,
|
||||||
script_pid: _,
|
|
||||||
kill_tx: _,
|
kill_tx: _,
|
||||||
task_handles: _,
|
|
||||||
log_buffer,
|
log_buffer,
|
||||||
current_command,
|
current_command,
|
||||||
input_buffer,
|
input_buffer,
|
||||||
@@ -137,6 +210,7 @@ fn render_popup(f: &mut Frame, popup: &mut Popup) {
|
|||||||
form_cursor,
|
form_cursor,
|
||||||
form_values,
|
form_values,
|
||||||
log_scroll_pos,
|
log_scroll_pos,
|
||||||
|
log_scroll_x,
|
||||||
log_follow_bottom,
|
log_follow_bottom,
|
||||||
finished,
|
finished,
|
||||||
} => {
|
} => {
|
||||||
@@ -172,13 +246,20 @@ fn render_popup(f: &mut Frame, popup: &mut Popup) {
|
|||||||
let start = pos;
|
let start = pos;
|
||||||
let end = (start + visible).min(total);
|
let end = (start + visible).min(total);
|
||||||
|
|
||||||
|
let viewport_w = chunks[0].width.saturating_sub(2) as usize;
|
||||||
|
let max_content_w: usize = log_buffer
|
||||||
|
.iter()
|
||||||
|
.map(|l| ansi::parse_line(l).iter().map(|(_, s)| s.chars().count()).sum::<usize>())
|
||||||
|
.max()
|
||||||
|
.unwrap_or(0);
|
||||||
|
let max_scroll_x = max_content_w.saturating_sub(viewport_w);
|
||||||
|
*log_scroll_x = (*log_scroll_x).min(max_scroll_x);
|
||||||
|
let scroll_x = *log_scroll_x;
|
||||||
|
|
||||||
let log_items: Vec<ListItem> = log_buffer[start..end]
|
let log_items: Vec<ListItem> = log_buffer[start..end]
|
||||||
.iter()
|
.iter()
|
||||||
.map(|line| {
|
.map(|line| {
|
||||||
let spans: Vec<Span> = ansi::parse_line(line)
|
let spans: Vec<Span> = h_scroll(ansi::parse_line(line), scroll_x);
|
||||||
.into_iter()
|
|
||||||
.map(|(style, text)| Span::styled(text, style))
|
|
||||||
.collect();
|
|
||||||
ListItem::new(Line::from(spans))
|
ListItem::new(Line::from(spans))
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
@@ -247,6 +328,26 @@ fn render_popup(f: &mut Frame, popup: &mut Popup) {
|
|||||||
f.render_stateful_widget(scrollbar, sb_area, &mut sb_state);
|
f.render_stateful_widget(scrollbar, sb_area, &mut sb_state);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── Horizontal scrollbar ─────────────────────────────────────────
|
||||||
|
if max_content_w > viewport_w {
|
||||||
|
let mut h_state = ScrollbarState::new(max_scroll_x).position(scroll_x);
|
||||||
|
let hscroll_area = Rect {
|
||||||
|
x: chunks[0].x + 1,
|
||||||
|
y: chunks[0].y + chunks[0].height.saturating_sub(1),
|
||||||
|
width: chunks[0].width.saturating_sub(2),
|
||||||
|
height: 1,
|
||||||
|
};
|
||||||
|
f.render_stateful_widget(
|
||||||
|
Scrollbar::new(ScrollbarOrientation::HorizontalBottom)
|
||||||
|
.begin_symbol(Some("◄"))
|
||||||
|
.end_symbol(Some("►"))
|
||||||
|
.thumb_symbol("▄")
|
||||||
|
.track_symbol(Some("─")),
|
||||||
|
hscroll_area,
|
||||||
|
&mut h_state,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
// ── Interactive command area ─────────────────────────────────────
|
// ── Interactive command area ─────────────────────────────────────
|
||||||
if cmd_height > 0 {
|
if cmd_height > 0 {
|
||||||
if let Some(cmd) = current_command {
|
if let Some(cmd) = current_command {
|
||||||
@@ -628,3 +729,66 @@ fn centered_rect(percent_x: u16, percent_y: u16, r: Rect) -> Rect {
|
|||||||
)
|
)
|
||||||
.split(popup_layout[1])[1]
|
.split(popup_layout[1])[1]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Wrap `text` into lines of at most `max_width` chars (word-wrap, hard-break on long words).
|
||||||
|
fn wrap_to_lines(text: &str, max_width: usize) -> Vec<String> {
|
||||||
|
if max_width == 0 || text.is_empty() {
|
||||||
|
return vec![text.to_string()];
|
||||||
|
}
|
||||||
|
let mut lines: Vec<String> = Vec::new();
|
||||||
|
let mut current = String::new();
|
||||||
|
for word in text.split_whitespace() {
|
||||||
|
let wlen = word.chars().count();
|
||||||
|
if current.is_empty() {
|
||||||
|
if wlen > max_width {
|
||||||
|
let chars: Vec<char> = word.chars().collect();
|
||||||
|
for chunk in chars.chunks(max_width) {
|
||||||
|
let s: String = chunk.iter().collect();
|
||||||
|
if s.chars().count() == max_width {
|
||||||
|
lines.push(s);
|
||||||
|
} else {
|
||||||
|
current = s;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
current = word.to_string();
|
||||||
|
}
|
||||||
|
} else if current.chars().count() + 1 + wlen <= max_width {
|
||||||
|
current.push(' ');
|
||||||
|
current.push_str(word);
|
||||||
|
} else {
|
||||||
|
lines.push(std::mem::take(&mut current));
|
||||||
|
current = word.to_string();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !current.is_empty() {
|
||||||
|
lines.push(current);
|
||||||
|
}
|
||||||
|
if lines.is_empty() {
|
||||||
|
lines.push(String::new());
|
||||||
|
}
|
||||||
|
lines
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Skip `offset` display chars from the start of a parsed ANSI span list.
|
||||||
|
fn h_scroll(parsed: Vec<(ratatui::style::Style, String)>, offset: usize) -> Vec<Span<'static>> {
|
||||||
|
let mut skip = offset;
|
||||||
|
let mut result = Vec::new();
|
||||||
|
for (style, text) in parsed {
|
||||||
|
if skip == 0 {
|
||||||
|
result.push(Span::styled(text, style));
|
||||||
|
} else {
|
||||||
|
let len = text.chars().count();
|
||||||
|
if skip >= len {
|
||||||
|
skip -= len;
|
||||||
|
} else {
|
||||||
|
let trimmed: String = text.chars().skip(skip).collect();
|
||||||
|
skip = 0;
|
||||||
|
if !trimmed.is_empty() {
|
||||||
|
result.push(Span::styled(trimmed, style));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user