use crate::config::EnvProfile;
use crate::tui::commands;
use crate::tui::state::{
AppState, ConfirmAction, FilterTarget, Overlay, PromptAction, RenameOutcome, SaveOutcome,
};
use crate::tui::view::Tab;
use anyhow::Result;
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Action {
None,
Quit,
Copy(String),
}
const PAGE: usize = 10;
fn ctrl(key: &KeyEvent) -> bool {
key.modifiers.contains(KeyModifiers::CONTROL)
}
fn alt(key: &KeyEvent) -> bool {
key.modifiers.contains(KeyModifiers::ALT)
}
fn ctrl_char(key: &KeyEvent, c: char) -> bool {
ctrl(key) && matches!(key.code, KeyCode::Char(k) if k.eq_ignore_ascii_case(&c))
}
pub fn handle_key(app: &mut AppState, key: KeyEvent) -> Result<Action> {
if app.overlay.is_some() {
return handle_overlay(app, key);
}
let armed = std::mem::take(&mut app.discard_armed);
if ctrl_char(&key, 'c') || ctrl_char(&key, 'q') {
return Ok(request_quit(app));
}
if ctrl_char(&key, 'p') {
commands::open_palette(app);
return Ok(Action::None);
}
if ctrl_char(&key, 's') {
save_tab(app, app.tab)?;
return Ok(Action::None);
}
if let (true, KeyCode::Char(c)) = (alt(&key), key.code) {
if let Some(tab) = Tab::from_digit(c) {
switch_tab(app, tab);
return Ok(Action::None);
}
}
if key.code == KeyCode::BackTab {
switch_tab(app, app.tab.prev());
return Ok(Action::None);
}
if key.code == KeyCode::Tab {
if app.completion.is_some() {
app.accept_completion();
return Ok(Action::None);
}
switch_tab(app, app.tab.next());
return Ok(Action::None);
}
if app.tab.is_buffer() {
handle_buffer(app, key, armed);
return Ok(Action::None);
}
match app.tab {
Tab::Profiles => handle_profiles(app, key),
Tab::Export => Ok(handle_export(app, key)),
_ => Ok(handle_help(app, key)),
}
}
pub fn handle_paste(app: &mut AppState, text: &str) {
let first = text.lines().next().unwrap_or("");
match &mut app.overlay {
Some(Overlay::Palette { input, .. })
| Some(Overlay::Prompt { input, .. })
| Some(Overlay::Picker { input, .. }) => input.push_str(first),
Some(Overlay::Filter { target }) => match target {
FilterTarget::Profiles => app.profiles_filter.push_str(first),
FilterTarget::Known => app.known_filter.push_str(first),
},
Some(Overlay::Confirm { .. }) => {}
None => {
let tab = app.tab;
let Some(buf) = app.buffer_mut(tab) else {
return;
};
buf.insert_str(text);
app.completion = None;
app.status.clear();
}
}
}
fn switch_tab(app: &mut AppState, tab: Tab) {
app.completion = None;
if app.tab != tab {
app.scroll = 0;
}
app.tab = tab;
}
pub fn request_quit(app: &mut AppState) -> Action {
let modified = app.modified_tabs();
if modified.is_empty() {
return Action::Quit;
}
commands::confirm(
app,
format!("quit without saving {}?", modified.join(", ")),
ConfirmAction::Quit,
);
Action::None
}
pub fn save_tab(app: &mut AppState, tab: Tab) -> Result<()> {
app.status = match app.save(tab)? {
SaveOutcome::Saved(message) | SaveOutcome::Blocked(message) => message,
SaveOutcome::Unchanged => "nothing to save".to_string(),
SaveOutcome::Invalid { line, message } => {
if let Some(buf) = app.buffer_mut(tab) {
buf.goto(line);
}
format!("not saved, line {}: {message}", line + 1)
}
};
Ok(())
}
pub fn use_profile_checked(app: &mut AppState, index: usize) {
if app.env.is_modified() && index != app.active_profile_index {
let message = format!(
"switch to {} and discard unsaved changes in {}?",
app.profiles[index].name,
app.env_title()
);
commands::confirm(app, message, ConfirmAction::UseProfile(index));
return;
}
use_profile_now(app, index);
}
fn use_profile_now(app: &mut AppState, index: usize) {
app.use_profile(index);
app.tab = Tab::Env;
app.status = format!("using {}", app.active_profile().name);
}
fn target_profile(app: &AppState) -> usize {
match app.tab {
Tab::Profiles => app.selected_profile().unwrap_or(app.active_profile_index),
_ => app.active_profile_index,
}
}
pub fn open_profile_prompt(app: &mut AppState, duplicate: bool) {
let index = target_profile(app);
let name = app.profiles[index].name.clone();
if !duplicate {
app.overlay = Some(Overlay::Prompt {
action: PromptAction::Rename(index),
input: name,
});
return;
}
app.overlay = Some(Overlay::Prompt {
action: PromptAction::Duplicate(index),
input: format!("{name}-copy"),
});
}
pub fn confirm_delete_profile(app: &mut AppState) {
if app.profiles.len() <= 1 {
app.status = "cannot delete the last profile".to_string();
return;
}
let index = target_profile(app);
let message = format!("delete profile {}?", app.profiles[index].name);
commands::confirm(app, message, ConfirmAction::DeleteProfile(index));
}
fn handle_buffer(app: &mut AppState, key: KeyEvent, armed: bool) {
let tab = app.tab;
if key.code == KeyCode::Esc {
escape(app, tab, armed);
return;
}
if let Some(c) = &mut app.completion {
let len = c.items.len();
match key.code {
KeyCode::Up => {
c.selected = (c.selected + len - 1) % len;
return;
}
KeyCode::Down => {
c.selected = (c.selected + 1) % len;
return;
}
_ => {}
}
}
if ctrl_char(&key, 'l') && tab == Tab::Env {
app.completion = None;
app.overlay = Some(Overlay::Picker {
input: String::new(),
selected: 0,
});
return;
}
if ctrl_char(&key, 'f') && tab == Tab::Defs {
app.overlay = Some(Overlay::Filter {
target: FilterTarget::Known,
});
return;
}
let indent = match (key.code, tab) {
(KeyCode::Enter, Tab::Env) => app.env_indent(),
_ => 0,
};
let Some(buf) = app.buffer_mut(tab) else {
return;
};
let edited = match (key.code, ctrl(&key), alt(&key)) {
(KeyCode::Char('k' | 'K'), true, _) => {
buf.delete_line();
true
}
(KeyCode::Char('d' | 'D'), true, _) => {
buf.duplicate_line();
true
}
(KeyCode::Char('z' | 'Z'), true, _) => buf.undo(),
(KeyCode::Up, _, true) => {
buf.move_line_up();
true
}
(KeyCode::Down, _, true) => {
buf.move_line_down();
true
}
(KeyCode::Char(c), false, false) => {
buf.insert_char(c);
true
}
(KeyCode::Enter, _, _) => {
if !buf.clear_indent_line() {
buf.newline(indent);
}
true
}
(KeyCode::Backspace, _, _) => {
buf.backspace();
true
}
(KeyCode::Delete, _, _) => {
buf.delete();
true
}
(KeyCode::Left, _, _) => {
buf.left();
false
}
(KeyCode::Right, _, _) => {
buf.right();
false
}
(KeyCode::Up, _, _) => {
buf.up(1);
false
}
(KeyCode::Down, _, _) => {
buf.down(1);
false
}
(KeyCode::PageUp, _, _) => {
buf.up(PAGE);
false
}
(KeyCode::PageDown, _, _) => {
buf.down(PAGE);
false
}
(KeyCode::Home, _, _) => {
buf.home();
false
}
(KeyCode::End, _, _) => {
buf.end();
false
}
_ => return,
};
if !edited {
app.completion = None;
return;
}
app.status.clear();
app.update_completion();
}
fn escape(app: &mut AppState, tab: Tab, armed: bool) {
if app.completion.take().is_some() {
return;
}
let modified = app.buffer(tab).is_some_and(|b| b.is_modified());
if !modified {
return;
}
if armed {
app.revert(tab);
app.status = "discarded unsaved changes".to_string();
return;
}
app.discard_armed = true;
app.status = "press Esc again to discard unsaved changes".to_string();
}
fn handle_profiles(app: &mut AppState, key: KeyEvent) -> Result<Action> {
let len = app.visible_profiles().len();
let selected = app.profile_list.selected().unwrap_or(0);
let last = len.saturating_sub(1);
match key.code {
KeyCode::Char('j') | KeyCode::Down => {
app.profile_list.select(Some((selected + 1).min(last)))
}
KeyCode::Char('k') | KeyCode::Up => {
app.profile_list.select(Some(selected.saturating_sub(1)))
}
KeyCode::Char('g') | KeyCode::Home => app.profile_list.select(Some(0)),
KeyCode::Char('G') | KeyCode::End => app.profile_list.select(Some(last)),
KeyCode::Enter => {
if let Some(index) = app.selected_profile() {
use_profile_checked(app, index);
}
}
KeyCode::Char('a' | 'A' | 'n') => {
app.overlay = Some(Overlay::Prompt {
action: PromptAction::Add,
input: String::new(),
});
}
KeyCode::Char('e' | 'E' | 'r') | KeyCode::F(2) => open_profile_prompt(app, false),
KeyCode::Char('y' | 'Y') => open_profile_prompt(app, true),
KeyCode::Char('d' | 'D') | KeyCode::Delete => confirm_delete_profile(app),
KeyCode::Char('/') => {
app.overlay = Some(Overlay::Filter {
target: FilterTarget::Profiles,
});
}
KeyCode::Esc => {
app.profiles_filter.clear();
app.profile_list.select(Some(0));
}
KeyCode::Char(':') => commands::open_palette(app),
KeyCode::Char('q') => return Ok(request_quit(app)),
_ => {}
}
Ok(Action::None)
}
fn scroll(app: &mut AppState, key: &KeyEvent) -> bool {
let step = match key.code {
KeyCode::Char('j') | KeyCode::Down => 1i32,
KeyCode::Char('k') | KeyCode::Up => -1,
KeyCode::PageDown | KeyCode::Char(' ') => PAGE as i32,
KeyCode::PageUp => -(PAGE as i32),
KeyCode::Char('g') | KeyCode::Home => -(app.scroll as i32),
_ => return false,
};
app.scroll = (app.scroll as i32 + step).max(0) as u16;
true
}
fn handle_export(app: &mut AppState, key: KeyEvent) -> Action {
if scroll(app, &key) {
return Action::None;
}
match key.code {
KeyCode::Char('m') => app.cycle_export_mode(),
KeyCode::Char('y') => {
app.status = "copied export to the clipboard".to_string();
return Action::Copy(app.export_text());
}
KeyCode::Char(':') => commands::open_palette(app),
KeyCode::Char('q') => return request_quit(app),
_ => {}
}
Action::None
}
fn handle_help(app: &mut AppState, key: KeyEvent) -> Action {
if scroll(app, &key) {
return Action::None;
}
match key.code {
KeyCode::Char(':') => commands::open_palette(app),
KeyCode::Char('q') => return request_quit(app),
_ => {}
}
Action::None
}
fn edit_text(input: &mut String, key: &KeyEvent) -> bool {
if ctrl_char(key, 'u') {
input.clear();
return true;
}
match (key.code, ctrl(key)) {
(KeyCode::Char(c), false) => {
input.push(c);
true
}
(KeyCode::Backspace, _) => input.pop().is_some(),
_ => false,
}
}
fn handle_overlay(app: &mut AppState, key: KeyEvent) -> Result<Action> {
let Some(overlay) = app.overlay.take() else {
return Ok(Action::None);
};
if ctrl_char(&key, 'c') {
return Ok(Action::None);
}
match overlay {
Overlay::Palette { input, selected } => palette_key(app, key, input, selected),
Overlay::Prompt { action, input } => {
prompt_key(app, key, action, input)?;
Ok(Action::None)
}
Overlay::Confirm { message, action } => confirm_key(app, key, message, action),
Overlay::Picker { input, selected } => {
picker_key(app, key, input, selected);
Ok(Action::None)
}
Overlay::Filter { target } => {
filter_key(app, key, target);
Ok(Action::None)
}
}
}
fn palette_key(
app: &mut AppState,
key: KeyEvent,
mut input: String,
mut selected: usize,
) -> Result<Action> {
match key.code {
KeyCode::Esc => return Ok(Action::None),
KeyCode::Enter => {
let line = commands::pick(app, &input, selected);
return commands::execute(app, &line);
}
KeyCode::Tab => {
let list = commands::suggestions(app, &input);
if let Some(s) = list.get(commands::clamp_selection(selected, list.len())) {
input = s.text.clone();
if commands::takes_argument(&input) {
input.push(' ');
}
selected = 0;
}
}
KeyCode::Up => selected = selected.saturating_sub(1),
KeyCode::Down => selected += 1,
_ => {
if edit_text(&mut input, &key) {
selected = 0;
}
}
}
let len = commands::suggestions(app, &input).len();
selected = commands::clamp_selection(selected, len);
app.overlay = Some(Overlay::Palette { input, selected });
Ok(Action::None)
}
fn select_profile_named(app: &mut AppState, name: &str) {
app.profiles_filter.clear();
let index = app.profiles.iter().position(|p| p.name == name);
app.profile_list.select(index);
}
fn prompt_key(
app: &mut AppState,
key: KeyEvent,
action: PromptAction,
mut input: String,
) -> Result<()> {
match key.code {
KeyCode::Esc => return Ok(()),
KeyCode::Enter => {
let name = input.trim().to_string();
let done = submit_prompt(app, &action, &name)?;
if done {
return Ok(());
}
}
_ => {
edit_text(&mut input, &key);
}
}
app.overlay = Some(Overlay::Prompt { action, input });
Ok(())
}
fn submit_prompt(app: &mut AppState, action: &PromptAction, name: &str) -> Result<bool> {
let ok = match action {
PromptAction::Add => app.add_profile(EnvProfile::new(name))?,
PromptAction::Duplicate(index) => app.duplicate_profile(*index, name)?,
PromptAction::Rename(index) => match app.update_profile(*index, name.to_string())? {
RenameOutcome::Renamed => true,
RenameOutcome::Unchanged => return Ok(true),
RenameOutcome::Rejected => false,
},
};
if !ok {
app.status = format!("'{name}' is blank or already taken");
return Ok(false);
}
select_profile_named(app, name);
app.status = match action {
PromptAction::Add => format!("added profile {name}"),
PromptAction::Duplicate(index) => {
format!("copied {} to {name}", app.profiles[*index].name)
}
PromptAction::Rename(_) => format!("renamed to {name}"),
};
Ok(true)
}
fn confirm_key(
app: &mut AppState,
key: KeyEvent,
message: String,
action: ConfirmAction,
) -> Result<Action> {
match key.code {
KeyCode::Char('y' | 'Y') | KeyCode::Enter => {}
KeyCode::Char('n' | 'N') | KeyCode::Esc => return Ok(Action::None),
_ => {
app.overlay = Some(Overlay::Confirm { message, action });
return Ok(Action::None);
}
}
match action {
ConfirmAction::Quit => return Ok(Action::Quit),
ConfirmAction::UseProfile(index) => use_profile_now(app, index),
ConfirmAction::DeleteProfile(index) => {
let name = app.profiles[index].name.clone();
if app.delete_profile(index)? {
app.status = format!("deleted profile {name}");
}
let last = app.visible_profiles().len().saturating_sub(1);
let selected = app.profile_list.selected().unwrap_or(0).min(last);
app.profile_list.select(Some(selected));
}
}
Ok(Action::None)
}
fn picker_key(app: &mut AppState, key: KeyEvent, mut input: String, mut selected: usize) {
match key.code {
KeyCode::Esc => return,
KeyCode::Enter => {
let items = app.picker_items(&input);
let Some(item) = items.get(selected.min(items.len().saturating_sub(1))) else {
return;
};
let value = item.value.clone();
app.env.insert_str(&value);
app.status = format!("inserted {value}");
return;
}
KeyCode::Up => selected = selected.saturating_sub(1),
KeyCode::Down => selected += 1,
_ => {
if edit_text(&mut input, &key) {
selected = 0;
}
}
}
let len = app.picker_items(&input).len();
selected = selected.min(len.saturating_sub(1));
app.overlay = Some(Overlay::Picker { input, selected });
}
fn filter_key(app: &mut AppState, key: KeyEvent, target: FilterTarget) {
let filter = match target {
FilterTarget::Profiles => &mut app.profiles_filter,
FilterTarget::Known => &mut app.known_filter,
};
match key.code {
KeyCode::Enter => return,
KeyCode::Esc => {
filter.clear();
app.profile_list.select(Some(0));
return;
}
_ => {
edit_text(filter, &key);
}
}
app.profile_list.select(Some(0));
app.overlay = Some(Overlay::Filter { target });
}
#[cfg(test)]
mod tests {
use super::*;
use crate::db;
use crate::tui::state::tests::test_app;
fn press(app: &mut AppState, code: KeyCode) -> Action {
handle_key(app, KeyEvent::new(code, KeyModifiers::NONE)).unwrap()
}
fn chord(app: &mut AppState, code: KeyCode, modifiers: KeyModifiers) -> Action {
handle_key(app, KeyEvent::new(code, modifiers)).unwrap()
}
fn type_keys(app: &mut AppState, text: &str) {
for c in text.chars() {
press(app, KeyCode::Char(c));
}
}
#[test]
fn shift_tab_cycles_back_and_alt_digit_jumps() {
let mut app = test_app(&["work"]);
press(&mut app, KeyCode::BackTab);
assert_eq!(app.tab, Tab::Help);
press(&mut app, KeyCode::BackTab);
assert_eq!(app.tab, Tab::Export);
chord(&mut app, KeyCode::Char('3'), KeyModifiers::ALT);
assert_eq!(app.tab, Tab::Library);
press(&mut app, KeyCode::Tab);
assert_eq!(app.tab, Tab::Defs);
}
#[test]
fn tab_accepts_completion_before_switching_tabs() {
let mut app = test_app(&["work"]);
type_keys(&mut app, "PGHO");
assert!(app.completion.is_some());
press(&mut app, KeyCode::Tab);
assert_eq!(app.tab, Tab::Env);
assert_eq!(app.env.current_line(), "PGHOST = ");
}
#[test]
fn typing_q_in_env_inserts_text() {
let mut app = test_app(&["work"]);
assert_eq!(press(&mut app, KeyCode::Char('q')), Action::None);
assert_eq!(app.env.current_line(), "q");
}
#[test]
fn esc_twice_discards_changes() {
let mut app = test_app(&["work"]);
type_keys(&mut app, "CC = clang");
press(&mut app, KeyCode::Esc);
assert!(app.env.is_modified());
press(&mut app, KeyCode::Esc);
assert!(!app.env.is_modified());
}
#[test]
fn esc_then_typing_disarms_discard() {
let mut app = test_app(&["work"]);
type_keys(&mut app, "CC = clang");
press(&mut app, KeyCode::Esc);
type_keys(&mut app, "x");
press(&mut app, KeyCode::Esc);
assert!(app.env.is_modified());
}
#[test]
fn ctrl_s_saves_and_reports_errors_with_line() -> Result<()> {
let mut app = test_app(&["work"]);
type_keys(&mut app, "CC = clang");
press(&mut app, KeyCode::Enter);
type_keys(&mut app, "PGP");
chord(&mut app, KeyCode::Char('s'), KeyModifiers::CONTROL);
assert!(app.status.contains("line 2"));
assert_eq!(app.env.row, 1);
press(&mut app, KeyCode::Backspace);
press(&mut app, KeyCode::Backspace);
press(&mut app, KeyCode::Backspace);
chord(&mut app, KeyCode::Char('s'), KeyModifiers::CONTROL);
assert_eq!(db::load_profile(&app.conn, "work")?.entries.len(), 1);
Ok(())
}
#[test]
fn quit_with_unsaved_changes_asks_first() {
let mut app = test_app(&["work"]);
assert_eq!(
chord(&mut app, KeyCode::Char('q'), KeyModifiers::CONTROL),
Action::Quit
);
type_keys(&mut app, "CC = clang");
assert_eq!(
chord(&mut app, KeyCode::Char('c'), KeyModifiers::CONTROL),
Action::None
);
assert!(matches!(app.overlay, Some(Overlay::Confirm { .. })));
assert_eq!(press(&mut app, KeyCode::Char('y')), Action::Quit);
}
#[test]
fn y_on_profiles_duplicates_with_prefilled_name() -> Result<()> {
let mut app = test_app(&["work"]);
app.tab = Tab::Profiles;
press(&mut app, KeyCode::Char('y'));
assert!(matches!(
&app.overlay,
Some(Overlay::Prompt { input, .. }) if input == "work-copy"
));
press(&mut app, KeyCode::Enter);
assert!(app.overlay.is_none());
assert_eq!(app.profiles.len(), 2);
assert!(db::load_profile(&app.conn, "work-copy").is_ok());
Ok(())
}
#[test]
fn palette_alias_runs_command() {
let mut app = test_app(&["work"]);
app.tab = Tab::Help;
chord(&mut app, KeyCode::Char('p'), KeyModifiers::CONTROL);
type_keys(&mut app, "ai");
press(&mut app, KeyCode::Enter);
assert!(app.overlay.is_none());
assert_eq!(app.tab, Tab::Library);
}
#[test]
fn switching_profile_with_unsaved_env_asks_first() {
let mut app = test_app(&["a", "b"]);
type_keys(&mut app, "CC = clang");
app.tab = Tab::Profiles;
press(&mut app, KeyCode::Char('j'));
press(&mut app, KeyCode::Enter);
assert!(matches!(app.overlay, Some(Overlay::Confirm { .. })));
press(&mut app, KeyCode::Char('n'));
assert_eq!(app.active_profile_index, 0);
press(&mut app, KeyCode::Enter);
press(&mut app, KeyCode::Char('y'));
assert_eq!(app.active_profile_index, 1);
assert_eq!(app.tab, Tab::Env);
}
#[test]
fn enter_on_empty_list_line_ends_the_list() {
let mut app = test_app(&["work"]);
type_keys(&mut app, "PATH = /a");
press(&mut app, KeyCode::Enter);
type_keys(&mut app, "/b");
press(&mut app, KeyCode::Enter);
press(&mut app, KeyCode::Enter);
type_keys(&mut app, "CC = clang");
assert_eq!(app.env.lines(), &["PATH = /a", " /b", "CC = clang"]);
}
#[test]
fn paste_inserts_multiple_lines() {
let mut app = test_app(&["work"]);
handle_paste(&mut app, "PATH = /a\n /b");
assert_eq!(app.env.lines(), &["PATH = /a", " /b"]);
}
#[test]
fn export_y_returns_copy_action() {
let mut app = test_app(&["work"]);
app.tab = Tab::Export;
assert!(matches!(
press(&mut app, KeyCode::Char('y')),
Action::Copy(_)
));
}
}