diff --git a/Cargo.lock b/Cargo.lock index ae33940..59be1d4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1189,10 +1189,12 @@ dependencies = [ "reis", "thiserror 2.0.21", "tokio", + "wayland-backend", "wayland-client", "wayland-protocols", "wayland-protocols-misc", "wayland-protocols-wlr", + "wayland-scanner", "windows", "windows-sys 0.61.2", "x11rb", diff --git a/app/src-tauri/src/engine.rs b/app/src-tauri/src/engine.rs index 8225e1a..2b98789 100644 --- a/app/src-tauri/src/engine.rs +++ b/app/src-tauri/src/engine.rs @@ -8,7 +8,7 @@ use std::collections::{HashMap, HashSet}; use std::net::SocketAddr; use std::path::PathBuf; use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; -use std::sync::{Arc, Mutex, MutexGuard}; +use std::sync::{Arc, Mutex, MutexGuard, Weak}; use std::time::{Duration, Instant}; use flow_core::Rect; @@ -223,6 +223,8 @@ fn auth_kind(kind: flow_platform::AuthKind) -> &'static str { pub struct UnsupportedView { pub hold_key: bool, pub local_hotkey: bool, + /// 在本机按快捷键映射的触发键(只有 Wayland 上做不到;Hyprland 能把它们注册成自己的快捷键)。 + pub local_mapping: bool, pub dwell: bool, pub edge_glow: bool, /// 按前台应用 / 全屏自动锁定:查不到前台是哪个应用。 @@ -234,6 +236,7 @@ impl From for UnsupportedView { Self { hold_key: l.hold_key, local_hotkey: l.local_hotkey, + local_mapping: l.local_mapping, dwell: l.dwell, edge_glow: l.edge_glow, auto_lock: l.foreground_app, @@ -409,6 +412,10 @@ struct Inner { /// 推给界面的状态的序号,在 `state` 锁里递增:两个任务同时推送时,界面丢掉先算出来却后到的那份。 view_seq: AtomicU64, capture_warned: AtomicBool, + /// 已经提示过"没能把快捷键映射注册到桌面"(Hyprland)。 + shortcut_warned: AtomicBool, + /// 桌面交来映射的触发键、却没发出去时的提示(对方可能刚断开),限制频率。 + shortcut_failures: Mutex, /// `shutdown()` 之后为 true:后台循环退出,不再重连、不再重新安装键鼠捕获。 stopped: AtomicBool, /// 系统接口失败后,下次重试的时间(避免频繁调用系统接口)。 @@ -529,17 +536,87 @@ fn map_key(from: Os, local: Os, win_keys: WinToMacKeys, code: KeyCode) -> KeyCod } } -/// 控制器实际使用的快捷键。看不到全局键盘的桌面(Linux 的 Wayland)不支持快捷键映射:键鼠在本机时 -/// 按触发键没有反应,只有键鼠已经切到别的电脑后才触发,和"不用切过去"的用途相反(用户反馈), -/// 设置页也不显示这一节,所以配置里留着的映射(比如从 X11 会话带过来的)一律不用。 +/// 控制器实际使用的快捷键。看不到全局键盘、又没有桌面能代劳的 Wayland 会话不支持快捷键映射: +/// 键鼠在本机时按触发键没有反应,只有键鼠已经切到别的电脑后才触发,和"不用切过去"的用途相反 +/// (用户反馈),设置页也不显示这一节,所以配置里留着的映射(比如从 X11 会话带过来的)一律不用。 +/// Hyprland 上映射的触发键由合成器交给流界(`LocalShortcut`),照常保留。 fn usable_hotkeys(hotkeys: &Hotkeys, limits: flow_platform::Limits) -> Hotkeys { let mut hotkeys = hotkeys.clone(); - if limits.local_hotkey { + if limits.local_mapping { hotkeys.mappings.clear(); } hotkeys } +/// 交给桌面注册的映射触发键(Hyprland):只包括现在真发得出去的映射——目标连着,而且认得 +/// `Message::KeyStroke`。共享暂停时一条都不注册。发不出去的触发键照常交给原来的去处。 +fn local_shortcuts( + hotkeys: &Hotkeys, + sendable: &HashSet, + paused: bool, +) -> Vec { + if paused { + return Vec::new(); + } + hotkeys + .mappings + .iter() + .enumerate() + .filter(|(_, m)| m.trigger.is_trigger() && sendable.contains(&m.device)) + .map(|(i, m)| flow_platform::LocalShortcut { + id: format!("mapping:{i}"), + combo: m.trigger, + description: format!("流界:快捷键映射 {}", i + 1), + }) + .collect() +} + +/// 桌面把某个映射的触发键交给流界了(Hyprland 的全局快捷键,`id` 是 `mapping:<序号>`)。 +/// 在协议线程里调用,不能等太久:只拿一下锁就发按键,发不出去时提示用户(限频)。 +fn local_shortcut(inner: &Weak, id: &str) { + let Some(inner) = inner.upgrade() else { + return; + }; + if inner.stopped.load(Ordering::Relaxed) { + return; + } + let engine = Engine { inner }; + let Some(index) = id + .strip_prefix("mapping:") + .and_then(|n| n.parse::().ok()) + else { + return; + }; + let name = { + let st = engine.lock(); + let Some(mapping) = st.config.settings.hotkeys.mappings.get(index) else { + return; + }; + st.config + .peer(&mapping.device) + .map(|p| p.name.clone()) + .unwrap_or_default() + }; + if engine.controller().run_shortcut(id) { + return; + } + if engine + .inner + .shortcut_failures + .lock() + .unwrap_or_else(|e| e.into_inner()) + .allow(engine.now_ms()) + { + let target = match name.is_empty() { + true => "目标电脑".to_owned(), + false => format!("「{name}」"), + }; + engine.notice(format!( + "快捷键映射没能发给{target}:可能刚刚断开,或者共享已暂停。" + )); + } +} + /// `limits`:当前系统做不到的切换方式。做不到的设置一律忽略,否则打开后永远切不过去 /// (比如看不到键盘,就永远等不到"修饰键按着")。 fn switch_policy(settings: &Settings, locked: bool, limits: flow_platform::Limits) -> SwitchPolicy { @@ -1034,6 +1111,8 @@ impl Engine { capture_on: AtomicBool::new(false), view_seq: AtomicU64::new(0), capture_warned: AtomicBool::new(false), + shortcut_warned: AtomicBool::new(false), + shortcut_failures: Mutex::new(RateLimit::new(2, 60_000)), stopped: AtomicBool::new(false), capture_retry_at: Mutex::new(None), controlled: Mutex::new(None), @@ -1068,6 +1147,14 @@ impl Engine { if let Some(dir) = &engine.inner.receive_dir { transfer::clean_staging(dir); } + // 桌面能替流界接下映射的触发键时(Hyprland),快捷键由 `sync_input` 注册过去, + // 合成器在用户按下时回调到这里。回调在协议线程里跑,只做转发。 + if engine.inner.input && flow_platform::desktop_shortcuts() { + let inner = Arc::downgrade(&engine.inner); + flow_platform::set_local_shortcut_handler(Box::new(move |id| { + local_shortcut(&inner, id) + })); + } if opts.discovery { let (tx, rx) = mpsc::unbounded_channel(); @@ -1119,6 +1206,8 @@ impl Engine { // 退出前恢复 AWDL。 let _ = flow_platform::low_latency::set_active(false); } + // 撤掉注册在桌面里的映射触发键(Hyprland),别让它们退出后还占着按键。 + flow_platform::clear_local_shortcuts(); self.inner.endpoint.close(0u32.into(), b"shutdown"); } @@ -1417,6 +1506,7 @@ impl Engine { /// 把当前可控制的设备、布局和防误触设置同步给跨屏控制器。 fn sync_input(&self) { let st = self.lock(); + let limits = flow_platform::limits(); self.inner .idle .store(st.sessions.is_empty(), Ordering::Relaxed); @@ -1437,6 +1527,21 @@ impl Engine { if self.inner.input { flow_platform::set_switch_edges(&layout.switch_edges(&local)); } + let hotkeys = usable_hotkeys(&st.config.settings.hotkeys, limits); + let remote_keys: HashSet = st + .sessions + .iter() + .filter(|(_, s)| s.remote_actions) + .map(|(id, _)| id.clone()) + .collect(); + // 桌面能接下触发键时(Hyprland),只注册现在真的发得出去的映射:发不出去的不占按键, + // 触发键照常交给原来的去处(和其他系统上"动作没做成就不算快捷键"一致)。 + let sendable: HashSet = remote_keys + .iter() + .filter(|id| outputs.contains_key(*id)) + .cloned() + .collect(); + let shortcuts = local_shortcuts(&hotkeys, &sendable, st.config.settings.sharing_paused); let cfg = ControllerConfig { layout, local_offset: st.config.local_offset, @@ -1444,7 +1549,7 @@ impl Engine { policy: switch_policy( &st.config.settings, st.locked || st.auto_lock.is_some(), - flow_platform::limits(), + limits, ), mapping: st.config.settings.mapping, wheel_percent: st.config.settings.wheel_percent(), @@ -1455,15 +1560,23 @@ impl Engine { .filter(|(_, s)| s.acks) .map(|(id, _)| id.clone()) .collect(), - hotkeys: usable_hotkeys(&st.config.settings.hotkeys, flow_platform::limits()), - remote_keys: st - .sessions - .iter() - .filter(|(_, s)| s.remote_actions) - .map(|(id, _)| id.clone()) - .collect(), + hotkeys, + remote_keys, }; + drop(st); self.controller().configure(cfg); + // 在本机按映射的触发键要靠桌面转交(曲线救国:Wayland 看不到全局键盘)。 + if self.inner.input && flow_platform::desktop_shortcuts() { + if let Err(e) = flow_platform::set_local_shortcuts(shortcuts) { + if !self.inner.shortcut_warned.swap(true, Ordering::Relaxed) { + warn!(error = %e, "没法把快捷键映射注册到桌面"); + self.notice(format!( + "没能把快捷键映射注册到桌面({})。设置里的映射暂时不能在本机触发。", + platform_reason(&e) + )); + } + } + } } fn notice(&self, msg: impl Into) { @@ -4768,6 +4881,7 @@ mod tests { assert_eq!(usable_hotkeys(&h, flow_platform::Limits::default()), h); let wayland = flow_platform::Limits { local_hotkey: true, + local_mapping: true, ..Default::default() }; let used = usable_hotkeys(&h, wayland); @@ -4775,6 +4889,45 @@ mod tests { // 切换用的快捷键照常保留(键鼠切过去之后用它切回来)。 assert_eq!(used.switch_left, h.switch_left); assert_eq!(used.switch_right, h.switch_right); + // Hyprland:看不到本机键盘(local_hotkey),但映射的触发键由合成器交给流界。 + let hypr = flow_platform::Limits { + local_hotkey: true, + ..Default::default() + }; + assert_eq!(usable_hotkeys(&h, hypr), h); + } + + #[test] + fn only_sendable_mappings_are_registered_with_the_desktop() { + use flow_core::hotkeys::{KeyCombo, KeyMapping}; + let ctrl_alt = Modifiers::CTRL | Modifiers::ALT; + let a = DeviceId("a".into()); + let b = DeviceId("b".into()); + let h = Hotkeys { + mappings: vec![ + // 目标连着、认得按键消息:注册。 + KeyMapping { + trigger: KeyCombo::new(ctrl_alt, KeyCode(0x16)), + send: KeyCombo::new(Modifiers::NONE, KeyCode(0x16)), + device: a.clone(), + }, + // 目标没连着:不注册。 + KeyMapping { + trigger: KeyCombo::new(ctrl_alt, KeyCode(0x17)), + send: KeyCombo::new(Modifiers::NONE, KeyCode(0x17)), + device: b, + }, + ], + ..Default::default() + }; + let sendable: HashSet = [a].into_iter().collect(); + let registered = local_shortcuts(&h, &sendable, false); + assert_eq!(registered.len(), 1); + // 序号还是设置里的序号(按下时按 id 找回对应的一条)。 + assert_eq!(registered[0].id, "mapping:0"); + assert_eq!(registered[0].combo, h.mappings[0].trigger); + // 共享暂停时一条也不注册,触发键留给本来的去处。 + assert!(local_shortcuts(&h, &sendable, true).is_empty()); } #[test] diff --git a/app/src-tauri/src/input.rs b/app/src-tauri/src/input.rs index 1fb0b8e..b48c523 100644 --- a/app/src-tauri/src/input.rs +++ b/app/src-tauri/src/input.rs @@ -570,6 +570,21 @@ impl Controller { } } + /// 桌面直接交给流界的快捷键(Hyprland 的全局快捷键,见 `flow_platform::LocalShortcut`): + /// `id` 是 `mapping:<序号>`,执行设置里对应的快捷键映射。和按下触发键走同一条路。 + pub fn run_shortcut(&mut self, id: &str) -> bool { + let index = id + .strip_prefix("mapping:") + .and_then(|n| n.parse::().ok()); + let Some(mapping) = index + .and_then(|i| self.cfg.hotkeys.mappings.get(i)) + .cloned() + else { + return false; + }; + self.send_keys(&mapping.device, mapping.send) + } + /// 快捷键映射:让 `device` 按一下 `keys`,键鼠不用切过去。对方没连着、被暂停、 /// 或版本太旧不认得这条消息时返回 `false`。锁定在本机不影响(它只限制键鼠切出去)。 fn send_keys(&mut self, device: &DeviceId, keys: KeyCombo) -> bool { diff --git a/app/src/HotkeySettings.tsx b/app/src/HotkeySettings.tsx index 1be3995..8dbf551 100644 --- a/app/src/HotkeySettings.tsx +++ b/app/src/HotkeySettings.tsx @@ -204,15 +204,20 @@ export function HotkeySettings({ state, update }: { state: StateView; update: (h

快捷键映射

- {state.unsupported.local_hotkey ? ( + {state.unsupported.local_mapping ? (

- 这台电脑用的是 Wayland,不支持快捷键映射:键鼠在本机时流界看不到键盘,按了没有反应。别的电脑设置的映射照常可以发到这台电脑。 + 这台电脑的桌面不支持快捷键映射:键鼠在本机时流界看不到键盘,按了没有反应。别的电脑设置的映射照常可以发到这台电脑。

) : ( <>

在这台电脑上按下一组键,让另一台电脑收到另一组键,键鼠不用切过去。比如按 {isMac ? "⌃ ⌥ S" : "Ctrl + Alt + S"},让另一台电脑收到 S;对方屏幕熄着时,发一个键过去也能把它点亮。

+ {state.unsupported.local_hotkey && ( +

+ Hyprland 上看不到全局键盘,映射的触发键会注册成 Hyprland 自己的全局快捷键(快捷键列表里显示为「流界:快捷键映射 N」),重载配置后会自动重新绑定。目标电脑没连着时不会注册,触发键照常交给原来的去处。 +

+ )}
{h.mappings.length === 0 && !draft &&
还没有映射。
} {h.mappings.map((m, i) => ( diff --git a/app/src/mock.ts b/app/src/mock.ts index 609c815..9fa7f35 100644 --- a/app/src/mock.ts +++ b/app/src/mock.ts @@ -47,7 +47,7 @@ export function createMock(): Api { permission_hint: null, controlled_by: null, low_latency: { supported: true, installed: false, active: false }, - unsupported: { hold_key: false, local_hotkey: false, dwell: false, edge_glow: false, auto_lock: false }, + unsupported: { hold_key: false, local_hotkey: false, local_mapping: false, dwell: false, edge_glow: false, auto_lock: false }, keep_awake_problem: null, about: { version: pkg.version, protocol: 1, data_dir: "~/Library/Application Support/app.flowacross.desktop", fingerprint: "3F2A 91C0 7B44 E1D9 0A6C 55F2 8E13 B7A0" }, transfers: [], diff --git a/app/src/types.ts b/app/src/types.ts index 057d7c9..6e566cb 100644 --- a/app/src/types.ts +++ b/app/src/types.ts @@ -180,6 +180,8 @@ export interface UnsupportedView { hold_key: boolean; /** 在这台电脑上按快捷键切到别的电脑(切过去之后用它切回来不受影响)。 */ local_hotkey: boolean; + /** 在这台电脑上按快捷键映射的触发键(Hyprland 能把它们注册成桌面的全局快捷键)。 */ + local_mapping: boolean; /** 「贴边停留」。 */ dwell: boolean; /** 边缘浮光。 */ diff --git a/crates/flow-platform/Cargo.toml b/crates/flow-platform/Cargo.toml index 568c445..9457413 100644 --- a/crates/flow-platform/Cargo.toml +++ b/crates/flow-platform/Cargo.toml @@ -49,6 +49,10 @@ x11rb = { version = "0.13", features = ["xinput", "xtest", "randr", "xfixes", "s # wayland-client 默认用纯 Rust 的协议实现,不链接 libwayland。 wayland-client = "0.31" wayland-protocols = { version = "0.32", features = ["client", "unstable"] } +# Hyprland 的全局快捷键协议不在 wayland-protocols 里:XML 放在 `protocols/`,编译时生成绑定。 +# 生成的代码直接引用 wayland-backend 的类型,要作为直接依赖。 +wayland-scanner = "0.31" +wayland-backend = "0.3" wayland-protocols-wlr = { version = "0.3", features = ["client"] } wayland-protocols-misc = { version = "0.3", features = ["client"] } # 虚拟键盘要自己提供键盘映射、自己算修饰键状态(链接系统的 libxkbcommon,打包时依赖 libxkbcommon-dev)。 diff --git a/crates/flow-platform/protocols/hyprland-global-shortcuts-v1.xml b/crates/flow-platform/protocols/hyprland-global-shortcuts-v1.xml new file mode 100644 index 0000000..784d887 --- /dev/null +++ b/crates/flow-platform/protocols/hyprland-global-shortcuts-v1.xml @@ -0,0 +1,112 @@ + + + + Copyright © 2022 Vaxry + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + + + This protocol allows a client to register triggerable actions, + meant to be global shortcuts. + + + + + This object is a manager which offers requests to create global shortcuts. + + + + + Register a new global shortcut. + + A global shortcut is anonymous, meaning the app does not know what key(s) trigger it. + + The shortcut's keybinding shall be dealt with by the compositor. + + In the case of a duplicate app_id + id combination, the already_taken protocol error is raised. + + + + + + + + + + + All objects created by the manager will still remain valid, until their + appropriate destroy request has been called. + + + + + + + + + + + This object represents a single shortcut. + + + + + The keystroke was pressed. + + tv_ values hold the timestamp of the occurrence. + + + + + + + + + The keystroke was released. + + tv_ values hold the timestamp of the occurrence. + + + + + + + + + Destroys the shortcut. Can be sent at any time by the client. + + + + diff --git a/crates/flow-platform/src/lib.rs b/crates/flow-platform/src/lib.rs index 633044a..9f7c345 100644 --- a/crates/flow-platform/src/lib.rs +++ b/crates/flow-platform/src/lib.rs @@ -25,6 +25,8 @@ mod linux_foreground; #[cfg(target_os = "linux")] mod linux_glow; #[cfg(target_os = "linux")] +mod linux_hypr_shortcuts; +#[cfg(target_os = "linux")] mod linux_input; #[cfg(target_os = "linux")] mod linux_portal; @@ -130,6 +132,60 @@ pub fn set_cursor_captured(captured: bool, restore_at: Option<(f64, f64)>) { let _ = (captured, restore_at); } +/// 由桌面直接注册的全局快捷键(目前只有 Hyprland):按下时由合成器通知流界, +/// 不用先在流界进程里看到键盘。 +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct LocalShortcut { + /// 按下时原样交还给回调的标识(引擎用它找对应的设置)。 + pub id: String, + /// 触发键。 + pub combo: flow_core::hotkeys::KeyCombo, + /// 在合成器自己的快捷键列表里显示的说明,例如「流界:快捷键映射 1」。 + pub description: String, +} + +/// 引擎接收 [`LocalShortcut`] 的回调:参数是 [`LocalShortcut::id`],在平台线程上调用, +/// 必须尽快返回(不能做网络 IO,只能投递到通道或直接改内存状态)。 +pub type LocalShortcutHandler = Box; + +/// 安装 [`LocalShortcut`] 的回调。要在 [`set_local_shortcuts`] 之前调用;重复调用替换旧的。 +pub fn set_local_shortcut_handler(handler: LocalShortcutHandler) { + #[cfg(target_os = "linux")] + linux::set_local_shortcut_handler(handler); + #[cfg(not(target_os = "linux"))] + let _ = handler; +} + +/// 把这些快捷键注册到桌面(Hyprland),按下时调用 [`set_local_shortcut_handler`] 装的回调。 +/// 每次调用整体替换上一组。当前桌面做不到时返回 [`PlatformError::Unsupported`]; +/// 注册在后台进行,不阻塞调用方。传空列表等于撤销全部注册。 +pub fn set_local_shortcuts(shortcuts: Vec) -> Result<(), PlatformError> { + #[cfg(target_os = "linux")] + return linux::set_local_shortcuts(shortcuts); + #[cfg(not(target_os = "linux"))] + { + let _ = shortcuts; + Err(PlatformError::Unsupported("快捷键映射")) + } +} + +/// 撤销全部 [`LocalShortcut`] 注册(退出时调用,等桌面里的绑定删掉再返回)。 +pub fn clear_local_shortcuts() { + #[cfg(target_os = "linux")] + linux::clear_local_shortcuts(); +} + +/// 当前桌面能不能替流界接下映射的触发键(Hyprland 的全局快捷键协议,见 [`LocalShortcut`])。 +/// +/// 和 [`limits`] 的 `local_mapping` 对应:这里为 `true` 时它一定是 `false`;它也是 `false` 的 +/// 其他系统本来就看得见全局键盘,用不着桌面代劳,这里同样返回 `false`。 +pub fn desktop_shortcuts() -> bool { + #[cfg(target_os = "linux")] + return linux_wl::hyprland_shortcuts(); + #[cfg(not(target_os = "linux"))] + false +} + /// 告诉平台层哪些屏幕边通往别的电脑:(本机显示器, 边)。布局或已连接的设备变化时由引擎调用。 /// /// 只有 Linux 的 Wayland 用得到:那里看不到全局的鼠标移动,只能在屏幕边上放一条很窄的窗口来感知 @@ -195,6 +251,9 @@ pub struct Limits { pub hold_key: bool, /// 在本机按 Ctrl+Alt+←/→ 切到别的电脑(切过去之后用它切回来不受影响)。 pub local_hotkey: bool, + /// 在本机按快捷键映射的触发键:看不到全局键盘,又没有可以代劳的桌面(Hyprland 有 + /// `hyprland-global-shortcuts-v1`,由它把按键交给流界,见 [`LocalShortcut`])。 + pub local_mapping: bool, /// 「停留一会儿才切换」:光标一碰到屏幕边系统就开始捕获,等不了。 pub dwell: bool, /// 边缘浮光。 diff --git a/crates/flow-platform/src/linux.rs b/crates/flow-platform/src/linux.rs index e404f7b..6ea122a 100644 --- a/crates/flow-platform/src/linux.rs +++ b/crates/flow-platform/src/linux.rs @@ -16,8 +16,9 @@ use x11rb::rust_connection::RustConnection; use crate::linux_wl::{self, Backend}; use crate::{ - ClipboardAccess, DisplayProvider, InputCapture, InputInjector, PlatformError, linux_clipboard, - linux_glow, linux_input, linux_portal, linux_wl_clipboard, linux_wl_glow, linux_wlr_input, + ClipboardAccess, DisplayProvider, InputCapture, InputInjector, LocalShortcut, + LocalShortcutHandler, PlatformError, linux_clipboard, linux_glow, linux_hypr_shortcuts, + linux_input, linux_portal, linux_wl_clipboard, linux_wl_glow, linux_wlr_input, }; // --------------------------------------------------------------------------- @@ -67,6 +68,22 @@ pub fn limits() -> crate::Limits { linux_wl::limits() } +/// 只有 Hyprland 能直接把全局快捷键交给流界(见 `linux_hypr_shortcuts.rs`)。 +pub fn set_local_shortcuts(shortcuts: Vec) -> Result<(), PlatformError> { + if !linux_wl::hyprland_shortcuts() { + return Err(PlatformError::Unsupported("快捷键映射")); + } + linux_hypr_shortcuts::set(shortcuts) +} + +pub fn set_local_shortcut_handler(handler: LocalShortcutHandler) { + linux_hypr_shortcuts::set_handler(handler); +} + +pub fn clear_local_shortcuts() { + linux_hypr_shortcuts::clear(); +} + pub fn set_cursor_captured(captured: bool, restore_at: Option<(f64, f64)>) { match linux_wl::backend() { Backend::X11 => linux_input::set_cursor_captured(captured, restore_at), diff --git a/crates/flow-platform/src/linux_hypr_shortcuts.rs b/crates/flow-platform/src/linux_hypr_shortcuts.rs new file mode 100644 index 0000000..7cf3eb4 --- /dev/null +++ b/crates/flow-platform/src/linux_hypr_shortcuts.rs @@ -0,0 +1,603 @@ +//! Hyprland 的全局快捷键:把快捷键映射注册成合成器的快捷键,按下时交给流界。 +//! +//! Wayland 的普通程序看不到全局键盘(见 `linux_wlr_input.rs`),Hyprland 为此提供了 +//! `hyprland-global-shortcuts-v1`:程序注册一组快捷键,合成器在用户按下时通知它。协议只负责通知, +//! 触发键还要在合成器里绑上(`global, :`),所以这里同时做两件事: +//! +//! - 在单独的线程里连着合成器,注册协议对象;按下时按 id 调用回调(界面上看到的是一次按键, +//! 不用先运行一个流界进程,和别的系统一样没有额外延迟)。 +//! - 用 `hyprctl` 把每个触发键绑到 `global, :`。Hyprland 0.57 起配置换成了 Lua, +//! 运行时绑定用 `hyprctl eval 'hl.bind(…)'`;更早的版本用 `hyprctl keyword bind …`,两种都支持。 +//! 配置文件重载会清掉这些运行时绑定,所以盯着合成器的 `.socket2.sock`,收到 `configreloaded` +//! 就重新绑定。 +//! +//! 触发键在合成器里按物理键位(`code:`)绑,和流界其他地方一致:字符仍由本机布局决定。 +//! 协议文件来自 Hyprland(`protocols/hyprland-global-shortcuts-v1.xml`,BSD 三条款许可,版权见文件头)。 + +use std::collections::{HashMap, HashSet}; +use std::io::{BufRead, BufReader}; +use std::os::unix::net::UnixStream; +use std::path::PathBuf; +use std::process::Command; +use std::sync::mpsc::{self, Receiver, Sender}; +use std::sync::{Mutex, OnceLock}; +use std::thread; +use std::time::Duration; + +use flow_core::hotkeys::KeyCombo; +use flow_core::keys::Modifiers; +use wayland_client::globals::{GlobalListContents, registry_queue_init}; +use wayland_client::protocol::wl_registry; +use wayland_client::{Connection, Dispatch, EventQueue, QueueHandle}; + +use crate::keymap; +use crate::linux_wl; +use crate::{LocalShortcut, PlatformError}; + +mod protocol { + //! `hyprland-global-shortcuts-v1` 的客户端绑定,由 `wayland-scanner` 从 `protocols/` 里的 XML 生成。 + //! 生成代码的警告不由我们控制。 + #![allow(dead_code, non_camel_case_types, unused_unsafe, unused_variables)] + #![allow(non_upper_case_globals, non_snake_case, unused_imports)] + #![allow(missing_docs, clippy::all)] + + use wayland_client; + use wayland_client::protocol::*; + + pub mod __interfaces { + use wayland_client::protocol::__interfaces::*; + + wayland_scanner::generate_interfaces!("protocols/hyprland-global-shortcuts-v1.xml"); + } + use self::__interfaces::*; + + wayland_scanner::generate_client_code!("protocols/hyprland-global-shortcuts-v1.xml"); +} + +use protocol::hyprland_global_shortcut_v1::{Event as ShortcutEvent, HyprlandGlobalShortcutV1}; +use protocol::hyprland_global_shortcuts_manager_v1::HyprlandGlobalShortcutsManagerV1; + +/// 注册到合成器的应用标识(和打包的应用标识一致;`global, :` 靠它找到流界)。 +const APP_ID: &str = "app.flowacross.desktop"; + +/// 按下的快捷键怎么通知引擎。 +type Handler = Box; + +static HANDLER: Mutex> = Mutex::new(None); + +/// 引擎装一个回调:合成的快捷键被按下时调用它(参数是 [`LocalShortcut::id`])。 +pub(crate) fn set_handler(handler: Handler) { + *HANDLER.lock().unwrap_or_else(|e| e.into_inner()) = Some(handler); +} + +fn pressed(id: &str) { + if let Some(handler) = HANDLER.lock().unwrap_or_else(|e| e.into_inner()).as_mut() { + handler(id); + } +} + +/// 和 Hyprland 的绑定怎么写。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum BindStyle { + /// Hyprland 0.57 起(配置是 Lua):`hyprctl eval 'hl.bind(…)'`。 + Lua, + /// 更早的版本:`hyprctl keyword bind …`。 + Classic, +} + +enum Request { + /// 换成这一组快捷键。带 `Sender` 时,处理完(绑定也写好了)回一个信号。 + Set(Vec, Option>), + /// Hyprland 重载了配置:运行时绑定被清掉,按当前设置重新绑。 + Rebind, +} + +struct Service { + tx: Sender, +} + +static SERVICE: OnceLock> = OnceLock::new(); + +/// 换一组要注册到 Hyprland 的快捷键,整体替换上一组。注册在后台线程上进行,不阻塞调用方。 +pub(crate) fn set(shortcuts: Vec) -> Result<(), PlatformError> { + // 第一条映射出现之前不用连合成器;引擎每次同步都会调用这里。 + if shortcuts.is_empty() && SERVICE.get().is_none() { + return Ok(()); + } + let service = match SERVICE.get_or_init(|| start_service().map_err(|e| e.to_string())) { + Ok(service) => service, + Err(reason) => return Err(PlatformError::Os(reason.clone())), + }; + service + .tx + .send(Request::Set(shortcuts, None)) + .map_err(|_| PlatformError::Os("Hyprland 快捷键线程已经停止".into())) +} + +/// 撤销全部注册(退出时调用,等绑定真的删掉再返回)。没启动过、或注册失败时什么都不做。 +pub(crate) fn clear() { + let Some(Ok(service)) = SERVICE.get() else { + return; + }; + let (ack, done) = mpsc::channel(); + if service.tx.send(Request::Set(Vec::new(), Some(ack))).is_ok() { + let _ = done.recv_timeout(Duration::from_secs(2)); + } +} + +/// 连上合成器、绑定 `hyprland-global-shortcuts-v1`,起两个线程:一个收合成器的事件, +/// 一个处理设置变化(注册 / 撤销协议对象、改 Hyprland 的绑定)。 +fn start_service() -> Result { + let conn = linux_wl::connect().map_err(|e| e.to_string())?; + let (globals, queue): (_, EventQueue) = + registry_queue_init(&conn).map_err(|e| format!("读取 Wayland 协议列表失败:{e}"))?; + let qh = queue.handle(); + let manager: HyprlandGlobalShortcutsManagerV1 = globals + .bind(&qh, 1..=1, ()) + .map_err(|e| format!("Hyprland 没有提供全局快捷键协议:{e}"))?; + let style = detect_style()?; + let (tx, rx) = mpsc::channel(); + + // Hyprland 重载配置时会把运行时加的绑定清掉,重新绑一次。 + if let Some(socket) = reload_socket() { + let tx = tx.clone(); + let _ = thread::Builder::new() + .name("flowacross-hypr-reload".into()) + .spawn(move || watch_reloads(socket, tx)); + } + + thread::Builder::new() + .name("flowacross-hypr-shortcuts".into()) + .spawn(move || { + let mut queue = queue; + let mut state = State; + loop { + match queue.blocking_dispatch(&mut state) { + Ok(_) => {} + Err(e) => { + // 合成器退出(或连接断了):等进程结束。重新连上要重新注册, + // 而 Hyprland 退出通常意味着整个会话要结束了。 + eprintln!("Hyprland 快捷键连接断开:{e}"); + break; + } + } + } + }) + .map_err(|e| format!("启动 Hyprland 快捷键线程失败:{e}"))?; + + thread::Builder::new() + .name("flowacross-hypr-bind".into()) + .spawn(move || command_loop(conn, manager, qh, style, rx)) + .map_err(|e| format!("启动 Hyprland 绑定线程失败:{e}"))?; + + Ok(Service { tx }) +} + +/// 收合成器的事件:只有 `pressed` 有用(`released` 也要读掉,不然队列会一直积着)。 +struct State; + +impl Dispatch for State { + fn event( + _: &mut Self, + _: &wl_registry::WlRegistry, + _: wl_registry::Event, + _: &GlobalListContents, + _: &Connection, + _: &QueueHandle, + ) { + } +} + +impl Dispatch for State { + fn event( + _: &mut Self, + _: &HyprlandGlobalShortcutsManagerV1, + _: ::Event, + _: &(), + _: &Connection, + _: &QueueHandle, + ) { + } +} + +impl Dispatch for State { + fn event( + _: &mut Self, + _: &HyprlandGlobalShortcutV1, + event: ShortcutEvent, + id: &String, + _: &Connection, + _: &QueueHandle, + ) { + if matches!(event, ShortcutEvent::Pressed { .. }) { + pressed(id); + } + } +} + +/// 现在注册到 Hyprland 里的东西:协议对象和绑定的触发键,撤销时按这个来。 +struct Bindings { + specs: Vec, + objects: HashMap, + /// 绑在 Hyprland 里的触发键(同一种写法,撤销时原样用)。 + keys: Vec, +} + +fn command_loop( + conn: Connection, + manager: HyprlandGlobalShortcutsManagerV1, + qh: QueueHandle, + style: BindStyle, + rx: Receiver, +) { + let mut bindings = Bindings { + specs: Vec::new(), + objects: HashMap::new(), + keys: Vec::new(), + }; + while let Ok(command) = rx.recv() { + let (specs, force, ack) = match command { + Request::Set(specs, ack) => (specs, false, ack), + // 重载后重新绑一次;协议对象还在,不用动。 + Request::Rebind => (bindings.specs.clone(), true, None), + }; + apply(&conn, &manager, &qh, style, specs, force, &mut bindings); + if let Some(ack) = ack { + let _ = ack.send(()); + } + } +} + +/// 把 Hyprland 里的绑定和协议注册换成 `specs`。任何一步失败都只记日志:下次设置变化时会再试。 +/// `force` 为真时内容没变也重新绑(Hyprland 重载配置后运行时绑定没了)。 +fn apply( + conn: &Connection, + manager: &HyprlandGlobalShortcutsManagerV1, + qh: &QueueHandle, + style: BindStyle, + specs: Vec, + force: bool, + bindings: &mut Bindings, +) { + let specs = normalize(specs); + // 引擎每次同步都会调用这里,内容没变就别再调 hyprctl。 + if !force && specs == bindings.specs { + return; + } + // 内容变了的(触发键、说明、目标)先撤销,再按新的注册。 + let stale: Vec = bindings + .objects + .iter() + .filter(|(id, (old, _))| specs.iter().find(|s| &s.id == *id) != Some(old)) + .map(|(id, _)| id.clone()) + .collect(); + for id in stale { + if let Some((_, shortcut)) = bindings.objects.remove(&id) { + shortcut.destroy(); + } + } + for spec in &specs { + if bindings.objects.contains_key(&spec.id) { + continue; + } + let trigger = key_string(style, &spec.combo).unwrap_or_default(); + let shortcut = manager.register_shortcut( + spec.id.clone(), + APP_ID.to_owned(), + spec.description.clone(), + trigger, + qh, + spec.id.clone(), + ); + bindings + .objects + .insert(spec.id.clone(), (spec.clone(), shortcut)); + } + if let Err(e) = conn.flush() { + eprintln!("注册 Hyprland 快捷键失败:{e}"); + } + bindings.keys = apply_binds(style, &bindings.keys, &specs); + bindings.specs = specs; +} + +/// 去掉重复和绑不了的:同一 id 只留第一个,键码表里查不到的组合([`keymap::to_linux`] 为空) +/// 跳过,不带修饰键又不是功能键的也不绑(那等于把整个按键从所有程序手里抢走)。 +fn normalize(specs: Vec) -> Vec { + let mut seen = HashSet::new(); + specs + .into_iter() + .filter(|s| !s.id.is_empty() && s.combo.is_trigger() && key_number(s.combo).is_some()) + .filter(|s| seen.insert(s.id.clone())) + .collect() +} + +/// 触发键在 Hyprland 里的写法: +/// - Lua(0.57 起):`CTRL + ALT + code:39`; +/// - 更早的版本:`CTRL ALT, code:39`。 +/// +/// 用键码而不是键名:`code:` 是 xkb 键码(evdev 加 8),和本机键盘布局无关,流界各处的键码表正好能换。 +fn key_string(style: BindStyle, combo: &KeyCombo) -> Option { + let code = key_number(*combo)?; + let mut mods = Vec::new(); + for (mask, name) in [ + (Modifiers::CTRL, "CTRL"), + (Modifiers::ALT, "ALT"), + (Modifiers::SHIFT, "SHIFT"), + (Modifiers::META, "SUPER"), + ] { + if combo.mods.contains(mask) { + mods.push(name); + } + } + let key = format!("code:{code}"); + Some(match style { + BindStyle::Lua => { + let mut parts: Vec = mods.iter().map(|s| (*s).to_owned()).collect(); + parts.push(key); + parts.join(" + ") + } + BindStyle::Classic if mods.is_empty() => key, + BindStyle::Classic => format!("{}, {key}", mods.join(" ")), + }) +} + +/// HID 键码 → xkb 键码(evdev 加 8);键码表里没有的键返回 `None`。 +fn key_number(combo: KeyCombo) -> Option { + keymap::to_linux(combo.key)?.checked_add(8) +} + +/// 在 Hyprland 里换掉绑定:先删掉上一次的(以及这次要用的,清掉上次崩溃留下的),再按现在的绑。 +/// 返回这次之后应该绑定着的触发键,供下一次撤销、以及退出时清理。 +fn apply_binds(style: BindStyle, old: &[String], specs: &[LocalShortcut]) -> Vec { + // 能绑的(触发键在键码表里查得到),按设置里的顺序。 + let keys: Vec<(String, &LocalShortcut)> = specs + .iter() + .filter_map(|s| Some((key_string(style, &s.combo)?, s))) + .collect(); + let mut unbind = old.to_vec(); + for (key, _) in &keys { + if !unbind.contains(key) { + unbind.push(key.clone()); + } + } + match style { + BindStyle::Lua => { + let mut script = String::new(); + for key in &unbind { + script.push_str(&format!("hl.unbind({})\n", lua_string(key))); + } + for (key, spec) in &keys { + script.push_str(&format!( + "hl.bind({}, hl.dsp.global({}), {{description = {}}})\n", + lua_string(key), + lua_string(&format!("{APP_ID}:{}", spec.id)), + lua_string(&spec.description) + )); + } + if !script.is_empty() { + run_hyprctl(&["eval", &script]); + } + } + BindStyle::Classic => { + for key in &unbind { + run_hyprctl(&["keyword", "unbind", key]); + } + for (key, spec) in &keys { + run_hyprctl(&[ + "keyword", + "bind", + &format!("{key}, global, {APP_ID}:{}", spec.id), + ]); + } + } + } + keys.into_iter().map(|(key, _)| key).collect() +} + +/// Lua 字符串字面量。说明文字是我们自己生成的,但仍然照规矩转义(将来可能带上设备名)。 +fn lua_string(s: &str) -> String { + let mut out = String::with_capacity(s.len() + 2); + out.push('"'); + for c in s.chars() { + match c { + '\\' => out.push_str("\\\\"), + '"' => out.push_str("\\\""), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + c if (c as u32) < 0x20 => out.push_str(&format!("\\{:03}", c as u32)), + c => out.push(c), + } + } + out.push('"'); + out +} + +/// 是 Lua 配置(0.57 起)还是老的 hyprlang 配置。老版本没有 `eval`,会回 "unknown request"。 +fn detect_style() -> Result { + match hyprctl(&["eval", "return 1"]) { + Ok(out) if !out.contains("unknown request") => Ok(BindStyle::Lua), + Ok(_) => Ok(BindStyle::Classic), + Err(e) => Err(format!( + "找不到可用的 hyprctl(Hyprland 的命令行工具):{e}" + )), + } +} + +fn run_hyprctl(args: &[&str]) { + if let Err(e) = hyprctl(args) { + eprintln!("hyprctl {} 失败:{e}", args.first().copied().unwrap_or("")); + } +} + +/// 运行 `hyprctl`,返回标准输出。失败时把错误输出(或系统错误)带回来。 +fn hyprctl(args: &[&str]) -> Result { + let out = Command::new("hyprctl") + .args(args) + .output() + .map_err(|e| e.to_string())?; + let stdout = String::from_utf8_lossy(&out.stdout).trim().to_owned(); + if !out.status.success() { + let stderr = String::from_utf8_lossy(&out.stderr); + let reason = stderr.trim(); + return Err(match reason.is_empty() { + true => format!("退出码 {}", out.status.code().unwrap_or(-1)), + false => reason.to_owned(), + }); + } + if stdout.starts_with("unknown request") { + // `keyword` 的未知请求也是退出码 0,由调用方看内容。 + return Ok(stdout); + } + Ok(stdout) +} + +/// Hyprland 事件套接字(`.socket2.sock`)的位置:新版本在 `$XDG_RUNTIME_DIR/hypr/<签名>/`, +/// 更早的在 `/tmp/hypr/<签名>/`。 +fn reload_socket() -> Option { + let sig = std::env::var_os("HYPRLAND_INSTANCE_SIGNATURE")?; + let newer = std::env::var_os("XDG_RUNTIME_DIR") + .map(PathBuf::from) + .map(|d| d.join("hypr").join(&sig).join(".socket2.sock")) + .filter(|p| p.exists()); + newer.or_else(|| { + let older = PathBuf::from("/tmp/hypr").join(&sig).join(".socket2.sock"); + older.exists().then_some(older) + }) +} + +/// 读 Hyprland 的事件流:配置文件重载后让绑定线程重新绑定。 +fn watch_reloads(path: PathBuf, tx: Sender) { + let Ok(stream) = UnixStream::connect(&path) else { + return; + }; + for line in BufReader::new(stream).lines().map_while(Result::ok) { + if line.starts_with("configreloaded") && tx.send(Request::Rebind).is_err() { + return; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use flow_core::keys::KeyCode; + + fn ctrl_alt(key: KeyCode) -> KeyCombo { + KeyCombo::new(Modifiers::CTRL | Modifiers::ALT, key) + } + + #[test] + fn trigger_keys_use_physical_keycodes() { + // S:HID 0x16 → evdev 31 → xkb 39。 + let s = KeyCombo::new(Modifiers::CTRL | Modifiers::ALT, KeyCode(0x16)); + assert_eq!( + key_string(BindStyle::Lua, &s).unwrap(), + "CTRL + ALT + code:39" + ); + assert_eq!( + key_string(BindStyle::Classic, &s).unwrap(), + "CTRL ALT, code:39" + ); + // 修饰键的顺序固定;⌘ / Win 在 Hyprland 里是 SUPER。 + let meta_shift = KeyCombo::new(Modifiers::META | Modifiers::SHIFT, KeyCode::A); + assert_eq!( + key_string(BindStyle::Lua, &meta_shift).unwrap(), + "SHIFT + SUPER + code:38" + ); + assert_eq!( + key_string(BindStyle::Classic, &meta_shift).unwrap(), + "SHIFT SUPER, code:38" + ); + // 功能键可以不带修饰键;← 是 xkb 113。 + let f5 = KeyCombo::new(Modifiers::NONE, KeyCode(0x3E)); + assert_eq!(key_string(BindStyle::Lua, &f5).unwrap(), "code:71"); + let left = KeyCombo::new(Modifiers::NONE, KeyCode::LEFT); + assert_eq!(key_string(BindStyle::Classic, &left).unwrap(), "code:113"); + // 多媒体键(借用键盘页的 0xE8–0xEB)也能绑。 + let play = KeyCombo::new(Modifiers::NONE, KeyCode::PLAY_PAUSE); + assert_eq!(key_string(BindStyle::Lua, &play).unwrap(), "code:172"); + } + + #[test] + fn unknown_keycodes_are_skipped() { + // 键码表里没有的键(这个值只在保留区里)绑不了。 + let odd = KeyCombo::new(Modifiers::CTRL, KeyCode(0xA0)); + assert_eq!(key_number(odd), None); + assert_eq!(key_string(BindStyle::Lua, &odd), None); + assert_eq!(key_string(BindStyle::Classic, &odd), None); + let specs = normalize(vec![ + LocalShortcut { + id: "a".into(), + combo: odd, + description: "x".into(), + }, + LocalShortcut { + id: "".into(), + combo: ctrl_alt(KeyCode(0x16)), + description: "x".into(), + }, + LocalShortcut { + id: "b".into(), + combo: ctrl_alt(KeyCode(0x16)), + description: "x".into(), + }, + LocalShortcut { + id: "b".into(), + combo: ctrl_alt(KeyCode(0x17)), + description: "y".into(), + }, + ]); + assert_eq!(specs.len(), 1); + assert_eq!(specs[0].id, "b"); + assert_eq!(specs[0].combo.key, KeyCode(0x16)); + } + + #[test] + fn plain_keys_are_not_taken_from_other_programs() { + // 没带修饰键、又不是功能键的按键不能注册成全局快捷键:那会把整个按键抢走。 + let specs = normalize(vec![LocalShortcut { + id: "mapping:0".into(), + combo: KeyCombo::new(Modifiers::NONE, KeyCode(0x16)), + description: "x".into(), + }]); + assert!(specs.is_empty()); + // 功能键可以单独用。 + let f = normalize(vec![LocalShortcut { + id: "mapping:0".into(), + combo: KeyCombo::new(Modifiers::NONE, KeyCode(0x3E)), + description: "x".into(), + }]); + assert_eq!(f.len(), 1); + } + + #[test] + fn lua_strings_are_escaped() { + assert_eq!( + lua_string("CTRL + ALT + code:39"), + "\"CTRL + ALT + code:39\"" + ); + assert_eq!(lua_string("流界:快捷键映射 1"), "\"流界:快捷键映射 1\""); + assert_eq!(lua_string("a\"b\\c"), "\"a\\\"b\\\\c\""); + assert_eq!(lua_string("a\nb"), "\"a\\nb\""); + } + + #[test] + fn normalize_keeps_the_first_of_each_id_order() { + let specs = normalize(vec![ + LocalShortcut { + id: "mapping:0".into(), + combo: ctrl_alt(KeyCode(0x16)), + description: "第一条".into(), + }, + LocalShortcut { + id: "mapping:1".into(), + combo: ctrl_alt(KeyCode(0x17)), + description: "第二条".into(), + }, + ]); + assert_eq!( + specs.iter().map(|s| s.id.as_str()).collect::>(), + vec!["mapping:0", "mapping:1"] + ); + } +} diff --git a/crates/flow-platform/src/linux_wl.rs b/crates/flow-platform/src/linux_wl.rs index e6209bc..d748a31 100644 --- a/crates/flow-platform/src/linux_wl.rs +++ b/crates/flow-platform/src/linux_wl.rs @@ -53,33 +53,60 @@ fn pick_backend(wayland: bool, globals: Option<&[String]>) -> Backend { } } -/// 当前会话的类型,以及合成器有没有 layer-shell(浮光要用)。进程启动后不会变,只判断一次。 -fn session() -> (Backend, bool) { - static SESSION: OnceLock<(Backend, bool)> = OnceLock::new(); - *SESSION.get_or_init(|| { +/// 当前会话的类型、合成器有没有 layer-shell(浮光要用)、以及是不是 Hyprland 并且能直接 +/// 注册全局快捷键。进程启动后不会变,只判断一次。 +struct Session { + backend: Backend, + layer_shell: bool, + /// 合成器提供 `hyprland-global-shortcuts-v1`,并且有 `hyprctl` 可用的 Hyprland 会话。 + hypr_shortcuts: bool, +} + +fn detect(wayland: bool, globals: Option<&[String]>, hypr_session: bool) -> Session { + let has = |g: &[String], name: &str| g.iter().any(|i| i == name); + let backend = pick_backend(wayland, globals); + Session { + backend, + layer_shell: globals.is_some_and(|g| has(g, "zwlr_layer_shell_v1")), + // 只有 Hyprland 有这套协议;再认一下环境变量,免得嵌套(别的合成器里跑的 Hyprland)时 + // 拿 hyprctl 去改错地方。 + hypr_shortcuts: backend == Backend::Wlr + && globals.is_some_and(|g| has(g, "hyprland_global_shortcuts_manager_v1")) + && hypr_session, + } +} + +fn session() -> &'static Session { + static SESSION: OnceLock = OnceLock::new(); + SESSION.get_or_init(|| { let wayland = wayland_session(); let globals = wayland.then(global_interfaces).and_then(Result::ok); - let layer_shell = globals - .as_deref() - .is_some_and(|g| g.iter().any(|i| i == "zwlr_layer_shell_v1")); - (pick_backend(wayland, globals.as_deref()), layer_shell) + let hypr = std::env::var_os("HYPRLAND_INSTANCE_SIGNATURE").is_some(); + detect(wayland, globals.as_deref(), hypr) }) } pub(crate) fn backend() -> Backend { - session().0 + session().backend +} + +/// 能不能把全局快捷键注册到 Hyprland(见 `linux_hypr_shortcuts.rs`)。 +pub(crate) fn hyprland_shortcuts() -> bool { + session().hypr_shortcuts } /// 这种会话里做不到的切换方式和效果。 -fn limits_for(backend: Backend, layer_shell: bool) -> Limits { - match backend { +fn limits_for(session: &Session) -> Limits { + match session.backend { Backend::X11 => Limits::default(), // 看不到全局键盘。 Backend::Wlr => Limits { hold_key: true, local_hotkey: true, + // Hyprland 能把映射的触发键注册成自己的全局快捷键,Sway 没有这个协议。 + local_mapping: !session.hypr_shortcuts, dwell: false, - edge_glow: !layer_shell, + edge_glow: !session.layer_shell, local_input: true, // 可以把边缘窗口铺满屏幕接住光标,见 `linux_wlr_input.rs` 的 `apply_summon`。 commanded_switch: false, @@ -89,8 +116,9 @@ fn limits_for(backend: Backend, layer_shell: bool) -> Limits { Backend::Portal => Limits { hold_key: true, local_hotkey: true, + local_mapping: true, dwell: true, - edge_glow: !layer_shell, + edge_glow: !session.layer_shell, local_input: true, commanded_switch: true, foreground_app: true, @@ -99,8 +127,7 @@ fn limits_for(backend: Backend, layer_shell: bool) -> Limits { } pub(crate) fn limits() -> Limits { - let (backend, layer_shell) = session(); - limits_for(backend, layer_shell) + limits_for(session()) } pub(crate) fn connect() -> Result { @@ -442,16 +469,59 @@ mod tests { assert_eq!(pick_backend(true, None), Backend::Portal); } + fn session(b: Backend, layer_shell: bool, hypr: bool) -> Session { + Session { + backend: b, + layer_shell, + hypr_shortcuts: hypr, + } + } + #[test] fn wayland_sessions_report_what_they_cannot_do() { - assert_eq!(limits_for(Backend::X11, false), Limits::default()); - let sway = limits_for(Backend::Wlr, true); + assert_eq!( + limits_for(&session(Backend::X11, false, false)), + Limits::default() + ); + let sway = limits_for(&session(Backend::Wlr, true, false)); assert!(sway.hold_key && sway.local_hotkey && sway.local_input && sway.foreground_app); assert!(!sway.dwell && !sway.edge_glow); - let kde = limits_for(Backend::Portal, true); + // 只有 Hyprland 能直接注册映射的触发键。 + assert!(sway.local_mapping); + let hypr = limits_for(&session(Backend::Wlr, true, true)); + assert!(!hypr.local_mapping); + assert!(hypr.local_hotkey && hypr.hold_key); + let kde = limits_for(&session(Backend::Portal, true, false)); assert!(kde.hold_key && kde.local_hotkey && kde.dwell && !kde.edge_glow); + assert!(kde.local_mapping); // GNOME 没有 layer-shell:浮光也没有。 - assert!(limits_for(Backend::Portal, false).edge_glow); + assert!(limits_for(&session(Backend::Portal, false, false)).edge_glow); + } + + #[test] + fn only_hyprland_sessions_can_register_shortcuts() { + let hypr = names(&[ + "wl_compositor", + "zwlr_layer_shell_v1", + "zwlr_virtual_pointer_manager_v1", + "zwp_virtual_keyboard_manager_v1", + "hyprland_global_shortcuts_manager_v1", + ]); + // 协议在、又是 Hyprland 会话(有 hyprctl)才算。 + let detected = detect(true, Some(&hypr), true); + assert_eq!(detected.backend, Backend::Wlr); + assert!(detected.hypr_shortcuts); + // 不在 Hyprland 会话里(嵌套的合成器)不算。 + assert!(!detect(true, Some(&hypr), false).hypr_shortcuts); + // Sway 没有这个协议。 + let sway = names(&[ + "zwlr_layer_shell_v1", + "zwlr_virtual_pointer_manager_v1", + "zwp_virtual_keyboard_manager_v1", + ]); + assert!(!detect(true, Some(&sway), true).hypr_shortcuts); + // X11 会话里不算。 + assert!(!detect(false, Some(&hypr), true).hypr_shortcuts); } fn output(mode: (i32, i32), logical: Option<((i32, i32), (i32, i32))>) -> Output { diff --git a/docs/architecture.md b/docs/architecture.md index 833498d..be43b54 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -98,7 +98,7 @@ - **快捷键与快捷键映射**(`flow-core::hotkeys`,设置里的 `Settings::hotkeys`):快捷键是"手边这台电脑"的——只有物理键盘所在的电脑看得到按键,所以各台电脑各设各的,由控制器(`input::Controller`)在捕获回调里匹配。一组键 = 修饰键位掩码 + 一个 HID 主键,修饰键按"恰好相等"匹配(Ctrl+Alt+S 和 Ctrl+Alt+Shift+S 是两个快捷键);触发键必须带 Ctrl、Alt 或 ⌘ / Win 之一,功能键(F1–F20、Print Screen、Scroll Lock、Pause)可以单独用(F21–F24 各系统的键码表里没有,不收)。保存前由 `Hotkeys::sanitized` 去掉不合法和重复的;设备被移除时指向它的一并删掉。三类动作: - 切到左 / 右相邻的电脑:默认 Ctrl+Alt+←/→,可以改、可以关。 - 切到指定的电脑(包括回到本机):`Controller::switch_to_device`,进入目标面积最大的那块屏幕的中央。 - - **快捷键映射**(用户需求,类似 Synergy 的 hotkey):按下一组键,让指定的电脑收到另一组键,键鼠不用切过去。控制方发 `Message::KeyStroke { keys }`(0.2.4 新增,修饰键在前),被控制方不需要先收到 `Enter`:依次按下、反序抬起,修饰键照常按第 5 节的规则换算。如果正在控制它的设备手上还按着修饰键(触发映射用的 Ctrl、Alt 多半已经发过去了),被控制方先把它们抬起、按完再按回去(`hotkeys::tap_sequence`),否则对方收到的是 Ctrl+Alt+S 而不是 S。发来的按键也算"有人在用",屏幕熄着会点亮。对方暂停了共享时不理会;锁定在本机不影响发送(没有把键鼠切出去)。看不到全局键盘的桌面(Linux 的 Wayland)不支持在本机设置映射:键鼠在本机时触发键按了没反应,设置页不显示这一节,配置里留着的映射控制器也不用(`engine::usable_hotkeys`);别的电脑发来的映射按键照常注入。 + - **快捷键映射**(用户需求,类似 Synergy 的 hotkey):按下一组键,让指定的电脑收到另一组键,键鼠不用切过去。控制方发 `Message::KeyStroke { keys }`(0.2.4 新增,修饰键在前),被控制方不需要先收到 `Enter`:依次按下、反序抬起,修饰键照常按第 5 节的规则换算。如果正在控制它的设备手上还按着修饰键(触发映射用的 Ctrl、Alt 多半已经发过去了),被控制方先把它们抬起、按完再按回去(`hotkeys::tap_sequence`),否则对方收到的是 Ctrl+Alt+S 而不是 S。发来的按键也算"有人在用",屏幕熄着会点亮。对方暂停了共享时不理会;锁定在本机不影响发送(没有把键鼠切出去)。看不到全局键盘的桌面要在本机用映射,得让桌面替流界看着触发键:Hyprland 上把每条映射注册成合成器的全局快捷键(`hyprland-global-shortcuts-v1`,见第 12 节),按下时合成器通过 `flow_platform::LocalShortcut` 交给流界,引擎再走和捕获回调里一样的 `Controller::run_shortcut`。注册表由 `Engine::sync_input` 在每次设备、连接、设置变化后整体替换,只包含现在真的发得出去的映射(目标电脑连着、认 `Message::KeyStroke`、共享没暂停):发不出去的不占触发键,按键照常交给原来的去处。Sway、GNOME / KDE 的 Wayland 没有能用的接口,不支持在本机设置映射:键鼠在本机时触发键按了没反应,设置页不显示这一节,配置里留着的映射控制器也不用(`engine::usable_hotkeys`)。别的电脑发来的映射按键照常注入。 - 动作做不成时(没有那台电脑、没连着、被暂停、对方版本太旧)不算快捷键,按键照常交给原来的去处,和以前"右边没有电脑时 Ctrl+Alt+→ 照常放行"一致。触发键的连发和抬起都拦截。 - 设置页录制快捷键时,按键是从网页的键盘事件(`KeyboardEvent.code`,物理键位)换算成 HID 的(`app/src/keys.ts`);录制期间界面通知引擎暂停响应快捷键(`set_hotkeys_suspended`),否则刚按下的组合键会直接把键鼠切走。 - Wayland 上键鼠在本机时看不到键盘(`Limits::local_hotkey`),这些快捷键只有在键鼠已经切到别的电脑之后才起作用。 @@ -267,12 +267,12 @@ Linux 上有三套实现,启动时按桌面会话选一套(`linux_wl.rs` 的 | 会话 | 实现 | 文件 | |---|---|---| | X11 | XInput2 / XTest / RandR / X 选区(纯 Rust 的 x11rb,不链接 libxcb / libX11) | `linux.rs`、`linux_input.rs`、`linux_clipboard.rs`、`linux_glow.rs` | -| Wayland,合成器有 wlroots 的虚拟输入和 layer-shell 协议(Sway、Hyprland 等) | 虚拟指针 / 虚拟键盘、layer-shell、data-control(纯 Rust 的 wayland-client;xkbcommon 链接系统库) | `linux_wl.rs`、`linux_wlr_input.rs`、`linux_wl_clipboard.rs`、`linux_wl_glow.rs` | +| Wayland,合成器有 wlroots 的虚拟输入和 layer-shell 协议(Sway、Hyprland 等) | 虚拟指针 / 虚拟键盘、layer-shell、data-control(纯 Rust 的 wayland-client;xkbcommon 链接系统库);Hyprland 另有全局快捷键协议 | `linux_wl.rs`、`linux_wlr_input.rs`、`linux_wl_clipboard.rs`、`linux_wl_glow.rs`、`linux_hypr_shortcuts.rs` | | Wayland,其他合成器(GNOME、KDE) | xdg-desktop-portal(ashpd)+ libei 协议(纯 Rust 的 reis) | `linux_portal.rs`,剪贴板和浮光尽量复用上一行的 | 做不到的切换方式由 `flow_platform::limits()` 报告(按会话类型和有没有 layer-shell 判断):引擎生成切换策略时忽略对应的设置(否则打开「按住修饰键才切换」就永远切不过去),并通过状态里的 `unsupported` 告诉界面,设置页和侧栏不显示这些选项。这是按现有实现判断的"做不到",其中几项换个做法可以实现,见路线图。 -Wayland 没有全局键鼠捕获和注入的统一接口,普通程序既看不到别的窗口的输入,也不知道光标在哪,所以两套 Wayland 实现和其他系统有几处共同的不同(下面各节细说):只在通往别的电脑的屏幕边上感知"光标推到了边上"(引擎用 `flow_platform::set_switch_edges` 告知是哪些边,由 `flow_core::Layout::switch_edges` 算出);没切到远端时看不到键盘,「按住修饰键才切换」和本机上的 Ctrl+Alt+←/→ 不起作用——Sway、Hyprland 上可以把合成器自己的快捷键绑到 `flowacross --switch left` / `right` 来代替(见第 5 节)。 +Wayland 没有全局键鼠捕获和注入的统一接口,普通程序既看不到别的窗口的输入,也不知道光标在哪,所以两套 Wayland 实现和其他系统有几处共同的不同(下面各节细说):只在通往别的电脑的屏幕边上感知"光标推到了边上"(引擎用 `flow_platform::set_switch_edges` 告知是哪些边,由 `flow_core::Layout::switch_edges` 算出);没切到远端时看不到键盘,「按住修饰键才切换」和本机上的 Ctrl+Alt+←/→ 不起作用——Sway、Hyprland 上可以把合成器自己的快捷键绑到 `flowacross --switch left` / `right` 来代替(见第 5 节)。快捷键映射的触发键在 Hyprland 上由合成器转交(`hyprland-global-shortcuts-v1`),Sway 和 GNOME / KDE 上仍然只能由别的电脑发过来。 ### X11 @@ -303,6 +303,7 @@ Wayland 没有全局键鼠捕获和注入的统一接口,普通程序既看不 - 按键事件没有连发,由流界按合成器给的重复速度自己产生(修饰键和 Caps Lock 不连发)。 - 键盘一还给本机就收不到按键的抬起了,所以放开时替还按着的键补发抬起(portal 那套同样处理)。不补的话控制器会一直以为它们按着:触发切换的方向键会被一直"吞掉",下次按快捷键要按两下才生效。 - 合成器不锁定指针且有多块显示器时,看不见的光标可能移到另一块屏幕上,那时收不到鼠标事件,移回来才恢复。 +- **全局快捷键**(`linux_hypr_shortcuts.rs`,只有 Hyprland):快捷键映射的触发键由合成器转交。普通 Wayland 程序看不到全局键盘,Hyprland 为此提供了 `hyprland-global-shortcuts-v1`(协议 XML 取自 Hyprland,放在 `protocols/`,编译时用 wayland-scanner 生成绑定):流界在单独的线程里连着合成器,把每组快捷键注册成 `register_shortcut(id, appid, 说明, 触发键)` 对象,按下时合成器回调 id(`flow_platform::set_local_shortcut_handler` 装的回调)。协议只管通知,触发键还要在合成器里绑上 `global, app.flowacross.desktop:`:运行时用 `hyprctl` 改,按物理键位(`code:`,evdev 加 8)绑,和流界其他地方一样与键盘布局无关。Hyprland 0.57 起配置换成了 Lua,绑定用 `hyprctl eval 'hl.bind(…)'`;更早的版本用 `hyprctl keyword bind`,启动时用 `hyprctl eval 'return 1'` 区分。重载配置会清掉运行时绑定,流界盯着合成器的 `.socket2.sock`,收到 `configreloaded` 就重新绑;退出时把协议对象和绑定都撤掉,别让它们占着按键。注册和绑定都在后台进行,不阻塞界面;内容没变时不重复调 `hyprctl`。xdg-desktop-portal-hyprland 虽然宣告了 GlobalShortcuts,但不会真的建绑定,所以走合成器自己的协议。 - **剪贴板**(`linux_wl_clipboard.rs`):`zwlr_data_control`,后台也能读写。结构和 X11 的一样:进程内唯一的后台服务负责应答。读:让数据源把某个格式写进套接字的一端,从另一端读到结束(文本和文件清单最多等 0.5 秒,图片 5 秒);写:建数据源、声明格式、设为选区,收到请求时在单独的线程里写。自己写入时变化计数直接加一,合成器随后回报的那一次不再重复计数。格式名和 X11 相同。 - **边缘浮光**(`linux_wl_glow.rs`):layer-shell 窗口,输入区域为空,按逻辑点的分辨率逐帧把 `glow::render` 的像素写进共享内存缓冲区。 - **测试**:`scripts/test-wayland.sh` 起一个无头的 sway(`WLR_BACKENDS=headless`、pixman 渲染),在里面串行跑标了 `#[ignore]` 的集成测试:注入的移动撞到屏幕边 → 上报向外推 → 锁定 → 位移、按键、按钮、滚轮、长按连发 → 放开后光标回位;只在指定的边上有反应;剪贴板和 wl-clipboard 双向互通(含 4 MB 图片);浮光用 grim 截屏比对像素。CI 的 Ubuntu 任务每次都跑。无头合成器里没有真实键鼠,用虚拟指针和虚拟键盘模拟,并让捕获接受"自己注入的移动"。 diff --git a/docs/roadmap.md b/docs/roadmap.md index 6d4e2b0..a4b8b5c 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -105,7 +105,8 @@ - 上面的"做不到"是指现有实现,其中几项换个做法可以实现(都还没做,做好后恢复显示对应的设置): - [ ] 按住修饰键才切换:光标碰到屏幕边时让边缘窗口临时拿一下键盘焦点,合成器会同时报告修饰键状态,没按着就还回去(副作用:前台程序短暂失去焦点);portal 上撞到屏障后同样能拿到修饰键状态 - [x] 本机快捷键切换:`flowacross --switch left|right|home|<设备名>`,在合成器里自己绑快捷键即可(例如 Hyprland:`bind = CTRL ALT, right, exec, flowacross --switch right`),各系统都能用(见架构文档第 5 节)。Sway、Hyprland 上为此补了"不碰屏幕边也能接管键鼠"的路径,在无头 sway 1.7 / 1.10 上测过(CI 每次都跑);**没有在 Hyprland 和真实键鼠上验证**。GNOME / KDE 的 Wayland 上键鼠在本机时这条命令切不出去(合成器只在光标撞到屏幕边时才交出键鼠) - - [x] Wayland 上不支持快捷键映射(GitHub 反馈 #4,CachyOS 控制 Mac,映射的触发键按了没反应):键鼠在本机时看不到键盘,做不到"不用切过去"。v0.2.5-beta.1 加过命令 `flowacross --mapping <序号>` 让用户在合成器里自己绑,嫌麻烦,随后去掉;改为 Wayland 上设置页不显示这一节并说明不支持,配置里留着的映射也不生效。X11 不受影响。反馈里没说明桌面是不是 Wayland(按之前 CachyOS + Hyprland 的反馈推断)。接入下面的全局快捷键 portal 后可以在 KDE / GNOME 上恢复 - - [ ] 接入全局快捷键 portal(Hyprland、KDE 等支持),让设置页里的快捷键在 Wayland 上直接生效,不用去合成器里绑 + - [x] Wayland 上不支持快捷键映射(GitHub 反馈 #4,CachyOS 控制 Mac,映射的触发键按了没反应):键鼠在本机时看不到键盘,做不到"不用切过去"。v0.2.5-beta.1 加过命令 `flowacross --mapping <序号>` 让用户在合成器里自己绑,嫌麻烦,随后去掉;改为 Wayland 上设置页不显示这一节并说明不支持,配置里留着的映射也不生效。X11 不受影响。反馈里没说明桌面是不是 Wayland(按之前 CachyOS + Hyprland 的反馈推断)。Hyprland 上已通过它自己的协议恢复(见下一条);KDE / GNOME 要等下面的 portal + - [x] Hyprland 上恢复快捷键映射(GitHub 反馈 #4 的后续):用 Hyprland 自己的 `hyprland-global-shortcuts-v1` 把设置里的映射注册成合成器的全局快捷键,自动在合成器里绑上触发键(按物理键位,Lua 配置和 0.57 以前的老式配置都支持),重载配置后自动重绑,退出时撤销;只注册现在真的发得出去的映射(目标没连着时触发键照常交给原来的去处)。设置页在 Hyprland 上重新显示这一节并说明。注册、绑定、按下回调、撤销在开发机的 Hyprland 0.57.2 上验证过(`hyprctl globalshortcuts` 和 `hyprctl binds` 里能看到,手动派发后流界收到 `mapping:0`);**按下的映射真的发到另一台电脑没有在真机上验证**(验证时没有配对设备),其他桌面没有改动。Sway、KDE、GNOME 仍不支持 + - [ ] 接入全局快捷键 portal(KDE、GNOME 等),让设置页里的快捷键在 Wayland 上直接生效,不用去合成器里绑。Hyprland 的 portal 虽然宣告了 GlobalShortcuts,但不会真的建绑定,用不了,所以 Hyprland 走的是上面那条自己的协议 - [ ] GNOME / KDE 的贴边停留:撞上屏障后先不放开,在停留时间内看用户是否继续往外推 - GNOME 的边缘浮光确实难做:没有在屏幕边上放置顶层窗口的协议,只能做成 Shell 扩展 diff --git a/docs/third-party-dependencies.json b/docs/third-party-dependencies.json index c9d575b..54f8bd1 100644 --- a/docs/third-party-dependencies.json +++ b/docs/third-party-dependencies.json @@ -1,7 +1,7 @@ { "description": "Declared licenses and notices from all locked Cargo dependencies (including build/dev and non-host targets) and production npm dependencies. Not a legal compatibility certification.", "lockfiles": { - "Cargo.lock": "ab7c221c3945ef48ba858044ba6d3e49038597ac58839c6f55120d439ace14b3", + "Cargo.lock": "95d66cd0ecdbb35f486ed8375345f2d42d4d92706fce1fd7e21561e423dbc22c", "app/package-lock.json": "c2afdebb5a9450d41668298adf1545b99ed31b3fdc1b79c19e9946c19a7511df" }, "dependencies": [