Various changes

This commit is contained in:
Uber Veng
2026-05-21 21:12:31 +07:00
parent 533df4a476
commit 56f08e36e6
10 changed files with 1010 additions and 618 deletions

View File

@@ -13,25 +13,28 @@ pub enum Event {
MenuLoaded(Result<MenuRoot>),
ActionCompleted,
Error(String),
StructuredCommand(executor::StructuredCommand), // для structured сессии
StructuredOutput(String), // строка вывода от скрипта
StructuredFinished(i32), // код завершения
StructuredCommand(executor::StructuredCommand),
StructuredOutput(String),
StructuredFinished(i32),
}
/// A pending request to hand the terminal to an external interactive process.
/// Set by the structured-protocol handler; consumed by the main event loop.
pub struct PendingExec {
pub shell: String,
pub reply_tx: tokio::sync::mpsc::UnboundedSender<String>,
}
pub struct App {
pub config: Config,
pub menu: Option<MenuRoot>,
pub error: Option<String>,
// Навигация: стек индексов к текущей категории
pub breadcrumbs: Vec<usize>,
pub selected_index: usize, // индекс в текущем списке
// Состояние popup'а
pub selected_index: usize,
pub popup: Option<Popup>,
// Канал для отправки событий самому себе (из асинхронных задач)
pub event_tx: UnboundedSender<Event>,
/// When set, main loop suspends ratatui, runs the command, then restores.
pub pending_exec: Option<PendingExec>,
}
pub enum Popup {
@@ -43,9 +46,19 @@ pub enum Popup {
ExecutingBashTerminal { child: tokio::process::Child },
ExecutingStructured {
reply_tx: tokio::sync::mpsc::UnboundedSender<String>,
/// Fires SIGTERM to the script's process group on Esc.
kill_tx: Option<tokio::sync::oneshot::Sender<()>>,
log_buffer: Vec<String>,
current_command: Option<executor::StructuredCommand>,
input_buffer: String,
/// Cursor position for Menu-type commands.
menu_selected_index: usize,
/// Index of the first visible line in log_buffer (0 = top of output).
log_scroll_pos: 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.
finished: Option<i32>,
},
Downloading { progress: f32, message: String },
Message { text: String, level: MessageLevel },
@@ -68,6 +81,7 @@ impl App {
selected_index: 0,
popup: None,
event_tx,
pending_exec: None,
}
}
@@ -82,7 +96,6 @@ impl App {
});
}
/// Возвращает текущий список пунктов меню (категория или корень)
pub fn current_items(&self) -> Vec<&MenuItem> {
if self.breadcrumbs.is_empty() {
self.menu
@@ -102,13 +115,11 @@ impl App {
}
}
/// Получить выбранный пункт
pub fn selected_item(&self) -> Option<&MenuItem> {
let items = self.current_items();
items.get(self.selected_index).copied()
}
/// Обработка событий
pub async fn handle_event(&mut self, event: Event) -> Result<bool> {
match event {
Event::Crossterm(evt) => self.handle_crossterm_event(evt).await,
@@ -130,22 +141,53 @@ impl App {
Ok(false)
}
Event::StructuredCommand(cmd) => {
if let Some(Popup::ExecutingStructured { current_command, .. }) = &mut self.popup {
// Exec hands the terminal to an external process — clone reply_tx,
// store as pending_exec, and skip setting current_command so the
// main loop can suspend ratatui immediately.
if let executor::StructuredCommand::Exec { shell } = &cmd {
if let Some(Popup::ExecutingStructured { reply_tx, .. }) = &self.popup {
self.pending_exec = Some(PendingExec {
shell: shell.clone(),
reply_tx: reply_tx.clone(),
});
}
return Ok(false);
}
if let Some(Popup::ExecutingStructured {
current_command,
menu_selected_index,
..
}) = &mut self.popup
{
if matches!(cmd, executor::StructuredCommand::Menu { .. }) {
*menu_selected_index = 0;
}
*current_command = Some(cmd);
}
Ok(false)
}
Event::StructuredOutput(line) => {
if let Some(Popup::ExecutingStructured { log_buffer, .. }) = &mut self.popup {
if let Some(Popup::ExecutingStructured {
log_buffer,
log_follow_bottom,
log_scroll_pos,
..
}) = &mut self.popup
{
log_buffer.push(line);
// log_follow_bottom: render will pin pos to bottom.
// Otherwise pos stays fixed → new line appears off-screen.
let _ = (log_follow_bottom, log_scroll_pos); // used by render
}
Ok(false)
}
Event::StructuredFinished(exit_code) => {
self.popup = Some(Popup::Message {
text: format!("Скрипт завершился с кодом {}", exit_code),
level: if exit_code == 0 { MessageLevel::Info } else { MessageLevel::Error },
});
if let Some(Popup::ExecutingStructured { finished, .. }) = &mut self.popup {
*finished = Some(exit_code);
}
// If popup was already closed (user pressed Esc to kill the
// script), we silently discard the exit event.
Ok(false)
}
}
@@ -154,11 +196,9 @@ impl App {
async fn handle_crossterm_event(&mut self, evt: CrosstermEvent) -> Result<bool> {
match evt {
CrosstermEvent::Key(key) if key.kind == KeyEventKind::Press => {
// Если есть popup, передаём ему
if let Some(popup) = &mut self.popup {
match popup {
Popup::Confirming { action, item_title: _, confirm_message: _ } => {
// confirm_message можно не использовать здесь, но нужно изменить паттерн
Popup::Confirming { action, .. } => {
match key.code {
KeyCode::Char('y') | KeyCode::Char('Y') => {
let action = action.clone();
@@ -172,19 +212,90 @@ impl App {
}
return Ok(false);
}
Popup::ExecutingStructured {
reply_tx,
kill_tx,
input_buffer,
current_command,
..
menu_selected_index,
log_scroll_pos,
log_follow_bottom,
log_buffer,
finished,
} => {
let is_menu = matches!(
current_command,
Some(executor::StructuredCommand::Menu { .. })
);
let is_confirm = matches!(
current_command,
Some(executor::StructuredCommand::Confirm { .. })
);
let has_command = current_command.is_some();
match key.code {
KeyCode::Char(c) => {
// ── Log scrolling (PageUp / PageDown always work) ─
KeyCode::PageUp => {
*log_scroll_pos = log_scroll_pos.saturating_sub(10);
*log_follow_bottom = false;
}
KeyCode::PageDown => {
*log_scroll_pos = log_scroll_pos.saturating_add(10);
// Render will clamp to max; if we're at the
// bottom, mark as following.
*log_follow_bottom =
*log_scroll_pos + 1 >= log_buffer.len();
}
// ── Arrow keys ────────────────────────────────────
KeyCode::Up if is_menu => {
if *menu_selected_index > 0 {
*menu_selected_index -= 1;
}
}
KeyCode::Down if is_menu => {
if let Some(executor::StructuredCommand::Menu {
options, ..
}) = current_command
{
if *menu_selected_index + 1 < options.len() {
*menu_selected_index += 1;
}
}
}
// Scroll log one line when no interactive command pending
KeyCode::Up if !has_command => {
*log_scroll_pos = log_scroll_pos.saturating_sub(1);
*log_follow_bottom = false;
}
KeyCode::Down if !has_command => {
*log_scroll_pos = log_scroll_pos.saturating_add(1);
*log_follow_bottom =
*log_scroll_pos + 1 >= log_buffer.len();
}
// ── Confirm shortcuts (immediate, no Enter needed) ─
KeyCode::Char('y') | KeyCode::Char('Y') if is_confirm => {
let _ = current_command.take();
let _ = reply_tx.send("y".to_string());
input_buffer.clear();
}
KeyCode::Char('n') | KeyCode::Char('N') if is_confirm => {
let _ = current_command.take();
let _ = reply_tx.send("n".to_string());
input_buffer.clear();
}
// ── Text input ────────────────────────────────────
KeyCode::Char(c) if !is_menu && !is_confirm => {
input_buffer.push(c);
}
KeyCode::Backspace => {
KeyCode::Backspace if !is_menu => {
input_buffer.pop();
}
// ── Enter: commit response ────────────────────────
KeyCode::Enter => {
if let Some(cmd) = current_command.take() {
let response = match &cmd {
@@ -192,24 +303,46 @@ impl App {
input_buffer.clone()
}
executor::StructuredCommand::Confirm { .. } => {
if input_buffer.to_lowercase() == "y" { "y".to_string() } else { "n".to_string() }
}
executor::StructuredCommand::Menu { .. } => {
input_buffer.clone()
if input_buffer.to_lowercase().starts_with('y') {
"y".to_string()
} else {
"n".to_string()
}
}
executor::StructuredCommand::Menu {
options, ..
} => options
.get(*menu_selected_index)
.map(|opt| opt.id.clone())
.unwrap_or_default(),
// Message / Progress: send empty ack.
_ => String::new(),
};
let _ = reply_tx.send(response);
input_buffer.clear();
*menu_selected_index = 0;
}
}
// ── Esc ──────────────────────────────────────────
KeyCode::Esc => {
self.popup = None;
if is_confirm {
let _ = current_command.take();
let _ = reply_tx.send("n".to_string());
} else {
// Kill the script if still running.
if let Some(kx) = kill_tx.take() {
let _ = kx.send(());
}
self.popup = None;
}
}
_ => {}
}
return Ok(false);
}
Popup::Message { .. } => {
self.popup = None;
return Ok(false);
@@ -218,7 +351,7 @@ impl App {
}
}
// Навигация по меню
// ── Main menu navigation ─────────────────────────────────────────
match key.code {
KeyCode::Char('q') => return Ok(true),
KeyCode::Up => {
@@ -258,21 +391,16 @@ impl App {
async fn activate_item(&mut self, item: MenuItem) -> Result<()> {
match item.kind {
MenuItemKind::Category { children: _ } => {
// Переход в категорию
if let Some(idx) = self
.current_items()
.iter()
.position(|i| i.id == item.id)
{
if let Some(idx) = self.current_items().iter().position(|i| i.id == item.id) {
self.breadcrumbs.push(idx);
self.selected_index = 0;
}
}
MenuItemKind::Action { action } => {
if action.confirm() {
let confirm_message = action.confirm_message(); // забираем до перемещения
let confirm_message = action.confirm_message();
self.popup = Some(Popup::Confirming {
action, // перемещаем
action,
item_title: item.title,
confirm_message,
});
@@ -293,7 +421,6 @@ impl App {
confirm_message: _,
} => match interaction {
InteractionMode::Terminal => {
// Запуск в PTY (упрощённо)
self.run_bash_terminal(&script).await?;
}
InteractionMode::Structured => {
@@ -302,12 +429,9 @@ impl App {
},
Action::Download {
url,
filename: _,
target_dir: _,
confirm: _,
confirm_message: _,
..
} => {
// Заглушка
self.popup = Some(Popup::Message {
text: format!("Скачивание {} пока не реализовано", url),
level: MessageLevel::Info,
@@ -321,18 +445,13 @@ impl App {
async fn run_bash_terminal(&mut self, script: &str) -> Result<()> {
use tokio::process::Command;
// В реальности здесь нужно создавать PTY через дополнительную библиотеку
// Пока заглушка
let child = Command::new("bash")
.arg("-c")
.arg(script)
.spawn()?;
let child = Command::new("bash").arg("-c").arg(script).spawn()?;
self.popup = Some(Popup::ExecutingBashTerminal { child });
Ok(())
}
async fn run_bash_structured(&mut self, script: &str) -> Result<()> {
let (output_rx, command_rx, finished_rx, reply_tx) =
let (output_rx, command_rx, finished_rx, reply_tx, kill_tx) =
executor::structured::spawn(script)?;
let tx_output = self.event_tx.clone();
@@ -363,9 +482,14 @@ impl App {
self.popup = Some(Popup::ExecutingStructured {
reply_tx,
kill_tx: Some(kill_tx),
log_buffer: Vec::new(),
current_command: None,
input_buffer: String::new(),
menu_selected_index: 0,
log_scroll_pos: 0,
log_follow_bottom: false,
finished: None,
});
Ok(())