Compare commits
3 Commits
b438cbd6b4
...
a9aa0ad736
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a9aa0ad736 | ||
|
|
a83987af19 | ||
|
|
3d6fd77d85 |
2
Cargo.lock
generated
2
Cargo.lock
generated
@@ -1123,7 +1123,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ostiary"
|
||||
version = "1.0.11"
|
||||
version = "1.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"crossterm",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "ostiary"
|
||||
version = "1.0.11"
|
||||
version = "1.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
|
||||
488
src/app.rs
488
src/app.rs
@@ -1,11 +1,11 @@
|
||||
// src/app.rs
|
||||
use crate::config::Config;
|
||||
use crate::error::Result;
|
||||
use crate::executor;
|
||||
use crate::menu::{Action, InteractionMode, MenuItem, MenuItemKind, MenuRoot};
|
||||
use crate::network;
|
||||
use crate::text_input::TextInput;
|
||||
use crate::updater;
|
||||
use crossterm::event::{Event as CrosstermEvent, KeyCode, KeyEventKind};
|
||||
use crossterm::event::{Event as CrosstermEvent, KeyCode, KeyEventKind, KeyModifiers};
|
||||
use tokio::sync::mpsc::UnboundedSender;
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -25,7 +25,6 @@ pub enum Event {
|
||||
}
|
||||
|
||||
/// 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>,
|
||||
@@ -40,9 +39,7 @@ pub struct App {
|
||||
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.
|
||||
pub pending_exec: Option<PendingExec>,
|
||||
/// Exe path to exec after update; captured before the binary was replaced.
|
||||
pub pending_restart: Option<std::path::PathBuf>,
|
||||
}
|
||||
|
||||
@@ -55,26 +52,35 @@ 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.
|
||||
input: TextInput,
|
||||
menu_selected_index: usize,
|
||||
/// Cursor position for Form-type commands.
|
||||
form_cursor: usize,
|
||||
/// Checked/selected state for each Form field (parallel to fields vec).
|
||||
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.
|
||||
finished: Option<i32>,
|
||||
},
|
||||
EndpointSelector {
|
||||
selected: usize,
|
||||
scroll_offset: usize,
|
||||
},
|
||||
/// Unified add/edit popup. `edit_index = None` → adding new endpoint.
|
||||
UpsertEndpoint {
|
||||
edit_index: Option<usize>,
|
||||
/// [0] = name, [1] = url
|
||||
fields: [TextInput; 2],
|
||||
active_field: usize,
|
||||
error: Option<String>,
|
||||
return_selected: usize,
|
||||
},
|
||||
ConfirmDeleteEndpoint {
|
||||
index: usize,
|
||||
return_selected: usize,
|
||||
},
|
||||
Downloading { progress: f32, message: String },
|
||||
Message { text: String, level: MessageLevel },
|
||||
UpdateConfirm {
|
||||
@@ -134,7 +140,7 @@ impl App {
|
||||
}
|
||||
|
||||
pub async fn load_menu(&mut self) {
|
||||
let server_url = self.config.server_url.clone();
|
||||
let server_url = self.config.active_url().to_string();
|
||||
let timeout = self.config.timeout_sec;
|
||||
let tx = self.event_tx.clone();
|
||||
|
||||
@@ -189,9 +195,6 @@ impl App {
|
||||
Ok(false)
|
||||
}
|
||||
Event::StructuredCommand(cmd) => {
|
||||
// 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 {
|
||||
@@ -225,17 +228,8 @@ impl App {
|
||||
Ok(false)
|
||||
}
|
||||
Event::StructuredOutput(line) => {
|
||||
if let Some(Popup::ExecutingStructured {
|
||||
log_buffer,
|
||||
log_follow_bottom,
|
||||
log_scroll_pos,
|
||||
..
|
||||
}) = &mut self.popup
|
||||
{
|
||||
if let Some(Popup::ExecutingStructured { log_buffer, .. }) = &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)
|
||||
}
|
||||
@@ -247,9 +241,6 @@ impl App {
|
||||
}) = &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 { .. })
|
||||
@@ -261,7 +252,6 @@ impl App {
|
||||
Ok(false)
|
||||
}
|
||||
Event::UpdateAvailable(info) => {
|
||||
// Only show if no popup is currently open (don't interrupt running scripts)
|
||||
if self.popup.is_none() {
|
||||
self.popup = Some(Popup::UpdateConfirm { info });
|
||||
}
|
||||
@@ -312,7 +302,7 @@ impl App {
|
||||
Popup::ExecutingStructured {
|
||||
reply_tx,
|
||||
kill_tx,
|
||||
input_buffer,
|
||||
input,
|
||||
current_command,
|
||||
menu_selected_index,
|
||||
form_cursor,
|
||||
@@ -335,9 +325,6 @@ impl App {
|
||||
current_command,
|
||||
Some(executor::StructuredCommand::Form { .. })
|
||||
);
|
||||
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 { .. })
|
||||
@@ -345,49 +332,40 @@ impl App {
|
||||
| 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,
|
||||
Some(executor::StructuredCommand::Input { .. })
|
||||
);
|
||||
let alt = key.modifiers.intersects(KeyModifiers::ALT | KeyModifiers::SUPER);
|
||||
|
||||
match key.code {
|
||||
// ── Log scrolling (PageUp / PageDown always work) ─
|
||||
// ── Log scrolling ────────────────────────────────
|
||||
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();
|
||||
*log_follow_bottom = *log_scroll_pos + 1 >= log_buffer.len();
|
||||
}
|
||||
|
||||
// ── Form: navigation and toggle ──────────────────
|
||||
// ── Form navigation ──────────────────────────────
|
||||
KeyCode::Up if is_form => {
|
||||
if *form_cursor > 0 { *form_cursor -= 1; }
|
||||
}
|
||||
KeyCode::Down if is_form => {
|
||||
let len = if let Some(
|
||||
executor::StructuredCommand::Form { fields, .. }
|
||||
) = current_command { fields.len() } else { 0 };
|
||||
let len = if let Some(executor::StructuredCommand::Form { fields, .. }) = current_command {
|
||||
fields.len()
|
||||
} else { 0 };
|
||||
if *form_cursor + 1 < len { *form_cursor += 1; }
|
||||
}
|
||||
KeyCode::Char(' ') if is_form => {
|
||||
let cursor = *form_cursor;
|
||||
// Collect toggle info before mutating form_values
|
||||
let toggle = if let Some(
|
||||
executor::StructuredCommand::Form { fields, .. }
|
||||
) = current_command {
|
||||
let toggle = if let Some(executor::StructuredCommand::Form { fields, .. }) = current_command {
|
||||
fields.get(cursor).map(|f| {
|
||||
let group_indices: Vec<usize> = fields.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, ff)| {
|
||||
ff.group.is_some()
|
||||
&& ff.group == f.group
|
||||
})
|
||||
.filter(|(_, ff)| ff.group.is_some() && ff.group == f.group)
|
||||
.map(|(i, _)| i)
|
||||
.collect();
|
||||
(f.field_type.clone(), group_indices)
|
||||
@@ -412,32 +390,29 @@ impl App {
|
||||
}
|
||||
}
|
||||
|
||||
// ── Arrow keys ────────────────────────────────────
|
||||
// ── Arrow / cursor keys ──────────────────────────
|
||||
KeyCode::Up if is_menu => {
|
||||
if *menu_selected_index > 0 {
|
||||
*menu_selected_index -= 1;
|
||||
}
|
||||
if *menu_selected_index > 0 { *menu_selected_index -= 1; }
|
||||
}
|
||||
KeyCode::Down if is_menu => {
|
||||
if let Some(executor::StructuredCommand::Menu {
|
||||
options, ..
|
||||
}) = current_command
|
||||
{
|
||||
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 !blocks_scroll => {
|
||||
*log_scroll_pos = log_scroll_pos.saturating_sub(1);
|
||||
*log_follow_bottom = false;
|
||||
}
|
||||
KeyCode::Down if !blocks_scroll => {
|
||||
*log_scroll_pos = log_scroll_pos.saturating_add(1);
|
||||
*log_follow_bottom =
|
||||
*log_scroll_pos + 1 >= log_buffer.len();
|
||||
*log_follow_bottom = *log_scroll_pos + 1 >= log_buffer.len();
|
||||
}
|
||||
KeyCode::Left if is_text_input && alt => { input.word_back(); }
|
||||
KeyCode::Right if is_text_input && alt => { input.word_fwd(); }
|
||||
KeyCode::Left if is_text_input => { input.move_left(); }
|
||||
KeyCode::Right if is_text_input => { input.move_right(); }
|
||||
KeyCode::Left if !is_text_input && !is_menu && !is_form => {
|
||||
*log_scroll_x = log_scroll_x.saturating_sub(4);
|
||||
}
|
||||
@@ -445,46 +420,37 @@ impl App {
|
||||
*log_scroll_x = log_scroll_x.saturating_add(4);
|
||||
}
|
||||
|
||||
// ── Confirm shortcuts (immediate, no Enter needed) ─
|
||||
// ── Confirm shortcuts ────────────────────────────
|
||||
KeyCode::Char('y') | KeyCode::Char('Y') if is_confirm => {
|
||||
let _ = current_command.take();
|
||||
let _ = reply_tx.send("y".to_string());
|
||||
input_buffer.clear();
|
||||
input.clear();
|
||||
}
|
||||
KeyCode::Char('n') | KeyCode::Char('N') if is_confirm => {
|
||||
let _ = current_command.take();
|
||||
let _ = reply_tx.send("n".to_string());
|
||||
input_buffer.clear();
|
||||
input.clear();
|
||||
}
|
||||
|
||||
// ── Text input ────────────────────────────────────
|
||||
// Excluded: vim motions (j/k/l/h/d/u) and form mode.
|
||||
// ── Text input ───────────────────────────────────
|
||||
KeyCode::Char('b') if is_text_input && alt => { input.word_back(); }
|
||||
KeyCode::Char('f') if is_text_input && alt => { input.word_fwd(); }
|
||||
KeyCode::Char(c)
|
||||
if !is_menu
|
||||
&& !is_confirm
|
||||
&& !is_form
|
||||
&& (is_text_input
|
||||
|| !matches!(c, 'j' | 'k' | 'l' | 'h' | 'd' | 'u')) =>
|
||||
if !is_menu && !is_confirm && !is_form
|
||||
&& (is_text_input || !matches!(c, 'j' | 'k' | 'l' | 'h' | 'd' | 'u')) =>
|
||||
{
|
||||
input_buffer.push(c);
|
||||
}
|
||||
KeyCode::Backspace if !is_menu && !is_form => {
|
||||
input_buffer.pop();
|
||||
input.insert(c);
|
||||
}
|
||||
KeyCode::Backspace if is_text_input && alt => { input.word_delete_back(); }
|
||||
KeyCode::Backspace if !is_menu && !is_form => { input.backspace(); }
|
||||
|
||||
// ── Enter: commit response ────────────────────────
|
||||
// ── Enter ────────────────────────────────────────
|
||||
KeyCode::Enter => {
|
||||
// Form submit: collect checked IDs
|
||||
if is_form {
|
||||
if let Some(executor::StructuredCommand::Form {
|
||||
fields, ..
|
||||
}) = current_command.take() {
|
||||
if let Some(executor::StructuredCommand::Form { fields, .. }) = current_command.take() {
|
||||
let response = fields.iter().enumerate()
|
||||
.filter_map(|(i, f)| {
|
||||
form_values.get(i)
|
||||
.copied()
|
||||
.filter(|&v| v)
|
||||
.map(|_| f.id.as_str())
|
||||
form_values.get(i).copied().filter(|&v| v).map(|_| f.id.as_str())
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
@@ -494,26 +460,17 @@ impl App {
|
||||
}
|
||||
} else if let Some(cmd) = current_command.take() {
|
||||
let response = match &cmd {
|
||||
executor::StructuredCommand::Input { .. } => {
|
||||
input_buffer.clone()
|
||||
}
|
||||
executor::StructuredCommand::Input { .. } => input.buf.clone(),
|
||||
executor::StructuredCommand::Confirm { .. } => {
|
||||
if input_buffer.to_lowercase().starts_with('y') {
|
||||
"y".to_string()
|
||||
} else {
|
||||
"n".to_string()
|
||||
}
|
||||
if input.buf.to_lowercase().starts_with('y') { "y".to_string() } else { "n".to_string() }
|
||||
}
|
||||
executor::StructuredCommand::Menu { options, .. } => {
|
||||
options.get(*menu_selected_index).map(|o| o.id.clone()).unwrap_or_default()
|
||||
}
|
||||
executor::StructuredCommand::Menu {
|
||||
options, ..
|
||||
} => options
|
||||
.get(*menu_selected_index)
|
||||
.map(|opt| opt.id.clone())
|
||||
.unwrap_or_default(),
|
||||
_ => String::new(),
|
||||
};
|
||||
let _ = reply_tx.send(response);
|
||||
input_buffer.clear();
|
||||
input.clear();
|
||||
*menu_selected_index = 0;
|
||||
}
|
||||
}
|
||||
@@ -531,7 +488,7 @@ impl App {
|
||||
}
|
||||
}
|
||||
|
||||
// ── Vim motions (off during text input) ───────────
|
||||
// ── Vim motions ──────────────────────────────────
|
||||
KeyCode::Char('k') if !is_text_input => {
|
||||
if is_menu {
|
||||
if *menu_selected_index > 0 { *menu_selected_index -= 1; }
|
||||
@@ -544,34 +501,27 @@ impl App {
|
||||
}
|
||||
KeyCode::Char('j') if !is_text_input => {
|
||||
if is_menu {
|
||||
if let Some(executor::StructuredCommand::Menu {
|
||||
options, ..
|
||||
}) = current_command {
|
||||
if let Some(executor::StructuredCommand::Menu { options, .. }) = current_command {
|
||||
if *menu_selected_index + 1 < options.len() {
|
||||
*menu_selected_index += 1;
|
||||
}
|
||||
}
|
||||
} else if is_form {
|
||||
let len = if let Some(
|
||||
executor::StructuredCommand::Form { fields, .. }
|
||||
) = current_command { fields.len() } else { 0 };
|
||||
let len = if let Some(executor::StructuredCommand::Form { fields, .. }) = current_command {
|
||||
fields.len()
|
||||
} else { 0 };
|
||||
if *form_cursor + 1 < len { *form_cursor += 1; }
|
||||
} else if !blocks_scroll {
|
||||
*log_scroll_pos = log_scroll_pos.saturating_add(1);
|
||||
*log_follow_bottom =
|
||||
*log_scroll_pos + 1 >= log_buffer.len();
|
||||
*log_follow_bottom = *log_scroll_pos + 1 >= log_buffer.len();
|
||||
}
|
||||
}
|
||||
KeyCode::Char('l') if !is_text_input => {
|
||||
// Form submit
|
||||
if is_form {
|
||||
if let Some(executor::StructuredCommand::Form {
|
||||
fields, ..
|
||||
}) = current_command.take() {
|
||||
if let Some(executor::StructuredCommand::Form { fields, .. }) = current_command.take() {
|
||||
let response = fields.iter().enumerate()
|
||||
.filter_map(|(i, f)| {
|
||||
form_values.get(i).copied()
|
||||
.filter(|&v| v).map(|_| f.id.as_str())
|
||||
form_values.get(i).copied().filter(|&v| v).map(|_| f.id.as_str())
|
||||
})
|
||||
.collect::<Vec<_>>().join(" ");
|
||||
let _ = reply_tx.send(response);
|
||||
@@ -580,18 +530,14 @@ impl App {
|
||||
}
|
||||
} else if let Some(cmd) = current_command.take() {
|
||||
let response = match &cmd {
|
||||
executor::StructuredCommand::Confirm { .. } => {
|
||||
"y".to_string()
|
||||
}
|
||||
executor::StructuredCommand::Confirm { .. } => "y".to_string(),
|
||||
executor::StructuredCommand::Menu { options, .. } => {
|
||||
options.get(*menu_selected_index)
|
||||
.map(|o| o.id.clone())
|
||||
.unwrap_or_default()
|
||||
options.get(*menu_selected_index).map(|o| o.id.clone()).unwrap_or_default()
|
||||
}
|
||||
_ => String::new(),
|
||||
};
|
||||
let _ = reply_tx.send(response);
|
||||
input_buffer.clear();
|
||||
input.clear();
|
||||
*menu_selected_index = 0;
|
||||
} else {
|
||||
*log_scroll_x = log_scroll_x.saturating_add(4);
|
||||
@@ -605,20 +551,15 @@ impl App {
|
||||
*log_scroll_x = log_scroll_x.saturating_sub(4);
|
||||
}
|
||||
}
|
||||
|
||||
// ── 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();
|
||||
*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);
|
||||
@@ -630,6 +571,208 @@ impl App {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
Popup::EndpointSelector { selected, scroll_offset: _ } => {
|
||||
match key.code {
|
||||
KeyCode::Up | KeyCode::Char('k') => {
|
||||
if *selected > 0 { *selected -= 1; }
|
||||
}
|
||||
KeyCode::Down | KeyCode::Char('j') => {
|
||||
let len = self.config.endpoints.len();
|
||||
if *selected + 1 < len { *selected += 1; }
|
||||
}
|
||||
KeyCode::Enter | KeyCode::Char('l') => {
|
||||
let sel = *selected;
|
||||
self.popup = None;
|
||||
let url = self.config.endpoints.get(sel).map(|ep| ep.url.clone());
|
||||
if let Some(url) = url {
|
||||
if url != self.config.active_endpoint {
|
||||
self.config.active_endpoint = url;
|
||||
let _ = self.config.save();
|
||||
self.menu = None;
|
||||
self.breadcrumbs.clear();
|
||||
self.selected_index = 0;
|
||||
self.menu_scroll_offset = 0;
|
||||
self.load_menu().await;
|
||||
}
|
||||
}
|
||||
}
|
||||
KeyCode::Char('d') | KeyCode::Char('D') => {
|
||||
let sel = *selected;
|
||||
if sel < self.config.endpoints.len() {
|
||||
self.popup = Some(Popup::ConfirmDeleteEndpoint {
|
||||
index: sel,
|
||||
return_selected: sel,
|
||||
});
|
||||
}
|
||||
}
|
||||
KeyCode::Char('e') | KeyCode::Char('E') => {
|
||||
let sel = *selected;
|
||||
if let Some(ep) = self.config.endpoints.get(sel) {
|
||||
let name = ep.name.clone();
|
||||
let url = ep.url.clone();
|
||||
self.popup = Some(Popup::UpsertEndpoint {
|
||||
edit_index: Some(sel),
|
||||
fields: [TextInput::with_text(name), TextInput::with_text(url)],
|
||||
active_field: 0,
|
||||
error: None,
|
||||
return_selected: sel,
|
||||
});
|
||||
}
|
||||
}
|
||||
KeyCode::Char('n') | KeyCode::Char('N') => {
|
||||
let sel = *selected;
|
||||
self.popup = Some(Popup::UpsertEndpoint {
|
||||
edit_index: None,
|
||||
fields: [TextInput::new(), TextInput::new()],
|
||||
active_field: 0,
|
||||
error: None,
|
||||
return_selected: sel,
|
||||
});
|
||||
}
|
||||
KeyCode::Esc | KeyCode::Tab => {
|
||||
self.popup = None;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
Popup::UpsertEndpoint {
|
||||
edit_index,
|
||||
fields,
|
||||
active_field,
|
||||
error,
|
||||
return_selected,
|
||||
} => {
|
||||
match key.code {
|
||||
KeyCode::Enter => {
|
||||
if *active_field == 0 {
|
||||
let name = fields[0].buf.trim().to_string();
|
||||
let edit_idx = *edit_index;
|
||||
if name.is_empty() {
|
||||
*error = Some("Название не может быть пустым".to_string());
|
||||
} else if let Some(conflict_url) = self.config.endpoints.iter()
|
||||
.enumerate()
|
||||
.find(|(i, ep)| Some(*i) != edit_idx && ep.name == name)
|
||||
.map(|(_, ep)| ep.url.clone())
|
||||
{
|
||||
*error = Some(format!(
|
||||
"Название \"{}\" уже используется для {}",
|
||||
name, conflict_url
|
||||
));
|
||||
} else {
|
||||
fields[0].buf = name;
|
||||
*active_field = 1;
|
||||
*error = None;
|
||||
}
|
||||
} else {
|
||||
let url = fields[1].buf.trim().to_string();
|
||||
let name = fields[0].buf.trim().to_string();
|
||||
let edit_idx = *edit_index;
|
||||
let ret = *return_selected;
|
||||
if url.is_empty() {
|
||||
*error = Some("URL не может быть пустым".to_string());
|
||||
} else if let Some(conflict_name) = self.config.endpoints.iter()
|
||||
.enumerate()
|
||||
.find(|(i, ep)| Some(*i) != edit_idx && ep.url == url)
|
||||
.map(|(_, ep)| ep.name.clone())
|
||||
{
|
||||
*error = Some(format!(
|
||||
"URL уже используется для эндпоинта \"{}\"",
|
||||
conflict_name
|
||||
));
|
||||
} else {
|
||||
match edit_idx {
|
||||
None => {
|
||||
self.config.endpoints.push(crate::config::Endpoint { name, url });
|
||||
let _ = self.config.save();
|
||||
let new_sel = self.config.endpoints.len() - 1;
|
||||
self.popup = Some(Popup::EndpointSelector {
|
||||
selected: new_sel,
|
||||
scroll_offset: ret,
|
||||
});
|
||||
}
|
||||
Some(idx) => {
|
||||
let was_active = self.config.endpoints
|
||||
.get(idx)
|
||||
.map(|ep| ep.url == self.config.active_endpoint)
|
||||
.unwrap_or(false);
|
||||
if let Some(ep) = self.config.endpoints.get_mut(idx) {
|
||||
ep.name = name;
|
||||
ep.url = url.clone();
|
||||
}
|
||||
if was_active {
|
||||
self.config.active_endpoint = url;
|
||||
}
|
||||
let _ = self.config.save();
|
||||
self.popup = Some(Popup::EndpointSelector {
|
||||
selected: ret,
|
||||
scroll_offset: 0,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
KeyCode::Esc => {
|
||||
let ret = *return_selected;
|
||||
self.popup = Some(Popup::EndpointSelector {
|
||||
selected: ret,
|
||||
scroll_offset: 0,
|
||||
});
|
||||
}
|
||||
_ => {
|
||||
let af = *active_field;
|
||||
if fields[af].handle_key(&key) {
|
||||
*error = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
Popup::ConfirmDeleteEndpoint { index, return_selected } => {
|
||||
match key.code {
|
||||
KeyCode::Char('y') | KeyCode::Char('Y') => {
|
||||
let idx = *index;
|
||||
let ret = *return_selected;
|
||||
self.popup = None;
|
||||
if idx < self.config.endpoints.len() {
|
||||
let was_active = self.config.endpoints[idx].url == self.config.active_endpoint;
|
||||
self.config.endpoints.remove(idx);
|
||||
let _ = self.config.save();
|
||||
if self.config.endpoints.is_empty() {
|
||||
self.config.active_endpoint = String::new();
|
||||
self.menu = None;
|
||||
} else {
|
||||
if was_active {
|
||||
self.config.active_endpoint = self.config.endpoints[0].url.clone();
|
||||
self.menu = None;
|
||||
self.breadcrumbs.clear();
|
||||
self.selected_index = 0;
|
||||
self.menu_scroll_offset = 0;
|
||||
self.load_menu().await;
|
||||
}
|
||||
let new_sel = ret.min(self.config.endpoints.len() - 1);
|
||||
self.popup = Some(Popup::EndpointSelector {
|
||||
selected: new_sel,
|
||||
scroll_offset: 0,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
KeyCode::Char('n') | KeyCode::Char('N') | KeyCode::Esc => {
|
||||
let ret = *return_selected;
|
||||
self.popup = Some(Popup::EndpointSelector {
|
||||
selected: ret,
|
||||
scroll_offset: 0,
|
||||
});
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
Popup::Message { .. } => {
|
||||
self.popup = None;
|
||||
return Ok(false);
|
||||
@@ -650,34 +793,21 @@ impl App {
|
||||
let tx = self.event_tx.clone();
|
||||
let info_clone = info.clone();
|
||||
|
||||
// Forward progress events
|
||||
tokio::spawn(async move {
|
||||
while let Some(bytes) = progress_rx.recv().await {
|
||||
let _ = tx.send(Event::UpdateProgress(bytes));
|
||||
}
|
||||
});
|
||||
|
||||
// Download and apply
|
||||
let tx2 = self.event_tx.clone();
|
||||
tokio::spawn(async move {
|
||||
match updater::download_and_apply(
|
||||
&info_clone,
|
||||
progress_tx,
|
||||
)
|
||||
.await
|
||||
{
|
||||
match updater::download_and_apply(&info_clone, progress_tx).await {
|
||||
Ok(exe_path) => {
|
||||
// Write expected version before exec so
|
||||
// the next startup can detect a failed
|
||||
// replacement (wrong asset, etc.).
|
||||
updater::write_update_target(
|
||||
&info_clone.new_version,
|
||||
);
|
||||
updater::write_update_target(&info_clone.new_version);
|
||||
let _ = tx2.send(Event::UpdateDone(exe_path));
|
||||
}
|
||||
Err(e) => {
|
||||
let _ =
|
||||
tx2.send(Event::UpdateError(e.to_string()));
|
||||
let _ = tx2.send(Event::UpdateError(e.to_string()));
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -696,7 +826,6 @@ impl App {
|
||||
if matches!(status, UpdatingStatus::Failed(_)) {
|
||||
self.popup = None;
|
||||
}
|
||||
// Ignore Esc while downloading/applying
|
||||
}
|
||||
return Ok(false);
|
||||
}
|
||||
@@ -705,7 +834,7 @@ impl App {
|
||||
}
|
||||
}
|
||||
|
||||
// ── Main menu navigation ─────────────────────────────────────────
|
||||
// ── Main menu navigation ──────────────────────────────────────────
|
||||
match key.code {
|
||||
KeyCode::Char('q') => return Ok(true),
|
||||
KeyCode::Up | KeyCode::Char('k') => {
|
||||
@@ -735,6 +864,15 @@ impl App {
|
||||
KeyCode::Char('r') | KeyCode::Char('R') => {
|
||||
self.load_menu().await;
|
||||
}
|
||||
KeyCode::Tab => {
|
||||
let sel = self.config.endpoints.iter()
|
||||
.position(|ep| ep.url == self.config.active_endpoint)
|
||||
.unwrap_or(0);
|
||||
self.popup = Some(Popup::EndpointSelector {
|
||||
selected: sel,
|
||||
scroll_offset: 0,
|
||||
});
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -742,14 +880,11 @@ impl App {
|
||||
use crossterm::event::MouseEventKind;
|
||||
match mouse.kind {
|
||||
MouseEventKind::ScrollUp => {
|
||||
if let Some(Popup::ExecutingStructured {
|
||||
log_scroll_pos,
|
||||
log_follow_bottom,
|
||||
..
|
||||
}) = &mut self.popup
|
||||
{
|
||||
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 let Some(Popup::EndpointSelector { selected, .. }) = &mut self.popup {
|
||||
if *selected > 0 { *selected -= 1; }
|
||||
} else if self.popup.is_none() {
|
||||
let len = self.current_items().len();
|
||||
if len > 0 {
|
||||
@@ -759,14 +894,13 @@ impl App {
|
||||
}
|
||||
MouseEventKind::ScrollDown => {
|
||||
if let Some(Popup::ExecutingStructured {
|
||||
log_scroll_pos,
|
||||
log_follow_bottom,
|
||||
log_buffer,
|
||||
..
|
||||
}) = &mut self.popup
|
||||
{
|
||||
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 let Some(Popup::EndpointSelector { selected, .. }) = &mut self.popup {
|
||||
let len = self.config.endpoints.len();
|
||||
if *selected + 1 < len { *selected += 1; }
|
||||
} else if self.popup.is_none() {
|
||||
let len = self.current_items().len();
|
||||
if len > 0 {
|
||||
@@ -808,24 +942,11 @@ impl App {
|
||||
|
||||
async fn run_action(&mut self, action: Action) -> Result<()> {
|
||||
match action {
|
||||
Action::Bash {
|
||||
script,
|
||||
interaction,
|
||||
confirm: _,
|
||||
confirm_message: _,
|
||||
} => match interaction {
|
||||
InteractionMode::Terminal => {
|
||||
self.run_bash_terminal(&script).await?;
|
||||
}
|
||||
InteractionMode::Structured => {
|
||||
self.run_bash_structured(&script).await?;
|
||||
}
|
||||
Action::Bash { script, interaction, confirm: _, confirm_message: _ } => match interaction {
|
||||
InteractionMode::Terminal => self.run_bash_terminal(&script).await?,
|
||||
InteractionMode::Structured => self.run_bash_structured(&script).await?,
|
||||
},
|
||||
Action::Download {
|
||||
url,
|
||||
confirm: _,
|
||||
..
|
||||
} => {
|
||||
Action::Download { url, confirm: _, .. } => {
|
||||
self.popup = Some(Popup::Message {
|
||||
text: format!("Скачивание {} пока не реализовано", url),
|
||||
level: MessageLevel::Info,
|
||||
@@ -852,9 +973,7 @@ impl App {
|
||||
tokio::spawn(async move {
|
||||
let mut rx = output_rx;
|
||||
while let Some(line) = rx.recv().await {
|
||||
if tx_output.send(Event::StructuredOutput(line)).is_err() {
|
||||
break;
|
||||
}
|
||||
if tx_output.send(Event::StructuredOutput(line)).is_err() { break; }
|
||||
}
|
||||
});
|
||||
|
||||
@@ -862,9 +981,7 @@ impl App {
|
||||
tokio::spawn(async move {
|
||||
let mut rx = command_rx;
|
||||
while let Some(cmd) = rx.recv().await {
|
||||
if tx_cmd.send(Event::StructuredCommand(cmd)).is_err() {
|
||||
break;
|
||||
}
|
||||
if tx_cmd.send(Event::StructuredCommand(cmd)).is_err() { break; }
|
||||
}
|
||||
});
|
||||
|
||||
@@ -879,7 +996,7 @@ impl App {
|
||||
kill_tx: Some(kill_tx),
|
||||
log_buffer: Vec::new(),
|
||||
current_command: None,
|
||||
input_buffer: String::new(),
|
||||
input: TextInput::new(),
|
||||
menu_selected_index: 0,
|
||||
form_cursor: 0,
|
||||
form_values: Vec::new(),
|
||||
@@ -892,4 +1009,3 @@ impl App {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3,9 +3,21 @@ use anyhow::Result;
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, Clone)]
|
||||
pub struct Endpoint {
|
||||
pub name: String,
|
||||
pub url: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, Clone)]
|
||||
pub struct Config {
|
||||
pub server_url: String,
|
||||
// Legacy field — present only in old configs; migrated to endpoints on load.
|
||||
#[serde(default, skip_serializing)]
|
||||
server_url: Option<String>,
|
||||
#[serde(default)]
|
||||
pub endpoints: Vec<Endpoint>,
|
||||
#[serde(default)]
|
||||
pub active_endpoint: String,
|
||||
pub timeout_sec: u64,
|
||||
#[serde(default = "default_theme")]
|
||||
pub theme: Theme,
|
||||
@@ -30,7 +42,6 @@ fn default_theme() -> Theme {
|
||||
}
|
||||
|
||||
pub fn config_path() -> PathBuf {
|
||||
// Respect XDG_CONFIG_HOME; fall back to ~/.config on all platforms.
|
||||
let base = std::env::var("XDG_CONFIG_HOME")
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|_| {
|
||||
@@ -42,41 +53,85 @@ pub fn config_path() -> PathBuf {
|
||||
}
|
||||
|
||||
impl Config {
|
||||
/// Returns true when a config file already exists.
|
||||
pub fn exists() -> bool {
|
||||
config_path().exists()
|
||||
}
|
||||
|
||||
/// Load config from disk. Panics-safe: returns error if file is missing or malformed.
|
||||
pub fn active_url(&self) -> &str {
|
||||
&self.active_endpoint
|
||||
}
|
||||
|
||||
pub fn load() -> Result<Self> {
|
||||
let path = config_path();
|
||||
let content = fs::read_to_string(&path)?;
|
||||
Ok(toml::from_str(&content)?)
|
||||
let mut cfg: Config = toml::from_str(&content)?;
|
||||
// Migrate old single server_url format to endpoints list.
|
||||
if cfg.endpoints.is_empty() {
|
||||
if let Some(url) = cfg.server_url.take() {
|
||||
cfg.active_endpoint = url.clone();
|
||||
cfg.endpoints.push(Endpoint {
|
||||
name: "Default".to_string(),
|
||||
url,
|
||||
});
|
||||
}
|
||||
}
|
||||
if cfg.active_endpoint.is_empty() {
|
||||
if let Some(ep) = cfg.endpoints.first() {
|
||||
cfg.active_endpoint = ep.url.clone();
|
||||
}
|
||||
}
|
||||
Ok(cfg)
|
||||
}
|
||||
|
||||
/// Create and persist a new config with the given server URL.
|
||||
pub fn create_with_url(server_url: &str) -> Result<Self> {
|
||||
pub fn create_with_endpoint(url: &str, name: &str) -> Result<Self> {
|
||||
let path = config_path();
|
||||
let config = Config {
|
||||
server_url: server_url.to_string(),
|
||||
server_url: None,
|
||||
endpoints: vec![Endpoint {
|
||||
name: name.to_string(),
|
||||
url: url.to_string(),
|
||||
}],
|
||||
active_endpoint: url.to_string(),
|
||||
timeout_sec: 10,
|
||||
theme: default_theme(),
|
||||
update_api: Some("https://git.vainend.com/api/v1/repos/admin/ostiary".to_string()),
|
||||
};
|
||||
let contents = format!(
|
||||
r#"server_url = "{}"
|
||||
timeout_sec = {}
|
||||
update_api = "https://git.vainend.com/api/v1/repos/admin/ostiary"
|
||||
|
||||
[theme]
|
||||
selected_bg = "{}"
|
||||
"#,
|
||||
config.server_url,
|
||||
config.timeout_sec,
|
||||
config.theme.selected_bg,
|
||||
);
|
||||
fs::create_dir_all(path.parent().unwrap())?;
|
||||
fs::write(&path, contents)?;
|
||||
fs::write(&path, config.to_toml())?;
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
pub fn save(&self) -> Result<()> {
|
||||
let path = config_path();
|
||||
fs::create_dir_all(path.parent().unwrap())?;
|
||||
fs::write(&path, self.to_toml())?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn to_toml(&self) -> String {
|
||||
let mut s = format!(
|
||||
"active_endpoint = \"{}\"\ntimeout_sec = {}\n",
|
||||
escape_toml(&self.active_endpoint),
|
||||
self.timeout_sec,
|
||||
);
|
||||
if let Some(api) = &self.update_api {
|
||||
s.push_str(&format!("update_api = \"{}\"\n", escape_toml(api)));
|
||||
}
|
||||
s.push_str(&format!(
|
||||
"\n[theme]\nselected_bg = \"{}\"\n",
|
||||
escape_toml(&self.theme.selected_bg),
|
||||
));
|
||||
for ep in &self.endpoints {
|
||||
s.push_str(&format!(
|
||||
"\n[[endpoints]]\nname = \"{}\"\nurl = \"{}\"\n",
|
||||
escape_toml(&ep.name),
|
||||
escape_toml(&ep.url),
|
||||
));
|
||||
}
|
||||
s
|
||||
}
|
||||
}
|
||||
|
||||
fn escape_toml(s: &str) -> String {
|
||||
s.replace('\\', "\\\\").replace('"', "\\\"")
|
||||
}
|
||||
|
||||
41
src/main.rs
41
src/main.rs
@@ -5,6 +5,7 @@ mod error;
|
||||
mod executor;
|
||||
mod menu;
|
||||
mod network;
|
||||
mod text_input;
|
||||
mod ui;
|
||||
mod updater;
|
||||
|
||||
@@ -23,8 +24,8 @@ async fn main() -> Result<()> {
|
||||
let config = if config::Config::exists() {
|
||||
config::Config::load()?
|
||||
} else {
|
||||
let url = prompt_server_url()?;
|
||||
config::Config::create_with_url(&url)?
|
||||
let (url, name) = prompt_first_endpoint()?;
|
||||
config::Config::create_with_endpoint(&url, &name)?
|
||||
};
|
||||
|
||||
enable_raw_mode()?;
|
||||
@@ -166,8 +167,8 @@ async fn run_exec(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Runs before ratatui starts. Prompts for the server URL on first launch.
|
||||
fn prompt_server_url() -> Result<String> {
|
||||
/// Runs before ratatui starts. Prompts for endpoint URL and name on first launch.
|
||||
fn prompt_first_endpoint() -> Result<(String, String)> {
|
||||
use std::io::Write;
|
||||
|
||||
println!();
|
||||
@@ -179,22 +180,34 @@ fn prompt_server_url() -> Result<String> {
|
||||
println!(" {}", config::config_path().display());
|
||||
println!();
|
||||
|
||||
loop {
|
||||
print!(" URL сервера меню: ");
|
||||
let name = loop {
|
||||
print!(" Название эндпоинта: ");
|
||||
std::io::stdout().flush()?;
|
||||
let mut buf = String::new();
|
||||
std::io::stdin().read_line(&mut buf)?;
|
||||
let val = buf.trim().to_string();
|
||||
if val.is_empty() {
|
||||
println!(" Название не может быть пустым. Попробуйте ещё раз.\n");
|
||||
continue;
|
||||
}
|
||||
break val;
|
||||
};
|
||||
|
||||
let mut url = String::new();
|
||||
std::io::stdin().read_line(&mut url)?;
|
||||
let url = url.trim().to_string();
|
||||
|
||||
if url.is_empty() {
|
||||
let url = loop {
|
||||
print!(" URL эндпоинта: ");
|
||||
std::io::stdout().flush()?;
|
||||
let mut buf = String::new();
|
||||
std::io::stdin().read_line(&mut buf)?;
|
||||
let val = buf.trim().to_string();
|
||||
if val.is_empty() {
|
||||
println!(" URL не может быть пустым. Попробуйте ещё раз.\n");
|
||||
continue;
|
||||
}
|
||||
break val;
|
||||
};
|
||||
|
||||
println!();
|
||||
return Ok(url);
|
||||
}
|
||||
println!();
|
||||
Ok((url, name))
|
||||
}
|
||||
|
||||
async fn read_crossterm_event() -> Result<Option<crossterm::event::Event>> {
|
||||
|
||||
98
src/text_input.rs
Normal file
98
src/text_input.rs
Normal file
@@ -0,0 +1,98 @@
|
||||
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
|
||||
|
||||
pub struct TextInput {
|
||||
pub buf: String,
|
||||
pub cursor: usize,
|
||||
}
|
||||
|
||||
impl TextInput {
|
||||
pub fn new() -> Self {
|
||||
Self { buf: String::new(), cursor: 0 }
|
||||
}
|
||||
|
||||
pub fn with_text(text: impl Into<String>) -> Self {
|
||||
let buf = text.into();
|
||||
let cursor = buf.chars().count();
|
||||
Self { buf, cursor }
|
||||
}
|
||||
|
||||
pub fn value(&self) -> &str {
|
||||
&self.buf
|
||||
}
|
||||
|
||||
pub fn clear(&mut self) {
|
||||
self.buf.clear();
|
||||
self.cursor = 0;
|
||||
}
|
||||
|
||||
pub fn move_left(&mut self) {
|
||||
self.cursor = self.cursor.saturating_sub(1);
|
||||
}
|
||||
|
||||
pub fn move_right(&mut self) {
|
||||
self.cursor = (self.cursor + 1).min(self.buf.chars().count());
|
||||
}
|
||||
|
||||
pub fn word_back(&mut self) {
|
||||
let chars: Vec<char> = self.buf.chars().collect();
|
||||
let mut pos = self.cursor;
|
||||
while pos > 0 && !is_word(chars[pos - 1]) { pos -= 1; }
|
||||
while pos > 0 && is_word(chars[pos - 1]) { pos -= 1; }
|
||||
self.cursor = pos;
|
||||
}
|
||||
|
||||
pub fn word_fwd(&mut self) {
|
||||
let chars: Vec<char> = self.buf.chars().collect();
|
||||
let len = chars.len();
|
||||
let mut pos = self.cursor;
|
||||
while pos < len && !is_word(chars[pos]) { pos += 1; }
|
||||
while pos < len && is_word(chars[pos]) { pos += 1; }
|
||||
self.cursor = pos;
|
||||
}
|
||||
|
||||
pub fn insert(&mut self, c: char) {
|
||||
let byte_idx = self.buf.char_indices().nth(self.cursor).map(|(b, _)| b).unwrap_or(self.buf.len());
|
||||
self.buf.insert(byte_idx, c);
|
||||
self.cursor += 1;
|
||||
}
|
||||
|
||||
pub fn backspace(&mut self) {
|
||||
if self.cursor == 0 { return; }
|
||||
let byte_idx = self.buf.char_indices().nth(self.cursor - 1).map(|(b, _)| b).unwrap_or(0);
|
||||
self.buf.remove(byte_idx);
|
||||
self.cursor -= 1;
|
||||
}
|
||||
|
||||
pub fn word_delete_back(&mut self) {
|
||||
let chars: Vec<char> = self.buf.chars().collect();
|
||||
let mut new_cursor = self.cursor;
|
||||
while new_cursor > 0 && !is_word(chars[new_cursor - 1]) { new_cursor -= 1; }
|
||||
while new_cursor > 0 && is_word(chars[new_cursor - 1]) { new_cursor -= 1; }
|
||||
if new_cursor == self.cursor { return; }
|
||||
let start_byte = self.buf.char_indices().nth(new_cursor).map(|(b, _)| b).unwrap_or(0);
|
||||
let end_byte = self.buf.char_indices().nth(self.cursor).map(|(b, _)| b).unwrap_or(self.buf.len());
|
||||
self.buf.drain(start_byte..end_byte);
|
||||
self.cursor = new_cursor;
|
||||
}
|
||||
|
||||
/// Returns true if the key was consumed.
|
||||
pub fn handle_key(&mut self, key: &KeyEvent) -> bool {
|
||||
let alt = key.modifiers.intersects(KeyModifiers::ALT | KeyModifiers::SUPER);
|
||||
match key.code {
|
||||
KeyCode::Left if alt => { self.word_back(); true }
|
||||
KeyCode::Right if alt => { self.word_fwd(); true }
|
||||
KeyCode::Char('b') if alt => { self.word_back(); true }
|
||||
KeyCode::Char('f') if alt => { self.word_fwd(); true }
|
||||
KeyCode::Left => { self.move_left(); true }
|
||||
KeyCode::Right => { self.move_right(); true }
|
||||
KeyCode::Backspace if alt => { self.word_delete_back(); true }
|
||||
KeyCode::Backspace => { self.backspace(); true }
|
||||
KeyCode::Char(c) => { self.insert(c); true }
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn is_word(c: char) -> bool {
|
||||
c.is_alphanumeric() || c == '_'
|
||||
}
|
||||
549
src/ui.rs
549
src/ui.rs
@@ -1,6 +1,8 @@
|
||||
use crate::ansi;
|
||||
use crate::config::Config;
|
||||
use crate::executor;
|
||||
use crate::app::{App, MessageLevel, Popup, UpdatingStatus};
|
||||
use crate::text_input::TextInput;
|
||||
use ratatui::{
|
||||
layout::{Alignment, Constraint, Direction, Layout, Rect},
|
||||
style::{Color, Modifier, Style},
|
||||
@@ -24,7 +26,7 @@ pub fn render(f: &mut Frame, app: &mut App) {
|
||||
render_description(f, app, chunks[1]);
|
||||
|
||||
if let Some(popup) = &mut app.popup {
|
||||
render_popup(f, popup);
|
||||
render_popup(f, popup, &app.config);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,7 +39,6 @@ fn render_menu(f: &mut Frame, app: &mut App, area: Rect) {
|
||||
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 { .. } => "📁 ",
|
||||
@@ -46,7 +47,6 @@ fn render_menu(f: &mut Frame, app: &mut App, area: Rect) {
|
||||
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;
|
||||
@@ -59,20 +59,14 @@ fn render_menu(f: &mut Frame, app: &mut App, area: Rect) {
|
||||
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 *offset > sel { *offset = sel; }
|
||||
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; }
|
||||
@@ -83,7 +77,6 @@ fn render_menu(f: &mut Frame, app: &mut App, area: Rect) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
// Clamp to valid range
|
||||
let max_off = total.saturating_sub(1);
|
||||
*offset = (*offset).min(max_off);
|
||||
}
|
||||
@@ -107,10 +100,15 @@ fn render_menu(f: &mut Frame, app: &mut App, area: Rect) {
|
||||
})
|
||||
.collect();
|
||||
|
||||
let endpoint_title = app.config.endpoints.iter()
|
||||
.find(|ep| ep.url == app.config.active_endpoint)
|
||||
.map(|ep| format!(" {} ", ep.name))
|
||||
.unwrap_or_else(|| " Меню ".to_string());
|
||||
|
||||
let list = List::new(list_items).block(
|
||||
Block::default()
|
||||
.borders(Borders::ALL)
|
||||
.title(" Меню ")
|
||||
.title(endpoint_title)
|
||||
.title(
|
||||
Line::from(Span::styled(
|
||||
format!(" v{} ", env!("CARGO_PKG_VERSION")),
|
||||
@@ -153,10 +151,9 @@ fn render_description(f: &mut Frame, app: &App, area: Rect) {
|
||||
f.render_widget(paragraph, area);
|
||||
}
|
||||
|
||||
fn render_popup(f: &mut Frame, popup: &mut Popup) {
|
||||
fn render_popup(f: &mut Frame, popup: &mut Popup, config: &Config) {
|
||||
let area = f.area();
|
||||
|
||||
// Use a smaller area for update-related popups
|
||||
let popup_area = match popup {
|
||||
Popup::UpdateConfirm { .. } | Popup::Updating { .. } => centered_rect(50, 40, area),
|
||||
_ => centered_rect(80, 90, area),
|
||||
@@ -165,11 +162,7 @@ fn render_popup(f: &mut Frame, popup: &mut Popup) {
|
||||
f.render_widget(Clear, popup_area);
|
||||
|
||||
match popup {
|
||||
Popup::Confirming {
|
||||
action: _,
|
||||
item_title,
|
||||
confirm_message,
|
||||
} => {
|
||||
Popup::Confirming { action: _, item_title, confirm_message } => {
|
||||
let block = Block::default()
|
||||
.borders(Borders::ALL)
|
||||
.title("Подтверждение")
|
||||
@@ -193,11 +186,10 @@ fn render_popup(f: &mut Frame, popup: &mut Popup) {
|
||||
)),
|
||||
]
|
||||
};
|
||||
let paragraph = Paragraph::new(text)
|
||||
.block(block)
|
||||
.alignment(Alignment::Center)
|
||||
.wrap(Wrap { trim: true });
|
||||
f.render_widget(paragraph, popup_area);
|
||||
f.render_widget(
|
||||
Paragraph::new(text).block(block).alignment(Alignment::Center).wrap(Wrap { trim: true }),
|
||||
popup_area,
|
||||
);
|
||||
}
|
||||
|
||||
Popup::ExecutingStructured {
|
||||
@@ -205,7 +197,7 @@ fn render_popup(f: &mut Frame, popup: &mut Popup) {
|
||||
kill_tx: _,
|
||||
log_buffer,
|
||||
current_command,
|
||||
input_buffer,
|
||||
input,
|
||||
menu_selected_index,
|
||||
form_cursor,
|
||||
form_values,
|
||||
@@ -215,12 +207,8 @@ fn render_popup(f: &mut Frame, popup: &mut Popup) {
|
||||
finished,
|
||||
} => {
|
||||
let cmd_height: u16 = match current_command {
|
||||
Some(executor::StructuredCommand::Menu { options, .. }) => {
|
||||
(options.len() as u16 + 2).min(14)
|
||||
}
|
||||
Some(executor::StructuredCommand::Form { fields, .. }) => {
|
||||
(fields.len() as u16 + 2).min(16)
|
||||
}
|
||||
Some(executor::StructuredCommand::Menu { options, .. }) => (options.len() as u16 + 2).min(14),
|
||||
Some(executor::StructuredCommand::Form { fields, .. }) => (fields.len() as u16 + 2).min(16),
|
||||
Some(_) => 5,
|
||||
None => 0,
|
||||
};
|
||||
@@ -231,11 +219,9 @@ fn render_popup(f: &mut Frame, popup: &mut Popup) {
|
||||
.constraints([Constraint::Min(3), Constraint::Length(cmd_height)].as_ref())
|
||||
.split(popup_area);
|
||||
|
||||
// ── Scrollable log ──────────────────────────────────────────────
|
||||
let visible = chunks[0].height.saturating_sub(2) as usize;
|
||||
let total = log_buffer.len();
|
||||
|
||||
// Clamp pos so we never show empty lines past the end.
|
||||
let max_pos = total.saturating_sub(visible);
|
||||
if *log_follow_bottom {
|
||||
*log_scroll_pos = max_pos;
|
||||
@@ -267,9 +253,7 @@ 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()
|
||||
@@ -282,36 +266,19 @@ fn render_popup(f: &mut Frame, popup: &mut Popup) {
|
||||
};
|
||||
|
||||
let (title, border_color): (String, Color) = match finished {
|
||||
Some(0) => (
|
||||
format!(" ✓ Завершено — Esc закрыть{} ", scroll_hint),
|
||||
Color::Green,
|
||||
),
|
||||
Some(code) => (
|
||||
format!(" ✗ Ошибка (код {}) — Esc закрыть{} ", code, scroll_hint),
|
||||
Color::Red,
|
||||
),
|
||||
None if at_top && at_bottom => (
|
||||
" Выполняется… ".to_string(),
|
||||
Color::DarkGray,
|
||||
),
|
||||
None if at_bottom => (
|
||||
" Выполняется… │ PgUp/↑ прокрутить вверх ".to_string(),
|
||||
Color::DarkGray,
|
||||
),
|
||||
None => (
|
||||
format!(" Выполняется… │ {}/{} │ PgDn/↓ вниз ", pos + 1, total),
|
||||
Color::Yellow,
|
||||
),
|
||||
Some(0) => (format!(" ✓ Завершено — Esc закрыть{} ", scroll_hint), Color::Green),
|
||||
Some(code) => (format!(" ✗ Ошибка (код {}) — Esc закрыть{} ", code, scroll_hint), Color::Red),
|
||||
None if at_top && at_bottom => (" Выполняется… ".to_string(), Color::DarkGray),
|
||||
None if at_bottom => (" Выполняется… │ PgUp/↑ прокрутить вверх ".to_string(), Color::DarkGray),
|
||||
None => (format!(" Выполняется… │ {}/{} │ PgDn/↓ вниз ", pos + 1, total), Color::Yellow),
|
||||
};
|
||||
|
||||
let log_block = Block::default()
|
||||
.borders(Borders::ALL)
|
||||
.title(title.as_str())
|
||||
.border_style(Style::default().fg(border_color));
|
||||
|
||||
f.render_widget(List::new(log_items).block(log_block), chunks[0]);
|
||||
|
||||
// ── Scrollbar ───────────────────────────────────────────────────
|
||||
if total > visible {
|
||||
let scrollbar = Scrollbar::default()
|
||||
.orientation(ScrollbarOrientation::VerticalRight)
|
||||
@@ -328,7 +295,6 @@ 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 {
|
||||
@@ -348,15 +314,9 @@ fn render_popup(f: &mut Frame, popup: &mut Popup) {
|
||||
);
|
||||
}
|
||||
|
||||
// ── Interactive command area ─────────────────────────────────────
|
||||
if cmd_height > 0 {
|
||||
if let Some(cmd) = current_command {
|
||||
render_command(
|
||||
f, cmd, input_buffer,
|
||||
*menu_selected_index,
|
||||
*form_cursor, form_values,
|
||||
chunks[1],
|
||||
);
|
||||
render_command(f, cmd, input, *menu_selected_index, *form_cursor, form_values, chunks[1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -371,20 +331,16 @@ fn render_popup(f: &mut Frame, popup: &mut Popup) {
|
||||
.borders(Borders::ALL)
|
||||
.title("Сообщение")
|
||||
.border_style(Style::default().fg(color));
|
||||
let paragraph = Paragraph::new(text.as_str())
|
||||
.block(block)
|
||||
.alignment(Alignment::Center)
|
||||
.wrap(Wrap { trim: true });
|
||||
f.render_widget(paragraph, popup_area);
|
||||
f.render_widget(
|
||||
Paragraph::new(text.as_str()).block(block).alignment(Alignment::Center).wrap(Wrap { trim: true }),
|
||||
popup_area,
|
||||
);
|
||||
}
|
||||
|
||||
Popup::UpdateConfirm { info } => {
|
||||
let mut lines = vec![
|
||||
Line::from(""),
|
||||
Line::from(Span::raw(format!(
|
||||
" {} → {}",
|
||||
info.current_version, info.new_version
|
||||
))),
|
||||
Line::from(Span::raw(format!(" {} → {}", info.current_version, info.new_version))),
|
||||
];
|
||||
if info.size > 0 {
|
||||
let mb = info.size as f64 / 1_048_576.0;
|
||||
@@ -400,17 +356,10 @@ fn render_popup(f: &mut Frame, popup: &mut Popup) {
|
||||
.borders(Borders::ALL)
|
||||
.title(" Доступно обновление ")
|
||||
.border_style(Style::default().fg(Color::Cyan));
|
||||
let paragraph = Paragraph::new(lines)
|
||||
.block(block)
|
||||
.wrap(Wrap { trim: true });
|
||||
f.render_widget(paragraph, popup_area);
|
||||
f.render_widget(Paragraph::new(lines).block(block).wrap(Wrap { trim: true }), popup_area);
|
||||
}
|
||||
|
||||
Popup::Updating {
|
||||
info,
|
||||
downloaded,
|
||||
status,
|
||||
} => {
|
||||
Popup::Updating { info, downloaded, status } => {
|
||||
let (title, border_color) = match status {
|
||||
UpdatingStatus::Downloading => (" Загрузка обновления… ", Color::Cyan),
|
||||
UpdatingStatus::Applying => (" Применение обновления… ", Color::Yellow),
|
||||
@@ -421,23 +370,14 @@ fn render_popup(f: &mut Frame, popup: &mut Popup) {
|
||||
let bar_width = popup_area.width.saturating_sub(4) as usize;
|
||||
|
||||
let progress_line = if info.size > 0 {
|
||||
let percent = ((*downloaded as f64 / info.size as f64) * 100.0)
|
||||
.min(100.0) as usize;
|
||||
let percent = ((*downloaded as f64 / info.size as f64) * 100.0).min(100.0) as usize;
|
||||
let filled = (percent * bar_width) / 100;
|
||||
format!(
|
||||
"[{}{}] {}%",
|
||||
"█".repeat(filled),
|
||||
"░".repeat(bar_width.saturating_sub(filled)),
|
||||
percent
|
||||
)
|
||||
format!("[{}{}] {}%", "█".repeat(filled), "░".repeat(bar_width.saturating_sub(filled)), percent)
|
||||
} else {
|
||||
// Indeterminate: animate based on downloaded bytes
|
||||
let pos = ((*downloaded / 4096) as usize) % bar_width.max(1);
|
||||
let thumb = 4.min(bar_width);
|
||||
let mut bar = vec!['░'; bar_width];
|
||||
for i in pos..((pos + thumb).min(bar_width)) {
|
||||
bar[i] = '█';
|
||||
}
|
||||
for i in pos..((pos + thumb).min(bar_width)) { bar[i] = '█'; }
|
||||
format!("[{}]", bar.iter().collect::<String>())
|
||||
};
|
||||
|
||||
@@ -448,8 +388,7 @@ fn render_popup(f: &mut Frame, popup: &mut Popup) {
|
||||
let mb_total = info.size as f64 / 1_048_576.0;
|
||||
format!(" {:.1} / {:.1} МБ", mb_done, mb_total)
|
||||
} else {
|
||||
let kb = *downloaded / 1024;
|
||||
format!(" {} КБ загружено", kb)
|
||||
format!(" {} КБ загружено", *downloaded / 1024)
|
||||
}
|
||||
}
|
||||
UpdatingStatus::Applying => " Применяется…".to_string(),
|
||||
@@ -466,30 +405,209 @@ fn render_popup(f: &mut Frame, popup: &mut Popup) {
|
||||
|
||||
if matches!(status, UpdatingStatus::Failed(_)) {
|
||||
lines.push(Line::from(""));
|
||||
lines.push(Line::from(Span::styled(
|
||||
" [Esc] Закрыть",
|
||||
Style::default().fg(Color::Yellow),
|
||||
)));
|
||||
lines.push(Line::from(Span::styled(" [Esc] Закрыть", Style::default().fg(Color::Yellow))));
|
||||
}
|
||||
|
||||
let block = Block::default()
|
||||
.borders(Borders::ALL)
|
||||
.title(title)
|
||||
.border_style(Style::default().fg(border_color));
|
||||
let paragraph = Paragraph::new(lines)
|
||||
.block(block)
|
||||
.wrap(Wrap { trim: true });
|
||||
f.render_widget(paragraph, popup_area);
|
||||
f.render_widget(Paragraph::new(lines).block(block).wrap(Wrap { trim: true }), popup_area);
|
||||
}
|
||||
|
||||
Popup::EndpointSelector { selected, scroll_offset } => {
|
||||
let popup_area = centered_rect(70, 60, area);
|
||||
f.render_widget(Clear, popup_area);
|
||||
|
||||
let endpoints = &config.endpoints;
|
||||
let total = endpoints.len();
|
||||
let inner_h = popup_area.height.saturating_sub(2) as usize;
|
||||
|
||||
let name_col_w = endpoints.iter()
|
||||
.map(|ep| ep.name.chars().count())
|
||||
.max()
|
||||
.unwrap_or(8)
|
||||
.max(8);
|
||||
|
||||
if *selected < *scroll_offset {
|
||||
*scroll_offset = *selected;
|
||||
} else if inner_h > 0 && *selected >= *scroll_offset + inner_h {
|
||||
*scroll_offset = selected.saturating_sub(inner_h - 1);
|
||||
}
|
||||
|
||||
let start = *scroll_offset;
|
||||
let end = (start + inner_h).min(total);
|
||||
|
||||
let items: Vec<ListItem> = endpoints.get(start..end).unwrap_or(&[])
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, ep)| {
|
||||
let abs = start + i;
|
||||
let is_selected = abs == *selected;
|
||||
let is_active = ep.url == config.active_endpoint;
|
||||
|
||||
let prefix = if is_selected { "▶ " } else { " " };
|
||||
let n = ep.name.chars().count();
|
||||
let pad = if n < name_col_w { " ".repeat(name_col_w - n) } else { String::new() };
|
||||
|
||||
let (bg, name_fg, url_fg) = if is_selected {
|
||||
(Color::Blue, Color::White, Color::Gray)
|
||||
} else {
|
||||
(Color::Reset, Color::White, Color::DarkGray)
|
||||
};
|
||||
|
||||
let name_style = if is_active {
|
||||
Style::default().fg(name_fg).bg(bg).add_modifier(Modifier::BOLD)
|
||||
} else {
|
||||
Style::default().fg(name_fg).bg(bg)
|
||||
};
|
||||
|
||||
ListItem::new(Line::from(vec![
|
||||
Span::styled(prefix, Style::default().bg(bg)),
|
||||
Span::styled(format!("{}{}", ep.name, pad), name_style),
|
||||
Span::styled(" ", Style::default().bg(bg)),
|
||||
Span::styled(ep.url.clone(), Style::default().fg(url_fg).bg(bg)),
|
||||
]))
|
||||
})
|
||||
.collect();
|
||||
|
||||
let active_name = config.endpoints.iter()
|
||||
.find(|ep| ep.url == config.active_endpoint)
|
||||
.map(|ep| ep.name.as_str())
|
||||
.unwrap_or("—");
|
||||
|
||||
let block = Block::default()
|
||||
.borders(Borders::ALL)
|
||||
.title(format!(" Эндпоинты [активен: {}] ", active_name))
|
||||
.title(
|
||||
Line::from(Span::styled(" [Esc] ", Style::default().fg(Color::DarkGray)))
|
||||
.alignment(Alignment::Right),
|
||||
)
|
||||
.title_bottom(
|
||||
Line::from(Span::styled(
|
||||
" [N] добавить [E] редактировать [D] удалить ",
|
||||
Style::default().fg(Color::DarkGray),
|
||||
))
|
||||
.alignment(Alignment::Right),
|
||||
)
|
||||
.border_style(Style::default().fg(Color::Cyan));
|
||||
|
||||
f.render_widget(List::new(items).block(block), popup_area);
|
||||
|
||||
if total > inner_h {
|
||||
let max_off = total.saturating_sub(inner_h);
|
||||
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: popup_area.x + popup_area.width.saturating_sub(1),
|
||||
y: popup_area.y + 1,
|
||||
width: 1,
|
||||
height: popup_area.height.saturating_sub(2),
|
||||
};
|
||||
f.render_stateful_widget(scrollbar, sb_area, &mut sb_state);
|
||||
}
|
||||
}
|
||||
|
||||
Popup::UpsertEndpoint { edit_index, fields, active_field, error, .. } => {
|
||||
let popup_area = centered_rect(60, 50, area);
|
||||
f.render_widget(Clear, popup_area);
|
||||
|
||||
let chunks = Layout::default()
|
||||
.direction(Direction::Vertical)
|
||||
.margin(1)
|
||||
.constraints([
|
||||
Constraint::Length(3),
|
||||
Constraint::Length(3),
|
||||
Constraint::Length(2),
|
||||
Constraint::Min(0),
|
||||
])
|
||||
.split(popup_area);
|
||||
|
||||
render_text_field(f, " Название ", &fields[0], *active_field == 0, chunks[0]);
|
||||
render_text_field(f, " URL ", &fields[1], *active_field == 1, chunks[1]);
|
||||
|
||||
if let Some(err) = error {
|
||||
f.render_widget(
|
||||
Paragraph::new(err.as_str())
|
||||
.style(Style::default().fg(Color::Red))
|
||||
.wrap(Wrap { trim: true }),
|
||||
chunks[2],
|
||||
);
|
||||
}
|
||||
|
||||
// Real terminal cursor in the active field
|
||||
let af = *active_field;
|
||||
let cx = (chunks[af].x + 1 + fields[af].cursor as u16)
|
||||
.min(chunks[af].x + chunks[af].width.saturating_sub(2));
|
||||
f.set_cursor_position((cx, chunks[af].y + 1));
|
||||
|
||||
let (title, hint) = if edit_index.is_some() {
|
||||
(" Редактировать эндпоинт ", " Enter — далее / сохранить ")
|
||||
} else {
|
||||
(" Добавить эндпоинт ", " Enter — далее / добавить ")
|
||||
};
|
||||
|
||||
f.render_widget(
|
||||
Block::default()
|
||||
.borders(Borders::ALL)
|
||||
.title(title)
|
||||
.title(
|
||||
Line::from(Span::styled(" [Esc] ", Style::default().fg(Color::DarkGray)))
|
||||
.alignment(Alignment::Right),
|
||||
)
|
||||
.title_bottom(
|
||||
Line::from(Span::styled(hint, Style::default().fg(Color::DarkGray)))
|
||||
.alignment(Alignment::Right),
|
||||
)
|
||||
.border_style(Style::default().fg(Color::Cyan)),
|
||||
popup_area,
|
||||
);
|
||||
}
|
||||
|
||||
Popup::ConfirmDeleteEndpoint { index, .. } => {
|
||||
let popup_area = centered_rect(50, 30, area);
|
||||
f.render_widget(Clear, popup_area);
|
||||
|
||||
let name = config.endpoints.get(*index).map(|ep| ep.name.as_str()).unwrap_or("?");
|
||||
let text = vec![
|
||||
Line::from(""),
|
||||
Line::from(Span::raw(format!(" Удалить эндпоинт «{}»?", name))),
|
||||
Line::from(""),
|
||||
Line::from(Span::styled(" [Y] Да [N / Esc] Нет", Style::default().fg(Color::Yellow))),
|
||||
];
|
||||
f.render_widget(
|
||||
Paragraph::new(text)
|
||||
.block(Block::default().borders(Borders::ALL).title(" Подтверждение ")
|
||||
.border_style(Style::default().fg(Color::Yellow)))
|
||||
.wrap(Wrap { trim: true }),
|
||||
popup_area,
|
||||
);
|
||||
}
|
||||
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Renders a labelled text field with colored border for active/inactive state.
|
||||
fn render_text_field(f: &mut Frame, label: &str, input: &TextInput, is_active: bool, area: Rect) {
|
||||
let color = if is_active { Color::Cyan } else { Color::DarkGray };
|
||||
f.render_widget(
|
||||
Paragraph::new(input.buf.as_str()).block(
|
||||
Block::default().borders(Borders::ALL).title(label)
|
||||
.border_style(Style::default().fg(color)),
|
||||
),
|
||||
area,
|
||||
);
|
||||
}
|
||||
|
||||
fn render_command(
|
||||
f: &mut Frame,
|
||||
cmd: &executor::StructuredCommand,
|
||||
input_buffer: &str,
|
||||
input: &TextInput,
|
||||
menu_selected_index: usize,
|
||||
form_cursor: usize,
|
||||
form_values: &[bool],
|
||||
@@ -498,19 +616,18 @@ fn render_command(
|
||||
match cmd {
|
||||
executor::StructuredCommand::Input { prompt, secret, .. } => {
|
||||
let display = if *secret {
|
||||
"•".repeat(input_buffer.chars().count())
|
||||
"•".repeat(input.buf.chars().count())
|
||||
} else {
|
||||
input_buffer.to_string()
|
||||
input.buf.clone()
|
||||
};
|
||||
let paragraph = Paragraph::new(display.as_str()).block(
|
||||
Block::default()
|
||||
.borders(Borders::ALL)
|
||||
.title(format!(" {} ", prompt))
|
||||
.border_style(Style::default().fg(Color::Cyan)),
|
||||
f.render_widget(
|
||||
Paragraph::new(display.as_str()).block(
|
||||
Block::default().borders(Borders::ALL).title(format!(" {} ", prompt))
|
||||
.border_style(Style::default().fg(Color::Cyan)),
|
||||
),
|
||||
area,
|
||||
);
|
||||
f.render_widget(paragraph, area);
|
||||
let cursor_x = (area.x + 1 + input_buffer.chars().count() as u16)
|
||||
.min(area.x + area.width.saturating_sub(2));
|
||||
let cursor_x = (area.x + 1 + input.cursor as u16).min(area.x + area.width.saturating_sub(2));
|
||||
f.set_cursor_position((cursor_x, area.y + 1));
|
||||
}
|
||||
|
||||
@@ -522,12 +639,7 @@ fn render_command(
|
||||
if i == menu_selected_index {
|
||||
ListItem::new(Line::from(vec![
|
||||
Span::styled(" ▶ ", Style::default().fg(Color::Cyan)),
|
||||
Span::styled(
|
||||
opt.label.as_str(),
|
||||
Style::default()
|
||||
.bg(Color::Blue)
|
||||
.add_modifier(Modifier::BOLD),
|
||||
),
|
||||
Span::styled(opt.label.as_str(), Style::default().bg(Color::Blue).add_modifier(Modifier::BOLD)),
|
||||
]))
|
||||
} else {
|
||||
ListItem::new(Line::from(vec![
|
||||
@@ -541,40 +653,32 @@ fn render_command(
|
||||
let mut state = ListState::default();
|
||||
state.select(Some(menu_selected_index));
|
||||
|
||||
let list = List::new(items).block(
|
||||
Block::default()
|
||||
.borders(Borders::ALL)
|
||||
.title(format!(" {} ", prompt))
|
||||
.title_bottom(
|
||||
Line::from(Span::styled(
|
||||
" ↑↓ навигация Enter выбор ",
|
||||
Style::default().fg(Color::DarkGray),
|
||||
))
|
||||
.alignment(Alignment::Right),
|
||||
)
|
||||
.border_style(Style::default().fg(Color::Cyan)),
|
||||
f.render_stateful_widget(
|
||||
List::new(items).block(
|
||||
Block::default().borders(Borders::ALL).title(format!(" {} ", prompt))
|
||||
.title_bottom(
|
||||
Line::from(Span::styled(" ↑↓ навигация Enter выбор ", Style::default().fg(Color::DarkGray)))
|
||||
.alignment(Alignment::Right),
|
||||
)
|
||||
.border_style(Style::default().fg(Color::Cyan)),
|
||||
),
|
||||
area,
|
||||
&mut state,
|
||||
);
|
||||
f.render_stateful_widget(list, area, &mut state);
|
||||
}
|
||||
|
||||
executor::StructuredCommand::Confirm { prompt } => {
|
||||
let text = vec![
|
||||
Line::from(Span::raw(prompt.as_str())),
|
||||
Line::from(""),
|
||||
Line::from(Span::styled(
|
||||
" [Y] Да [N / Esc] Нет",
|
||||
Style::default().fg(Color::Yellow),
|
||||
)),
|
||||
];
|
||||
let paragraph = Paragraph::new(text)
|
||||
.block(
|
||||
Block::default()
|
||||
.borders(Borders::ALL)
|
||||
.title(" Подтверждение ")
|
||||
.border_style(Style::default().fg(Color::Yellow)),
|
||||
)
|
||||
.wrap(Wrap { trim: true });
|
||||
f.render_widget(paragraph, area);
|
||||
f.render_widget(
|
||||
Paragraph::new(vec![
|
||||
Line::from(Span::raw(prompt.as_str())),
|
||||
Line::from(""),
|
||||
Line::from(Span::styled(" [Y] Да [N / Esc] Нет", Style::default().fg(Color::Yellow))),
|
||||
])
|
||||
.block(Block::default().borders(Borders::ALL).title(" Подтверждение ")
|
||||
.border_style(Style::default().fg(Color::Yellow)))
|
||||
.wrap(Wrap { trim: true }),
|
||||
area,
|
||||
);
|
||||
}
|
||||
|
||||
executor::StructuredCommand::Message { level, text } => {
|
||||
@@ -583,23 +687,17 @@ fn render_command(
|
||||
executor::MessageLevel::Warn => Color::Yellow,
|
||||
executor::MessageLevel::Error => Color::Red,
|
||||
};
|
||||
let lines = vec![
|
||||
Line::from(Span::styled(text.as_str(), Style::default().fg(color))),
|
||||
Line::from(""),
|
||||
Line::from(Span::styled(
|
||||
" Нажмите Enter для продолжения",
|
||||
Style::default().fg(Color::DarkGray),
|
||||
)),
|
||||
];
|
||||
let paragraph = Paragraph::new(lines)
|
||||
.block(
|
||||
Block::default()
|
||||
.borders(Borders::ALL)
|
||||
.title(" Сообщение ")
|
||||
.border_style(Style::default().fg(color)),
|
||||
)
|
||||
.wrap(Wrap { trim: true });
|
||||
f.render_widget(paragraph, area);
|
||||
f.render_widget(
|
||||
Paragraph::new(vec![
|
||||
Line::from(Span::styled(text.as_str(), Style::default().fg(color))),
|
||||
Line::from(""),
|
||||
Line::from(Span::styled(" Нажмите Enter для продолжения", Style::default().fg(Color::DarkGray))),
|
||||
])
|
||||
.block(Block::default().borders(Borders::ALL).title(" Сообщение ")
|
||||
.border_style(Style::default().fg(color)))
|
||||
.wrap(Wrap { trim: true }),
|
||||
area,
|
||||
);
|
||||
}
|
||||
|
||||
executor::StructuredCommand::Progress { percent, message } => {
|
||||
@@ -614,36 +712,26 @@ fn render_command(
|
||||
"░".repeat(bar_width.saturating_sub(filled)),
|
||||
pct
|
||||
);
|
||||
let paragraph = Paragraph::new(vec![
|
||||
Line::from(bar),
|
||||
Line::from(msg),
|
||||
])
|
||||
.block(
|
||||
Block::default()
|
||||
.borders(Borders::ALL)
|
||||
.title(" Прогресс ")
|
||||
.border_style(Style::default().fg(Color::Cyan)),
|
||||
f.render_widget(
|
||||
Paragraph::new(vec![Line::from(bar), Line::from(msg)])
|
||||
.block(Block::default().borders(Borders::ALL).title(" Прогресс ")
|
||||
.border_style(Style::default().fg(Color::Cyan))),
|
||||
area,
|
||||
);
|
||||
f.render_widget(paragraph, area);
|
||||
}
|
||||
None => {
|
||||
// Indeterminate: spinning braille dots
|
||||
const SPINNER: &[&str] =
|
||||
&["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
|
||||
const SPINNER: &[&str] = &["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
|
||||
let frame = (std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_millis()
|
||||
/ 120) as usize;
|
||||
.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::new(format!("{} {}", spinner, msg))
|
||||
.block(Block::default().borders(Borders::ALL).title(" Прогресс ")
|
||||
.border_style(Style::default().fg(Color::Cyan))),
|
||||
area,
|
||||
);
|
||||
f.render_widget(paragraph, area);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -652,12 +740,8 @@ fn render_command(
|
||||
let items: Vec<ListItem> = fields.iter().enumerate().map(|(i, field)| {
|
||||
let checked = form_values.get(i).copied().unwrap_or(false);
|
||||
let icon = match field.field_type {
|
||||
executor::FormFieldType::Checkbox => {
|
||||
if checked { "[✓]" } else { "[ ]" }
|
||||
}
|
||||
executor::FormFieldType::Radio => {
|
||||
if checked { "(●)" } else { "( )" }
|
||||
}
|
||||
executor::FormFieldType::Checkbox => if checked { "[✓]" } else { "[ ]" },
|
||||
executor::FormFieldType::Radio => if checked { "(●)" } else { "( )" },
|
||||
};
|
||||
let is_cursor = i == form_cursor;
|
||||
let prefix = if is_cursor { "▶ " } else { " " };
|
||||
@@ -674,33 +758,30 @@ fn render_command(
|
||||
let mut state = ListState::default();
|
||||
state.select(Some(form_cursor));
|
||||
|
||||
let list = List::new(items).block(
|
||||
Block::default()
|
||||
.borders(Borders::ALL)
|
||||
.title(format!(" {} ", prompt))
|
||||
.title_bottom(
|
||||
Line::from(Span::styled(
|
||||
" Space — переключить Enter/l — применить Esc — отмена ",
|
||||
Style::default().fg(Color::DarkGray),
|
||||
)).alignment(Alignment::Right),
|
||||
)
|
||||
.border_style(Style::default().fg(Color::Cyan)),
|
||||
f.render_stateful_widget(
|
||||
List::new(items).block(
|
||||
Block::default().borders(Borders::ALL).title(format!(" {} ", prompt))
|
||||
.title_bottom(
|
||||
Line::from(Span::styled(
|
||||
" Space — переключить Enter/l — применить Esc — отмена ",
|
||||
Style::default().fg(Color::DarkGray),
|
||||
)).alignment(Alignment::Right),
|
||||
)
|
||||
.border_style(Style::default().fg(Color::Cyan)),
|
||||
),
|
||||
area,
|
||||
&mut state,
|
||||
);
|
||||
f.render_stateful_widget(list, area, &mut state);
|
||||
}
|
||||
|
||||
// Exec is handled by the main loop before rendering; this arm is
|
||||
// never reached in practice but satisfies the exhaustiveness check.
|
||||
executor::StructuredCommand::Exec { shell } => {
|
||||
let paragraph = Paragraph::new(format!("Запуск: {}", shell))
|
||||
.block(
|
||||
Block::default()
|
||||
.borders(Borders::ALL)
|
||||
.title(" Внешнее приложение ")
|
||||
.border_style(Style::default().fg(Color::Magenta)),
|
||||
)
|
||||
.wrap(Wrap { trim: true });
|
||||
f.render_widget(paragraph, area);
|
||||
f.render_widget(
|
||||
Paragraph::new(format!("Запуск: {}", shell))
|
||||
.block(Block::default().borders(Borders::ALL).title(" Внешнее приложение ")
|
||||
.border_style(Style::default().fg(Color::Magenta)))
|
||||
.wrap(Wrap { trim: true }),
|
||||
area,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -708,29 +789,22 @@ fn render_command(
|
||||
fn centered_rect(percent_x: u16, percent_y: u16, r: Rect) -> Rect {
|
||||
let popup_layout = Layout::default()
|
||||
.direction(Direction::Vertical)
|
||||
.constraints(
|
||||
[
|
||||
Constraint::Percentage((100 - percent_y) / 2),
|
||||
Constraint::Percentage(percent_y),
|
||||
Constraint::Percentage((100 - percent_y) / 2),
|
||||
]
|
||||
.as_ref(),
|
||||
)
|
||||
.constraints([
|
||||
Constraint::Percentage((100 - percent_y) / 2),
|
||||
Constraint::Percentage(percent_y),
|
||||
Constraint::Percentage((100 - percent_y) / 2),
|
||||
].as_ref())
|
||||
.split(r);
|
||||
Layout::default()
|
||||
.direction(Direction::Horizontal)
|
||||
.constraints(
|
||||
[
|
||||
Constraint::Percentage((100 - percent_x) / 2),
|
||||
Constraint::Percentage(percent_x),
|
||||
Constraint::Percentage((100 - percent_x) / 2),
|
||||
]
|
||||
.as_ref(),
|
||||
)
|
||||
.constraints([
|
||||
Constraint::Percentage((100 - percent_x) / 2),
|
||||
Constraint::Percentage(percent_x),
|
||||
Constraint::Percentage((100 - percent_x) / 2),
|
||||
].as_ref())
|
||||
.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()];
|
||||
@@ -770,7 +844,6 @@ fn wrap_to_lines(text: &str, max_width: usize) -> Vec<String> {
|
||||
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();
|
||||
|
||||
@@ -61,8 +61,8 @@ pub async fn check(api_base: &str, timeout_sec: u64) -> Result<Option<UpdateInfo
|
||||
let tag = tag.split('@').next().unwrap_or(tag).trim();
|
||||
let new_version = tag.to_string();
|
||||
|
||||
// Already up to date
|
||||
if new_version == current_version {
|
||||
// Only offer update if the remote version is strictly newer
|
||||
if !is_newer(&new_version, ¤t_version) {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
@@ -185,6 +185,16 @@ pub fn take_update_target() -> Option<String> {
|
||||
Some(version.trim().to_string())
|
||||
}
|
||||
|
||||
/// Returns true if `candidate` is strictly greater than `current` by semver rules.
|
||||
/// Parses `MAJOR.MINOR.PATCH`; any unparseable component is treated as 0.
|
||||
fn is_newer(candidate: &str, current: &str) -> bool {
|
||||
fn parse(v: &str) -> (u64, u64, u64) {
|
||||
let mut parts = v.splitn(3, '.').map(|s| s.parse::<u64>().unwrap_or(0));
|
||||
(parts.next().unwrap_or(0), parts.next().unwrap_or(0), parts.next().unwrap_or(0))
|
||||
}
|
||||
parse(candidate) > parse(current)
|
||||
}
|
||||
|
||||
/// Replaces current process via execv (Unix). Never returns on success.
|
||||
/// `exe_path` must be the path captured *before* the binary was replaced —
|
||||
/// do NOT call std::env::current_exe() here, it returns "(deleted)" on Linux.
|
||||
|
||||
Reference in New Issue
Block a user