Skip to main content

par_term/platform/
modifiers.rs

1//! Cross-platform keyboard modifier helpers.
2//!
3//! Terminal emulators face a fundamental conflict on non-macOS platforms: `Ctrl`
4//! is the standard OS-level modifier *and* also generates POSIX control codes
5//! inside a terminal (e.g. `Ctrl+C` = SIGINT, `Ctrl+W` = delete-word).
6//!
7//! par-term resolves this by using different "primary" modifiers per platform:
8//!
9//! | Platform | Primary modifier | Rationale |
10//! |---|---|---|
11//! | macOS | `Cmd` (`super_key`) | Separate from Ctrl; no terminal conflicts |
12//! | Windows / Linux | `Ctrl` (`control_key`) | macOS `Cmd` key unavailable |
13//!
14//! When a shortcut needs `Cmd+X` on macOS and `Ctrl+Shift+X` on others (to avoid
15//! clobbering Ctrl-only terminal bindings), callers should:
16//! 1. Check `primary_modifier(mods)` for the first modifier.
17//! 2. Check `primary_modifier_with_shift(mods)` when `Shift` must also be held.
18//!
19//! This avoids scattered `#[cfg(target_os = "macos")]` pairs at every call site.
20
21use winit::keyboard::ModifiersState;
22
23/// Returns `true` when **only** the platform's **primary** modifier key is held
24/// (no Shift, no Alt, and no cross modifier), i.e.:
25///
26/// - macOS: `Cmd` pressed; `Shift`, `Alt`, and `Ctrl` not pressed
27/// - Windows/Linux: `Ctrl` pressed; `Shift`, `Alt`, and `Super` not pressed
28///
29/// Use this for single-key shortcuts (`Cmd+T` on macOS / `Ctrl+T` elsewhere).
30/// Excluding the cross modifier prevents e.g. `Ctrl+Cmd+T` from triggering a
31/// hardcoded `Cmd+T` handler on macOS, which would otherwise shadow any
32/// registered `Ctrl+Cmd+T` keybinding.
33pub fn primary_modifier(mods: &ModifiersState) -> bool {
34    #[cfg(target_os = "macos")]
35    {
36        mods.super_key() && !mods.shift_key() && !mods.alt_key() && !mods.control_key()
37    }
38    #[cfg(not(target_os = "macos"))]
39    {
40        mods.control_key() && !mods.shift_key() && !mods.alt_key() && !mods.super_key()
41    }
42}
43
44/// Returns `true` when the platform's **primary** modifier key and **Shift**
45/// are held, and no other modifiers are held, i.e.:
46///
47/// - macOS: `Cmd+Shift`; `Alt` and `Ctrl` not pressed
48/// - Windows/Linux: `Ctrl+Shift`; `Alt` and `Super` not pressed
49///
50/// Use this for shortcuts that require Shift to avoid conflicts
51/// (`Cmd+Shift+]` on macOS / `Ctrl+Shift+]` elsewhere). Like
52/// [`primary_modifier`], this excludes the cross modifier and Alt so that
53/// combos such as `Ctrl+Cmd+Shift+]` do not shadow separate keybindings.
54pub fn primary_modifier_with_shift(mods: &ModifiersState) -> bool {
55    #[cfg(target_os = "macos")]
56    {
57        mods.super_key() && mods.shift_key() && !mods.alt_key() && !mods.control_key()
58    }
59    #[cfg(not(target_os = "macos"))]
60    {
61        mods.control_key() && mods.shift_key() && !mods.alt_key() && !mods.super_key()
62    }
63}