From fc8a271d28b5dc02fb7b037c82bb2e1efc270515 Mon Sep 17 00:00:00 2001
From: pingod <358093+pingod@users.noreply.github.com>
Date: Wed, 25 Nov 2026 14:12:38 +0800
Subject: [PATCH] =?UTF-8?q?Hyprland=20=E4=B8=8A=E6=94=AF=E6=8C=81=E5=BF=AB?=
=?UTF-8?q?=E6=8D=B7=E9=94=AE=E6=98=A0=E5=B0=84=EF=BC=9A=E6=B3=A8=E5=86=8C?=
=?UTF-8?q?=E6=88=90=E5=90=88=E6=88=90=E5=99=A8=E8=87=AA=E5=B7=B1=E7=9A=84?=
=?UTF-8?q?=E5=85=A8=E5=B1=80=E5=BF=AB=E6=8D=B7=E9=94=AE?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Wayland 看不到全局键盘,之前 Wayland 上设置页不显示快捷键映射。Hyprland 提供
hyprland-global-shortcuts-v1,由合成器把按下的触发键交给流界:
- 平台层新增 LocalShortcut:后台线程注册快捷键对象,并用 hyprctl 把触发键绑成
global, app.flowacross.desktop:(按物理键位;0.57 起的 Lua 配置和更早的
老式配置都支持);重载配置后自动重绑,退出时撤销。
- 引擎只把现在真发得出去的映射注册过去(目标连着、认得 KeyStroke、共享没暂停),
发不出去的触发键照常交给原来的去处;按下后走 Controller::run_shortcut,和本机
捕获是同一条路;没发出去时限频提示。
- 设置页在 Hyprland 上重新显示快捷键映射并说明绑定方式;Limits 新增 local_mapping。
- 架构第 5、12 节和路线图同步更新,第三方依赖清单重新生成。
验证:flow-platform 单测、clippy、前端构建通过;开发机 Hyprland 0.57.2 上实测
注册、按下回调、撤销;按下的映射真的发到另一台电脑尚未在真机上验证。
---
Cargo.lock | 2 +
app/src-tauri/src/engine.rs | 179 +++++-
app/src-tauri/src/input.rs | 15 +
app/src/HotkeySettings.tsx | 9 +-
app/src/mock.ts | 2 +-
app/src/types.ts | 2 +
crates/flow-platform/Cargo.toml | 4 +
.../hyprland-global-shortcuts-v1.xml | 112 ++++
crates/flow-platform/src/lib.rs | 59 ++
crates/flow-platform/src/linux.rs | 21 +-
.../flow-platform/src/linux_hypr_shortcuts.rs | 603 ++++++++++++++++++
crates/flow-platform/src/linux_wl.rs | 108 +++-
docs/architecture.md | 7 +-
docs/roadmap.md | 5 +-
docs/third-party-dependencies.json | 2 +-
15 files changed, 1087 insertions(+), 43 deletions(-)
create mode 100644 crates/flow-platform/protocols/hyprland-global-shortcuts-v1.xml
create mode 100644 crates/flow-platform/src/linux_hypr_shortcuts.rs
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