Skip to main content

hyprshell_exec_lib/
binds.rs

1use core_lib::binds::{ExecBind, ExecBindBehavior, Mod};
2use core_lib::{LAUNCHER_NAMESPACE, OVERVIEW_NAMESPACE, SWITCH_NAMESPACE};
3use hyprland::bind_new::{Binding, Flag, Mod as HyprlandMod};
4use hyprland::data::Binds;
5use hyprland::dispatch_new::Dispatch;
6use hyprland::prelude::{HyprData, HyprDataVec};
7use hyprland::window_rule::{LayerEffect, LayerMatch, LayerRule};
8use tracing::trace;
9
10const HYPRSHELL_BIND_DESCRIPTION_PREFIX: &str = "hyprshell-keybind: ";
11
12pub fn apply_layerrules() -> anyhow::Result<()> {
13    // TODO add option to enable blur
14    let rules = vec![
15        LayerRule {
16            name: None,
17            r#match: vec![LayerMatch::Namespace(LAUNCHER_NAMESPACE.into())],
18            effects: vec![LayerEffect::NoAnim(true), LayerEffect::Xray(false)],
19        },
20        LayerRule {
21            name: None,
22            r#match: vec![LayerMatch::Namespace(OVERVIEW_NAMESPACE.into())],
23            effects: vec![LayerEffect::NoAnim(true), LayerEffect::Xray(false)],
24        },
25        LayerRule {
26            name: None,
27            r#match: vec![LayerMatch::Namespace(SWITCH_NAMESPACE.into())],
28            effects: vec![
29                LayerEffect::NoAnim(true),
30                LayerEffect::Xray(false),
31                LayerEffect::DimAround(true),
32            ],
33        },
34    ];
35
36    for rule in rules {
37        rule.apply()?;
38    }
39    Ok(())
40}
41
42pub fn apply_exec_bind(bind: &ExecBind) -> anyhow::Result<()> {
43    let desc = format!("{}{}", HYPRSHELL_BIND_DESCRIPTION_PREFIX, bind.desc);
44
45    let exec_prefix = if std::env::var_os("HYPRSHELL_ADD_KEYBIND_NOTIFICATIONS").is_some() {
46        format!(
47            "notify-send \"{} + {:?}\" \"{}\" -t 1000 -a hyprshell-settings && ",
48            bind.key, bind.mods, bind.desc
49        )
50    } else {
51        String::new()
52    };
53    let exec = format!("{}{}", exec_prefix, bind.exec);
54
55    let dispatcher = dispatcher_for_bind(bind, exec);
56
57    let binding = Binding {
58        mods: bind
59            .mods
60            .iter()
61            .map(|m| match m {
62                Mod::Alt => hyprland::bind_new::Mod::Alt,
63                Mod::Ctrl => hyprland::bind_new::Mod::Ctrl,
64                Mod::Super => hyprland::bind_new::Mod::Super,
65                Mod::Shift => hyprland::bind_new::Mod::Shift,
66            })
67            .collect(),
68        key: bind.key.to_string(),
69        flags: flags_for_behavior(bind.behavior, desc),
70        dispatcher,
71    };
72    trace!("binding exec: {binding:?}");
73    binding.bind()?;
74    Ok(())
75}
76
77fn flags_for_behavior(behavior: ExecBindBehavior, desc: String) -> Vec<Flag> {
78    let mut flags = vec![Flag::AutoConsuming, Flag::Description(desc)];
79    match behavior {
80        ExecBindBehavior::PressOnce => {}
81        ExecBindBehavior::Repeating => flags.push(Flag::Repeating),
82        ExecBindBehavior::Release => flags.push(Flag::Release),
83        ExecBindBehavior::TransparentReleaseIgnoringMods { .. } => {
84            // Do not swallow ordinary key presses just to watch for releases.
85            flags.extend([
86                Flag::Release,
87                Flag::Transparent,
88                Flag::IgnoreMods,
89                Flag::NonConsuming,
90            ]);
91        }
92    }
93    flags
94}
95
96/// Remove any keybinds left by this application before registering the current set.
97///
98/// Hyprland keeps dynamically registered binds across config reloads, so merely
99/// registering the current set can leave stale binds behind when the config changes.
100#[tracing::instrument]
101pub fn remove_hyprshell_keybinds() -> anyhow::Result<()> {
102    let binds = Binds::get()?.to_vec();
103    let hyprshell_binds = binds.into_iter().filter(|bind| {
104        bind.description
105            .starts_with(HYPRSHELL_BIND_DESCRIPTION_PREFIX)
106    });
107
108    for bind in hyprshell_binds {
109        let mods = mods_from_mask(bind.modmask);
110        let key = if bind.key.is_empty() {
111            format!("code:{}", bind.keycode)
112        } else {
113            bind.key
114        };
115
116        tracing::trace!(?mods, %key, "unregistering hyprshell keybind");
117        Binding {
118            mods,
119            key,
120            // `bind_new::Binding::unbind` only uses the key and modifiers.
121            dispatcher: Dispatch::ExecCmd(String::new(), None),
122            flags: Vec::new(),
123        }
124        .unbind()?;
125    }
126
127    Ok(())
128}
129
130fn mods_from_mask(mask: u16) -> Vec<HyprlandMod> {
131    // These are the XKB modifier-mask bits used by Hyprland's `binds` JSON.
132    // Hyprshell keybinds use the four modifiers represented by its config.
133    [
134        (1, HyprlandMod::Shift),
135        (4, HyprlandMod::Ctrl),
136        (8, HyprlandMod::Alt),
137        (64, HyprlandMod::Super),
138    ]
139    .into_iter()
140    .filter_map(|(bit, modifier)| (mask & bit != 0).then_some(modifier))
141    .collect()
142}
143
144fn dispatcher_for_bind(bind: &ExecBind, exec: String) -> Dispatch {
145    let dispatcher = Dispatch::ExecCmd(exec, None);
146    if let ExecBindBehavior::TransparentReleaseIgnoringMods {
147        unless_keys_down: Some((left, right)),
148    } = bind.behavior
149    {
150        // Evaluate in Hyprland at the key release, before spawning the socket command.
151        // The Tab release must not close the switcher while Alt is still held.
152        Dispatch::Unimplemented(format!(
153            "function() if not hl.is_key_down(\"{left}\") and not hl.is_key_down(\"{right}\") then hl.dispatch({dispatcher}) end end"
154        ))
155    } else {
156        dispatcher
157    }
158}
159
160#[cfg(test)]
161mod tests {
162    use super::*;
163
164    #[test]
165    fn conditional_release_checks_both_sides_before_dispatch() {
166        let bind = ExecBind {
167            mods: vec![],
168            key: "Tab".into(),
169            exec: String::new(),
170            behavior: ExecBindBehavior::TransparentReleaseIgnoringMods {
171                unless_keys_down: Some(("Alt_L", "Alt_R")),
172            },
173            desc: String::new(),
174        };
175        assert_eq!(
176            dispatcher_for_bind(&bind, "echo close".into()).to_string(),
177            "function() if not hl.is_key_down(\"Alt_L\") and not hl.is_key_down(\"Alt_R\") then hl.dispatch(hl.dsp.exec_cmd(\"echo close\")) end end"
178        );
179    }
180
181    #[test]
182    fn modifier_mask_is_converted_to_hyprland_modifiers() {
183        assert_eq!(
184            mods_from_mask(1 | 4 | 64),
185            vec![HyprlandMod::Shift, HyprlandMod::Ctrl, HyprlandMod::Super]
186        );
187    }
188
189    #[test]
190    fn press_once_uses_normal_consuming_press_flags() {
191        assert_eq!(
192            flags_for_behavior(ExecBindBehavior::PressOnce, "overview".into()),
193            vec![Flag::AutoConsuming, Flag::Description("overview".into())]
194        );
195    }
196
197    #[test]
198    fn release_binding_has_no_repeat_or_transparent_flags() {
199        assert_eq!(
200            flags_for_behavior(ExecBindBehavior::Release, "overview".into()),
201            vec![
202                Flag::AutoConsuming,
203                Flag::Description("overview".into()),
204                Flag::Release,
205            ]
206        );
207    }
208
209    #[test]
210    fn switch_binding_flag_semantics_are_unchanged() {
211        assert_eq!(
212            flags_for_behavior(ExecBindBehavior::Repeating, "switch".into()),
213            vec![
214                Flag::AutoConsuming,
215                Flag::Description("switch".into()),
216                Flag::Repeating,
217            ]
218        );
219        assert_eq!(
220            flags_for_behavior(
221                ExecBindBehavior::TransparentReleaseIgnoringMods {
222                    unless_keys_down: None
223                },
224                "switch release".into()
225            ),
226            vec![
227                Flag::AutoConsuming,
228                Flag::Description("switch release".into()),
229                Flag::Release,
230                Flag::Transparent,
231                Flag::IgnoreMods,
232                Flag::NonConsuming,
233            ]
234        );
235    }
236}