diff --git a/src/app/form.rs b/src/app/form.rs index 4f41f1c..ae2efbd 100644 --- a/src/app/form.rs +++ b/src/app/form.rs @@ -1,10 +1,46 @@ -use crate::config::{AuthMethod, JumpHop, Profile, profile_name_is_path_safe, profile_names_equal}; +use crate::config::{ + AuthMethod, JumpHop, Profile, ProfileHop, profile_name_is_path_safe, profile_names_equal, +}; use super::{ - AuthDraft, DEFAULT_PORT, FormField, KeySource, ProfileDraft, SaveMode, + AuthDraft, DEFAULT_PORT, FormField, JumpChoice, KeySource, ProfileDraft, SaveMode, helpers::{parse_endpoint_shorthand, parse_jump_chain, path_to_string}, }; +impl JumpChoice { + /// Read the selector back from a saved chain. + fn from_chain(chain: &[JumpHop]) -> Self { + match chain { + [] => Self::Direct, + [JumpHop::Profile(reference)] => Self::Profile(reference.profile_id.clone()), + _ => Self::Custom, + } + } + + /// Every choice the selector offers for the given saved profiles. + pub(super) fn options(profiles: &[Profile]) -> Vec { + let mut options = vec![Self::Direct]; + options.extend( + profiles + .iter() + .map(|profile| Self::Profile(profile.id.clone())), + ); + options.push(Self::Custom); + options + } + + /// Move `delta` steps through `options`, wrapping at both ends. + pub(super) fn cycle(&mut self, profiles: &[Profile], delta: i32) { + let options = Self::options(profiles); + let index = options + .iter() + .position(|option| option == self) + .unwrap_or(0); + let next = (index as i32 + delta).rem_euclid(options.len() as i32) as usize; + *self = options[next].clone(); + } +} + impl AuthDraft { fn from_auth(auth: &AuthMethod) -> Self { match auth { @@ -33,6 +69,7 @@ pub struct FormState { pub port: String, pub username: String, pub jump_chain: Vec, + pub jump: JumpChoice, pub auth: AuthDraft, pub field: FormField, pub cursor: usize, @@ -54,6 +91,7 @@ impl std::fmt::Debug for FormState { .field("port", &self.port) .field("username", &self.username) .field("jump_chain", &self.jump_chain) + .field("jump", &self.jump) .field("auth", &self.auth) .field("field", &self.field) .field("cursor", &self.cursor) @@ -74,6 +112,7 @@ impl FormState { port: DEFAULT_PORT.to_string(), username: "root".to_owned(), jump_chain: Vec::new(), + jump: JumpChoice::Direct, auth: AuthDraft::Password { password: String::new(), }, @@ -103,6 +142,7 @@ impl FormState { port: profile.port.to_string(), username: profile.username.clone(), jump_chain: profile.jump_chain.clone(), + jump: JumpChoice::from_chain(&profile.jump_chain), auth, field: FormField::Name, cursor: profile.name.chars().count(), @@ -118,6 +158,7 @@ impl FormState { FormField::Username, FormField::Host, FormField::Port, + FormField::Jump, FormField::Authentication, ]; match &self.auth { @@ -164,7 +205,10 @@ impl FormState { AuthDraft::Key { public_key, .. } => public_key.as_deref(), _ => None, }, - FormField::Authentication | FormField::ShowPassword | FormField::KeySource => None, + FormField::Jump + | FormField::Authentication + | FormField::ShowPassword + | FormField::KeySource => None, } } @@ -191,7 +235,10 @@ impl FormState { } _ => None, }, - FormField::Authentication | FormField::ShowPassword | FormField::KeySource => None, + FormField::Jump + | FormField::Authentication + | FormField::ShowPassword + | FormField::KeySource => None, } } @@ -289,9 +336,17 @@ impl FormState { return Err("Port must be a number between 1 and 65535".into()); } + // A chain pasted into the Host field is explicit input, so it wins + // over whatever the jump selector happens to show. let jump_chain = match jump_from_host { Some(spec) => parse_jump_chain(&spec)?, - None => self.jump_chain.clone(), + None => match &self.jump { + JumpChoice::Direct => Vec::new(), + JumpChoice::Profile(profile_id) => vec![JumpHop::Profile(ProfileHop { + profile_id: profile_id.clone(), + })], + JumpChoice::Custom => self.jump_chain.clone(), + }, }; let auth = match &self.auth { diff --git a/src/app/input/form.rs b/src/app/input/form.rs index 4d1bc71..ea225f0 100644 --- a/src/app/input/form.rs +++ b/src/app/input/form.rs @@ -107,6 +107,17 @@ impl App { } _ => {} }, + Some(FormField::Jump) => match key.code { + KeyCode::Left => { + self.cycle_jump(-1); + return AppAction::None; + } + KeyCode::Right | KeyCode::Char(' ') => { + self.cycle_jump(1); + return AppAction::None; + } + _ => {} + }, Some(FormField::KeySource) => match key.code { KeyCode::Left => { self.cycle_key_source(-1); diff --git a/src/app/input/keys.rs b/src/app/input/keys.rs index a49d26b..bbab508 100644 --- a/src/app/input/keys.rs +++ b/src/app/input/keys.rs @@ -31,6 +31,13 @@ impl App { } } + pub(super) fn cycle_jump(&mut self, delta: i32) { + let profiles = self.profiles.clone(); + if let Some(form) = self.form.as_mut() { + form.jump.cycle(&profiles, delta); + } + } + pub(crate) fn ensure_existing_key_selected(&mut self) { let first = self.available_keys.first().cloned(); let Some(form) = self.form.as_mut() else { diff --git a/src/app/mod.rs b/src/app/mod.rs index 306b2a0..7c39ad8 100644 --- a/src/app/mod.rs +++ b/src/app/mod.rs @@ -17,8 +17,8 @@ pub use form::FormState; pub use mouse::{MouseRegions, MouseTarget}; pub use state::App; pub use types::{ - AppAction, AuthDraft, DEFAULT_PORT, FormField, KeyChoice, KeySource, ProfileDraft, SaveMode, - Screen, + AppAction, AuthDraft, DEFAULT_PORT, FormField, JumpChoice, KeyChoice, KeySource, ProfileDraft, + SaveMode, Screen, }; #[cfg(test)] diff --git a/src/app/tests.rs b/src/app/tests.rs index 2e7fd85..8ba0a37 100644 --- a/src/app/tests.rs +++ b/src/app/tests.rs @@ -4,7 +4,7 @@ use crossterm::event::{ Event, KeyCode, KeyEvent, KeyModifiers, MouseButton, MouseEvent, MouseEventKind, }; -use crate::config::{AuthMethod, JumpHop, Profile}; +use crate::config::{AuthMethod, JumpHop, Profile, ProfileHop}; use super::*; @@ -773,6 +773,145 @@ fn multi_hop_paste_rejects_an_empty_hop() { ); } +#[test] +fn jump_selector_cycles_through_direct_saved_profiles_and_custom() { + let mut app = App::new(vec![profile("1", "Bastion"), profile("2", "Edge")]); + app.begin_add(); + let form = app.form_mut().unwrap(); + form.field = FormField::Jump; + + let mut seen = vec![format!("{:?}", form.jump.clone())]; + for _ in 0..3 { + app.handle_key(key(KeyCode::Right, KeyModifiers::NONE)); + seen.push(format!("{:?}", app.form().unwrap().jump.clone())); + } + + assert_eq!( + seen, + vec![ + "Direct".to_owned(), + r#"Profile("1")"#.to_owned(), + r#"Profile("2")"#.to_owned(), + "Custom".to_owned(), + ] + ); + + app.handle_key(key(KeyCode::Left, KeyModifiers::NONE)); + assert_eq!(app.form().unwrap().jump, JumpChoice::Profile("2".into())); +} + +#[test] +fn choosing_a_saved_profile_saves_it_as_the_only_hop() { + let mut app = App::new(vec![profile("1", "Bastion")]); + app.begin_add(); + { + let form = app.form_mut().unwrap(); + form.name = "Target".into(); + form.host = "10.77.0.2".into(); + form.jump = JumpChoice::Profile("1".into()); + form.auth = AuthDraft::Password { + password: "secret".into(), + }; + } + + let action = app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE)); + + assert!(matches!( + action, + AppAction::Save(ProfileDraft { jump_chain, .. }) + if jump_chain == vec![JumpHop::Profile(ProfileHop { profile_id: "1".into() })] + )); +} + +#[test] +fn choosing_direct_clears_a_saved_chain() { + let mut existing = profile("1", "Target"); + existing.jump_chain = vec![JumpHop::endpoint( + Some("root".into()), + "124.222.134.112", + 22, + )]; + let mut app = App::new(vec![existing]); + app.begin_edit(); + app.form_mut().unwrap().jump = JumpChoice::Direct; + + let draft = app.form().unwrap().draft(app.profiles()).unwrap(); + + assert!(draft.jump_chain.is_empty()); +} + +#[test] +fn pasted_jump_chain_still_wins_over_the_selector() { + let mut app = App::new(vec![profile("1", "Bastion")]); + app.begin_add(); + { + let form = app.form_mut().unwrap(); + form.name = "Target".into(); + form.host = "ssh -J root@jump-a,root@jump-b root@10.77.0.2".into(); + form.jump = JumpChoice::Direct; + form.auth = AuthDraft::Password { + password: "secret".into(), + }; + } + + let action = app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE)); + + assert!(matches!( + action, + AppAction::Save(ProfileDraft { jump_chain, .. }) if jump_chain.len() == 2 + )); +} + +#[test] +fn editing_a_profile_backed_hop_selects_that_profile() { + let target = { + let mut target = profile("2", "Target"); + target.jump_chain = vec![JumpHop::Profile(ProfileHop { + profile_id: "1".into(), + })]; + target + }; + let mut app = App::new(vec![profile("1", "Bastion"), target]); + app.select(1); + app.begin_edit(); + + assert_eq!(app.form().unwrap().jump, JumpChoice::Profile("1".into())); + assert_eq!( + app.form() + .unwrap() + .draft(app.profiles()) + .unwrap() + .jump_chain, + vec![JumpHop::Profile(ProfileHop { + profile_id: "1".into() + })] + ); +} + +#[test] +fn editing_a_pasted_chain_keeps_the_custom_choice() { + let mut existing = profile("1", "Target"); + existing.jump_chain = vec![ + JumpHop::endpoint(Some("root".into()), "jump-a", 22), + JumpHop::endpoint(Some("root".into()), "jump-b", 2222), + ]; + let mut app = App::new(vec![existing]); + app.begin_edit(); + + assert_eq!(app.form().unwrap().jump, JumpChoice::Custom); + assert_eq!( + app.form() + .unwrap() + .draft(app.profiles()) + .unwrap() + .jump_chain, + vec![ + JumpHop::endpoint(Some("root".into()), "jump-a", 22), + JumpHop::endpoint(Some("root".into()), "jump-b", 2222), + ] + ); +} + #[test] fn editing_profile_keeps_the_whole_multi_hop_chain() { let mut existing = profile("1", "one"); diff --git a/src/app/types.rs b/src/app/types.rs index a0f3154..d19a4c4 100644 --- a/src/app/types.rs +++ b/src/app/types.rs @@ -134,6 +134,7 @@ pub enum FormField { Host, Port, Username, + Jump, Authentication, Password, ShowPassword, @@ -142,6 +143,17 @@ pub enum FormField { PublicKey, } +/// What the form's jump field selects. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum JumpChoice { + /// No jump host. + Direct, + /// Use another saved profile as the only hop. + Profile(String), + /// Keep the chain pasted into the Host field, or the one already saved. + Custom, +} + impl FormField { pub(super) fn is_text(self) -> bool { matches!( diff --git a/src/ui/form/layout.rs b/src/ui/form/layout.rs index cb0a5a2..ce4eb98 100644 --- a/src/ui/form/layout.rs +++ b/src/ui/form/layout.rs @@ -25,31 +25,33 @@ pub(super) fn form_layout(area: Rect, form: &FormState) -> FormLayout { .saturating_sub(if area.width >= 48 { 4 } else { 0 }) .min(EDITOR_MAX_WIDTH); let roomy = width.saturating_sub(4) >= ROOMY_BODY_WIDTH; + // Every mode reserves one extra row above Authentication for the inline + // jump selector. let body_height = match (&form.auth, roomy) { - (AuthDraft::Password { .. }, _) => 12, + (AuthDraft::Password { .. }, _) => 13, ( AuthDraft::Key { source: KeySource::Existing, .. }, true, - ) => 16, + ) => 20, ( AuthDraft::Key { source: KeySource::Existing, .. }, false, - ) => 14, + ) => 15, ( AuthDraft::Key { source: KeySource::Paste, .. }, true, - ) => 19, - (AuthDraft::Key { .. }, true) => 17, - (AuthDraft::Key { .. }, false) => 15, + ) => 23, + (AuthDraft::Key { .. }, true) => 18, + (AuthDraft::Key { .. }, false) => 16, }; let header_height: u16 = if roomy { 3 } else { 2 }; let preferred_height = body_height + header_height + 5; @@ -244,7 +246,7 @@ mod tests { fn editor_stays_content_sized_on_large_terminals() { let app = App::new(Vec::new()); let layout = form_layout(Rect::new(0, 0, 240, 64), app.form().unwrap()); - assert_eq!(layout.editor, Rect::new(72, 22, 96, 20)); + assert_eq!(layout.editor, Rect::new(72, 21, 96, 21)); assert_parts_are_inside_editor(layout); } diff --git a/src/ui/form/sections.rs b/src/ui/form/sections.rs index 73c5761..028edd4 100644 --- a/src/ui/form/sections.rs +++ b/src/ui/form/sections.rs @@ -1,9 +1,20 @@ -use ratatui::{Frame, layout::Rect, style::Style, widgets::Paragraph}; +use ratatui::{ + Frame, + layout::Rect, + style::Style, + text::{Line, Span}, + widgets::Paragraph, +}; -use crate::app::{App, AuthDraft, FormField, FormState, KeySource, MouseRegions}; +use crate::app::{ + App, AuthDraft, FormField, FormState, JumpChoice, KeySource, MouseRegions, MouseTarget, +}; use super::{ - super::theme::MUTED, + super::{ + helpers::truncate, + theme::{ACCENT_2, MUTED, TEXT}, + }, auth::{ key_value, password_label, render_existing_key_action, render_key_sources, render_public_key, render_segmented_auth, render_show_password, @@ -67,7 +78,8 @@ pub(super) fn draw_form_fields( let (host, port) = split_trailing_field(row(area, if roomy { 3 } else { 4 }, 2), 9); input(frame, host, "Host", &form.host, FormField::Host, regions); input(frame, port, "Port", &form.port, FormField::Port, regions); - let auth_y = if roomy { 7 } else { 8 }; + let auth_y = if roomy { 8 } else { 9 }; + render_jump_selector(frame, row(area, auth_y - 2, 1), app, form, regions); hint(frame, row(area, auth_y - 1, 1), "Authentication"); render_segmented_auth(frame, row(area, auth_y, 1), form, regions); match &form.auth { @@ -149,6 +161,71 @@ pub(super) fn draw_form_fields( } } +/// Render the jump selector: `direct`, one entry per saved connection, and +/// the pasted-custom chain. +fn render_jump_selector( + frame: &mut Frame<'_>, + rect: Rect, + app: &App, + form: &FormState, + regions: &mut MouseRegions, +) { + if rect.width == 0 || rect.height == 0 { + return; + } + let active = form.field == FormField::Jump; + let label = match &form.jump { + JumpChoice::Direct => "direct".to_owned(), + JumpChoice::Profile(profile_id) => app + .profiles() + .iter() + .find(|profile| profile.id == *profile_id) + .map(|profile| profile.name.clone()) + .unwrap_or_else(|| format!("missing ({profile_id})")), + JumpChoice::Custom => custom_jump_label(form), + }; + let value_style = if active { + Style::default().fg(ACCENT_2) + } else { + Style::default().fg(TEXT) + }; + let text = Line::from(vec![ + Span::styled("Jump ", Style::default().fg(MUTED)), + Span::styled( + truncate( + &format!("‹ {label} ›"), + rect.width.saturating_sub(8) as usize, + ), + value_style, + ), + ]); + frame.render_widget( + Paragraph::new(text), + Rect::new( + rect.x + 2, + rect.y, + rect.width.saturating_sub(2), + rect.height, + ), + ); + regions.add( + rect.x, + rect.y, + rect.width, + rect.height, + MouseTarget::Field(FormField::Jump), + ); +} + +/// Summarize the pasted chain in one selector label. +fn custom_jump_label(form: &FormState) -> String { + match form.jump_chain.len() { + 0 => "custom".to_owned(), + 1 => "custom (1 hop)".to_owned(), + count => format!("custom ({count} hops)"), + } +} + fn hint(frame: &mut Frame<'_>, rect: Rect, text: &str) { frame.render_widget( Paragraph::new(text).style(Style::default().fg(MUTED)), diff --git a/src/ui/tests.rs b/src/ui/tests.rs index a5ebef7..42ce990 100644 --- a/src/ui/tests.rs +++ b/src/ui/tests.rs @@ -6,7 +6,9 @@ use crossterm::event::{ use ratatui::{Terminal, backend::TestBackend}; use crate::{ - app::{App, AppAction, AuthDraft, FormField, KeyChoice, KeySource, MouseTarget, Screen}, + app::{ + App, AppAction, AuthDraft, FormField, JumpChoice, KeyChoice, KeySource, MouseTarget, Screen, + }, config::{AuthMethod, JumpHop, Profile, ProfileHop}, }; @@ -320,6 +322,37 @@ fn browse_detail_reports_a_direct_connection() { assert!(rendered.contains("Jump direct"), "{rendered}"); } +#[test] +fn connection_form_shows_the_jump_selector() { + let mut app = App::new(vec![profile("Bastion")]); + app.begin_add(); + app.form_mut().unwrap().jump = JumpChoice::Profile("Bastion".into()); + + let backend = TestBackend::new(100, 32); + let mut terminal = Terminal::new(backend).unwrap(); + terminal.draw(|frame| draw(frame, &mut app)).unwrap(); + + let rendered = rendered_text(&terminal); + assert!(rendered.contains("Jump ‹ Bastion ›"), "{rendered}"); +} + +#[test] +fn connection_form_marks_a_missing_jump_profile() { + let mut app = App::new(Vec::new()); + app.begin_add(); + app.form_mut().unwrap().jump = JumpChoice::Profile("deleted".into()); + + let backend = TestBackend::new(100, 32); + let mut terminal = Terminal::new(backend).unwrap(); + terminal.draw(|frame| draw(frame, &mut app)).unwrap(); + + let rendered = rendered_text(&terminal); + assert!( + rendered.contains("Jump ‹ missing (deleted) ›"), + "{rendered}" + ); +} + #[test] fn responsive_layouts_render_at_supported_terminal_sizes() { for (width, height) in [(100, 32), (72, 24), (60, 24), (40, 22)] {