tsc-platform: global push-to-talk hotkeys, notifications, app directories

- hotkey: HotkeyManager picks a backend and register() returns a stream of
  Pressed/Released events:
  - xdg-desktop-portal GlobalShortcuts through ashpd (Wayland; Activated /
    Deactivated; the portal owns the binding, ours is the preferred trigger)
  - X11 XInput2 raw key/button events on the root window (no grab, the key
    still reaches the focused app); tested under Xvfb with XTEST input
  - Windows low-level keyboard and mouse hooks on a dedicated thread (the
    crate's only unsafe code, in one module)
  Hotkey/Key/Modifiers parse and serialize as "Ctrl+Shift+T", "F13",
  "RightCtrl", "MouseBack", with X11 keysym, Windows VK and xdg names.
- notify: desktop notifications through notify-rust (D-Bus / toasts)
- paths: data/config/cache/state dirs under "tsc" (as the desktop app
  already uses), TSC_*_DIR overrides, Flatpak and display server detection

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G
This commit is contained in:
Claude committed 2026-09-26 04:56:23 +00:00
1 parent 5fb64b8189
commit edb9c0a958
13 files changed
+1946 -43

No files matched your search

Generated
+213 -43
View File
@@ -107,8 +107,8 @@ dependencies = [
"accesskit_consumer",
"hashbrown 0.16.1",
"static_assertions",
"windows",
"windows-core",
"windows 0.62.2",
"windows-core 0.62.2",
]
[[package]]
@@ -424,6 +424,20 @@ dependencies = [
"libloading",
]
[[package]]
name = "ashpd"
version = "0.13.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fb8421aaa9644a5faf26735f258b669b15f063313ef8f8e2bdb28912a1a6f111"
dependencies = [
"enumflags2",
"futures-util",
"getrandom 0.4.3",
"serde",
"tokio",
"zbus",
]
[[package]]
name = "asn1-rs"
version = "0.7.2"
@@ -1140,7 +1154,7 @@ dependencies = [
"js-sys",
"num-traits",
"wasm-bindgen",
"windows-link",
"windows-link 0.2.1",
]
[[package]]
@@ -1471,8 +1485,8 @@ dependencies = [
"objc2-core-foundation",
"objc2-foundation 0.3.2",
"web-sys",
"windows",
"windows-core",
"windows 0.62.2",
"windows-core 0.62.2",
]
[[package]]
@@ -2532,8 +2546,8 @@ dependencies = [
"read-fonts",
"roxmltree",
"smallvec",
"windows",
"windows-core",
"windows 0.62.2",
"windows-core 0.62.2",
"yeslogic-fontconfig-sys",
]
@@ -2731,7 +2745,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8"
dependencies = [
"rustix 1.1.5",
"windows-link",
"windows-link 0.2.1",
]
[[package]]
@@ -2931,7 +2945,7 @@ dependencies = [
"log",
"presser",
"thiserror 2.0.21",
"windows",
"windows 0.62.2",
]
[[package]]
@@ -3410,7 +3424,7 @@ dependencies = [
"wasm-bindgen",
"web-sys",
"webbrowser",
"windows",
"windows 0.62.2",
"winit",
"zbus",
]
@@ -3518,7 +3532,7 @@ dependencies = [
"web-sys",
"web-time",
"wgpu",
"windows",
"windows 0.62.2",
]
[[package]]
@@ -3587,8 +3601,8 @@ dependencies = [
"vtable",
"wgpu",
"wgpu-hal",
"windows",
"windows-core",
"windows 0.62.2",
"windows-core 0.62.2",
"write-fonts",
]
@@ -3623,7 +3637,7 @@ dependencies = [
"js-sys",
"log",
"wasm-bindgen",
"windows-core",
"windows-core 0.62.2",
]
[[package]]
@@ -3931,7 +3945,7 @@ dependencies = [
"socket2",
"widestring",
"windows-registry",
"windows-result",
"windows-result 0.4.1",
"windows-sys 0.61.2",
]
@@ -4010,7 +4024,7 @@ dependencies = [
"simd_cesu8",
"thiserror 2.0.21",
"walkdir",
"windows-link",
"windows-link 0.2.1",
]
[[package]]
@@ -4182,7 +4196,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55"
dependencies = [
"cfg-if",
"windows-link",
"windows-link 0.2.1",
]
[[package]]
@@ -4353,6 +4367,20 @@ dependencies = [
"num-traits",
]
[[package]]
name = "mac-notification-sys"
version = "0.6.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fd604973958ddcc11b561193c0fb96ba146506ef2f231ef2e7c35fd2cbc9beca"
dependencies = [
"cc",
"log",
"objc2 0.6.4",
"objc2-foundation 0.3.2",
"time",
"uuid",
]
[[package]]
name = "mach2"
version = "0.6.0"
@@ -4629,6 +4657,20 @@ dependencies = [
"memchr",
]
[[package]]
name = "notify-rust"
version = "4.18.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c5b4c1b4f2aa9f25f63a7a49d3dd0ed567b3670da15330a66b29434be899b891"
dependencies = [
"futures-lite",
"log",
"mac-notification-sys",
"serde",
"tauri-winrt-notification",
"zbus",
]
[[package]]
name = "nu-ansi-term"
version = "0.50.3"
@@ -5325,8 +5367,8 @@ dependencies = [
"sha2 0.11.0",
"thiserror 2.0.21",
"tokio",
"windows",
"windows-strings",
"windows 0.62.2",
"windows-strings 0.5.1",
]
[[package]]
@@ -5355,7 +5397,7 @@ dependencies = [
"libc",
"redox_syscall 0.5.18",
"smallvec",
"windows-link",
"windows-link 0.2.1",
]
[[package]]
@@ -7183,7 +7225,7 @@ checksum = "c61cb643dac43067f3eb76c866635a74377ac0abca0ff2590674e1e295514c3d"
dependencies = [
"bitflags 2.13.2",
"skia-bindings",
"windows",
"windows 0.62.2",
]
[[package]]
@@ -7822,6 +7864,17 @@ dependencies = [
"pin-project-lite",
]
[[package]]
name = "tauri-winrt-notification"
version = "0.7.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ed071c670382e85fc2f48ae706492d8c338f4f89bf72520d32f8abfe880aade"
dependencies = [
"thiserror 2.0.21",
"windows 0.61.3",
"windows-version",
]
[[package]]
name = "tempfile"
version = "3.27.0"
@@ -8025,6 +8078,7 @@ dependencies = [
"signal-hook-registry",
"socket2",
"tokio-macros",
"tracing",
"windows-sys 0.61.2",
]
@@ -8407,6 +8461,23 @@ dependencies = [
"tsc-query",
]
[[package]]
name = "tsc-platform"
version = "0.1.0"
dependencies = [
"ashpd",
"dirs",
"futures-util",
"notify-rust",
"serde",
"serde_json",
"thiserror 2.0.21",
"tokio",
"tracing",
"windows 0.62.2",
"x11rb",
]
[[package]]
name = "tsc-query"
version = "0.1.0"
@@ -9257,8 +9328,8 @@ dependencies = [
"thiserror 2.0.21",
"wgpu-naga-bridge",
"wgpu-types",
"windows",
"windows-core",
"windows 0.62.2",
"windows-core 0.62.2",
]
[[package]]
@@ -9331,16 +9402,38 @@ dependencies = [
"num-traits",
]
[[package]]
name = "windows"
version = "0.61.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9babd3a767a4c1aef6900409f85f5d53ce2544ccdfaa86dad48c91782c6d6893"
dependencies = [
"windows-collections 0.2.0",
"windows-core 0.61.2",
"windows-future 0.2.1",
"windows-link 0.1.3",
"windows-numerics 0.2.0",
]
[[package]]
name = "windows"
version = "0.62.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580"
dependencies = [
"windows-collections",
"windows-core",
"windows-future",
"windows-numerics",
"windows-collections 0.3.2",
"windows-core 0.62.2",
"windows-future 0.3.2",
"windows-numerics 0.3.1",
]
[[package]]
name = "windows-collections"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3beeceb5e5cfd9eb1d76b381630e82c4241ccd0d27f1a39ed41b2760b255c5e8"
dependencies = [
"windows-core 0.61.2",
]
[[package]]
@@ -9349,7 +9442,20 @@ version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610"
dependencies = [
"windows-core",
"windows-core 0.62.2",
]
[[package]]
name = "windows-core"
version = "0.61.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c0fdd3ddb90610c7638aa2b3a3ab2904fb9e5cdbecc643ddb3647212781c4ae3"
dependencies = [
"windows-implement",
"windows-interface",
"windows-link 0.1.3",
"windows-result 0.3.4",
"windows-strings 0.4.2",
]
[[package]]
@@ -9360,9 +9466,20 @@ checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
dependencies = [
"windows-implement",
"windows-interface",
"windows-link",
"windows-result",
"windows-strings",
"windows-link 0.2.1",
"windows-result 0.4.1",
"windows-strings 0.5.1",
]
[[package]]
name = "windows-future"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc6a41e98427b19fe4b73c550f060b59fa592d7d686537eebf9385621bfbad8e"
dependencies = [
"windows-core 0.61.2",
"windows-link 0.1.3",
"windows-threading 0.1.0",
]
[[package]]
@@ -9371,9 +9488,9 @@ version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb"
dependencies = [
"windows-core",
"windows-link",
"windows-threading",
"windows-core 0.62.2",
"windows-link 0.2.1",
"windows-threading 0.2.1",
]
[[package]]
@@ -9398,6 +9515,12 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "windows-link"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e6ad25900d524eaabdbbb96d20b4311e1e7ae1699af4fb28c17ae66c80d798a"
[[package]]
name = "windows-link"
version = "0.2.1"
@@ -9417,14 +9540,24 @@ dependencies = [
"zeroize",
]
[[package]]
name = "windows-numerics"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9150af68066c4c5c07ddc0ce30421554771e528bde427614c61038bc2c92c2b1"
dependencies = [
"windows-core 0.61.2",
"windows-link 0.1.3",
]
[[package]]
name = "windows-numerics"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26"
dependencies = [
"windows-core",
"windows-link",
"windows-core 0.62.2",
"windows-link 0.2.1",
]
[[package]]
@@ -9433,9 +9566,18 @@ version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720"
dependencies = [
"windows-link",
"windows-result",
"windows-strings",
"windows-link 0.2.1",
"windows-result 0.4.1",
"windows-strings 0.5.1",
]
[[package]]
name = "windows-result"
version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "56f42bd332cc6c8eac5af113fc0c1fd6a8fd2aa08a0119358686e5160d0586c6"
dependencies = [
"windows-link 0.1.3",
]
[[package]]
@@ -9444,7 +9586,16 @@ version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"
dependencies = [
"windows-link",
"windows-link 0.2.1",
]
[[package]]
name = "windows-strings"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "56e6c93f3a0c3b36176cb1327a4958a0353d5d166c2a35cb268ace15e91d3b57"
dependencies = [
"windows-link 0.1.3",
]
[[package]]
@@ -9453,7 +9604,7 @@ version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"
dependencies = [
"windows-link",
"windows-link 0.2.1",
]
[[package]]
@@ -9480,7 +9631,7 @@ version = "0.61.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
dependencies = [
"windows-link",
"windows-link 0.2.1",
]
[[package]]
@@ -9514,13 +9665,31 @@ dependencies = [
"windows_x86_64_msvc 0.52.6",
]
[[package]]
name = "windows-threading"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b66463ad2e0ea3bbf808b7f1d371311c80e115c0b71d60efc142cafbcfb057a6"
dependencies = [
"windows-link 0.1.3",
]
[[package]]
name = "windows-threading"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37"
dependencies = [
"windows-link",
"windows-link 0.2.1",
]
[[package]]
name = "windows-version"
version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e4060a1da109b9d0326b7262c8e12c84df67cc0dbc9e33cf49e01ccc2eb63631"
dependencies = [
"windows-link 0.2.1",
]
[[package]]
@@ -9923,6 +10092,7 @@ dependencies = [
"rustix 1.1.5",
"serde",
"serde_repr",
"tokio",
"tracing",
"uds_windows",
"uuid",
+2
View File
@@ -14,6 +14,7 @@ members = [
"crates/tsc-gateway-proto",
"crates/tsc-model",
"crates/tsc-observer",
"crates/tsc-platform",
"crates/tsc-query",
"crates/tsc-store",
"crates/tsc-stream",
@@ -33,6 +34,7 @@ default-members = [
"crates/tsc-gateway-proto",
"crates/tsc-model",
"crates/tsc-observer",
"crates/tsc-platform",
"crates/tsc-query",
"crates/tsc-store",
"crates/tsc-stream",
+49
View File
@@ -0,0 +1,49 @@
[package]
name = "tsc-platform"
version = "0.1.0"
description = "Desktop integration: global push-to-talk hotkeys, notifications and app directories."
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true
publish.workspace = true
[features]
default = ["portal", "x11"]
# Wayland global shortcuts through xdg-desktop-portal (Linux).
portal = ["dep:ashpd", "dep:futures-util"]
# X11 global hotkeys through XInput2 raw events (Linux).
x11 = ["dep:x11rb"]
[dependencies]
dirs = "6"
serde = { version = "1.0.228", features = ["derive"] }
thiserror = "2"
tokio = { version = "1", features = ["rt", "sync"] }
tracing = "0.1"
[target.'cfg(all(unix, not(target_os = "macos")))'.dependencies]
ashpd = { version = "0.13", default-features = false, features = ["tokio", "global_shortcuts"], optional = true }
futures-util = { version = "0.3", optional = true }
notify-rust = { version = "4.18", default-features = false, features = ["z-with-tokio"] }
x11rb = { version = "0.13", features = ["xinput"], optional = true }
[target.'cfg(windows)'.dependencies]
notify-rust = { version = "4.18", default-features = false }
windows = { version = "0.62", features = [
"Win32_Foundation",
"Win32_System_LibraryLoader",
"Win32_System_Threading",
"Win32_UI_Input_KeyboardAndMouse",
"Win32_UI_WindowsAndMessaging",
] }
[dev-dependencies]
serde_json = "1"
tokio = { version = "1", features = ["macros", "rt-multi-thread", "time"] }
[target.'cfg(all(unix, not(target_os = "macos")))'.dev-dependencies]
x11rb = { version = "0.13", features = ["xinput", "xtest"] }
[lints]
workspace = true
+456
View File
@@ -0,0 +1,456 @@
//! Keys and key combinations, with their X11 keysyms, Windows virtual-key
//! codes and xdg "shortcuts" names.
use std::fmt;
use std::str::FromStr;
use serde::{Deserialize, Serialize};
use crate::Error;
macro_rules! named_keys {
($($variant:ident $name:literal $keysym:literal $vk:literal $xdg:literal;)*) => {
/// Keys that are not letters, digits, function or keypad digit keys.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum NamedKey {
$($variant,)*
}
impl NamedKey {
pub const ALL: &[NamedKey] = &[$(NamedKey::$variant,)*];
pub fn name(self) -> &'static str {
match self {
$(NamedKey::$variant => $name,)*
}
}
fn keysym(self) -> u32 {
match self {
$(NamedKey::$variant => $keysym,)*
}
}
fn vk(self) -> u16 {
match self {
$(NamedKey::$variant => $vk,)*
}
}
fn xdg(self) -> &'static str {
match self {
$(NamedKey::$variant => $xdg,)*
}
}
}
};
}
// Mouse buttons have no keysym (0) and no xdg name (""); their codes are
// handled by the backends.
named_keys! {
Space "Space" 0x0020 0x20 "space";
Tab "Tab" 0xff09 0x09 "Tab";
CapsLock "CapsLock" 0xffe5 0x14 "Caps_Lock";
Backquote "Backquote" 0x0060 0xc0 "grave";
Minus "Minus" 0x002d 0xbd "minus";
Equal "Equal" 0x003d 0xbb "equal";
BracketLeft "BracketLeft" 0x005b 0xdb "bracketleft";
BracketRight "BracketRight" 0x005d 0xdd "bracketright";
Backslash "Backslash" 0x005c 0xdc "backslash";
Semicolon "Semicolon" 0x003b 0xba "semicolon";
Quote "Quote" 0x0027 0xde "apostrophe";
Comma "Comma" 0x002c 0xbc "comma";
Period "Period" 0x002e 0xbe "period";
Slash "Slash" 0x002f 0xbf "slash";
Enter "Enter" 0xff0d 0x0d "Return";
Escape "Escape" 0xff1b 0x1b "Escape";
Backspace "Backspace" 0xff08 0x08 "BackSpace";
Insert "Insert" 0xff63 0x2d "Insert";
Delete "Delete" 0xffff 0x2e "Delete";
Home "Home" 0xff50 0x24 "Home";
End "End" 0xff57 0x23 "End";
PageUp "PageUp" 0xff55 0x21 "Prior";
PageDown "PageDown" 0xff56 0x22 "Next";
Left "Left" 0xff51 0x25 "Left";
Up "Up" 0xff52 0x26 "Up";
Right "Right" 0xff53 0x27 "Right";
Down "Down" 0xff54 0x28 "Down";
Pause "Pause" 0xff13 0x13 "Pause";
ScrollLock "ScrollLock" 0xff14 0x91 "Scroll_Lock";
PrintScreen "PrintScreen" 0xff61 0x2c "Print";
NumLock "NumLock" 0xff7f 0x90 "Num_Lock";
NumpadAdd "NumpadAdd" 0xffab 0x6b "KP_Add";
NumpadSubtract "NumpadSubtract" 0xffad 0x6d "KP_Subtract";
NumpadMultiply "NumpadMultiply" 0xffaa 0x6a "KP_Multiply";
NumpadDivide "NumpadDivide" 0xffaf 0x6f "KP_Divide";
NumpadDecimal "NumpadDecimal" 0xffae 0x6e "KP_Decimal";
// Windows reports it as Enter with the extended flag.
NumpadEnter "NumpadEnter" 0xff8d 0x0d "KP_Enter";
Menu "Menu" 0xff67 0x5d "Menu";
LeftCtrl "LeftCtrl" 0xffe3 0xa2 "Control_L";
RightCtrl "RightCtrl" 0xffe4 0xa3 "Control_R";
LeftShift "LeftShift" 0xffe1 0xa0 "Shift_L";
RightShift "RightShift" 0xffe2 0xa1 "Shift_R";
LeftAlt "LeftAlt" 0xffe9 0xa4 "Alt_L";
RightAlt "RightAlt" 0xffea 0xa5 "Alt_R";
LeftSuper "LeftSuper" 0xffeb 0x5b "Super_L";
RightSuper "RightSuper" 0xffec 0x5c "Super_R";
MouseMiddle "MouseMiddle" 0 0x04 "";
MouseBack "MouseBack" 0 0x05 "";
MouseForward "MouseForward" 0 0x06 "";
}
/// X11 keysym of AltGr on most layouts, sitting on the right Alt key.
const XK_ISO_LEVEL3_SHIFT: u32 = 0xfe03;
/// A physical key (or mouse side button) as a hotkey trigger.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Key {
/// `'A'..='Z'`.
Letter(char),
/// 0 to 9 on the main keyboard.
Digit(u8),
/// F1 to F24.
F(u8),
/// 0 to 9 on the keypad.
Numpad(u8),
Named(NamedKey),
}
/// Which modifier a key is, if it is one.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ModifierKind {
Ctrl,
Shift,
Alt,
Super,
}
impl Key {
fn validate(self) -> Result<Self, Error> {
let ok = match self {
Key::Letter(c) => c.is_ascii_uppercase(),
Key::Digit(d) | Key::Numpad(d) => d <= 9,
Key::F(n) => (1..=24).contains(&n),
Key::Named(_) => true,
};
if ok { Ok(self) } else { Err(Error::InvalidHotkey(format!("{self:?}"))) }
}
pub fn is_mouse(self) -> bool {
matches!(
self,
Key::Named(NamedKey::MouseMiddle | NamedKey::MouseBack | NamedKey::MouseForward)
)
}
#[cfg(any(test, windows, all(unix, not(target_os = "macos"), feature = "x11")))]
pub(crate) fn modifier(self) -> Option<ModifierKind> {
match self {
Key::Named(NamedKey::LeftCtrl | NamedKey::RightCtrl) => Some(ModifierKind::Ctrl),
Key::Named(NamedKey::LeftShift | NamedKey::RightShift) => Some(ModifierKind::Shift),
Key::Named(NamedKey::LeftAlt | NamedKey::RightAlt) => Some(ModifierKind::Alt),
Key::Named(NamedKey::LeftSuper | NamedKey::RightSuper) => Some(ModifierKind::Super),
_ => None,
}
}
/// X11 keysym (for letters the lowercase one). 0 for mouse buttons.
pub fn x11_keysym(self) -> u32 {
match self {
Key::Letter(c) => c.to_ascii_lowercase() as u32,
Key::Digit(d) => 0x30 + d as u32,
Key::F(n) => 0xffbe + n as u32 - 1,
Key::Numpad(d) => 0xffb0 + d as u32,
Key::Named(k) => k.keysym(),
}
}
/// The key an X11 keysym belongs to (any shift level).
pub fn from_x11_keysym(keysym: u32) -> Option<Key> {
match keysym {
0x61..=0x7a => Some(Key::Letter((keysym as u8 - 0x20) as char)),
0x41..=0x5a => Some(Key::Letter(keysym as u8 as char)),
0x30..=0x39 => Some(Key::Digit((keysym - 0x30) as u8)),
0xffbe..=0xffd5 => Some(Key::F((keysym - 0xffbe + 1) as u8)),
0xffb0..=0xffb9 => Some(Key::Numpad((keysym - 0xffb0) as u8)),
XK_ISO_LEVEL3_SHIFT => Some(Key::Named(NamedKey::RightAlt)),
0 => None,
_ => NamedKey::ALL.iter().find(|k| k.keysym() == keysym).map(|&k| Key::Named(k)),
}
}
/// Windows virtual-key code. Mouse buttons use VK_MBUTTON/VK_XBUTTON1/2.
pub fn windows_vk(self) -> u16 {
match self {
Key::Letter(c) => c as u16,
Key::Digit(d) => 0x30 + d as u16,
Key::F(n) => 0x70 + n as u16 - 1,
Key::Numpad(d) => 0x60 + d as u16,
Key::Named(k) => k.vk(),
}
}
/// The key for a Windows virtual-key code; `extended` is the
/// low-level hook's extended-key flag (tells keypad Enter apart).
pub fn from_windows_vk(vk: u16, extended: bool) -> Option<Key> {
match vk {
0x0d if extended => Some(Key::Named(NamedKey::NumpadEnter)),
0x41..=0x5a => Some(Key::Letter(vk as u8 as char)),
0x30..=0x39 => Some(Key::Digit((vk - 0x30) as u8)),
0x70..=0x87 => Some(Key::F((vk - 0x70 + 1) as u8)),
0x60..=0x69 => Some(Key::Numpad((vk - 0x60) as u8)),
// Generic Ctrl/Shift/Alt (never sent to low-level hooks, but cheap).
0x10 => Some(Key::Named(NamedKey::LeftShift)),
0x11 => Some(Key::Named(NamedKey::LeftCtrl)),
0x12 => Some(Key::Named(NamedKey::LeftAlt)),
_ => NamedKey::ALL
.iter()
.find(|k| k.vk() == vk && **k != NamedKey::NumpadEnter)
.map(|&k| Key::Named(k)),
}
}
/// Keysym name as used by the xdg "shortcuts" specification (portal
/// preferred triggers). `None` for mouse buttons.
pub fn xdg_name(self) -> Option<String> {
let name = match self {
Key::Letter(c) => c.to_ascii_lowercase().to_string(),
Key::Digit(d) => d.to_string(),
Key::F(n) => format!("F{n}"),
Key::Numpad(d) => format!("KP_{d}"),
Key::Named(k) => k.xdg().to_string(),
};
(!name.is_empty()).then_some(name)
}
}
impl fmt::Display for Key {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Key::Letter(c) => write!(f, "{c}"),
Key::Digit(d) => write!(f, "{d}"),
Key::F(n) => write!(f, "F{n}"),
Key::Numpad(d) => write!(f, "Numpad{d}"),
Key::Named(k) => f.write_str(k.name()),
}
}
}
impl FromStr for Key {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Error> {
let invalid = || Error::InvalidHotkey(s.to_string());
let key = if s.len() == 1 {
let c = s.chars().next().ok_or_else(invalid)?;
match c {
'a'..='z' | 'A'..='Z' => Key::Letter(c.to_ascii_uppercase()),
'0'..='9' => Key::Digit(c as u8 - b'0'),
_ => return Err(invalid()),
}
} else if let Some(d) = s.strip_prefix("Numpad").and_then(|d| d.parse().ok()) {
Key::Numpad(d)
} else if let Some(n) = s.strip_prefix(['F', 'f']).and_then(|n| n.parse().ok()) {
Key::F(n)
} else {
let named = NamedKey::ALL.iter().find(|k| k.name().eq_ignore_ascii_case(s));
Key::Named(*named.ok_or_else(invalid)?)
};
key.validate().map_err(|_| invalid())
}
}
/// Modifiers that must be held with a hotkey's key. Either side counts.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct Modifiers {
pub ctrl: bool,
pub shift: bool,
pub alt: bool,
/// The Windows / Command / "logo" key.
pub logo: bool,
}
impl Modifiers {
pub const NONE: Modifiers = Modifiers { ctrl: false, shift: false, alt: false, logo: false };
/// Every modifier in `self` is also in `held`.
pub fn is_subset_of(self, held: Modifiers) -> bool {
(!self.ctrl || held.ctrl)
&& (!self.shift || held.shift)
&& (!self.alt || held.alt)
&& (!self.logo || held.logo)
}
pub(crate) fn add(&mut self, kind: ModifierKind) {
match kind {
ModifierKind::Ctrl => self.ctrl = true,
ModifierKind::Shift => self.shift = true,
ModifierKind::Alt => self.alt = true,
ModifierKind::Super => self.logo = true,
}
}
fn names(self) -> impl Iterator<Item = (&'static str, &'static str)> {
[
(self.ctrl, "Ctrl", "CTRL"),
(self.shift, "Shift", "SHIFT"),
(self.alt, "Alt", "ALT"),
(self.logo, "Super", "LOGO"),
]
.into_iter()
.filter(|(on, ..)| *on)
.map(|(_, name, xdg)| (name, xdg))
}
}
/// A key plus required modifiers, e.g. `Ctrl+Shift+T`, `F13`, `RightCtrl`
/// or `MouseBack`.
///
/// Fires when the key goes down while at least these modifiers are held
/// (extra modifiers do not prevent it, so push-to-talk keeps working while
/// typing with Shift), and releases when the key goes up. Serialized as
/// that string.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(try_from = "String", into = "String")]
pub struct Hotkey {
pub modifiers: Modifiers,
pub key: Key,
}
impl Hotkey {
pub fn new(key: Key) -> Self {
Self { modifiers: Modifiers::NONE, key }
}
pub fn with(mut self, modifiers: Modifiers) -> Self {
self.modifiers = modifiers;
self
}
/// Trigger in the xdg "shortcuts" format (`CTRL+SHIFT+t`), as the
/// portal's preferred trigger. `None` for mouse buttons.
pub fn xdg_trigger(&self) -> Option<String> {
let key = self.key.xdg_name()?;
let mut parts: Vec<String> = self.modifiers.names().map(|(_, x)| x.to_string()).collect();
parts.push(key);
Some(parts.join("+"))
}
}
impl fmt::Display for Hotkey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for (name, _) in self.modifiers.names() {
write!(f, "{name}+")?;
}
write!(f, "{}", self.key)
}
}
impl FromStr for Hotkey {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Error> {
let mut parts: Vec<&str> = s.split('+').map(str::trim).collect();
// "Ctrl++" is not supported; Plus is not a key here.
let key = parts.pop().filter(|k| !k.is_empty());
let key: Key = key.ok_or_else(|| Error::InvalidHotkey(s.to_string()))?.parse()?;
let mut modifiers = Modifiers::NONE;
for part in parts {
let kind = match part.to_ascii_lowercase().as_str() {
"ctrl" | "control" => ModifierKind::Ctrl,
"shift" => ModifierKind::Shift,
"alt" => ModifierKind::Alt,
"super" | "logo" | "win" | "meta" => ModifierKind::Super,
_ => return Err(Error::InvalidHotkey(s.to_string())),
};
modifiers.add(kind);
}
Ok(Hotkey { modifiers, key })
}
}
impl TryFrom<String> for Hotkey {
type Error = Error;
fn try_from(s: String) -> Result<Self, Error> {
s.parse()
}
}
impl From<Hotkey> for String {
fn from(h: Hotkey) -> String {
h.to_string()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_and_display() {
for s in
["Ctrl+Shift+T", "F13", "RightCtrl", "MouseBack", "Alt+Numpad5", "Super+Space", "7"]
{
let h: Hotkey = s.parse().unwrap();
assert_eq!(h.to_string(), s);
}
let h: Hotkey = "control + shift + t".parse().unwrap();
assert_eq!(h.to_string(), "Ctrl+Shift+T");
assert_eq!("win+f1".parse::<Hotkey>().unwrap().to_string(), "Super+F1");
for bad in ["", "Ctrl+", "Hyper+A", "F25", "F0", "Numpad10", "NoSuchKey", "Ctrl+Shift"] {
assert!(bad.parse::<Hotkey>().is_err(), "{bad} should not parse");
}
}
#[test]
fn serde_as_string() {
let h: Hotkey = "Ctrl+F13".parse().unwrap();
let json = serde_json::to_string(&h).unwrap();
assert_eq!(json, r#""Ctrl+F13""#);
assert_eq!(serde_json::from_str::<Hotkey>(&json).unwrap(), h);
assert!(serde_json::from_str::<Hotkey>(r#""Ctrl+Nope""#).is_err());
}
#[test]
fn platform_codes_roundtrip() {
let mut keys: Vec<Key> = NamedKey::ALL.iter().map(|&k| Key::Named(k)).collect();
keys.extend(('A'..='Z').map(Key::Letter));
keys.extend((0..=9).map(Key::Digit));
keys.extend((0..=9).map(Key::Numpad));
keys.extend((1..=24).map(Key::F));
for key in keys {
let extended = key == Key::Named(NamedKey::NumpadEnter);
assert_eq!(Key::from_windows_vk(key.windows_vk(), extended), Some(key), "{key}");
if !key.is_mouse() {
assert_eq!(Key::from_x11_keysym(key.x11_keysym()), Some(key), "{key}");
assert!(key.xdg_name().is_some());
}
assert_eq!(key.to_string().parse::<Key>().unwrap(), key);
}
// Shifted letters and AltGr.
assert_eq!(Key::from_x11_keysym(0x41), Some(Key::Letter('A')));
assert_eq!(Key::from_x11_keysym(0xfe03), Some(Key::Named(NamedKey::RightAlt)));
assert_eq!(Key::from_x11_keysym(0x1234), None);
}
#[test]
fn xdg_triggers() {
let h: Hotkey = "Ctrl+Shift+T".parse().unwrap();
assert_eq!(h.xdg_trigger().as_deref(), Some("CTRL+SHIFT+t"));
let h: Hotkey = "Super+PageUp".parse().unwrap();
assert_eq!(h.xdg_trigger().as_deref(), Some("LOGO+Prior"));
assert_eq!("MouseBack".parse::<Hotkey>().unwrap().xdg_trigger(), None);
}
#[test]
fn modifier_subsets() {
let ctrl = Modifiers { ctrl: true, ..Modifiers::NONE };
let ctrl_shift = Modifiers { shift: true, ..ctrl };
assert!(Modifiers::NONE.is_subset_of(ctrl));
assert!(ctrl.is_subset_of(ctrl_shift));
assert!(!ctrl_shift.is_subset_of(ctrl));
}
}
+216
View File
@@ -0,0 +1,216 @@
//! Global hotkeys with press and release events, for push-to-talk.
//!
//! Backends, picked by [`HotkeyManager::new`]:
//!
//! - **Portal** (Wayland): the xdg-desktop-portal `GlobalShortcuts`
//! interface. The compositor owns the binding: our [`Hotkey`] is only the
//! preferred trigger, the user confirms or changes it in a system dialog,
//! and the portal reports `Activated` / `Deactivated`. Needs KDE Plasma
//! 5.27+, GNOME 48+ or another desktop implementing it.
//! - **X11**: XInput2 raw key and button events on the root window. They are
//! delivered whatever window has focus and nothing is grabbed, so the key
//! still reaches the focused application. Under Wayland this only sees keys
//! while an X11 (XWayland) window has focus.
//! - **Windows**: a low-level keyboard and mouse hook (`WH_KEYBOARD_LL`,
//! `WH_MOUSE_LL`) on its own thread. `RegisterHotKey` would only report
//! presses and swallow the key.
// Builds without a backend (other platforms, or Linux without both
// features) compile, but have nothing to register with.
#![cfg_attr(
not(any(
windows,
all(unix, not(target_os = "macos"), any(feature = "portal", feature = "x11"))
)),
allow(unused_variables, unreachable_code)
)]
mod key;
#[cfg(any(test, windows, all(unix, not(target_os = "macos"), feature = "x11")))]
mod tracker;
#[cfg(all(unix, not(target_os = "macos"), feature = "portal"))]
mod portal;
#[cfg(windows)]
mod windows;
#[cfg(all(unix, not(target_os = "macos"), feature = "x11"))]
mod x11;
pub use key::{Hotkey, Key, Modifiers, NamedKey};
use tokio::sync::mpsc;
use crate::{Error, Result};
/// A registered hotkey went down or up.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum HotkeyEvent {
Pressed,
Released,
}
/// Events of one registration; dropping it unregisters the hotkey on the
/// next key event (X11, Windows) or on [`HotkeyManager::unregister`].
pub type HotkeyEvents = mpsc::UnboundedReceiver<HotkeyEvent>;
/// How hotkeys are captured.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BackendKind {
Portal,
X11,
WindowsHook,
}
enum Backend {
#[cfg(all(unix, not(target_os = "macos"), feature = "portal"))]
Portal(portal::PortalBackend),
#[cfg(all(unix, not(target_os = "macos"), feature = "x11"))]
X11(x11::X11Backend),
#[cfg(windows)]
Windows(windows::HookBackend),
/// Keeps matches exhaustive on platforms without any backend.
#[allow(dead_code)]
None(std::convert::Infallible),
}
/// Registers global hotkeys. See the [module docs](self) for the backends.
pub struct HotkeyManager {
backend: Backend,
}
impl HotkeyManager {
/// The best backend for this desktop session: the portal on Wayland
/// (falling back to X11 when the desktop does not offer it), X11 on X11,
/// the hook on Windows. Must be called within a Tokio runtime (the portal
/// listens for its signals on a task).
pub async fn new() -> Result<Self> {
let mut errors = Vec::new();
for kind in preferred_backends() {
match Self::with_backend(kind).await {
Ok(manager) => return Ok(manager),
Err(e) => {
tracing::debug!(?kind, %e, "hotkey backend unavailable");
errors.push(format!("{kind:?}: {e}"));
}
}
}
Err(Error::Unsupported(if errors.is_empty() {
"no hotkey backend for this platform".into()
} else {
errors.join("; ")
}))
}
/// Use a specific backend.
pub async fn with_backend(kind: BackendKind) -> Result<Self> {
let backend = match kind {
#[cfg(all(unix, not(target_os = "macos"), feature = "portal"))]
BackendKind::Portal => Backend::Portal(portal::PortalBackend::new().await?),
#[cfg(all(unix, not(target_os = "macos"), feature = "x11"))]
BackendKind::X11 => Backend::X11(x11::X11Backend::connect(None)?),
#[cfg(windows)]
BackendKind::WindowsHook => Backend::Windows(windows::HookBackend::start()?),
#[allow(unreachable_patterns)]
_ => return Err(Error::Unsupported(format!("{kind:?} is not available in this build"))),
};
Ok(Self { backend })
}
/// X11 on a specific display (e.g. `":1"`), mainly for tests.
#[cfg(all(unix, not(target_os = "macos"), feature = "x11"))]
pub fn x11(display: &str) -> Result<Self> {
Ok(Self { backend: Backend::X11(x11::X11Backend::connect(Some(display))?) })
}
pub fn backend(&self) -> BackendKind {
match &self.backend {
#[cfg(all(unix, not(target_os = "macos"), feature = "portal"))]
Backend::Portal(_) => BackendKind::Portal,
#[cfg(all(unix, not(target_os = "macos"), feature = "x11"))]
Backend::X11(_) => BackendKind::X11,
#[cfg(windows)]
Backend::Windows(_) => BackendKind::WindowsHook,
Backend::None(never) => match *never {},
}
}
/// Register `hotkey` under a stable `id` (the portal remembers the
/// user's choice by it); `description` is shown in the portal's dialog.
/// Registering an id again replaces it.
///
/// With the portal this may show a dialog and waits for the user.
pub async fn register(
&mut self,
id: &str,
description: &str,
hotkey: Hotkey,
) -> Result<HotkeyEvents> {
let _ = description;
match &mut self.backend {
#[cfg(all(unix, not(target_os = "macos"), feature = "portal"))]
Backend::Portal(p) => p.register(id, description, hotkey).await,
#[cfg(all(unix, not(target_os = "macos"), feature = "x11"))]
Backend::X11(x) => Ok(x.register(id, hotkey)),
#[cfg(windows)]
Backend::Windows(w) => Ok(w.register(id, hotkey)),
Backend::None(never) => match *never {},
}
}
pub async fn unregister(&mut self, id: &str) -> Result<()> {
match &mut self.backend {
#[cfg(all(unix, not(target_os = "macos"), feature = "portal"))]
Backend::Portal(p) => p.unregister(id).await,
#[cfg(all(unix, not(target_os = "macos"), feature = "x11"))]
Backend::X11(x) => {
x.unregister(id);
Ok(())
}
#[cfg(windows)]
Backend::Windows(w) => {
w.unregister(id);
Ok(())
}
Backend::None(never) => match *never {},
}
}
/// What actually triggers `id`, as the desktop describes it (portal
/// only: the user may have picked another key). Other backends return
/// `None`; the registered [`Hotkey`] is the trigger.
pub fn trigger_description(&self, id: &str) -> Option<String> {
match &self.backend {
#[cfg(all(unix, not(target_os = "macos"), feature = "portal"))]
Backend::Portal(p) => p.trigger_description(id),
#[allow(unreachable_patterns)]
_ => {
let _ = id;
None
}
}
}
}
/// Backends to try, best first.
fn preferred_backends() -> Vec<BackendKind> {
if cfg!(windows) {
return vec![BackendKind::WindowsHook];
}
if !cfg!(all(unix, not(target_os = "macos"))) {
return Vec::new();
}
let wayland = std::env::var_os("WAYLAND_DISPLAY").is_some()
|| std::env::var("XDG_SESSION_TYPE").is_ok_and(|t| t == "wayland");
let x11 = std::env::var_os("DISPLAY").is_some();
let mut kinds = Vec::new();
if wayland {
kinds.push(BackendKind::Portal);
}
if x11 {
kinds.push(BackendKind::X11);
}
if !wayland {
// E.g. a portal without a Wayland session, or no display variables.
kinds.push(BackendKind::Portal);
}
kinds
}
+162
View File
@@ -0,0 +1,162 @@
//! Wayland backend: xdg-desktop-portal `GlobalShortcuts`.
//!
//! The portal binds all shortcuts of a session at once, so every change
//! closes the session and binds the full list in a new one. Shortcuts the
//! user already confirmed are remembered by id and do not ask again.
use std::collections::HashMap;
use std::sync::{Arc, Mutex, PoisonError};
use ashpd::desktop::global_shortcuts::{
Activated, BindShortcutsOptions, Deactivated, GlobalShortcuts, NewShortcut,
};
use ashpd::desktop::{CreateSessionOptions, Session};
use futures_util::{Stream, StreamExt};
use tokio::sync::mpsc;
use tracing::debug;
use super::{Hotkey, HotkeyEvent, HotkeyEvents};
use crate::{APP_ID, Error, Result};
type Senders = Arc<Mutex<HashMap<String, mpsc::UnboundedSender<HotkeyEvent>>>>;
fn portal_error(e: ashpd::Error) -> Error {
Error::Backend(format!("portal: {e}"))
}
struct Shortcut {
id: String,
description: String,
hotkey: Hotkey,
}
pub(crate) struct PortalBackend {
portal: GlobalShortcuts,
session: Option<Session<GlobalShortcuts>>,
shortcuts: Vec<Shortcut>,
senders: Senders,
triggers: HashMap<String, String>,
listener: tokio::task::JoinHandle<()>,
}
impl PortalBackend {
pub async fn new() -> Result<Self> {
// Outside a sandbox the portal learns our app id this way (newer
// portals need it for global shortcuts); older ones lack the call.
if let Ok(app_id) = APP_ID.parse()
&& let Err(e) = ashpd::register_host_app(app_id).await
{
debug!(%e, "portal host app registration");
}
let portal = GlobalShortcuts::new().await.map_err(portal_error)?;
let activated = portal.receive_activated().await.map_err(portal_error)?;
let deactivated = portal.receive_deactivated().await.map_err(portal_error)?;
let senders = Senders::default();
let listener = tokio::spawn(listen(activated, deactivated, senders.clone()));
Ok(Self {
portal,
session: None,
shortcuts: Vec::new(),
senders,
triggers: HashMap::new(),
listener,
})
}
fn senders(
&self,
) -> std::sync::MutexGuard<'_, HashMap<String, mpsc::UnboundedSender<HotkeyEvent>>> {
self.senders.lock().unwrap_or_else(PoisonError::into_inner)
}
pub async fn register(
&mut self,
id: &str,
description: &str,
hotkey: Hotkey,
) -> Result<HotkeyEvents> {
if hotkey.key.is_mouse() {
return Err(Error::Unsupported("the portal does not bind mouse buttons".into()));
}
self.shortcuts.retain(|s| s.id != id);
self.shortcuts.push(Shortcut { id: id.into(), description: description.into(), hotkey });
if let Err(e) = self.rebind().await {
self.shortcuts.retain(|s| s.id != id);
return Err(e);
}
let (tx, rx) = mpsc::unbounded_channel();
self.senders().insert(id.into(), tx);
Ok(rx)
}
pub async fn unregister(&mut self, id: &str) -> Result<()> {
self.senders().remove(id);
self.shortcuts.retain(|s| s.id != id);
self.rebind().await
}
pub fn trigger_description(&self, id: &str) -> Option<String> {
self.triggers.get(id).cloned()
}
async fn rebind(&mut self) -> Result<()> {
if let Some(old) = self.session.take() {
let _ = old.close().await;
}
self.triggers.clear();
if self.shortcuts.is_empty() {
return Ok(());
}
let session = self
.portal
.create_session(CreateSessionOptions::default())
.await
.map_err(portal_error)?;
let new: Vec<NewShortcut> = self
.shortcuts
.iter()
.map(|s| {
let trigger = s.hotkey.xdg_trigger();
NewShortcut::new(&s.id, &s.description).preferred_trigger(trigger.as_deref())
})
.collect();
let request = self
.portal
.bind_shortcuts(&session, &new, None, BindShortcutsOptions::default())
.await
.map_err(portal_error)?;
let bound = request.response().map_err(portal_error)?;
self.triggers = bound
.shortcuts()
.iter()
.map(|s| (s.id().to_string(), s.trigger_description().to_string()))
.collect();
self.session = Some(session);
Ok(())
}
}
impl Drop for PortalBackend {
fn drop(&mut self) {
// Closing the session needs an await; the portal closes it when our
// D-Bus connection goes away.
self.listener.abort();
}
}
/// Forward `Activated` / `Deactivated` to the registration with that id.
async fn listen(
activated: impl Stream<Item = Activated>,
deactivated: impl Stream<Item = Deactivated>,
senders: Senders,
) {
let activated = activated.map(|a| (a.shortcut_id().to_string(), HotkeyEvent::Pressed));
let deactivated = deactivated.map(|d| (d.shortcut_id().to_string(), HotkeyEvent::Released));
let mut events = std::pin::pin!(futures_util::stream::select(activated, deactivated));
while let Some((id, event)) = events.next().await {
let senders = senders.lock().unwrap_or_else(PoisonError::into_inner);
if let Some(tx) = senders.get(&id) {
let _ = tx.send(event);
}
}
}
+147
View File
@@ -0,0 +1,147 @@
//! Turns raw key presses and releases into hotkey events. Used by the
//! backends that see every key (X11 raw events, the Windows keyboard hook);
//! the portal does its own matching.
use std::collections::HashSet;
use tokio::sync::mpsc;
use super::{Hotkey, HotkeyEvent, HotkeyEvents, Key, Modifiers};
struct Registration {
id: String,
hotkey: Hotkey,
events: mpsc::UnboundedSender<HotkeyEvent>,
active: bool,
}
#[derive(Default)]
pub(crate) struct Tracker {
registrations: Vec<Registration>,
held: HashSet<Key>,
}
impl Tracker {
/// Register (or replace) `id`.
pub fn add(&mut self, id: &str, hotkey: Hotkey) -> HotkeyEvents {
self.remove(id);
let (tx, rx) = mpsc::unbounded_channel();
self.registrations.push(Registration { id: id.into(), hotkey, events: tx, active: false });
rx
}
pub fn remove(&mut self, id: &str) -> bool {
let before = self.registrations.len();
self.registrations.retain(|r| r.id != id);
self.registrations.len() != before
}
#[cfg(test)]
pub fn is_empty(&self) -> bool {
self.registrations.is_empty()
}
fn held_modifiers(&self) -> Modifiers {
let mut m = Modifiers::NONE;
for kind in self.held.iter().filter_map(|k| k.modifier()) {
m.add(kind);
}
m
}
/// A key went down (`pressed`) or up. Auto-repeat presses are ignored.
pub fn key(&mut self, key: Key, pressed: bool) {
if pressed {
self.held.insert(key);
let held = self.held_modifiers();
for r in &mut self.registrations {
if !r.active && r.hotkey.key == key && r.hotkey.modifiers.is_subset_of(held) {
r.active = true;
let _ = r.events.send(HotkeyEvent::Pressed);
}
}
} else {
self.held.remove(&key);
for r in &mut self.registrations {
if r.active && r.hotkey.key == key {
r.active = false;
let _ = r.events.send(HotkeyEvent::Released);
}
}
}
// Receivers that were dropped unregister themselves.
self.registrations.retain(|r| !r.events.is_closed());
}
/// Release everything (e.g. the keyboard state was lost).
pub fn release_all(&mut self) {
self.held.clear();
for r in &mut self.registrations {
if r.active {
r.active = false;
let _ = r.events.send(HotkeyEvent::Released);
}
}
}
}
#[cfg(test)]
mod tests {
use super::super::NamedKey;
use super::*;
fn drain(rx: &mut HotkeyEvents) -> Vec<HotkeyEvent> {
std::iter::from_fn(|| rx.try_recv().ok()).collect()
}
#[test]
fn press_release_with_modifiers() {
use HotkeyEvent::*;
let mut t = Tracker::default();
let mut ptt = t.add("ptt", "Ctrl+F13".parse().unwrap());
let mut plain = t.add("mute", "M".parse().unwrap());
let ctrl = Key::Named(NamedKey::RightCtrl);
// Without Ctrl nothing happens for Ctrl+F13.
t.key(Key::F(13), true);
t.key(Key::F(13), false);
assert!(drain(&mut ptt).is_empty());
t.key(ctrl, true);
t.key(Key::F(13), true);
t.key(Key::F(13), true); // auto-repeat
// Letting go of Ctrl first keeps it pressed until F13 is released.
t.key(ctrl, false);
assert_eq!(drain(&mut ptt), vec![Pressed]);
t.key(Key::F(13), false);
assert_eq!(drain(&mut ptt), vec![Released]);
// Extra modifiers do not block a plain hotkey.
t.key(Key::Named(NamedKey::LeftShift), true);
t.key(Key::Letter('M'), true);
t.key(Key::Letter('M'), false);
assert_eq!(drain(&mut plain), vec![Pressed, Released]);
}
#[test]
fn modifier_alone_and_unregister() {
use HotkeyEvent::*;
let mut t = Tracker::default();
let mut rx = t.add("ptt", "RightCtrl".parse().unwrap());
let key = Key::Named(NamedKey::RightCtrl);
t.key(key, true);
t.release_all();
assert_eq!(drain(&mut rx), vec![Pressed, Released]);
assert!(t.remove("ptt"));
assert!(!t.remove("ptt"));
t.key(key, true);
assert!(rx.try_recv().is_err());
// A dropped receiver unregisters on the next key.
let rx = t.add("x", "A".parse().unwrap());
drop(rx);
t.key(Key::Letter('B'), true);
assert!(t.is_empty());
}
}
+179
View File
@@ -0,0 +1,179 @@
//! Windows backend: low-level keyboard and mouse hooks.
//!
//! `RegisterHotKey` only reports presses and takes the key away from other
//! applications, so push-to-talk uses `WH_KEYBOARD_LL` / `WH_MOUSE_LL`
//! instead. The hooks run on a dedicated thread with a message loop (Windows
//! calls low-level hooks on the installing thread) and always pass events
//! on. Hook procedures get no user data, so the thread's tracker lives in a
//! thread local.
//!
//! This is the crate's only unsafe code: the Win32 calls and reading the
//! hook structs Windows hands to the callbacks.
#![allow(unsafe_code)]
use std::cell::RefCell;
use std::sync::{Arc, Mutex, PoisonError, mpsc as std_mpsc};
use std::thread;
use windows::Win32::Foundation::{HINSTANCE, LPARAM, LRESULT, WPARAM};
use windows::Win32::System::LibraryLoader::GetModuleHandleW;
use windows::Win32::System::Threading::GetCurrentThreadId;
use windows::Win32::UI::WindowsAndMessaging::{
CallNextHookEx, DispatchMessageW, GetMessageW, HC_ACTION, HHOOK, KBDLLHOOKSTRUCT,
LLKHF_EXTENDED, MSG, MSLLHOOKSTRUCT, PostThreadMessageW, SetWindowsHookExW, TranslateMessage,
UnhookWindowsHookEx, WH_KEYBOARD_LL, WH_MOUSE_LL, WM_KEYDOWN, WM_KEYUP, WM_MBUTTONDOWN,
WM_MBUTTONUP, WM_QUIT, WM_SYSKEYDOWN, WM_SYSKEYUP, WM_XBUTTONDOWN, WM_XBUTTONUP,
};
use windows::core::PCWSTR;
use super::tracker::Tracker;
use super::{Hotkey, HotkeyEvents, Key, NamedKey};
use crate::{Error, Result};
thread_local! {
/// The tracker of the hook thread this runs on.
static TRACKER: RefCell<Option<Arc<Mutex<Tracker>>>> = const { RefCell::new(None) };
}
fn with_tracker(f: impl FnOnce(&mut Tracker)) {
TRACKER.with(|t| {
if let Some(tracker) = &*t.borrow() {
f(&mut tracker.lock().unwrap_or_else(PoisonError::into_inner));
}
});
}
/// Keyboard hook procedure.
unsafe extern "system" fn keyboard_proc(code: i32, wparam: WPARAM, lparam: LPARAM) -> LRESULT {
if code == HC_ACTION as i32 {
// SAFETY: for WH_KEYBOARD_LL with HC_ACTION, lparam points to a
// KBDLLHOOKSTRUCT that is valid for the duration of this call.
let info = unsafe { &*(lparam.0 as *const KBDLLHOOKSTRUCT) };
let pressed = match wparam.0 as u32 {
WM_KEYDOWN | WM_SYSKEYDOWN => Some(true),
WM_KEYUP | WM_SYSKEYUP => Some(false),
_ => None,
};
let extended = info.flags.contains(LLKHF_EXTENDED);
if let (Some(pressed), Some(key)) =
(pressed, Key::from_windows_vk(info.vkCode as u16, extended))
{
with_tracker(|t| t.key(key, pressed));
}
}
// SAFETY: passing the unchanged arguments on to the next hook.
unsafe { CallNextHookEx(None, code, wparam, lparam) }
}
/// Mouse hook procedure: middle and side buttons.
unsafe extern "system" fn mouse_proc(code: i32, wparam: WPARAM, lparam: LPARAM) -> LRESULT {
if code == HC_ACTION as i32 {
// SAFETY: for WH_MOUSE_LL with HC_ACTION, lparam points to a
// MSLLHOOKSTRUCT that is valid for the duration of this call.
let info = unsafe { &*(lparam.0 as *const MSLLHOOKSTRUCT) };
let side = |pressed| {
// The high word of mouseData: 1 = XBUTTON1 (back), 2 = forward.
let key = match info.mouseData >> 16 {
1 => NamedKey::MouseBack,
2 => NamedKey::MouseForward,
_ => return None,
};
Some((Key::Named(key), pressed))
};
let event = match wparam.0 as u32 {
WM_MBUTTONDOWN => Some((Key::Named(NamedKey::MouseMiddle), true)),
WM_MBUTTONUP => Some((Key::Named(NamedKey::MouseMiddle), false)),
WM_XBUTTONDOWN => side(true),
WM_XBUTTONUP => side(false),
_ => None,
};
if let Some((key, pressed)) = event {
with_tracker(|t| t.key(key, pressed));
}
}
// SAFETY: passing the unchanged arguments on to the next hook.
unsafe { CallNextHookEx(None, code, wparam, lparam) }
}
/// Install both hooks on this thread.
fn install() -> windows::core::Result<(HHOOK, HHOOK)> {
// SAFETY: plain Win32 calls with valid arguments; the hook procedures
// have the HOOKPROC signature and live for the whole program.
unsafe {
let module = HINSTANCE::from(GetModuleHandleW(PCWSTR::null())?);
let keyboard = SetWindowsHookExW(WH_KEYBOARD_LL, Some(keyboard_proc), Some(module), 0)?;
match SetWindowsHookExW(WH_MOUSE_LL, Some(mouse_proc), Some(module), 0) {
Ok(mouse) => Ok((keyboard, mouse)),
Err(e) => {
let _ = UnhookWindowsHookEx(keyboard);
Err(e)
}
}
}
}
fn hook_thread(tracker: Arc<Mutex<Tracker>>, ready: std_mpsc::Sender<Result<u32>>) {
TRACKER.with(|t| *t.borrow_mut() = Some(tracker.clone()));
let hooks = match install() {
Ok(hooks) => hooks,
Err(e) => {
let _ = ready.send(Err(Error::Backend(format!("keyboard hook: {e}"))));
return;
}
};
// SAFETY: returns the id of the calling thread.
let _ = ready.send(Ok(unsafe { GetCurrentThreadId() }));
let mut msg = MSG::default();
// SAFETY: standard message loop on this thread's queue; `msg` is valid.
// GetMessageW returns 0 for WM_QUIT and -1 on errors.
unsafe {
while GetMessageW(&mut msg, None, 0, 0).0 > 0 {
let _ = TranslateMessage(&msg);
DispatchMessageW(&msg);
}
let _ = UnhookWindowsHookEx(hooks.0);
let _ = UnhookWindowsHookEx(hooks.1);
}
tracker.lock().unwrap_or_else(PoisonError::into_inner).release_all();
}
pub(crate) struct HookBackend {
tracker: Arc<Mutex<Tracker>>,
thread_id: u32,
}
impl HookBackend {
pub fn start() -> Result<Self> {
let tracker = Arc::new(Mutex::new(Tracker::default()));
let (ready_tx, ready_rx) = std_mpsc::channel();
{
let tracker = tracker.clone();
thread::Builder::new()
.name("tsc-hotkeys-hook".into())
.spawn(move || hook_thread(tracker, ready_tx))
.map_err(|e| Error::Backend(format!("keyboard hook: {e}")))?;
}
let thread_id =
ready_rx.recv().map_err(|_| Error::Backend("keyboard hook thread ended".into()))??;
Ok(Self { tracker, thread_id })
}
fn tracker(&self) -> std::sync::MutexGuard<'_, Tracker> {
self.tracker.lock().unwrap_or_else(PoisonError::into_inner)
}
pub fn register(&mut self, id: &str, hotkey: Hotkey) -> HotkeyEvents {
self.tracker().add(id, hotkey)
}
pub fn unregister(&mut self, id: &str) {
self.tracker().remove(id);
}
}
impl Drop for HookBackend {
fn drop(&mut self) {
// SAFETY: posting WM_QUIT to our hook thread's queue ends its loop.
let _ = unsafe { PostThreadMessageW(self.thread_id, WM_QUIT, WPARAM(0), LPARAM(0)) };
}
}
+193
View File
@@ -0,0 +1,193 @@
//! X11 backend: XInput2 raw key and button events on the root window.
//!
//! Raw events reach us whichever window has focus, and nothing is grabbed,
//! so the key also reaches the focused application. A thread blocks on the
//! connection; dropping the backend wakes it with a client message to a
//! private input-only window.
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, PoisonError};
use std::thread;
use tracing::{debug, warn};
use x11rb::connection::Connection;
use x11rb::protocol::Event;
use x11rb::protocol::xinput::{self, ConnectionExt as _, XIEventMask};
use x11rb::protocol::xproto::{
AtomEnum, ClientMessageEvent, ConnectionExt as _, CreateWindowAux, EventMask, Window,
WindowClass,
};
use x11rb::rust_connection::RustConnection;
use super::tracker::Tracker;
use super::{Hotkey, HotkeyEvents, Key, NamedKey};
use crate::{Error, Result};
fn x11_error(e: impl std::fmt::Display) -> Error {
Error::Backend(format!("X11: {e}"))
}
/// Keycode to keysyms, from the server's keyboard mapping.
struct Keymap {
min_keycode: u8,
per_keycode: usize,
keysyms: Vec<u32>,
}
impl Keymap {
fn load(conn: &RustConnection) -> Result<Self> {
let setup = conn.setup();
let (min, max) = (setup.min_keycode, setup.max_keycode);
let reply = conn
.get_keyboard_mapping(min, max - min + 1)
.map_err(x11_error)?
.reply()
.map_err(x11_error)?;
Ok(Self {
min_keycode: min,
per_keycode: reply.keysyms_per_keycode as usize,
keysyms: reply.keysyms,
})
}
/// The key on this keycode, by the first of its keysyms we know.
fn key(&self, keycode: u32) -> Option<Key> {
let index = (keycode.checked_sub(self.min_keycode as u32)? as usize) * self.per_keycode;
let syms = self.keysyms.get(index..index + self.per_keycode)?;
syms.iter().find_map(|&s| Key::from_x11_keysym(s))
}
}
/// Raw (physical) button numbers: 2 middle, 8 back, 9 forward.
fn button_key(button: u32) -> Option<Key> {
match button {
2 => Some(Key::Named(NamedKey::MouseMiddle)),
8 => Some(Key::Named(NamedKey::MouseBack)),
9 => Some(Key::Named(NamedKey::MouseForward)),
_ => None,
}
}
pub(crate) struct X11Backend {
conn: Arc<RustConnection>,
wake_window: Window,
tracker: Arc<Mutex<Tracker>>,
stop: Arc<AtomicBool>,
}
impl X11Backend {
/// Connect to `display`, or `$DISPLAY` for `None`.
pub fn connect(display: Option<&str>) -> Result<Self> {
let (conn, screen) = x11rb::connect(display).map_err(x11_error)?;
let root = conn.setup().roots[screen].root;
let version =
conn.xinput_xi_query_version(2, 0).map_err(x11_error)?.reply().map_err(x11_error)?;
if version.major_version < 2 {
return Err(Error::Backend("X11: XInput 2 is not available".into()));
}
let mask = XIEventMask::RAW_KEY_PRESS
| XIEventMask::RAW_KEY_RELEASE
| XIEventMask::RAW_BUTTON_PRESS
| XIEventMask::RAW_BUTTON_RELEASE;
let masks =
[xinput::EventMask { deviceid: xinput::Device::ALL_MASTER.into(), mask: vec![mask] }];
conn.xinput_xi_select_events(root, &masks)
.map_err(x11_error)?
.check()
.map_err(x11_error)?;
let wake_window = conn.generate_id().map_err(x11_error)?;
conn.create_window(
0,
wake_window,
root,
0,
0,
1,
1,
0,
WindowClass::INPUT_ONLY,
0,
&CreateWindowAux::new(),
)
.map_err(x11_error)?
.check()
.map_err(x11_error)?;
let keymap = Keymap::load(&conn)?;
let conn = Arc::new(conn);
let tracker = Arc::new(Mutex::new(Tracker::default()));
let stop = Arc::new(AtomicBool::new(false));
{
let (conn, tracker, stop) = (conn.clone(), tracker.clone(), stop.clone());
thread::Builder::new()
.name("tsc-hotkeys-x11".into())
.spawn(move || event_loop(&conn, keymap, &tracker, &stop))
.map_err(|e| Error::Backend(format!("X11: {e}")))?;
}
Ok(Self { conn, wake_window, tracker, stop })
}
fn tracker(&self) -> std::sync::MutexGuard<'_, Tracker> {
self.tracker.lock().unwrap_or_else(PoisonError::into_inner)
}
pub fn register(&mut self, id: &str, hotkey: Hotkey) -> HotkeyEvents {
self.tracker().add(id, hotkey)
}
pub fn unregister(&mut self, id: &str) {
self.tracker().remove(id);
}
}
impl Drop for X11Backend {
fn drop(&mut self) {
self.stop.store(true, Ordering::Relaxed);
// With an empty event mask the event goes to the window's creator: us.
let wake = ClientMessageEvent::new(32, self.wake_window, AtomEnum::NONE, [0u32; 5]);
let _ = self.conn.send_event(false, self.wake_window, EventMask::NO_EVENT, wake);
let _ = self.conn.flush();
}
}
fn event_loop(
conn: &RustConnection,
mut keymap: Keymap,
tracker: &Mutex<Tracker>,
stop: &AtomicBool,
) {
let lock = || tracker.lock().unwrap_or_else(PoisonError::into_inner);
loop {
let event = match conn.wait_for_event() {
Ok(event) => event,
Err(error) => {
warn!(%error, "X11 hotkey connection lost");
lock().release_all();
return;
}
};
if stop.load(Ordering::Relaxed) {
lock().release_all();
return;
}
let (key, pressed) = match event {
Event::XinputRawKeyPress(e) => (keymap.key(e.detail), true),
Event::XinputRawKeyRelease(e) => (keymap.key(e.detail), false),
Event::XinputRawButtonPress(e) => (button_key(e.detail), true),
Event::XinputRawButtonRelease(e) => (button_key(e.detail), false),
Event::MappingNotify(_) => {
match Keymap::load(conn) {
Ok(k) => keymap = k,
Err(error) => debug!(%error, "keeping the old keymap"),
}
continue;
}
_ => continue,
};
if let Some(key) = key {
lock().key(key, pressed);
}
}
}
+34
View File
@@ -0,0 +1,34 @@
//! Desktop integration.
//!
//! - [`hotkey`]: global push-to-talk hotkeys with press and release events
//! (xdg-desktop-portal on Wayland, XInput2 on X11, a keyboard hook on
//! Windows)
//! - [`notify`]: desktop notifications
//! - [`paths`]: data, config, cache and state directories
pub mod hotkey;
pub mod notify;
pub mod paths;
pub use hotkey::{BackendKind, Hotkey, HotkeyEvent, HotkeyEvents, HotkeyManager, Key, Modifiers};
pub use notify::{Notification, notify};
/// Application id: desktop file, icon, portal registrations. A placeholder
/// until the product has a name.
pub const APP_ID: &str = "io.github.faumaray.TsClient";
/// Name shown in notifications. A placeholder until the product has a name.
pub const APP_NAME: &str = "TS Client";
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("invalid hotkey: {0}")]
InvalidHotkey(String),
#[error("not supported: {0}")]
Unsupported(String),
#[error("{0}")]
Backend(String),
#[error("notification: {0}")]
Notification(String),
}
pub type Result<T> = std::result::Result<T, Error>;
+74
View File
@@ -0,0 +1,74 @@
//! Desktop notifications through notify-rust: the freedesktop notification
//! service over D-Bus on Linux (works from Flatpak too), toasts on Windows.
use std::time::Duration;
use crate::{APP_NAME, Error, Result};
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Notification {
pub title: String,
pub body: String,
/// How long it stays; `None` for the desktop's default.
pub timeout: Option<Duration>,
/// Urgent (a poke, a private message): kept until dismissed where the
/// desktop supports that.
pub urgent: bool,
}
impl Notification {
pub fn new(title: impl Into<String>, body: impl Into<String>) -> Self {
Self { title: title.into(), body: body.into(), ..Default::default() }
}
}
#[cfg(any(windows, all(unix, not(target_os = "macos"))))]
fn native(n: &Notification) -> notify_rust::Notification {
let mut native = notify_rust::Notification::new();
native.summary(&n.title).body(&n.body).appname(APP_NAME);
if let Some(timeout) = n.timeout {
native.timeout(notify_rust::Timeout::Milliseconds(timeout.as_millis() as u32));
}
#[cfg(all(unix, not(target_os = "macos")))]
{
// The desktop file and icon are installed under the app id.
native.icon(crate::APP_ID).hint(notify_rust::Hint::DesktopEntry(crate::APP_ID.into()));
if n.urgent {
native.urgency(notify_rust::Urgency::Critical);
}
}
native
}
/// Show a notification. Fails when there is no notification service (e.g. no
/// D-Bus session); callers usually just log that.
pub async fn notify(n: &Notification) -> Result<()> {
#[cfg(all(unix, not(target_os = "macos")))]
{
native(n).show_async().await.map_err(|e| Error::Notification(e.to_string()))?;
Ok(())
}
#[cfg(windows)]
{
native(n).show().map_err(|e| Error::Notification(e.to_string()))?;
Ok(())
}
#[cfg(not(any(windows, all(unix, not(target_os = "macos")))))]
{
let _ = (n, APP_NAME);
Err(Error::Unsupported("notifications".into()))
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Without a notification service this must fail, not hang or panic.
#[tokio::test]
async fn notify_returns() {
let n = Notification { urgent: true, ..Notification::new("Poke", "from a test") };
let result = tokio::time::timeout(Duration::from_secs(10), notify(&n)).await;
assert!(result.is_ok(), "notify hung");
}
}
+106
View File
@@ -0,0 +1,106 @@
//! Where the app keeps its files.
//!
//! `<base>/tsc` for the platform's data, config, cache and state bases (XDG
//! on Linux, where Flatpak points them into `~/.var/app/<app id>/`; Known
//! Folders on Windows: `%APPDATA%` for data and config, `%LOCALAPPDATA%` for
//! cache and state). Each can be overridden with an environment variable,
//! e.g. for portable installs or tests.
use std::path::{Path, PathBuf};
/// Directory name under each base; the desktop app's store already lives in
/// `<data>/tsc`.
pub const APP_DIR: &str = "tsc";
fn resolve(var: &str, base: Option<PathBuf>) -> PathBuf {
match std::env::var_os(var).filter(|v| !v.is_empty()) {
Some(dir) => dir.into(),
None => base.unwrap_or_else(|| PathBuf::from(".")).join(APP_DIR),
}
}
/// Identities, bookmarks, chat history. `TSC_DATA_DIR` overrides.
pub fn data_dir() -> PathBuf {
resolve("TSC_DATA_DIR", dirs::data_dir())
}
/// Settings files. `TSC_CONFIG_DIR` overrides.
pub fn config_dir() -> PathBuf {
resolve("TSC_CONFIG_DIR", dirs::config_dir())
}
/// Disposable files (avatars, downloaded codecs). `TSC_CACHE_DIR` overrides.
pub fn cache_dir() -> PathBuf {
resolve("TSC_CACHE_DIR", dirs::cache_dir())
}
/// Logs and crash reports. `TSC_STATE_DIR` overrides.
pub fn state_dir() -> PathBuf {
resolve("TSC_STATE_DIR", dirs::state_dir().or_else(dirs::data_local_dir))
}
/// Create `dir` and its parents if needed.
pub fn ensure(dir: &Path) -> std::io::Result<&Path> {
std::fs::create_dir_all(dir)?;
Ok(dir)
}
/// Running inside a Flatpak sandbox.
pub fn is_flatpak() -> bool {
cfg!(target_os = "linux") && Path::new("/.flatpak-info").exists()
}
/// The display server of this session, as far as the environment tells.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DisplayServer {
Wayland,
X11,
Windows,
MacOs,
Unknown,
}
pub fn display_server() -> DisplayServer {
if cfg!(windows) {
DisplayServer::Windows
} else if cfg!(target_os = "macos") {
DisplayServer::MacOs
} else if std::env::var_os("WAYLAND_DISPLAY").is_some()
|| std::env::var("XDG_SESSION_TYPE").is_ok_and(|t| t == "wayland")
{
DisplayServer::Wayland
} else if std::env::var_os("DISPLAY").is_some() {
DisplayServer::X11
} else {
DisplayServer::Unknown
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn dirs_end_in_app_dir_or_override() {
for dir in [data_dir(), config_dir(), cache_dir(), state_dir()] {
assert!(dir.is_absolute() || dir.starts_with("."), "{}", dir.display());
}
assert_eq!(
resolve("TSC_TEST_UNSET_VARIABLE", Some("/base".into())),
Path::new("/base/tsc")
);
assert_eq!(resolve("TSC_TEST_UNSET_VARIABLE", None), Path::new("./tsc"));
// PATH is always set: stands in for an override.
let path = std::env::var_os("PATH").unwrap();
assert_eq!(resolve("PATH", Some("/base".into())), PathBuf::from(path));
}
#[test]
fn ensure_creates() {
let dir =
std::env::temp_dir().join(format!("tsc-platform-{}", std::process::id())).join("a");
assert_eq!(ensure(&dir).unwrap(), dir);
assert!(dir.is_dir());
std::fs::remove_dir_all(dir.parent().unwrap()).unwrap();
}
}
+115
View File
@@ -0,0 +1,115 @@
//! Global hotkeys against a real X server, typing through XTEST.
//!
//! Needs `TSC_X11_TEST_DISPLAY` naming a display to use (e.g. an Xvfb
//! started for the test, as CI does); skipped otherwise.
#![cfg(all(unix, not(target_os = "macos"), feature = "x11"))]
use std::time::Duration;
use tokio::time::timeout;
use tsc_platform::{HotkeyEvent, HotkeyEvents, HotkeyManager};
use x11rb::connection::Connection;
use x11rb::protocol::xproto::{
BUTTON_PRESS_EVENT, BUTTON_RELEASE_EVENT, ConnectionExt as _, KEY_PRESS_EVENT,
KEY_RELEASE_EVENT,
};
use x11rb::protocol::xtest::ConnectionExt as _;
use x11rb::rust_connection::RustConnection;
use x11rb::wrapper::ConnectionExt as _;
struct Typist {
conn: RustConnection,
root: u32,
}
impl Typist {
fn new(display: &str) -> Self {
let (conn, screen) = x11rb::connect(Some(display)).unwrap();
let root = conn.setup().roots[screen].root;
Self { conn, root }
}
fn keycode(&self, keysym: u32) -> u8 {
let setup = self.conn.setup();
let (min, max) = (setup.min_keycode, setup.max_keycode);
let map = self.conn.get_keyboard_mapping(min, max - min + 1).unwrap().reply().unwrap();
let per = map.keysyms_per_keycode as usize;
let index = map.keysyms.iter().position(|&s| s == keysym).expect("keysym in keymap");
min + (index / per) as u8
}
fn fake(&self, kind: u8, detail: u8) {
self.conn.xtest_fake_input(kind, detail, 0, self.root, 0, 0, 0).unwrap();
self.conn.sync().unwrap();
}
fn key(&self, keysym: u32, down: bool) {
let kind = if down { KEY_PRESS_EVENT } else { KEY_RELEASE_EVENT };
self.fake(kind, self.keycode(keysym));
}
fn button(&self, button: u8, down: bool) {
self.fake(if down { BUTTON_PRESS_EVENT } else { BUTTON_RELEASE_EVENT }, button);
}
}
async fn next(events: &mut HotkeyEvents) -> Option<HotkeyEvent> {
timeout(Duration::from_secs(2), events.recv()).await.ok().flatten()
}
async fn nothing(events: &mut HotkeyEvents) -> bool {
timeout(Duration::from_millis(300), events.recv()).await.is_err()
}
const XK_CONTROL_L: u32 = 0xffe3;
const XK_F9: u32 = 0xffc6;
const XK_A: u32 = 0x61;
#[tokio::test]
async fn xinput2_press_and_release() {
let Ok(display) = std::env::var("TSC_X11_TEST_DISPLAY") else {
eprintln!("TSC_X11_TEST_DISPLAY not set, skipping");
return;
};
let mut manager = HotkeyManager::x11(&display).unwrap();
let mut ptt =
manager.register("ptt", "Push to talk", "Ctrl+F9".parse().unwrap()).await.unwrap();
let mut plain = manager.register("a", "Plain key", "A".parse().unwrap()).await.unwrap();
let mut back = manager.register("back", "Mouse", "MouseBack".parse().unwrap()).await.unwrap();
let typist = Typist::new(&display);
// F9 alone does not trigger Ctrl+F9.
typist.key(XK_F9, true);
typist.key(XK_F9, false);
assert!(nothing(&mut ptt).await);
typist.key(XK_CONTROL_L, true);
typist.key(XK_F9, true);
assert_eq!(next(&mut ptt).await, Some(HotkeyEvent::Pressed));
// Still held while Ctrl goes up first.
typist.key(XK_CONTROL_L, false);
assert!(nothing(&mut ptt).await);
typist.key(XK_F9, false);
assert_eq!(next(&mut ptt).await, Some(HotkeyEvent::Released));
typist.key(XK_A, true);
typist.key(XK_A, false);
assert_eq!(next(&mut plain).await, Some(HotkeyEvent::Pressed));
assert_eq!(next(&mut plain).await, Some(HotkeyEvent::Released));
typist.button(8, true);
typist.button(8, false);
assert_eq!(next(&mut back).await, Some(HotkeyEvent::Pressed));
assert_eq!(next(&mut back).await, Some(HotkeyEvent::Released));
manager.unregister("a").await.unwrap();
typist.key(XK_A, true);
typist.key(XK_A, false);
// The sender is gone: the channel ends.
assert_eq!(next(&mut plain).await, None);
// Dropping the manager stops its thread and closes the channels.
drop(manager);
assert_eq!(next(&mut ptt).await, None);
}