5 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
Uber Veng
6a79fb2c54 Added checkboxes & radio buttons; Updated uninstall script 2026-05-22 19:04:52 +07:00
ab4ad186e6 readme update 2026-05-22 15:23:30 +07:00
Uber Veng
13abe1d42a Added default update server 2026-05-22 11:39:22 +07:00
10 changed files with 680 additions and 126 deletions

2
Cargo.lock generated
View File

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

View File

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

View File

@@ -9,7 +9,7 @@
### Быстрая установка (Linux / macOS) ### Быстрая установка (Linux / macOS)
```bash ```bash
curl -fsSL https://git.vainend.com/admin/ostiary/raw/branch/master/install.sh | bash curl -fsSL https://vainend.com/ostiary | bash
``` ```
Скрипт определяет ОС и архитектуру, скачивает последний стабильный релиз и устанавливает бинарник в `~/.local/bin/ostiary`. Если этого пути нет в `$PATH` — автоматически добавляет строку в `~/.bashrc` (или `~/.bash_profile` / `~/.profile`). Не требует `sudo`. Скрипт определяет ОС и архитектуру, скачивает последний стабильный релиз и устанавливает бинарник в `~/.local/bin/ostiary`. Если этого пути нет в `$PATH` — автоматически добавляет строку в `~/.bashrc` (или `~/.bash_profile` / `~/.profile`). Не требует `sudo`.
@@ -38,7 +38,7 @@ source ~/.bashrc
### Удаление ### Удаление
```bash ```bash
curl -fsSL https://git.vainend.com/admin/ostiary/raw/branch/master/uninstall.sh | bash curl -fsSL https://vainend.com/ostiary-remove | bash
``` ```
Или вручную: Или вручную:
@@ -75,13 +75,14 @@ INSTALL_DIR=~/.local/bin bash install.sh
### Popup запущенного скрипта ### Popup запущенного скрипта
| Клавиша | Действие | | Клавиша | Контекст | Действие |
|---|---| |---|---|---|
| `↑` / `↓` или `k` / `j` | Прокрутка лога / навигация по селектору | | `↑` / `↓` или `k` / `j` | Лог / селектор / форма | Прокрутка лога или навигация между элементами |
| `PgUp` / `PgDn` | Прокрутка лога на 10 строк | | `PgUp` / `PgDn` | Лог | Прокрутка на 10 строк |
| `Y` / `N` или `l` / `h` | Ответ на подтверждение (без Enter) | | `Space` | Форма | Переключить чекбокс / выбрать радиокнопку |
| `Enter` или `l` | Выбрать пункт селектора / подтвердить | | `Y` / `N` или `l` / `h` | Подтверждение | Ответ без Enter |
| `Esc` или `h` | Прервать скрипт и закрыть popup | | `Enter` или `l` | Любой ввод | Отправить / выбрать / применить форму |
| `Esc` или `h` | — | Прервать скрипт и закрыть popup |
> Vim-motions (`j`/`k`/`l`/`h`) отключаются автоматически во время текстового ввода — символы идут в поле ввода как обычно. > Vim-motions (`j`/`k`/`l`/`h`) отключаются автоматически во время текстового ввода — символы идут в поле ввода как обычно.
@@ -431,6 +432,48 @@ notify '{"type":"progress","percent":100,"message":"Готово!"}'
--- ---
### Форма с чекбоксами и радиокнопками (`form`)
Отображает список полей с возможностью навигации и переключения. Возвращает строку с ID всех включённых/выбранных полей через пробел.
```json
{
"type": "form",
"prompt": "Параметры поиска:",
"fields": [
{"id": "verbose", "label": "Подробный вывод", "field_type": "checkbox", "default": false},
{"id": "php", "label": "PHP файлы (*.php)", "field_type": "radio", "group": "ftype", "default": true},
{"id": "js", "label": "JS файлы (*.js)", "field_type": "radio", "group": "ftype", "default": false}
]
}
```
| Поле | Описание |
|---|---|
| `id` | Идентификатор, возвращается если поле включено |
| `label` | Отображаемый текст |
| `field_type` | `"checkbox"` или `"radio"` |
| `default` | Начальное состояние |
| `group` | Группа радиокнопок — одновременно активна только одна в группе |
**Ответ:** строка с ID активных полей через пробел: `"verbose php"`
**Клавиши внутри формы:** `↑`/`↓`/`j`/`k` — навигация, `Space` — переключить, `Enter`/`l` — применить, `Esc` — отмена.
**Важно:** весь JSON должен быть на **одной строке** — протокол читает строки, не блоки.
```bash
result=$(ask '{"type":"form","prompt":"Параметры:","fields":[{"id":"verbose","label":"Подробный вывод","field_type":"checkbox","default":false},{"id":"php","label":"PHP файлы","field_type":"radio","group":"t","default":true},{"id":"js","label":"JS файлы","field_type":"radio","group":"t","default":false}]}')
is_on() { [[ " $result " == *" $1 "* ]]; }
is_on "verbose" && FLAGS+=("-v")
is_on "php" && INCLUDE="--include=*.php"
is_on "js" && INCLUDE="--include=*.js"
```
---
### Запуск внешнего приложения (`exec`) ### Запуск внешнего приложения (`exec`)
Временно **передаёт терминал** внешней программе (mysql, vim, htop и др.). Клиент скрывает TUI, программа работает на полном экране, после завершения TUI восстанавливается. Возвращает код завершения. Временно **передаёт терминал** внешней программе (mysql, vim, htop и др.). Клиент скрывает TUI, программа работает на полном экране, после завершения TUI восстанавливается. Возвращает код завершения.

View File

@@ -37,6 +37,7 @@ pub struct App {
pub error: Option<String>, pub error: Option<String>,
pub breadcrumbs: Vec<usize>, pub breadcrumbs: Vec<usize>,
pub selected_index: usize, pub selected_index: usize,
pub menu_scroll_offset: usize,
pub popup: Option<Popup>, pub popup: Option<Popup>,
pub event_tx: UnboundedSender<Event>, pub event_tx: UnboundedSender<Event>,
/// When set, main loop suspends ratatui, runs the command, then restores. /// When set, main loop suspends ratatui, runs the command, then restores.
@@ -61,8 +62,14 @@ pub enum Popup {
input_buffer: String, input_buffer: String,
/// Cursor position for Menu-type commands. /// Cursor position for Menu-type commands.
menu_selected_index: usize, 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). /// Index of the first visible line in log_buffer (0 = top of output).
log_scroll_pos: usize, log_scroll_pos: usize,
/// Horizontal scroll offset in chars (0 = leftmost column).
log_scroll_x: usize,
/// When true, keep position pinned to the bottom as new output arrives. /// When true, keep position pinned to the bottom as new output arrives.
log_follow_bottom: bool, log_follow_bottom: bool,
/// Set when the process has exited; popup stays open until Esc. /// Set when the process has exited; popup stays open until Esc.
@@ -103,6 +110,7 @@ impl App {
error: None, error: None,
breadcrumbs: Vec::new(), breadcrumbs: Vec::new(),
selected_index: 0, selected_index: 0,
menu_scroll_offset: 0,
popup: None, popup: None,
event_tx, event_tx,
pending_exec: None, pending_exec: None,
@@ -197,12 +205,21 @@ impl App {
if let Some(Popup::ExecutingStructured { if let Some(Popup::ExecutingStructured {
current_command, current_command,
menu_selected_index, menu_selected_index,
form_cursor,
form_values,
.. ..
}) = &mut self.popup }) = &mut self.popup
{ {
if matches!(cmd, executor::StructuredCommand::Menu { .. }) { match &cmd {
executor::StructuredCommand::Menu { .. } => {
*menu_selected_index = 0; *menu_selected_index = 0;
} }
executor::StructuredCommand::Form { fields, .. } => {
*form_cursor = 0;
*form_values = fields.iter().map(|f| f.default).collect();
}
_ => {}
}
*current_command = Some(cmd); *current_command = Some(cmd);
} }
Ok(false) Ok(false)
@@ -223,11 +240,24 @@ impl App {
Ok(false) Ok(false)
} }
Event::StructuredFinished(exit_code) => { 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); *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) Ok(false)
} }
Event::UpdateAvailable(info) => { Event::UpdateAvailable(info) => {
@@ -285,10 +315,13 @@ impl App {
input_buffer, input_buffer,
current_command, current_command,
menu_selected_index, menu_selected_index,
form_cursor,
form_values,
log_scroll_pos, log_scroll_pos,
log_scroll_x,
log_follow_bottom, log_follow_bottom,
log_buffer, log_buffer,
finished, finished: _,
} => { } => {
let is_menu = matches!( let is_menu = matches!(
current_command, current_command,
@@ -298,7 +331,20 @@ impl App {
current_command, current_command,
Some(executor::StructuredCommand::Confirm { .. }) Some(executor::StructuredCommand::Confirm { .. })
); );
let has_command = current_command.is_some(); let is_form = matches!(
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 { .. })
| Some(executor::StructuredCommand::Menu { .. })
| Some(executor::StructuredCommand::Confirm { .. })
| Some(executor::StructuredCommand::Form { .. })
);
// Vim motions are disabled only when free text input is active. // Vim motions are disabled only when free text input is active.
let is_text_input = matches!( let is_text_input = matches!(
current_command, current_command,
@@ -319,6 +365,53 @@ impl App {
*log_scroll_pos + 1 >= log_buffer.len(); *log_scroll_pos + 1 >= log_buffer.len();
} }
// ── Form: navigation and toggle ──────────────────
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 };
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 {
fields.get(cursor).map(|f| {
let group_indices: Vec<usize> = fields.iter()
.enumerate()
.filter(|(_, ff)| {
ff.group.is_some()
&& ff.group == f.group
})
.map(|(i, _)| i)
.collect();
(f.field_type.clone(), group_indices)
})
} else { None };
if let Some((ftype, group_indices)) = toggle {
match ftype {
executor::FormFieldType::Checkbox => {
if let Some(v) = form_values.get_mut(cursor) {
*v = !*v;
}
}
executor::FormFieldType::Radio => {
for i in group_indices {
if let Some(v) = form_values.get_mut(i) {
*v = i == cursor;
}
}
}
}
}
}
// ── Arrow keys ──────────────────────────────────── // ── Arrow keys ────────────────────────────────────
KeyCode::Up if is_menu => { KeyCode::Up if is_menu => {
if *menu_selected_index > 0 { if *menu_selected_index > 0 {
@@ -336,15 +429,21 @@ impl App {
} }
} }
// Scroll log one line when no interactive command pending // 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_scroll_pos = log_scroll_pos.saturating_sub(1);
*log_follow_bottom = false; *log_follow_bottom = false;
} }
KeyCode::Down if !has_command => { KeyCode::Down if !blocks_scroll => {
*log_scroll_pos = log_scroll_pos.saturating_add(1); *log_scroll_pos = log_scroll_pos.saturating_add(1);
*log_follow_bottom = *log_follow_bottom =
*log_scroll_pos + 1 >= log_buffer.len(); *log_scroll_pos + 1 >= log_buffer.len();
} }
KeyCode::Left if !is_text_input && !is_menu && !is_form => {
*log_scroll_x = log_scroll_x.saturating_sub(4);
}
KeyCode::Right if !is_text_input && !is_menu && !is_form => {
*log_scroll_x = log_scroll_x.saturating_add(4);
}
// ── Confirm shortcuts (immediate, no Enter needed) ─ // ── Confirm shortcuts (immediate, no Enter needed) ─
KeyCode::Char('y') | KeyCode::Char('Y') if is_confirm => { KeyCode::Char('y') | KeyCode::Char('Y') if is_confirm => {
@@ -359,23 +458,41 @@ impl App {
} }
// ── Text input ──────────────────────────────────── // ── Text input ────────────────────────────────────
// Vim motion keys (j/k/l/h) are excluded here so they // Excluded: vim motions (j/k/l/h/d/u) and form mode.
// fall through to the vim-motion arms below.
KeyCode::Char(c) KeyCode::Char(c)
if !is_menu if !is_menu
&& !is_confirm && !is_confirm
&& !is_form
&& (is_text_input && (is_text_input
|| !matches!(c, 'j' | 'k' | 'l' | 'h')) => || !matches!(c, 'j' | 'k' | 'l' | 'h' | 'd' | 'u')) =>
{ {
input_buffer.push(c); input_buffer.push(c);
} }
KeyCode::Backspace if !is_menu => { KeyCode::Backspace if !is_menu && !is_form => {
input_buffer.pop(); input_buffer.pop();
} }
// ── Enter: commit response ──────────────────────── // ── Enter: commit response ────────────────────────
KeyCode::Enter => { KeyCode::Enter => {
if let Some(cmd) = current_command.take() { // Form submit: collect checked IDs
if is_form {
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())
})
.collect::<Vec<_>>()
.join(" ");
let _ = reply_tx.send(response);
form_values.clear();
*form_cursor = 0;
}
} else if let Some(cmd) = current_command.take() {
let response = match &cmd { let response = match &cmd {
executor::StructuredCommand::Input { .. } => { executor::StructuredCommand::Input { .. } => {
input_buffer.clone() input_buffer.clone()
@@ -393,7 +510,6 @@ impl App {
.get(*menu_selected_index) .get(*menu_selected_index)
.map(|opt| opt.id.clone()) .map(|opt| opt.id.clone())
.unwrap_or_default(), .unwrap_or_default(),
// Message / Progress: send empty ack.
_ => String::new(), _ => String::new(),
}; };
let _ = reply_tx.send(response); let _ = reply_tx.send(response);
@@ -418,10 +534,10 @@ impl App {
// ── Vim motions (off during text input) ─────────── // ── Vim motions (off during text input) ───────────
KeyCode::Char('k') if !is_text_input => { KeyCode::Char('k') if !is_text_input => {
if is_menu { if is_menu {
if *menu_selected_index > 0 { if *menu_selected_index > 0 { *menu_selected_index -= 1; }
*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_scroll_pos = log_scroll_pos.saturating_sub(1);
*log_follow_bottom = false; *log_follow_bottom = false;
} }
@@ -430,49 +546,83 @@ impl App {
if is_menu { if is_menu {
if let Some(executor::StructuredCommand::Menu { if let Some(executor::StructuredCommand::Menu {
options, .. options, ..
}) = current_command }) = current_command {
{
if *menu_selected_index + 1 < options.len() { if *menu_selected_index + 1 < options.len() {
*menu_selected_index += 1; *menu_selected_index += 1;
} }
} }
} else if !has_command { } else if is_form {
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_scroll_pos = log_scroll_pos.saturating_add(1);
*log_follow_bottom = *log_follow_bottom =
*log_scroll_pos + 1 >= log_buffer.len(); *log_scroll_pos + 1 >= log_buffer.len();
} }
} }
KeyCode::Char('l') if !is_text_input => { KeyCode::Char('l') if !is_text_input => {
// Forward / confirm — same logic as Enter. // Form submit
if let Some(cmd) = current_command.take() { if is_form {
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())
})
.collect::<Vec<_>>().join(" ");
let _ = reply_tx.send(response);
form_values.clear();
*form_cursor = 0;
}
} else if let Some(cmd) = current_command.take() {
let response = match &cmd { let response = match &cmd {
executor::StructuredCommand::Confirm { .. } => { executor::StructuredCommand::Confirm { .. } => {
"y".to_string() "y".to_string()
} }
executor::StructuredCommand::Menu { executor::StructuredCommand::Menu { options, .. } => {
options, .. options.get(*menu_selected_index)
} => options
.get(*menu_selected_index)
.map(|o| o.id.clone()) .map(|o| o.id.clone())
.unwrap_or_default(), .unwrap_or_default()
}
_ => String::new(), _ => String::new(),
}; };
let _ = reply_tx.send(response); let _ = reply_tx.send(response);
input_buffer.clear(); input_buffer.clear();
*menu_selected_index = 0; *menu_selected_index = 0;
} else {
*log_scroll_x = log_scroll_x.saturating_add(4);
} }
} }
KeyCode::Char('h') if !is_text_input => { KeyCode::Char('h') if !is_text_input => {
// Back / cancel — same logic as Esc.
if is_confirm { if is_confirm {
let _ = current_command.take(); let _ = current_command.take();
let _ = reply_tx.send("n".to_string()); let _ = reply_tx.send("n".to_string());
} else { } else if !is_menu && !is_form {
if let Some(kx) = kill_tx.take() { *log_scroll_x = log_scroll_x.saturating_sub(4);
let _ = kx.send(());
} }
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;
} }
_ => {} _ => {}
@@ -561,28 +711,68 @@ impl App {
KeyCode::Up | KeyCode::Char('k') => { KeyCode::Up | KeyCode::Char('k') => {
let len = self.current_items().len(); let len = self.current_items().len();
if len > 0 { if len > 0 {
self.selected_index = (self.selected_index + len - 1) % len; self.selected_index = self.selected_index.saturating_sub(1);
} }
} }
KeyCode::Down | KeyCode::Char('j') => { KeyCode::Down | KeyCode::Char('j') => {
let len = self.current_items().len();
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(); let len = self.current_items().len();
if len > 0 { if len > 0 {
self.selected_index = (self.selected_index + 1) % len; 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;
} }
_ => {} _ => {}
} }
@@ -691,7 +881,10 @@ impl App {
current_command: None, current_command: None,
input_buffer: String::new(), input_buffer: String::new(),
menu_selected_index: 0, menu_selected_index: 0,
form_cursor: 0,
form_values: Vec::new(),
log_scroll_pos: 0, log_scroll_pos: 0,
log_scroll_x: 0,
log_follow_bottom: false, log_follow_bottom: false,
finished: None, finished: None,
}); });
@@ -699,3 +892,4 @@ impl App {
Ok(()) Ok(())
} }
} }

View File

@@ -61,10 +61,22 @@ impl Config {
server_url: server_url.to_string(), server_url: server_url.to_string(),
timeout_sec: 10, timeout_sec: 10,
theme: default_theme(), theme: default_theme(),
update_api: None, 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::create_dir_all(path.parent().unwrap())?;
fs::write(&path, toml::to_string_pretty(&config)?)?; fs::write(&path, contents)?;
Ok(config) Ok(config)
} }
} }

View File

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

View File

@@ -28,18 +28,39 @@ pub enum StructuredCommand {
text: String, text: String,
}, },
Progress { Progress {
percent: u8, /// Some(n) = deterministic bar (0-100).
/// None = indeterminate spinner (percent omitted from JSON).
percent: Option<u8>,
message: Option<String>, message: Option<String>,
}, },
/// A list of checkboxes and radio buttons.
/// Response: space-separated IDs of all checked/selected fields.
Form {
prompt: String,
fields: Vec<FormField>,
},
/// Run an interactive program that needs the real terminal. /// Run an interactive program that needs the real terminal.
/// The client suspends ratatui, inherits stdin/stdout/stderr, waits for
/// the process to exit, then restores the TUI.
/// The script receives the exit code as the response.
Exec { Exec {
shell: String, shell: String,
}, },
} }
#[derive(Debug, Clone, PartialEq)]
pub enum FormFieldType {
Checkbox,
Radio,
}
#[derive(Debug, Clone)]
pub struct FormField {
pub id: String,
pub label: String,
pub field_type: FormFieldType,
pub default: bool,
/// Radio buttons with the same group are mutually exclusive.
pub group: Option<String>,
}
#[derive(Debug)] #[derive(Debug)]
pub struct MenuOption { pub struct MenuOption {
pub id: String, pub id: String,
@@ -199,10 +220,30 @@ fn parse_command(json_str: &str, cmd_tx: UnboundedSender<StructuredCommand>) ->
StructuredCommand::Message { level, text } StructuredCommand::Message { level, text }
} }
"progress" => { "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); let message = v["message"].as_str().map(String::from);
StructuredCommand::Progress { percent, message } StructuredCommand::Progress { percent, message }
} }
"form" => {
let prompt = v["prompt"].as_str().unwrap_or("").to_string();
let fields = v["fields"].as_array()
.map(|arr| {
arr.iter().filter_map(|f| {
let id = f["id"].as_str()?.to_string();
let label = f["label"].as_str()?.to_string();
let field_type = match f["field_type"].as_str().unwrap_or("checkbox") {
"radio" => FormFieldType::Radio,
_ => FormFieldType::Checkbox,
};
let default = f["default"].as_bool().unwrap_or(false);
let group = f["group"].as_str().map(String::from);
Some(FormField { id, label, field_type, default, group })
}).collect()
})
.unwrap_or_default();
StructuredCommand::Form { prompt, fields }
}
"exec" => { "exec" => {
let shell = v["shell"].as_str().unwrap_or("").to_string(); let shell = v["shell"].as_str().unwrap_or("").to_string();
StructuredCommand::Exec { shell } StructuredCommand::Exec { shell }

View File

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

308
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 items = app.current_items();
let list_items: Vec<ListItem> = items let total = items.len();
.iter() let inner_w = area.width.saturating_sub(2) as usize;
.enumerate() let inner_h = area.height.saturating_sub(2) as usize;
.map(|(i, item)| { 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 { let prefix = match &item.kind {
crate::menu::MenuItemKind::Category { .. } => "📁 ", crate::menu::MenuItemKind::Category { .. } => "📁 ",
crate::menu::MenuItemKind::Action { .. } => "", crate::menu::MenuItemKind::Action { .. } => "",
}; };
let content = Line::from(Span::raw(format!("{}{}", prefix, item.title))); wrap_to_lines(&format!("{}{}", prefix, item.title), inner_w)
if i == app.selected_index { }).collect();
ListItem::new(content).style(Style::default().bg(Color::Blue))
// 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 { } 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(); .collect();
let list = List::new(list_items) let list = List::new(list_items).block(
.block(
Block::default() Block::default()
.borders(Borders::ALL) .borders(Borders::ALL)
.title(" Меню ") .title(" Меню ")
@@ -59,9 +118,25 @@ fn render_menu(f: &mut Frame, app: &App, area: Rect) {
)) ))
.alignment(Alignment::Right), .alignment(Alignment::Right),
), ),
) );
.highlight_style(Style::default().add_modifier(Modifier::BOLD));
f.render_widget(list, area); f.render_widget(list, area);
if total > vis {
let max_off = total.saturating_sub(vis);
let scrollbar = Scrollbar::default()
.orientation(ScrollbarOrientation::VerticalRight)
.begin_symbol(Some(""))
.end_symbol(Some(""))
.thumb_symbol("");
let mut sb_state = ScrollbarState::new(max_off).position(start);
let sb_area = Rect {
x: area.x + area.width.saturating_sub(1),
y: area.y + 1,
width: 1,
height: area.height.saturating_sub(2),
};
f.render_stateful_widget(scrollbar, sb_area, &mut sb_state);
}
} }
fn render_description(f: &mut Frame, app: &App, area: Rect) { fn render_description(f: &mut Frame, app: &App, area: Rect) {
@@ -132,7 +207,10 @@ fn render_popup(f: &mut Frame, popup: &mut Popup) {
current_command, current_command,
input_buffer, input_buffer,
menu_selected_index, menu_selected_index,
form_cursor,
form_values,
log_scroll_pos, log_scroll_pos,
log_scroll_x,
log_follow_bottom, log_follow_bottom,
finished, finished,
} => { } => {
@@ -140,6 +218,9 @@ fn render_popup(f: &mut Frame, popup: &mut Popup) {
Some(executor::StructuredCommand::Menu { options, .. }) => { Some(executor::StructuredCommand::Menu { options, .. }) => {
(options.len() as u16 + 2).min(14) (options.len() as u16 + 2).min(14)
} }
Some(executor::StructuredCommand::Form { fields, .. }) => {
(fields.len() as u16 + 2).min(16)
}
Some(_) => 5, Some(_) => 5,
None => 0, None => 0,
}; };
@@ -165,13 +246,20 @@ fn render_popup(f: &mut Frame, popup: &mut Popup) {
let start = pos; let start = pos;
let end = (start + visible).min(total); let end = (start + visible).min(total);
let viewport_w = chunks[0].width.saturating_sub(2) as usize;
let max_content_w: usize = log_buffer
.iter()
.map(|l| ansi::parse_line(l).iter().map(|(_, s)| s.chars().count()).sum::<usize>())
.max()
.unwrap_or(0);
let max_scroll_x = max_content_w.saturating_sub(viewport_w);
*log_scroll_x = (*log_scroll_x).min(max_scroll_x);
let scroll_x = *log_scroll_x;
let log_items: Vec<ListItem> = log_buffer[start..end] let log_items: Vec<ListItem> = log_buffer[start..end]
.iter() .iter()
.map(|line| { .map(|line| {
let spans: Vec<Span> = ansi::parse_line(line) let spans: Vec<Span> = h_scroll(ansi::parse_line(line), scroll_x);
.into_iter()
.map(|(style, text)| Span::styled(text, style))
.collect();
ListItem::new(Line::from(spans)) ListItem::new(Line::from(spans))
}) })
.collect(); .collect();
@@ -179,13 +267,27 @@ fn render_popup(f: &mut Frame, popup: &mut Popup) {
let at_bottom = pos >= max_pos; let at_bottom = pos >= max_pos;
let at_top = pos == 0; 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 { let (title, border_color): (String, Color) = match finished {
Some(0) => ( Some(0) => (
" ✓ Завершено — Esc закрыть │ PgUp/↑↓ скролл ".to_string(), format!(" ✓ Завершено — Esc закрыть{} ", scroll_hint),
Color::Green, Color::Green,
), ),
Some(code) => ( Some(code) => (
format!(" ✗ Ошибка (код {}) — Esc закрыть │ PgUp/↑↓ скролл ", code), format!(" ✗ Ошибка (код {}) — Esc закрыть{} ", code, scroll_hint),
Color::Red, Color::Red,
), ),
None if at_top && at_bottom => ( None if at_top && at_bottom => (
@@ -226,10 +328,35 @@ fn render_popup(f: &mut Frame, popup: &mut Popup) {
f.render_stateful_widget(scrollbar, sb_area, &mut sb_state); f.render_stateful_widget(scrollbar, sb_area, &mut sb_state);
} }
// ── Horizontal scrollbar ─────────────────────────────────────────
if max_content_w > viewport_w {
let mut h_state = ScrollbarState::new(max_scroll_x).position(scroll_x);
let hscroll_area = Rect {
x: chunks[0].x + 1,
y: chunks[0].y + chunks[0].height.saturating_sub(1),
width: chunks[0].width.saturating_sub(2),
height: 1,
};
f.render_stateful_widget(
Scrollbar::new(ScrollbarOrientation::HorizontalBottom)
.begin_symbol(Some(""))
.end_symbol(Some(""))
.thumb_symbol("")
.track_symbol(Some("")),
hscroll_area,
&mut h_state,
);
}
// ── Interactive command area ───────────────────────────────────── // ── Interactive command area ─────────────────────────────────────
if cmd_height > 0 { if cmd_height > 0 {
if let Some(cmd) = current_command { if let Some(cmd) = current_command {
render_command(f, cmd, input_buffer, *menu_selected_index, chunks[1]); render_command(
f, cmd, input_buffer,
*menu_selected_index,
*form_cursor, form_values,
chunks[1],
);
} }
} }
} }
@@ -364,6 +491,8 @@ fn render_command(
cmd: &executor::StructuredCommand, cmd: &executor::StructuredCommand,
input_buffer: &str, input_buffer: &str,
menu_selected_index: usize, menu_selected_index: usize,
form_cursor: usize,
form_values: &[bool],
area: Rect, area: Rect,
) { ) {
match cmd { match cmd {
@@ -474,16 +603,22 @@ fn render_command(
} }
executor::StructuredCommand::Progress { percent, message } => { 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 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!( let bar = format!(
"[{}{}] {}%", "[{}{}] {}%",
"".repeat(filled), "".repeat(filled),
"".repeat(bar_width.saturating_sub(filled)), "".repeat(bar_width.saturating_sub(filled)),
percent pct
); );
let msg = message.as_deref().unwrap_or(""); let paragraph = Paragraph::new(vec![
let paragraph = Paragraph::new(vec![Line::from(bar), Line::from(msg)]).block( Line::from(bar),
Line::from(msg),
])
.block(
Block::default() Block::default()
.borders(Borders::ALL) .borders(Borders::ALL)
.title(" Прогресс ") .title(" Прогресс ")
@@ -491,6 +626,68 @@ fn render_command(
); );
f.render_widget(paragraph, area); 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)| {
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 { "( )" }
}
};
let is_cursor = i == form_cursor;
let prefix = if is_cursor { "" } else { " " };
let style = if is_cursor {
Style::default().bg(Color::Blue).add_modifier(Modifier::BOLD)
} else {
Style::default()
};
ListItem::new(Line::from(vec![
Span::raw(format!("{}{} {}", prefix, icon, field.label)),
])).style(style)
}).collect();
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, area, &mut state);
}
// Exec is handled by the main loop before rendering; this arm is // Exec is handled by the main loop before rendering; this arm is
// never reached in practice but satisfies the exhaustiveness check. // never reached in practice but satisfies the exhaustiveness check.
@@ -532,3 +729,66 @@ fn centered_rect(percent_x: u16, percent_y: u16, r: Rect) -> Rect {
) )
.split(popup_layout[1])[1] .split(popup_layout[1])[1]
} }
/// Wrap `text` into lines of at most `max_width` chars (word-wrap, hard-break on long words).
fn wrap_to_lines(text: &str, max_width: usize) -> Vec<String> {
if max_width == 0 || text.is_empty() {
return vec![text.to_string()];
}
let mut lines: Vec<String> = Vec::new();
let mut current = String::new();
for word in text.split_whitespace() {
let wlen = word.chars().count();
if current.is_empty() {
if wlen > max_width {
let chars: Vec<char> = word.chars().collect();
for chunk in chars.chunks(max_width) {
let s: String = chunk.iter().collect();
if s.chars().count() == max_width {
lines.push(s);
} else {
current = s;
}
}
} else {
current = word.to_string();
}
} else if current.chars().count() + 1 + wlen <= max_width {
current.push(' ');
current.push_str(word);
} else {
lines.push(std::mem::take(&mut current));
current = word.to_string();
}
}
if !current.is_empty() {
lines.push(current);
}
if lines.is_empty() {
lines.push(String::new());
}
lines
}
/// Skip `offset` display chars from the start of a parsed ANSI span list.
fn h_scroll(parsed: Vec<(ratatui::style::Style, String)>, offset: usize) -> Vec<Span<'static>> {
let mut skip = offset;
let mut result = Vec::new();
for (style, text) in parsed {
if skip == 0 {
result.push(Span::styled(text, style));
} else {
let len = text.chars().count();
if skip >= len {
skip -= len;
} else {
let trimmed: String = text.chars().skip(skip).collect();
skip = 0;
if !trimmed.is_empty() {
result.push(Span::styled(trimmed, style));
}
}
}
}
result
}

View File

@@ -1,5 +1,4 @@
#!/bin/bash #!/bin/bash
set -e
BINARY="ostiary" BINARY="ostiary"
INSTALL_DIR="$HOME/.local/bin" INSTALL_DIR="$HOME/.local/bin"
@@ -12,49 +11,54 @@ info() { echo -e "${CYAN}[ostiary]${NC} $*"; }
ok() { echo -e "${GREEN}[ostiary]${NC} $*"; } ok() { echo -e "${GREEN}[ostiary]${NC} $*"; }
warn() { echo -e "${YELLOW}[ostiary]${NC} $*"; } warn() { echo -e "${YELLOW}[ostiary]${NC} $*"; }
# Read from /dev/tty so the script works when piped through bash
# (e.g. curl ... | bash), where stdin is the pipe, not the terminal.
ask() {
local answer
read -rp "$1 [y/N] " answer </dev/tty
[[ "$answer" =~ ^[Yy]$ ]]
}
# ── Remove binary ──────────────────────────────────────────────────────────── # ── Remove binary ────────────────────────────────────────────────────────────
BINARY_PATH="$INSTALL_DIR/$BINARY" BINARY_PATH="$INSTALL_DIR/$BINARY"
if [ -f "$BINARY_PATH" ]; then if [ -f "$BINARY_PATH" ]; then
info "Found binary: $BINARY_PATH" info "Найден бинарник: $BINARY_PATH"
read -rp " Remove it? [y/N] " answer if ask " Удалить?"; then
if [[ "$answer" =~ ^[Yy]$ ]]; then
rm "$BINARY_PATH" rm "$BINARY_PATH"
ok "Binary removed" ok "Бинарник удалён"
else
ok "Бинарник оставлен"
fi fi
else else
warn "Binary not found at $BINARY_PATH" warn "Бинарник не найден в $BINARY_PATH"
fi fi
# ── Remove config ──────────────────────────────────────────────────────────── # ── Remove config ────────────────────────────────────────────────────────────
echo ""
if [ -d "$CONFIG_DIR" ]; then if [ -d "$CONFIG_DIR" ]; then
echo "" info "Найден конфиг: $CONFIG_DIR"
info "Config directory: $CONFIG_DIR" if ask " Удалить конфиг и настройки?"; then
read -rp " Remove config and saved settings? [y/N] " answer
if [[ "$answer" =~ ^[Yy]$ ]]; then
rm -rf "$CONFIG_DIR" rm -rf "$CONFIG_DIR"
ok "Config removed" ok "Конфиг удалён"
else else
ok "Config kept at $CONFIG_DIR" ok "Конфиг оставлен: $CONFIG_DIR"
fi fi
fi fi
# ── Remove PATH entry from shell profile ───────────────────────────────────── # ── Remove PATH entry from shell profile ─────────────────────────────────────
for PROFILE in "$HOME/.bashrc" "$HOME/.bash_profile" "$HOME/.profile"; do for PROFILE in "$HOME/.bashrc" "$HOME/.bash_profile" "$HOME/.profile"; do
if [ -f "$PROFILE" ] && grep -qF ".local/bin" "$PROFILE"; then if [ -f "$PROFILE" ] && grep -qF "# Added by ostiary installer" "$PROFILE"; then
echo "" echo ""
info "Found PATH entry in $PROFILE" info "Найдена запись PATH в $PROFILE"
read -rp " Remove the PATH line added by ostiary installer? [y/N] " answer if ask " Удалить строку PATH, добавленную установщиком?"; then
if [[ "$answer" =~ ^[Yy]$ ]]; then sed -i '/# Added by ostiary installer/d' "$PROFILE"
# Remove the comment and the export line added by install.sh sed -i '/\.local\/bin.*PATH/d' "$PROFILE"
sed -i.bak '/# Added by ostiary installer/d' "$PROFILE" ok "Запись PATH удалена из $PROFILE"
sed -i.bak '/\.local\/bin.*PATH/d' "$PROFILE"
rm -f "${PROFILE}.bak"
ok "PATH entry removed from $PROFILE"
fi fi
break break
fi fi
done done
echo "" echo ""
ok "Done" ok "Готово"