Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,14 @@ TUI keys: arrows or hjkl move, type or `=` to enter, Enter/F2 edit, Tab commit
right, Del clear, Ctrl+Z / Ctrl+Y undo and redo, `[` `]` switch sheet, `<` `>`
column width, `g` go to, `:w file.xlsx` save as, `:q` quit, `?` all keys.

**Quitting:** Ctrl+Q, `:q` then Enter, or Ctrl+C twice (the first Ctrl+C copies).
With unsaved changes it asks once; press it again, or `:q!` to discard.

**Commands:** press `:` and the bottom line becomes `CMD :` — type the command
there and press Enter: `:w report.xlsx` saves as, `:e other.xlsx` opens, `:q`
quits, `:sort B desc`, `:filter C > 100`. Esc cancels. The key hints on the
bottom line are buttons too: click `: cmd`, `^S save` or `^Q quit`.

## Mouse, selection, sort and filter

- **Select:** click a cell, drag for a range, Shift+click to extend,
Expand Down
5 changes: 5 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,11 @@ mod tests {
let e = Engine::new().unwrap();
let _e = crate::tui::mouse_flow_for_test(e);
}
// Quitting and finding the command line (Ctrl+C twice, Esc hint, clickable hints).
{
let e = Engine::new().unwrap();
let _e = crate::tui::quit_flow_for_test(e);
}

// Sort and filter without the TUI: CLI `sort` / `cat --where`, MCP `sort_range` / `read_range` `where`.
{
Expand Down
190 changes: 172 additions & 18 deletions src/tui.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,9 @@ const HELP: &[(&str, &str)] = &[
(":sheet NAME", "switch sheet (:addsheet :delsheet :rename NEW)"),
(":ir :dr :ic :dc", "insert / delete row or column at the cursor"),
(":q :q! Ctrl+Q", "quit (:q! discards changes)"),
("Ctrl+C Ctrl+C", "quit (the first Ctrl+C copies; twice quits)"),
(":", "command line at the bottom: w FILE, e FILE, q, sort, filter"),
("click the bottom bar", "the hints are buttons: help, cmd, ask, save, quit"),
];

/// Width of the " [Ask] " button at the right end of the formula bar.
Expand Down Expand Up @@ -104,6 +107,8 @@ struct State {
help_top: usize,
clip: Option<Clip>,
quit_armed: bool,
/// Ctrl+C was just pressed (and copied): a second Ctrl+C quits.
ctrl_c_armed: bool,
quit: bool,
// geometry from the last frame, for mouse hit testing and paging
grid_y: usize,
Expand Down Expand Up @@ -219,6 +224,7 @@ fn new_state(engine: Engine, path: Option<PathBuf>, message: String) -> State {
help_top: 0,
clip: None,
quit_armed: false,
ctrl_c_armed: false,
quit: false,
grid_y: 3,
grid_rows: 20,
Expand Down Expand Up @@ -573,7 +579,7 @@ fn view(ui: &mut Container<'_>, s: Snapshot) {
let st = Style::new().with_bg(t.surface);
surface.fill_rect(0, sy, width, 1, &st, ' '.into());
let mx = surface.text(0, sy, &format!(" {} ", s.mode_label), &TextOptions::new().fg(t.background).bg(t.primary).attrs(Attrs::BOLD));
let hint = if s.info.is_empty() { "? help ^K ask ^S save ^Q quit " } else { "? help " };
let hint = hints(s.mode_label == "CMD", !s.info.is_empty());
let hint_x = width.saturating_sub(hint.len());
surface.text(hint_x as isize, sy, hint, &TextOptions::new().fg(t.muted).bg(t.surface));
let mut msg_room = hint_x.saturating_sub(mx + 2);
Expand Down Expand Up @@ -852,7 +858,86 @@ fn drag_cell(st: &State, x: usize, y: usize) -> (usize, usize) {
(r, c)
}

/// Key hints at the right of the status bar. Each `key word` pair is also a
/// click target (see `hint_click`), so the way out is always on screen.
fn hints(command: bool, has_info: bool) -> &'static str {
if command {
"Enter run Esc cancel w FILE save as q quit e FILE open "
} else if has_info {
"? help : cmd ^Q quit "
} else {
"? help : cmd ^K ask ^S save ^Q quit "
}
}

/// Quit, or ask first when there are unsaved changes (Ctrl+Q, Ctrl+C twice, a click).
fn quit_request(st: &mut State) {
if st.dirty && !st.quit_armed {
st.quit_armed = true;
err(st, "unsaved changes: Ctrl+Q again to quit without saving, Ctrl+S to save");
} else {
st.quit = true;
}
}

/// A click on the status-bar hints runs that hint.
fn hint_click(st: &mut State, x: usize) -> bool {
let has_info = !filter_status(st).is_empty() || !summary(st).is_empty();
let hint = hints(st.mode == Mode::Command, has_info);
let x0 = st.width.saturating_sub(hint.len());
if x < x0 {
return false;
}
let off = x - x0;
// Hints are separated by two spaces; find the one under the click.
let mut start = 0;
for item in hint.trim_end().split(" ") {
let end = start + item.len();
if off >= start && off < end {
match item {
"? help" => st.help = true,
": cmd" => {
st.mode = Mode::Command;
st.buf.clear();
st.caret = 0;
}
"^K ask" => ask_key_normal(st),
"^S save" => command(st, "w"),
"^Q quit" | "q quit" => {
st.mode = Mode::Normal;
quit_request(st);
}
"Esc cancel" => {
st.mode = Mode::Normal;
info(st, "");
}
"Enter run" => {
let line: String = st.buf.iter().collect();
st.mode = Mode::Normal;
command(st, &line);
}
"w FILE save as" => {
st.buf = "w ".chars().collect();
st.caret = 2;
}
"e FILE open" => {
st.buf = "e ".chars().collect();
st.caret = 2;
}
_ => {}
}
return true;
}
start = end + 2;
}
false
}

fn mouse(st: &mut State, m: &MouseEvent) {
// Status-bar hints (bottom line) are buttons.
if m.action == MouseAction::Press && m.button == MouseButton::Left && m.y == st.grid_y + st.grid_rows && hint_click(st, m.x) {
return;
}
// The [Ask] button at the right end of the formula bar.
let on_button = m.action == MouseAction::Press
&& m.button == MouseButton::Left
Expand Down Expand Up @@ -1195,9 +1280,12 @@ fn key(st: &mut State, k: &KeyEvent) {
}
return;
}
if k.key != "ctrl+q" {
if k.key != "ctrl+q" && k.key != "ctrl+c" {
st.quit_armed = false;
}
if k.key != "ctrl+c" {
st.ctrl_c_armed = false;
}
if st.asking.is_some() {
// Only Esc means something while c0mpute is thinking.
if k.key == "escape" {
Expand All @@ -1211,7 +1299,7 @@ fn key(st: &mut State, k: &KeyEvent) {
match st.mode {
Mode::Edit => match k.key.as_str() {
"ctrl+k" => start_ask(st),
"escape" => {
"escape" | "ctrl+c" => {
st.mode = Mode::Normal;
info(st, "edit cancelled");
}
Expand Down Expand Up @@ -1240,7 +1328,7 @@ fn key(st: &mut State, k: &KeyEvent) {
}
},
Mode::Command | Mode::Goto => match k.key.as_str() {
"escape" => {
"escape" | "ctrl+c" => {
st.mode = Mode::Normal;
info(st, "");
}
Expand Down Expand Up @@ -1296,14 +1384,24 @@ fn normal_key(st: &mut State, k: &KeyEvent) {
"escape" => {
st.sel.select(st.row, st.col);
st.drag = None;
info(st, "");
info(st, "Ctrl+Q or :q quits : runs a command (:w file.xlsx saves as) ? shows every key");
}
"enter" | "f2" => start_edit(st, None),
"ctrl+k" => ask_key_normal(st),
"delete" | "backspace" => clear_selection(st),
"ctrl+z" | "u" => undo(st),
"ctrl+y" | "ctrl+r" => redo(st),
"ctrl+c" => copy(st),
"ctrl+c" => {
if st.ctrl_c_armed {
st.ctrl_c_armed = false;
quit_request(st);
} else {
copy(st);
st.ctrl_c_armed = true;
let m = format!("{} Ctrl+C again to quit", st.message);
info(st, m);
}
}
"ctrl+v" => paste_clip(st),
"s" | "S" => {
let spec = if k.key == "S" { "desc" } else { "" };
Expand All @@ -1314,14 +1412,7 @@ fn normal_key(st: &mut State, k: &KeyEvent) {
}
"f" => toggle_filter(st),
"ctrl+s" => command(st, "w"),
"ctrl+q" => {
if st.dirty && !st.quit_armed {
st.quit_armed = true;
err(st, "unsaved changes: Ctrl+Q again to quit, Ctrl+S to save");
} else {
st.quit = true;
}
}
"ctrl+q" => quit_request(st),
":" => {
st.mode = Mode::Command;
st.buf.clear();
Expand Down Expand Up @@ -1649,6 +1740,63 @@ pub(crate) fn ask_flow_for_test(engine: Engine) -> Engine {

/// Drive selection, sort, filter and the clipboard headlessly through the real
/// input parser (SGR mouse reports and key bytes, as a terminal sends them).
#[cfg(test)]
/// Getting out and finding the command line: Ctrl+C twice, Esc hint, clickable hints.
pub(crate) fn quit_flow_for_test(engine: Engine) -> Engine {
let (w, h) = (100, 20);
let key = |name: &str, ctrl: bool| {
let k = if ctrl { format!("ctrl+{name}") } else { name.to_string() };
InputEvent::Key(KeyEvent { name: name.into(), ctrl, alt: false, shift: false, char: None, key: k, raw: String::new() })
};
let mut st = new_state(engine, None, String::new());
layout(&mut st, w, h);

// Ctrl+C copies and says how to quit; another key disarms; Ctrl+C twice quits.
handle(&mut st, key("c", true));
assert!(!st.quit && st.message.contains("Ctrl+C again to quit"), "{}", st.message);
handle(&mut st, key("down", false));
handle(&mut st, key("c", true));
assert!(!st.quit, "a key in between disarms the second Ctrl+C");
handle(&mut st, key("c", true));
assert!(st.quit, "Ctrl+C twice quits a clean sheet");

// Ctrl+C cancels an edit instead of copying.
st.quit = false;
handle(&mut st, key("enter", false));
assert!(st.mode == Mode::Edit);
handle(&mut st, key("c", true));
assert!(st.mode == Mode::Normal && !st.quit);

// Esc in the grid tells you how to quit and where commands go.
handle(&mut st, key("escape", false));
assert!(st.message.contains(":q") && st.message.contains(":w"), "{}", st.message);

// The bottom-bar hints are buttons: ": cmd" opens the command line, "q quit" quits.
let bar_y = st.grid_y + st.grid_rows;
let hint = hints(false, false);
let at = |word: &str| st.width - hint.len() + hint.find(word).unwrap() + 1;
let click = |x: usize| InputEvent::Mouse(MouseEvent { action: MouseAction::Press, button: MouseButton::Left, x, y: bar_y, scroll: 0, ctrl: false, alt: false, shift: false });
let cmd_x = at(": cmd");
handle(&mut st, click(cmd_x));
assert!(st.mode == Mode::Command, "clicking `: cmd` opens the command line");
let chint = hints(true, false);
let wx = st.width - chint.len() + chint.find("w FILE").unwrap() + 1;
handle(&mut st, click(wx));
assert_eq!(st.buf.iter().collect::<String>(), "w ", "clicking `w FILE save as` starts the command");
handle(&mut st, key("escape", false));

// Unsaved changes: the first quit asks, the second quits.
st.engine.set(1, 1, "42").unwrap();
st.dirty = true;
st.quit = false;
let qx = st.width - hint.len() + hint.find("^Q quit").unwrap() + 1;
handle(&mut st, click(qx));
assert!(!st.quit && st.message.contains("unsaved"), "{}", st.message);
handle(&mut st, key("q", true));
assert!(st.quit, "second Ctrl+Q quits");
st.engine
}

#[cfg(test)]
pub(crate) fn mouse_flow_for_test(mut engine: Engine) -> Engine {
use hqtui::InputParser;
Expand Down Expand Up @@ -1885,10 +2033,16 @@ pub(crate) fn mouse_flow_for_test(mut engine: Engine) -> Engine {
feed(&mut st, "?");
let text = screen(&mut st).text();
assert!(text.contains("Ctrl or Alt+click") && text.contains("PgDn more"), "{text}");
feed(&mut st, "\x1b[6~\x1b[6~");
assert!(st.help, "PgDn pages the help");
let text = screen(&mut st).text();
assert!(text.contains(":filter C > 100") && text.contains(":q :q! Ctrl+Q"), "{text}");
// Page through the help; every key line shows on some page.
let mut pages = String::new();
for _ in 0..2 {
feed(&mut st, "\x1b[6~");
assert!(st.help, "PgDn pages the help");
pages.push_str(&screen(&mut st).text());
}
for want in [":filter C > 100", ":q :q! Ctrl+Q", "Ctrl+C Ctrl+C", "click the bottom bar"] {
assert!(pages.contains(want), "{want} missing from help pages:\n{pages}");
}
feed(&mut st, "q");
assert!(!st.help);
st.engine
Expand Down
Loading