2 Commits

Author SHA1 Message Date
Uber Veng
b438cbd6b4 minor changes in scrolling 2026-05-25 20:17:31 +07:00
Uber Veng
25ccff3a37 Vain attempts to stop script 2026-05-22 22:06:32 +07:00
7 changed files with 376 additions and 74 deletions

2
Cargo.lock generated
View File

@@ -1123,7 +1123,7 @@ dependencies = [
[[package]]
name = "ostiary"
version = "1.0.10"
version = "1.0.11"
dependencies = [
"anyhow",
"crossterm",

View File

@@ -1,6 +1,6 @@
[package]
name = "ostiary"
version = "1.0.10"
version = "1.0.11"
edition = "2024"
[dependencies]

View File

@@ -37,6 +37,7 @@ pub struct App {
pub error: Option<String>,
pub breadcrumbs: Vec<usize>,
pub selected_index: usize,
pub menu_scroll_offset: usize,
pub popup: Option<Popup>,
pub event_tx: UnboundedSender<Event>,
/// When set, main loop suspends ratatui, runs the command, then restores.
@@ -67,6 +68,8 @@ pub enum Popup {
form_values: Vec<bool>,
/// Index of the first visible line in log_buffer (0 = top of output).
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.
log_follow_bottom: bool,
/// Set when the process has exited; popup stays open until Esc.
@@ -107,6 +110,7 @@ impl App {
error: None,
breadcrumbs: Vec::new(),
selected_index: 0,
menu_scroll_offset: 0,
popup: None,
event_tx,
pending_exec: None,
@@ -236,11 +240,24 @@ impl App {
Ok(false)
}
Event::StructuredFinished(exit_code) => {
if let Some(Popup::ExecutingStructured { finished, .. }) = &mut self.popup {
if let Some(Popup::ExecutingStructured {
finished,
current_command,
..
}) = &mut self.popup
{
*finished = Some(exit_code);
// Clear any lingering non-interactive command (e.g. Progress
// left by a notify() call just before the script exited).
// Leaving it set would make has_command=true and block scroll.
if matches!(
current_command,
Some(executor::StructuredCommand::Progress { .. })
| Some(executor::StructuredCommand::Message { .. })
) {
*current_command = None;
}
}
// If popup was already closed (user pressed Esc to kill the
// script), we silently discard the exit event.
Ok(false)
}
Event::UpdateAvailable(info) => {
@@ -301,9 +318,10 @@ impl App {
form_cursor,
form_values,
log_scroll_pos,
log_scroll_x,
log_follow_bottom,
log_buffer,
finished,
finished: _,
} => {
let is_menu = matches!(
current_command,
@@ -317,7 +335,16 @@ impl App {
current_command,
Some(executor::StructuredCommand::Form { .. })
);
let has_command = current_command.is_some();
let _has_command = current_command.is_some();
// Only interactive commands block scroll/navigation.
// Progress and Message are display-only and must not block arrows.
let blocks_scroll = matches!(
current_command,
Some(executor::StructuredCommand::Input { .. })
| Some(executor::StructuredCommand::Menu { .. })
| Some(executor::StructuredCommand::Confirm { .. })
| Some(executor::StructuredCommand::Form { .. })
);
// Vim motions are disabled only when free text input is active.
let is_text_input = matches!(
current_command,
@@ -402,15 +429,21 @@ impl App {
}
}
// Scroll log one line when no interactive command pending
KeyCode::Up if !has_command => {
KeyCode::Up if !blocks_scroll => {
*log_scroll_pos = log_scroll_pos.saturating_sub(1);
*log_follow_bottom = false;
}
KeyCode::Down if !has_command => {
KeyCode::Down if !blocks_scroll => {
*log_scroll_pos = log_scroll_pos.saturating_add(1);
*log_follow_bottom =
*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) ─
KeyCode::Char('y') | KeyCode::Char('Y') if is_confirm => {
@@ -425,13 +458,13 @@ impl App {
}
// ── Text input ────────────────────────────────────
// Excluded: vim motions (j/k/l/h) and form mode.
// Excluded: vim motions (j/k/l/h/d/u) and form mode.
KeyCode::Char(c)
if !is_menu
&& !is_confirm
&& !is_form
&& (is_text_input
|| !matches!(c, 'j' | 'k' | 'l' | 'h')) =>
|| !matches!(c, 'j' | 'k' | 'l' | 'h' | 'd' | 'u')) =>
{
input_buffer.push(c);
}
@@ -504,7 +537,7 @@ impl App {
if *menu_selected_index > 0 { *menu_selected_index -= 1; }
} else if is_form {
if *form_cursor > 0 { *form_cursor -= 1; }
} else if !has_command {
} else if !blocks_scroll {
*log_scroll_pos = log_scroll_pos.saturating_sub(1);
*log_follow_bottom = false;
}
@@ -523,7 +556,7 @@ impl App {
executor::StructuredCommand::Form { fields, .. }
) = current_command { fields.len() } else { 0 };
if *form_cursor + 1 < len { *form_cursor += 1; }
} else if !has_command {
} else if !blocks_scroll {
*log_scroll_pos = log_scroll_pos.saturating_add(1);
*log_follow_bottom =
*log_scroll_pos + 1 >= log_buffer.len();
@@ -560,19 +593,36 @@ impl App {
let _ = reply_tx.send(response);
input_buffer.clear();
*menu_selected_index = 0;
} else {
*log_scroll_x = log_scroll_x.saturating_add(4);
}
}
KeyCode::Char('h') if !is_text_input => {
// Back / cancel — same logic as Esc.
if is_confirm {
let _ = current_command.take();
let _ = reply_tx.send("n".to_string());
} else {
if let Some(kx) = kill_tx.take() {
let _ = kx.send(());
} else if !is_menu && !is_form {
*log_scroll_x = log_scroll_x.saturating_sub(4);
}
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) ──
KeyCode::Char('d') if !is_text_input && !is_form => {
*log_scroll_pos = log_scroll_pos.saturating_add(10);
*log_follow_bottom =
*log_scroll_pos + 1 >= log_buffer.len();
}
KeyCode::Char('u') if !is_text_input && !is_form => {
*log_scroll_pos = log_scroll_pos.saturating_sub(10);
*log_follow_bottom = false;
}
_ => {}
@@ -661,28 +711,68 @@ impl App {
KeyCode::Up | KeyCode::Char('k') => {
let len = self.current_items().len();
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') => {
let len = self.current_items().len();
if len > 0 && self.selected_index + 1 < len {
self.selected_index += 1;
}
}
KeyCode::Enter | KeyCode::Char('l') | KeyCode::Right => {
if let Some(item) = self.selected_item().cloned() {
self.activate_item(item).await?;
}
}
KeyCode::Esc | KeyCode::Char('h') | KeyCode::Left => {
if !self.breadcrumbs.is_empty() {
self.breadcrumbs.pop();
self.selected_index = 0;
self.menu_scroll_offset = 0;
}
}
KeyCode::Char('r') | KeyCode::Char('R') => {
self.load_menu().await;
}
_ => {}
}
}
CrosstermEvent::Mouse(mouse) => {
use crossterm::event::MouseEventKind;
match mouse.kind {
MouseEventKind::ScrollUp => {
if let Some(Popup::ExecutingStructured {
log_scroll_pos,
log_follow_bottom,
..
}) = &mut self.popup
{
*log_scroll_pos = log_scroll_pos.saturating_sub(3);
*log_follow_bottom = false;
} else if self.popup.is_none() {
let len = self.current_items().len();
if len > 0 {
self.selected_index = (self.selected_index + len - 1) % len;
}
}
}
MouseEventKind::ScrollDown => {
if let Some(Popup::ExecutingStructured {
log_scroll_pos,
log_follow_bottom,
log_buffer,
..
}) = &mut self.popup
{
*log_scroll_pos = log_scroll_pos.saturating_add(3);
*log_follow_bottom = *log_scroll_pos + 1 >= log_buffer.len();
} else if self.popup.is_none() {
let len = self.current_items().len();
if len > 0 {
self.selected_index = (self.selected_index + 1) % len;
}
}
KeyCode::Enter | KeyCode::Char('l') => {
if let Some(item) = self.selected_item().cloned() {
self.activate_item(item).await?;
}
}
KeyCode::Esc | KeyCode::Char('h') => {
if !self.breadcrumbs.is_empty() {
self.breadcrumbs.pop();
self.selected_index = 0;
}
}
KeyCode::Char('r') | KeyCode::Char('R') => {
self.load_menu().await;
}
_ => {}
}
@@ -794,6 +884,7 @@ impl App {
form_cursor: 0,
form_values: Vec::new(),
log_scroll_pos: 0,
log_scroll_x: 0,
log_follow_bottom: false,
finished: None,
});
@@ -801,3 +892,4 @@ impl App {
Ok(())
}
}

View File

@@ -1,4 +1,4 @@
pub mod structured;
pub use structured::{StructuredCommand, MessageLevel, FormField, FormFieldType};
pub use structured::{StructuredCommand, MessageLevel, FormFieldType};
// Здесь могут быть функции для download, http и т.д.

View File

@@ -28,7 +28,9 @@ pub enum StructuredCommand {
text: String,
},
Progress {
percent: u8,
/// Some(n) = deterministic bar (0-100).
/// None = indeterminate spinner (percent omitted from JSON).
percent: Option<u8>,
message: Option<String>,
},
/// A list of checkboxes and radio buttons.
@@ -218,7 +220,8 @@ fn parse_command(json_str: &str, cmd_tx: UnboundedSender<StructuredCommand>) ->
StructuredCommand::Message { level, text }
}
"progress" => {
let percent = v["percent"].as_u64().unwrap_or(0) as u8;
// percent absent or null → None (indeterminate spinner)
let percent = v["percent"].as_u64().map(|n| n.min(100) as u8);
let message = v["message"].as_str().map(String::from);
StructuredCommand::Progress { percent, message }
}

View File

@@ -107,7 +107,7 @@ async fn run_app(
terminal.show_cursor()?;
#[cfg(unix)]
updater::exec_updated(&exe_path);
// fallback for non-unix or if exec failed
#[cfg(not(unix))]
break;
}

253
src/ui.rs
View File

@@ -28,27 +28,86 @@ 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 list_items: Vec<ListItem> = items
.iter()
.enumerate()
.map(|(i, item)| {
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 { .. } => "",
};
let content = Line::from(Span::raw(format!("{}{}", prefix, item.title)));
if i == app.selected_index {
ListItem::new(content).style(Style::default().bg(Color::Blue))
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 {
ListItem::new(content)
// 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()
.enumerate()
.map(|(i, lines)| {
let abs = start + i;
let text: Vec<Line> = lines.iter().map(|l| Line::from(l.clone())).collect();
let li = ListItem::new(ratatui::text::Text::from(text));
if abs == sel {
li.style(Style::default().bg(Color::Blue).add_modifier(Modifier::BOLD))
} else {
li
}
})
.collect();
let list = List::new(list_items)
.block(
let list = List::new(list_items).block(
Block::default()
.borders(Borders::ALL)
.title(" Меню ")
@@ -59,9 +118,25 @@ fn render_menu(f: &mut Frame, app: &App, area: Rect) {
))
.alignment(Alignment::Right),
),
)
.highlight_style(Style::default().add_modifier(Modifier::BOLD));
);
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) {
@@ -135,6 +210,7 @@ fn render_popup(f: &mut Frame, popup: &mut Popup) {
form_cursor,
form_values,
log_scroll_pos,
log_scroll_x,
log_follow_bottom,
finished,
} => {
@@ -170,13 +246,20 @@ fn render_popup(f: &mut Frame, popup: &mut Popup) {
let start = pos;
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]
.iter()
.map(|line| {
let spans: Vec<Span> = ansi::parse_line(line)
.into_iter()
.map(|(style, text)| Span::styled(text, style))
.collect();
let spans: Vec<Span> = h_scroll(ansi::parse_line(line), scroll_x);
ListItem::new(Line::from(spans))
})
.collect();
@@ -184,13 +267,27 @@ fn render_popup(f: &mut Frame, popup: &mut Popup) {
let at_bottom = pos >= max_pos;
let at_top = pos == 0;
// Reusable scroll hint based on current position
let scroll_hint = if total <= visible {
// All content fits — nothing to scroll
String::new()
} else if at_top && at_bottom {
String::new()
} else if at_top {
format!(" │ PgDn/↓ вниз ({}/{})", end, total)
} else if at_bottom {
format!(" │ PgUp/↑ вверх ({}/{})", end, total)
} else {
format!(" │ PgUp ↑ PgDn ↓ ({}/{})", end, total)
};
let (title, border_color): (String, Color) = match finished {
Some(0) => (
" ✓ Завершено — Esc закрыть │ PgUp/↑↓ скролл ".to_string(),
format!(" ✓ Завершено — Esc закрыть{} ", scroll_hint),
Color::Green,
),
Some(code) => (
format!(" ✗ Ошибка (код {}) — Esc закрыть │ PgUp/↑↓ скролл ", code),
format!(" ✗ Ошибка (код {}) — Esc закрыть{} ", code, scroll_hint),
Color::Red,
),
None if at_top && at_bottom => (
@@ -231,6 +328,26 @@ fn render_popup(f: &mut Frame, popup: &mut Popup) {
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 ─────────────────────────────────────
if cmd_height > 0 {
if let Some(cmd) = current_command {
@@ -486,16 +603,22 @@ fn render_command(
}
executor::StructuredCommand::Progress { percent, message } => {
let msg = message.as_deref().unwrap_or("");
match percent {
Some(pct) => {
let bar_width = area.width.saturating_sub(4) as usize;
let filled = (*percent as usize * bar_width) / 100;
let filled = (*pct as usize * bar_width) / 100;
let bar = format!(
"[{}{}] {}%",
"".repeat(filled),
"".repeat(bar_width.saturating_sub(filled)),
percent
pct
);
let msg = message.as_deref().unwrap_or("");
let paragraph = Paragraph::new(vec![Line::from(bar), Line::from(msg)]).block(
let paragraph = Paragraph::new(vec![
Line::from(bar),
Line::from(msg),
])
.block(
Block::default()
.borders(Borders::ALL)
.title(" Прогресс ")
@@ -503,6 +626,27 @@ fn render_command(
);
f.render_widget(paragraph, area);
}
None => {
// Indeterminate: spinning braille dots
const SPINNER: &[&str] =
&["", "", "", "", "", "", "", "", "", ""];
let frame = (std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_millis()
/ 120) as usize;
let spinner = SPINNER[frame % SPINNER.len()];
let line = format!("{} {}", spinner, msg);
let paragraph = Paragraph::new(line).block(
Block::default()
.borders(Borders::ALL)
.title(" Прогресс ")
.border_style(Style::default().fg(Color::Cyan)),
);
f.render_widget(paragraph, area);
}
}
}
executor::StructuredCommand::Form { prompt, fields } => {
let items: Vec<ListItem> = fields.iter().enumerate().map(|(i, field)| {
@@ -585,3 +729,66 @@ fn centered_rect(percent_x: u16, percent_y: u16, r: Rect) -> Rect {
)
.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
}