diff options
Diffstat (limited to '')
| -rw-r--r-- | src/config.rs | 111 | ||||
| -rw-r--r-- | src/main.rs | 165 |
2 files changed, 217 insertions, 59 deletions
diff --git a/src/config.rs b/src/config.rs index c1b00ae..3532f80 100644 --- a/src/config.rs +++ b/src/config.rs @@ -16,7 +16,7 @@ pub struct Config { pub muted: u32, pub border: u32, pub show_status_bar: bool, - pub status_bar_toggle: String, + pub shortcuts: HashMap<String, String>, pub width: f32, pub height: f32, pub scrollback: usize, @@ -44,9 +44,51 @@ pub fn color(s: &str) -> Result<u32> { Ok(u32::from_str_radix(s, 16)?) } impl Config { + pub fn action_for(&self, key: &gpui::Keystroke) -> Option<String> { + self.shortcuts.iter().find_map(|(binding, action)| { + let parsed = gpui::Keystroke::parse(binding).ok()?; + (parsed.modifiers == key.modifiers && parsed.key.eq_ignore_ascii_case(&key.key)) + .then(|| action.clone()) + }) + } + pub fn shortcut(&self, action: &str) -> String { + let mut keys = self + .shortcuts + .iter() + .filter(|(_, a)| a.as_str() == action) + .map(|(k, _)| k.clone()) + .collect::<Vec<_>>(); + keys.sort(); + keys.first() + .map(|k| { + k.split('-') + .map(|part| match part { + "ctrl" => "Ctrl".into(), + "alt" => "Alt".into(), + "shift" => "Shift".into(), + s => s.to_uppercase(), + }) + .collect::<Vec<String>>() + .join("+") + }) + .unwrap_or_else(|| "unbound".into()) + } pub fn load() -> Result<Self> { let dir = directory(); std::fs::create_dir_all(&dir)?; + let themes = dir.join("themes"); + std::fs::create_dir_all(&themes)?; + for (name, source) in [ + ("ember", include_str!("../assets/themes/ember.lua")), + ("glacier", include_str!("../assets/themes/glacier.lua")), + ("paper", include_str!("../assets/themes/paper.lua")), + ("lagoon", include_str!("../assets/themes/lagoon.lua")), + ] { + let path = themes.join(format!("{name}.lua")); + if !path.exists() { + std::fs::write(path, source)?; + } + } let prompt = dir.join("shell.bash"); if !prompt.exists() { std::fs::write(&prompt, include_str!("../assets/shell.bash"))?; @@ -139,7 +181,7 @@ impl Config { .map_err(|e| anyhow::anyhow!(e.to_string()))?, )?, show_status_bar: get!("show_status_bar"), - status_bar_toggle: get!("status_bar_toggle"), + shortcuts: get!("shortcuts"), width: get!("width"), height: get!("height"), scrollback: get!("scrollback"), @@ -166,6 +208,32 @@ impl Config { "invalid font, spacing, window dimensions, scrollback, or palette (requires 16 colors)" ); } + for (key, action) in &c.shortcuts { + gpui::Keystroke::parse(key) + .map_err(|e| anyhow::anyhow!("invalid shortcut {key}: {e}"))?; + let valid = matches!( + action.as_str(), + "new_tab" + | "close_tab" + | "copy" + | "paste" + | "reload" + | "toggle_status" + | "interrupt" + | "next_tab" + | "previous_tab" + | "font_larger" + | "font_smaller" + | "scroll_up" + | "scroll_down" + ) || action + .strip_prefix("tab:") + .and_then(|s| s.parse::<usize>().ok()) + .is_some_and(|i| i > 0); + if !valid { + bail!("unknown shortcut action: {action}"); + } + } Ok(c) } } @@ -184,6 +252,45 @@ mod tests { assert_eq!(c.palette.len(), 16); } #[test] + fn lua_shortcuts_separate_copy_interrupt_and_tab_selection() { + let c = Config::parse(DEFAULT, std::path::Path::new("/tmp")).unwrap(); + for (key, action) in [ + ("ctrl-c", "copy"), + ("ctrl-alt-c", "interrupt"), + ("alt-4", "tab:4"), + ("ctrl-r", "reload"), + ] { + assert_eq!( + c.action_for(&gpui::Keystroke::parse(key).unwrap()) + .as_deref(), + Some(action) + ); + } + let custom = Config::parse( + "return {shortcuts={['alt-x']='copy'}}", + std::path::Path::new("/tmp"), + ) + .unwrap(); + assert_eq!( + custom + .action_for(&gpui::Keystroke::parse("alt-x").unwrap()) + .as_deref(), + Some("copy") + ); + assert!( + custom + .action_for(&gpui::Keystroke::parse("ctrl-c").unwrap()) + .is_none() + ); + assert!( + Config::parse( + "return {shortcuts={['alt-x']='typo'}}", + std::path::Path::new("/tmp") + ) + .is_err() + ); + } + #[test] fn prompt_path_uses_platform_config_directory() { let dir = std::path::Path::new("/Users/example/Library/Application Support/ducky"); let c = Config::parse(DEFAULT, dir).unwrap(); diff --git a/src/main.rs b/src/main.rs index f6a6dfb..f2e2165 100644 --- a/src/main.rs +++ b/src/main.rs @@ -80,13 +80,23 @@ impl Ducky { cx.notify(); } fn close_tab(&mut self, cx: &mut Context<Self>) { - self.tabs.remove(self.active); + self.close_tab_at(self.active, cx); + } + fn close_tab_at(&mut self, index: usize, cx: &mut Context<Self>) { + if index >= self.tabs.len() { + return; + } + let terminal = self.tabs.remove(index); + // Waiting for an old shell to exit must never stall GPUI's event loop. + std::thread::spawn(move || drop(terminal)); if self.tabs.is_empty() { cx.quit(); return; } - self.active = self.active.min(self.tabs.len() - 1); + self.active = active_after_close(self.active, index, self.tabs.len()); self.selection = None; + self.dragging = false; + self.composition.clear(); cx.notify(); } fn reload(&mut self, cx: &mut Context<Self>) { @@ -147,61 +157,59 @@ impl Ducky { } fn key(&mut self, event: &KeyDownEvent, window: &mut Window, cx: &mut Context<Self>) { let key = &event.keystroke; - let m = key.modifiers; - if key.unparse() == self.config.status_bar_toggle { - self.config.show_status_bar = !self.config.show_status_bar; - cx.notify(); + // User byte bindings can override application actions deliberately. + let stroke = key.unparse(); + if let Some(data) = self.config.bindings.get(&stroke).cloned() { + self.send(data.as_bytes(), cx); cx.stop_propagation(); return; } - if m.control && m.shift { - match key.key.to_lowercase().as_str() { - "t" => self.new_tab(cx), - "w" => self.close_tab(cx), - "r" => self.reload(cx), - "c" => self.copy(cx), - "v" => self.paste(cx), - "tab" => { + let action = self.config.action_for(key); + if let Some(action) = action { + match action.as_str() { + "new_tab" => self.new_tab(cx), + "close_tab" => self.close_tab(cx), + "copy" => self.copy(cx), + "paste" => self.paste(cx), + "reload" => self.reload(cx), + "toggle_status" => { + self.config.show_status_bar = !self.config.show_status_bar; + } + "interrupt" => self.send(&[3], cx), + "next_tab" => { + self.active = (self.active + 1) % self.tabs.len(); + self.selection = None; + } + "previous_tab" => { self.active = (self.active + self.tabs.len() - 1) % self.tabs.len(); self.selection = None; - cx.notify(); } - "=" | "+" => { + "font_larger" => { self.config.font_size = (self.config.font_size + 1.).min(48.); self.config.line_height = self.config.font_size * 1.4; - cx.notify(); } - "-" => { + "font_smaller" => { self.config.font_size = (self.config.font_size - 1.).max(8.); self.config.line_height = self.config.font_size * 1.4; - cx.notify(); } + "scroll_up" => self.tabs[self.active].scroll(20), + "scroll_down" => self.tabs[self.active].scroll(-20), _ => { - if let Some(data) = self.config.bindings.get(&key.unparse()).cloned() { - self.send(data.as_bytes(), cx); - } else { - return; + if let Some(index) = action + .strip_prefix("tab:") + .and_then(|s| s.parse::<usize>().ok()) + { + if index <= self.tabs.len() { + self.active = index - 1; + self.selection = None; + } } } } - cx.stop_propagation(); - return; - } - if m.control && key.key == "tab" { - self.active = (self.active + 1) % self.tabs.len(); - self.selection = None; - cx.notify(); - cx.stop_propagation(); - return; - } - if let Some(data) = self.config.bindings.get(&key.unparse()).cloned() { - self.send(data.as_bytes(), cx); - cx.stop_propagation(); - return; - } - if m.shift && (key.key == "pageup" || key.key == "pagedown") { - self.tabs[self.active].scroll(if key.key == "pageup" { 20 } else { -20 }); - cx.notify(); + if !self.tabs.is_empty() { + cx.notify(); + } + window.prevent_default(); cx.stop_propagation(); return; } @@ -365,6 +373,12 @@ impl Ducky { } } +fn active_after_close(active: usize, closed: usize, remaining: usize) -> usize { + active + .saturating_sub(usize::from(closed < active)) + .min(remaining.saturating_sub(1)) +} + fn key_bytes(key: &Keystroke, application: bool) -> Option<Vec<u8>> { let m = key.modifiers; let code = match key.key.as_str() { @@ -473,7 +487,38 @@ impl Render for Ducky { "" } )) - .on_click(cx.listener(move |this, _, _, cx| { + .child( + div() + .id(("close-tab", i)) + .size(px(18.)) + .rounded_sm() + .flex() + .items_center() + .justify_center() + .text_color(rgb(c.muted)) + .hover(|s| s.bg(rgb(c.border)).text_color(rgb(c.foreground))) + .child("×") + .on_mouse_down( + MouseButton::Left, + cx.listener(move |this, _, window, cx| { + cx.stop_propagation(); + window.prevent_default(); + this.close_tab_at(i, cx); + window.focus(&this.focus); + }), + ), + ) + .on_mouse_down( + MouseButton::Middle, + cx.listener(move |this, _, window, cx| { + cx.stop_propagation(); + window.prevent_default(); + this.close_tab_at(i, cx); + window.focus(&this.focus); + }), + ) + .on_click(cx.listener(move |this, _, window, cx| { + window.focus(&this.focus); this.active = i; this.selection = None; cx.notify(); @@ -486,11 +531,14 @@ impl Render for Ducky { .unwrap() .screen() .scrollback(); - let toggle = c - .status_bar_toggle - .replace('-', "+") - .replace("ctrl", "Ctrl") - .replace("shift", "Shift"); + let toggle = c.shortcut("toggle_status"); + let hints = format!( + "{} tab · {} copy · {} paste · {} reload", + c.shortcut("new_tab"), + c.shortcut("copy"), + c.shortcut("paste"), + c.shortcut("reload") + ); div() .size_full() .flex() @@ -690,15 +738,11 @@ impl Render for Ducky { }), )) .child( - div() - .flex() - .gap_4() - .child("Ctrl+Shift T tab · C copy · V paste · R reload") - .child( - div() - .text_color(rgb(c.accent)) - .child(format!("{toggle} hide")), - ), + div().flex().gap_4().child(hints).child( + div() + .text_color(rgb(c.accent)) + .child(format!("{toggle} hide")), + ), ), ) }) @@ -791,7 +835,7 @@ fn main() -> anyhow::Result<()> { } if args.iter().any(|s| s == "--help") { println!( - "Ducky Shell\n\nUsage: ducky [--check-config | --config-dir | --version]\n\nCtrl+Shift+T/W: new/close tab\nCtrl+Tab: next tab\nCtrl+Shift+C/V: copy/paste\nCtrl+Shift+R: reload Lua config\nCtrl+Shift+B: toggle status bar\nCtrl+Shift++/-: font size\nShift+PageUp/Down: scrollback" + "Ducky Shell\n\nUsage: ducky [--check-config | --config-dir | --version]\n\nCtrl+T/W: new/close tab\nAlt+1..9 / Alt+0: select tab\nCtrl+Tab: next tab\nCtrl+C/V: copy/paste\nCtrl+Alt+C: terminal interrupt\nCtrl+R: reload Lua config\nCtrl+B: toggle status bar\nCtrl+=/-: font size\nShift+PageUp/Down: scrollback" ); return Ok(()); } @@ -849,6 +893,13 @@ fn main() -> anyhow::Result<()> { mod tests { use super::*; #[test] + fn closing_earlier_or_inactive_tabs_preserves_selection() { + assert_eq!(active_after_close(3, 0, 3), 2); + assert_eq!(active_after_close(0, 2, 3), 0); + assert_eq!(active_after_close(2, 2, 2), 1); + assert_eq!(active_after_close(1, 1, 3), 1); + } + #[test] fn terminal_key_encoding() { assert_eq!( key_bytes(&Keystroke::parse("ctrl-c").unwrap(), false), |