fix(linux): Wayland 下通过 KWin 桥接获取全局光标,修复视线跟随

XWayland 的 XQueryPointer 只在指针位于 X11 窗口上时更新,指针进入原生
Wayland 窗口后 screen.getCursorScreenPoint() 会冻结,导致视线停在最后位置。

- 新增 src/main/kwinCursor.ts:屏幕外的 16x16 辅助窗口(skipTaskbar/
  skipSwitcher/keepBelow),由 KWin 脚本移动到 (光标.x-20000, 光标.y)
- 新增 assets/kwin/sodiumpet-cursor.js:监听 workspace.cursorPosChanged
- globalCursor() 优先读取桥接结果,视线跟随与拖拽共用
- 通过 D-Bus 自动加载/补装 KWin 脚本,SODIUM_PET_KWIN_CURSOR=0 可关闭
- 视线复位哨兵从负数改为 NaN(窗口外负坐标是合法的)
- README / CHANGELOG 更新
This commit is contained in:
2026-12-02 07:36:20 +09:00
parent b24a5c3f1b
commit 91bb31b0e0
6 changed files with 311 additions and 2 deletions
+24 -1
View File
@@ -81,13 +81,34 @@ Wayland 的 `xdg-toplevel` 协议**不允许客户端自己决定窗口位置**
| 后端 | 窗口定位 | 始终置顶 | 拖拽 | 视线跟随 | 说明 | | 后端 | 窗口定位 | 始终置顶 | 拖拽 | 视线跟随 | 说明 |
| --- | --- | --- | --- | --- | --- | | --- | --- | --- | --- | --- | --- |
| `x11`(XWayland,默认) | ✅ | ✅ | ✅ | ✅ | 推荐,仍是同一个 Wayland 桌面 | | `x11`(XWayland,默认) | ✅ | ✅ | ✅ | ✅(KDE 全局) | 推荐,仍是同一个 Wayland 桌面 |
| `wayland`(原生) | ❌ 由合成器决定 | ❌ | ❌ | 仅窗口内 | 仅在没有 XWayland 时兜底 | | `wayland`(原生) | ❌ 由合成器决定 | ❌ | ❌ | 仅窗口内 | 仅在没有 XWayland 时兜底 |
启动时自动判断:只要会话里有 `WAYLAND_DISPLAY` 和 `DISPLAY`(KDE/GNOME 默认会带 启动时自动判断:只要会话里有 `WAYLAND_DISPLAY` 和 `DISPLAY`(KDE/GNOME 默认会带
XWayland),就用 XWayland;只有 `WAYLAND_DISPLAY` 时才退回原生 Wayland,并在日志里提示。 XWayland),就用 XWayland;只有 `WAYLAND_DISPLAY` 时才退回原生 Wayland,并在日志里提示。
可以用 `SODIUM_PET_OZONE=wayland` 强制原生 Wayland。 可以用 `SODIUM_PET_OZONE=wayland` 强制原生 Wayland。
### 全局视线跟随(KDE Plasma)
Wayland 不允许应用读取全局鼠标位置;XWayland 也只在指针位于 X11 窗口上方时才更新坐标。
所以「鼠标一移出小钠,视线就停在最后的位置」不是渲染问题,而是根本拿不到光标。
KDE 下应用会自动启用一个 KWin 脚本桥接(`assets/kwin/sodiumpet-cursor.js`):
1. 创建一个 **16×16、屏幕外、不显示在任务栏 / Alt-Tab** 的辅助窗口(标题 `SodiumPetCursor`);
2. 通过 D-Bus 让 KWin 加载脚本,脚本监听 `workspace.cursorPosChanged`,
把辅助窗口移动到 `(光标.x − 20000, 光标.y)`;
3. 应用读取该窗口的 X11 几何位置还原光标坐标,视线跟随与拖拽都使用它。
这个辅助窗口始终在屏幕外(x < 0),不会挡鼠标、不会出现在截图里,
脚本还会把它设为 `skipTaskbar` / `skipSwitcher` / `keepBelow` 并清掉「请求注意」状态。
- 关闭桥接:`SODIUM_PET_KWIN_CURSOR=0`(关闭后回到「只在 X11 窗口上跟随」)。
- 隐私:脚本只在本机读取光标坐标,供视线与拖拽使用,不会写入文件或上传。
注销/重启后 KWin 会清除脚本,应用下次启动时重新加载。
- GNOME / Sway 等非 KDE 桌面没有等价接口,只能退回 X11 光标:指针在小钠或其它 X11 窗口
上方时正常跟随,移到原生 Wayland 窗口上方后会停在最后的位置。
### 安装(当前用户,无需 root) ### 安装(当前用户,无需 root)
```bash ```bash
@@ -126,6 +147,8 @@ npm run start:linux # 等价于 scripts/linux/run.sh
| `SODIUM_PET_HOME` | `~/.local/share/SodiumPet` | 数据目录(存档、皮肤、缓存、日志) | | `SODIUM_PET_HOME` | `~/.local/share/SodiumPet` | 数据目录(存档、皮肤、缓存、日志) |
| `SODIUM_PET_OZONE` | `auto` | `auto` / `x11` / `wayland`,强制显示后端 | | `SODIUM_PET_OZONE` | `auto` | `auto` / `x11` / `wayland`,强制显示后端 |
| `SODIUM_PET_DISABLE_GPU` | `0` | 设为 `1` 关闭硬件加速(虚拟机、黑屏时试试) | | `SODIUM_PET_DISABLE_GPU` | `0` | 设为 `1` 关闭硬件加速(虚拟机、黑屏时试试) |
| `SODIUM_PET_KWIN_CURSOR` | `1` | 设为 `0` 关闭 KDE 的全局光标桥接 |
| `SODIUM_PET_LOOK_DEBUG` | `0` | 设为 `1` 每秒打印一次用于视线跟随的光标坐标 |
| `SODIUM_PET_LOG` | `1` | 启动器是否把输出写入 `logs/sodiumpet.log` | | `SODIUM_PET_LOG` | `1` | 启动器是否把输出写入 `logs/sodiumpet.log` |
### 常见问题 ### 常见问题
+69
View File
@@ -0,0 +1,69 @@
// SodiumPet 全局光标桥接(KWin 脚本)
//
// 由应用通过 D-Bus 加载:org.kde.KWin /Scripting loadScript <此文件> sodiumpet-cursor
// 作用:监听 KWin 的真实全局光标位置,把标题为 SodiumPetCursor 的辅助窗口
// 移动到 (光标.x − 20000, 光标.y)。窗口在屏幕外,不可见也不挡鼠标;
// 应用读取这个 X11 窗口的几何位置即可还原光标坐标。
//
// 辅助窗口会同时被设置成「不显示在任务栏 / Alt-Tab、保持在最底层、不请求注意」,
// 避免在桌面上留下多余的窗口。
(function () {
var HELPER_TITLE = "SodiumPetCursor"
var OFFSET = 20000
var THROTTLE_MS = 30
var lastX = -1
var lastY = -1
var lastAt = 0
function findHelpers() {
var list = workspace.windowList ? workspace.windowList() : workspace.clientList()
var out = []
for (var i = 0; i < list.length; i++) {
var w = list[i]
if (w && w.caption === HELPER_TITLE) out.push(w)
}
return out
}
function apply(w, x, y) {
try {
if (!w.skipTaskbar) w.skipTaskbar = true
if (!w.skipSwitcher) w.skipSwitcher = true
if (!w.keepBelow) w.keepBelow = true
if (w.demandsAttention) w.demandsAttention = false
w.frameGeometry = { x: x, y: y, width: 16, height: 16 }
} catch (e) {
/* 窗口可能刚好被销毁 */
}
}
function move() {
var p = workspace.cursorPos
if (!p) return
var now = Date.now ? Date.now() : 0
if (now && now - lastAt < THROTTLE_MS) return
if (p.x === lastX && p.y === lastY) return
lastX = p.x
lastY = p.y
lastAt = now
var list = findHelpers()
for (var i = 0; i < list.length; i++) apply(list[i], p.x - OFFSET, p.y)
}
// 应用重启后新窗口出现时,即使鼠标没动也要先摆好位置
function onWindowAdded(w) {
if (!w || w.caption !== HELPER_TITLE) return
var p = workspace.cursorPos
if (p) apply(w, p.x - OFFSET, p.y)
}
if (workspace.cursorPosChanged && workspace.cursorPosChanged.connect) {
workspace.cursorPosChanged.connect(move)
move()
} else {
print("SodiumPet: workspace.cursorPosChanged 不可用,光标桥接未启动")
}
if (workspace.windowAdded && workspace.windowAdded.connect) workspace.windowAdded.connect(onWindowAdded)
else if (workspace.clientAdded && workspace.clientAdded.connect) workspace.clientAdded.connect(onWindowAdded)
})()
+15
View File
@@ -1,5 +1,20 @@
# 变更记录 # 变更记录
## L3(修复:Wayland 下鼠标移出窗口后视线停止跟随)
- 根因:Wayland 不提供全局光标;XWayland 的 `XQueryPointer` 只在指针位于 X11 窗口上方时才更新,
指针一进入原生 Wayland 窗口(Firefox、Plasma 面板…),`screen.getCursorScreenPoint()` 就冻结在离开点。
已用「全屏 X11 探针 + uinput 注入」A/B 验证:窗口内坐标实时变化,窗口关闭后坐标 7 秒纹丝不动。
- 修复:新增 KDE 专属的全局光标桥接(`src/main/kwinCursor.ts` + `assets/kwin/sodiumpet-cursor.js`):
- 辅助窗口 16×16、屏幕外、skipTaskbar/skipSwitcher/keepBelow,不参与鼠标命中;
- KWin 脚本监听 `workspace.cursorPosChanged`,把辅助窗口移到 `(光标.x−20000, 光标.y)`;
- 主进程读取辅助窗口的 X11 几何位置还原光标,`globalCursor()` 优先使用它,视线跟随与拖拽共享。
- 脚本通过 D-Bus 自动加载(`loadScript <path> sodiumpet-cursor` + `start`),注销后自动补装;
`SODIUM_PET_KWIN_CURSOR=0` 可关闭。非 KDE 桌面退回 X11 光标(行为同旧版)。
- 顺带把视线复位的哨兵值从负数改成 NaN(负数在窗口外是合法坐标),避免误判复位。
- 验证:在 Firefox(原生 Wayland)上方移动鼠标,日志中的光标坐标与辅助窗口位置持续更新;
桌宠眼睛随光标左右移动。
## L2(修复:开启视线跟随后,鼠标移出窗口视线就不再跟随) ## L2(修复:开启视线跟随后,鼠标移出窗口视线就不再跟随)
- 根因:`src/renderer/src/pet/adapters/live2d.ts` 的 `lookAt()` 用「x < 0 或 y < 0」表示「复位正视」, - 根因:`src/renderer/src/pet/adapters/live2d.ts` 的 `lookAt()` 用「x < 0 或 y < 0」表示「复位正视」,
+11
View File
@@ -42,6 +42,7 @@ import {
showOnAllWorkspaces, showOnAllWorkspaces,
IS_LINUX IS_LINUX
} from './platform' } from './platform'
import { startKwinCursorBridge } from './kwinCursor'
// Linux 下需要在 app ready 前指定 Ozone 后端(Wayland 会话默认走 XWayland) // Linux 下需要在 app ready 前指定 Ozone 后端(Wayland 会话默认走 XWayland)
bootstrapPlatform() bootstrapPlatform()
@@ -2357,6 +2358,8 @@ if (!gotLock) {
console.log('[pet] home =', HOME) console.log('[pet] home =', HOME)
registerProtocol() registerProtocol()
registerIpc() registerIpc()
// KDE/Wayland:用 KWin 脚本桥接真实的全局光标(否则指针离开 X11 窗口后就读不到位置)
startKwinCursorBridge(path.join(bundledDir('kwin'), 'sodiumpet-cursor.js'))
createWindow() createWindow()
createTray() createTray()
applyConfig(store.getConfig()) applyConfig(store.getConfig())
@@ -2382,12 +2385,20 @@ if (!gotLock) {
// 全屏视线跟随:主进程按 50ms 轮询光标位置,发给宠物窗口 // 全屏视线跟随:主进程按 50ms 轮询光标位置,发给宠物窗口
// 原生 Wayland 读不到全局光标,改为只跟随窗口内的鼠标(渲染层已处理) // 原生 Wayland 读不到全局光标,改为只跟随窗口内的鼠标(渲染层已处理)
let lastLookLogAt = 0
if (capabilities.cursor) { if (capabilities.cursor) {
setInterval(() => { setInterval(() => {
const cfgNow = store.getConfig() const cfgNow = store.getConfig()
if (!cfgNow.eyeFollow || !mainWindow || !mainWindow.isVisible()) return if (!cfgNow.eyeFollow || !mainWindow || !mainWindow.isVisible()) return
const p = globalCursor() const p = globalCursor()
if (!p) return if (!p) return
if (process.env.SODIUM_PET_LOOK_DEBUG === '1') {
const now = Date.now()
if (now - lastLookLogAt > 1000) {
lastLookLogAt = now
console.log('[look] cursor =', p.x, p.y)
}
}
const b = mainWindow.getBounds() const b = mainWindow.getBounds()
mainWindow.webContents.send('pet:look', { mainWindow.webContents.send('pet:look', {
x: p.x - b.x + cfgNow.cropLeft, x: p.x - b.x + cfgNow.cropLeft,
+183
View File
@@ -0,0 +1,183 @@
/**
* KDE Plasma / KWin 全局光标桥接
*
* 为什么需要它:
* Wayland 出于安全考虑不提供「读取全局鼠标位置」的协议。应用跑在 XWayland 上时,
* `screen.getCursorScreenPoint()` 只在指针位于 X11 窗口(小钠自己、QQ、Steam…)上方时才更新;
* 指针一到原生 Wayland 窗口(Firefox、Plasma 面板…)上方,坐标就会冻结在离开 X11 的最后一个点。
* 结果就是「鼠标移出桌宠窗口后,视线卡在最后的位置」。
*
* 做法:
* 1. 创建一个 16×16、透明、被 KWin 管理的辅助窗口(标题 SodiumPetCursor),
* 放在屏幕外(x = 光标 x − 20000),因此完全不挡鼠标、不可见;
* 2. 通过 D-Bus 让 KWin 加载一个小脚本,脚本监听 `workspace.cursorPosChanged`,
* 把辅助窗口挪到「光标位置 − 20000」,KWin 拥有真正的全局光标;
* 3. 主进程读取辅助窗口的 X11 几何位置,加回 20000 就得到全局光标坐标。
*
* 仅 KDE 需要;其它桌面(GNOME/Sway…)自动退回 X11 光标读取(同样只在 X11 窗口上有效)。
* 用 SODIUM_PET_KWIN_CURSOR=0 可以关闭。
*/
import { BrowserWindow } from 'electron'
import { execFile } from 'node:child_process'
import * as fs from 'node:fs'
/** 水平偏移:保证辅助窗口始终在屏幕外,不参与命中测试 */
export const KWIN_CURSOR_OFFSET = 20000
const HELPER_TITLE = 'SodiumPetCursor'
const SCRIPT_NAME = 'sodiumpet-cursor'
let helper: BrowserWindow | null = null
let scriptLoaded = false
let scriptPath = ''
let ensureTimer: NodeJS.Timeout | null = null
/** 当前桌面是否是 KDE(KWin 提供 workspace.cursorPos) */
export function kwinCursorSupported(): boolean {
if (process.platform !== 'linux') return false
if (process.env.SODIUM_PET_KWIN_CURSOR === '0') return false
if (process.env.SODIUM_PET_OZONE === 'wayland') return false
if (!process.env.DISPLAY) return false // 辅助窗口必须是 X11 窗口,坐标才是可读的
const desktop = [
process.env.XDG_CURRENT_DESKTOP,
process.env.KDE_FULL_SESSION,
process.env.DESKTOP_SESSION
]
.filter(Boolean)
.join(' ')
// 环境变量缺失(例如从 SSH/终端启动)时不要直接放弃:交给后面的 qdbus 探测
if (desktop && !/kde|plasma/i.test(desktop)) return false
return true
}
export function kwinCursorActive(): boolean {
return scriptLoaded && !!helper && !helper.isDestroyed()
}
/** 读取 KWin 报告的全局光标;还没收到数据时返回 null,由调用方退回 X11 坐标 */
export function kwinCursorPoint(): { x: number; y: number } | null {
if (!kwinCursorActive()) return null
try {
const b = helper!.getBounds()
// 初始位置是 (−20000, −20000);y 仍为 −20000 说明脚本还没送来任何位置
// 脚本每次都会把窗口设成 16×16;初始的 8×8 表示脚本还没送来过坐标
if (b.width !== 16 || b.height !== 16) return null
if (b.x > -KWIN_CURSOR_OFFSET / 2) return null
return { x: b.x + KWIN_CURSOR_OFFSET, y: b.y }
} catch {
return null
}
}
function qdbus(method: string, args: string[], done: (ok: boolean, out: string) => void): void {
const bins = ['qdbus6', 'qdbus']
const attempt = (i: number): void => {
if (i >= bins.length) {
done(false, '')
return
}
execFile(
bins[i],
['org.kde.KWin', '/Scripting', method, ...args],
{ timeout: 4000 },
(err, stdout) => {
if (err) attempt(i + 1)
else done(true, String(stdout).trim())
}
)
}
attempt(0)
}
function installScript(): void {
if (!scriptPath || !fs.existsSync(scriptPath)) {
console.warn('[kwin] 找不到光标桥接脚本:', scriptPath)
return
}
qdbus('isScriptLoaded', [SCRIPT_NAME], (ok, loaded) => {
if (ok && loaded === 'true') {
if (!scriptLoaded) console.log('[kwin] 全局光标桥接已就绪')
scriptLoaded = true
return
}
qdbus('loadScript', [scriptPath, SCRIPT_NAME], (okLoad) => {
if (!okLoad) {
console.warn('[kwin] KWin 不允许加载脚本,将退回 X11 光标(指针离开 X11 窗口后会停住)')
return
}
qdbus('start', [], () => {
qdbus('isScriptLoaded', [SCRIPT_NAME], (okCheck, running) => {
scriptLoaded = okCheck && running === 'true'
console.log(
'[kwin] 全局光标桥接' + (scriptLoaded ? '已启用' : '启用失败,退回 X11 光标')
)
})
})
})
})
}
function createHelper(): void {
if (helper && !helper.isDestroyed()) return
helper = new BrowserWindow({
// 初始放在屏幕外;脚本跑起来后会改成「光标 − 偏移」
x: -KWIN_CURSOR_OFFSET,
y: -KWIN_CURSOR_OFFSET,
width: 8,
height: 8,
show: false,
frame: false,
transparent: true,
backgroundColor: '#00000000',
resizable: false,
minimizable: false,
maximizable: false,
fullscreenable: false,
skipTaskbar: true,
hasShadow: false,
// KWin 只管理「可聚焦」的窗口;showInactive 保证它不会抢焦点
focusable: true,
title: HELPER_TITLE,
webPreferences: { sandbox: true, contextIsolation: true, nodeIntegration: false }
})
helper.webContents.on('page-title-updated', (e) => e.preventDefault())
helper.setIgnoreMouseEvents(true)
helper.loadURL('about:blank')
helper.once('ready-to-show', () => {
helper?.showInactive()
// 等 KWin 把窗口纳入管理(windowAdded)再加载脚本
setTimeout(installScript, 400)
})
helper.on('closed', () => {
helper = null
})
}
/**
* 启动桥接。脚本路径由调用方给出(打包后在 resources/kwin,开发时在 assets/kwin)。
*/
export function startKwinCursorBridge(jsPath: string): void {
if (!kwinCursorSupported()) {
console.log('[kwin] 非 KDE 桌面或已禁用,跳过全局光标桥接')
return
}
scriptPath = jsPath
createHelper()
// KWin 重启(例如崩溃恢复)后脚本会丢失;每分钟确认一次,必要时补装
if (ensureTimer) clearInterval(ensureTimer)
ensureTimer = setInterval(() => installScript(), 60_000)
ensureTimer.unref?.()
}
export function stopKwinCursorBridge(): void {
if (ensureTimer) {
clearInterval(ensureTimer)
ensureTimer = null
}
try {
helper?.destroy()
} catch {
/* 忽略 */
}
helper = null
scriptLoaded = false
}
+9 -1
View File
@@ -17,6 +17,7 @@
import { app, screen, type BrowserWindow } from 'electron' import { app, screen, type BrowserWindow } from 'electron'
import * as os from 'node:os' import * as os from 'node:os'
import * as path from 'node:path' import * as path from 'node:path'
import { kwinCursorPoint } from './kwinCursor'
export type OzoneMode = 'x11' | 'wayland' | '' export type OzoneMode = 'x11' | 'wayland' | ''
@@ -133,8 +134,15 @@ export function showOnAllWorkspaces(win: BrowserWindow | null): void {
win.setVisibleOnAllWorkspaces(true, { visibleOnFullScreen: true }) win.setVisibleOnAllWorkspaces(true, { visibleOnFullScreen: true })
} }
/** 读取全局鼠标位置;原生 Wayland 下返回 null */ /**
* 读取全局鼠标位置。
*
* 优先使用 KDE 的 KWin 桥接(能拿到 Wayland 原生窗口上方的真实光标);
* 没有桥接时退回 XQueryPointer —— 注意后者在指针离开 X11 窗口后会停住。
*/
export function globalCursor(): { x: number; y: number } | null { export function globalCursor(): { x: number; y: number } | null {
const bridged = kwinCursorPoint()
if (bridged) return bridged
if (!capabilities.cursor) return null if (!capabilities.cursor) return null
try { try {
return screen.getCursorScreenPoint() return screen.getCursorScreenPoint()