aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--src/config.rs104
-rw-r--r--src/main.rs19
2 files changed, 89 insertions, 34 deletions
diff --git a/src/config.rs b/src/config.rs
index 3532f80..6181d77 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -1,4 +1,5 @@
use anyhow::{Context, Result, bail};
+use gpui::Keystroke;
use mlua::{Lua, Table};
use std::{collections::HashMap, path::PathBuf};
@@ -43,32 +44,63 @@ 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 const MACOS: bool = cfg!(target_os = "macos");
+pub const SHORTCUT_MODIFIER: &str = if MACOS { "Cmd" } else { "Ctrl" };
+pub const ALT_MODIFIER: &str = if MACOS { "Option" } else { "Alt" };
+
+fn parse_binding(binding: &str) -> Result<Keystroke, gpui::InvalidKeystrokeError> {
+ let mut key = Keystroke::parse(binding)?;
+ // macOS reserves Command+Tab for switching applications.
+ if MACOS && key.modifiers.control && !key.modifiers.platform && key.key != "tab" {
+ key.modifiers.control = false;
+ key.modifiers.platform = true;
+ }
+ Ok(key)
+}
+
+fn binding_value<'a>(bindings: &'a HashMap<String, String>, key: &Keystroke) -> Option<&'a str> {
+ let stroke = key.unparse();
+ bindings
+ .iter()
+ .filter(|(binding, _)| {
+ parse_binding(binding).is_ok_and(|parsed| {
+ parsed.modifiers == key.modifiers && parsed.key.eq_ignore_ascii_case(&key.key)
+ })
})
+ .min_by_key(|(binding, _)| (binding.as_str() != stroke, binding.as_str()))
+ .map(|(_, value)| value.as_str())
+}
+
+impl Config {
+ pub fn action_for(&self, key: &Keystroke) -> Option<&str> {
+ binding_value(&self.shortcuts, key)
+ }
+
+ pub fn bytes_for(&self, key: &Keystroke) -> Option<&str> {
+ binding_value(&self.bindings, key)
}
+
pub fn shortcut(&self, action: &str) -> String {
- let mut keys = self
- .shortcuts
+ self.shortcuts
.iter()
- .filter(|(_, a)| a.as_str() == action)
- .map(|(k, _)| k.clone())
- .collect::<Vec<_>>();
- keys.sort();
- keys.first()
- .map(|k| {
- k.split('-')
+ .filter(|(_, value)| value.as_str() == action)
+ .map(|(binding, _)| binding)
+ .min()
+ .and_then(|binding| parse_binding(binding).ok())
+ .map(|key| {
+ let stroke = key.unparse();
+ let modifiers = stroke.strip_suffix(&key.key).unwrap_or_default();
+ modifiers
+ .split_terminator('-')
.map(|part| match part {
"ctrl" => "Ctrl".into(),
- "alt" => "Alt".into(),
+ "cmd" => "Cmd".into(),
+ "alt" => ALT_MODIFIER.into(),
"shift" => "Shift".into(),
s => s.to_uppercase(),
})
- .collect::<Vec<String>>()
+ .chain(std::iter::once(key.key.to_uppercase()))
+ .collect::<Vec<_>>()
.join("+")
})
.unwrap_or_else(|| "unbound".into())
@@ -209,8 +241,7 @@ impl Config {
);
}
for (key, action) in &c.shortcuts {
- gpui::Keystroke::parse(key)
- .map_err(|e| anyhow::anyhow!("invalid shortcut {key}: {e}"))?;
+ parse_binding(key).map_err(|e| anyhow::anyhow!("invalid shortcut {key}: {e}"))?;
let valid = matches!(
action.as_str(),
"new_tab"
@@ -254,16 +285,31 @@ mod tests {
#[test]
fn lua_shortcuts_separate_copy_interrupt_and_tab_selection() {
let c = Config::parse(DEFAULT, std::path::Path::new("/tmp")).unwrap();
+ let primary = if MACOS { "cmd" } else { "ctrl" };
for (key, action) in [
- ("ctrl-c", "copy"),
- ("ctrl-alt-c", "interrupt"),
- ("alt-4", "tab:4"),
- ("ctrl-r", "reload"),
+ (format!("{primary}-c"), "copy"),
+ (format!("{primary}-alt-c"), "interrupt"),
+ (format!("{primary}-r"), "reload"),
+ ("alt-4".into(), "tab:4"),
+ ("ctrl-tab".into(), "next_tab"),
+ ("ctrl-shift-tab".into(), "previous_tab"),
] {
- assert_eq!(
- c.action_for(&gpui::Keystroke::parse(key).unwrap())
- .as_deref(),
- Some(action)
+ assert_eq!(c.action_for(&Keystroke::parse(&key).unwrap()), Some(action));
+ }
+ assert_eq!(c.shortcut("copy"), format!("{SHORTCUT_MODIFIER}+C"));
+ assert_eq!(c.shortcut("font_smaller"), format!("{SHORTCUT_MODIFIER}+-"));
+ assert_eq!(c.shortcut("next_tab"), "Ctrl+TAB");
+ assert_eq!(c.shortcut("tab:4"), format!("{ALT_MODIFIER}+4"));
+ assert_eq!(
+ c.bytes_for(&Keystroke::parse(&format!("{primary}-g")).unwrap()),
+ Some("git status\r")
+ );
+ if MACOS {
+ assert!(c.action_for(&Keystroke::parse("ctrl-c").unwrap()).is_none());
+ assert!(c.bytes_for(&Keystroke::parse("ctrl-g").unwrap()).is_none());
+ assert!(
+ c.action_for(&Keystroke::parse("cmd-tab").unwrap())
+ .is_none()
);
}
let custom = Config::parse(
@@ -272,9 +318,7 @@ mod tests {
)
.unwrap();
assert_eq!(
- custom
- .action_for(&gpui::Keystroke::parse("alt-x").unwrap())
- .as_deref(),
+ custom.action_for(&gpui::Keystroke::parse("alt-x").unwrap()),
Some("copy")
);
assert!(
diff --git a/src/main.rs b/src/main.rs
index f2e2165..c5494f4 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -158,15 +158,15 @@ impl Ducky {
fn key(&mut self, event: &KeyDownEvent, window: &mut Window, cx: &mut Context<Self>) {
let key = &event.keystroke;
// User byte bindings can override application actions deliberately.
- let stroke = key.unparse();
- if let Some(data) = self.config.bindings.get(&stroke).cloned() {
+ if let Some(data) = self.config.bytes_for(key).map(str::to_owned) {
self.send(data.as_bytes(), cx);
+ window.prevent_default();
cx.stop_propagation();
return;
}
let action = self.config.action_for(key);
if let Some(action) = action {
- match action.as_str() {
+ match action {
"new_tab" => self.new_tab(cx),
"close_tab" => self.close_tab(cx),
"copy" => self.copy(cx),
@@ -381,6 +381,9 @@ fn active_after_close(active: usize, closed: usize, remaining: usize) -> usize {
fn key_bytes(key: &Keystroke, application: bool) -> Option<Vec<u8>> {
let m = key.modifiers;
+ if config::MACOS && m.platform {
+ return None;
+ }
let code = match key.key.as_str() {
"enter" => "\r",
"backspace" => "\x7f",
@@ -834,8 +837,10 @@ fn main() -> anyhow::Result<()> {
return Ok(());
}
if args.iter().any(|s| s == "--help") {
+ let primary = config::SHORTCUT_MODIFIER;
+ let alt = config::ALT_MODIFIER;
println!(
- "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"
+ "Ducky Shell\n\nUsage: ducky [--check-config | --config-dir | --version]\n\n{primary}+T/W: new/close tab\n{alt}+1..9 / {alt}+0: select tab\nCtrl+Tab / Ctrl+Shift+Tab: next/previous tab\n{primary}+C/V: copy/paste\n{primary}+{alt}+C: terminal interrupt\n{primary}+R: reload Lua config\n{primary}+B: toggle status bar\n{primary}+=/-: font size\nShift+PageUp/Down: scrollback"
);
return Ok(());
}
@@ -905,6 +910,12 @@ mod tests {
key_bytes(&Keystroke::parse("ctrl-c").unwrap(), false),
Some(vec![3])
);
+ if config::MACOS {
+ assert_eq!(
+ key_bytes(&Keystroke::parse("cmd-enter").unwrap(), false),
+ None
+ );
+ }
assert_eq!(
key_bytes(&Keystroke::parse("up").unwrap(), true),
Some(b"\x1bOA".to_vec())