diff --git a/1400 b/1400 deleted file mode 100644 index e69de29..0000000 diff --git a/1428 b/1428 deleted file mode 100644 index e69de29..0000000 diff --git a/1432 b/1432 deleted file mode 100644 index e69de29..0000000 diff --git a/1684 b/1684 deleted file mode 100644 index 6f2b2fe..0000000 --- a/1684 +++ /dev/null @@ -1 +0,0 @@ -[10288:1130/213349.240:WARNING:viz_main_impl.cc(85)] VizNullHypothesis is disabled (not a warning) diff --git a/1716 b/1716 deleted file mode 100644 index f141b00..0000000 --- a/1716 +++ /dev/null @@ -1,2 +0,0 @@ -[30660:1130/213123.980:WARNING:viz_main_impl.cc(85)] VizNullHypothesis is disabled (not a warning) -[15080:1130/214402.633:WARNING:viz_main_impl.cc(85)] VizNullHypothesis is disabled (not a warning) diff --git a/1728 b/1728 deleted file mode 100644 index 0d5eb6d..0000000 --- a/1728 +++ /dev/null @@ -1,3 +0,0 @@ -[18976:1130/213008.389:WARNING:viz_main_impl.cc(85)] VizNullHypothesis is disabled (not a warning) -[24448:1130/213218.435:WARNING:viz_main_impl.cc(85)] VizNullHypothesis is disabled (not a warning) -[5900:1130/213728.400:WARNING:viz_main_impl.cc(85)] VizNullHypothesis is disabled (not a warning) diff --git a/1736 b/1736 deleted file mode 100644 index cfa7066..0000000 --- a/1736 +++ /dev/null @@ -1 +0,0 @@ -[4204:1130/213632.373:WARNING:viz_main_impl.cc(85)] VizNullHypothesis is disabled (not a warning) diff --git a/1744 b/1744 deleted file mode 100644 index 8875aee..0000000 --- a/1744 +++ /dev/null @@ -1 +0,0 @@ -[24076:1130/213546.972:WARNING:viz_main_impl.cc(85)] VizNullHypothesis is disabled (not a warning) diff --git a/1748 b/1748 deleted file mode 100644 index 3b99b78..0000000 --- a/1748 +++ /dev/null @@ -1 +0,0 @@ -[29800:1130/213312.074:WARNING:viz_main_impl.cc(85)] VizNullHypothesis is disabled (not a warning) diff --git a/1756 b/1756 deleted file mode 100644 index eb467c1..0000000 --- a/1756 +++ /dev/null @@ -1,2 +0,0 @@ -[31004:1130/213446.763:WARNING:viz_main_impl.cc(85)] VizNullHypothesis is disabled (not a warning) -[30796:1130/213949.760:WARNING:viz_main_impl.cc(85)] VizNullHypothesis is disabled (not a warning) diff --git a/1764 b/1764 deleted file mode 100644 index 49e777f..0000000 --- a/1764 +++ /dev/null @@ -1 +0,0 @@ -[30504:1130/214138.764:WARNING:viz_main_impl.cc(85)] VizNullHypothesis is disabled (not a warning) diff --git a/1792 b/1792 deleted file mode 100644 index b2205a6..0000000 --- a/1792 +++ /dev/null @@ -1 +0,0 @@ -[12680:1130/214226.718:WARNING:viz_main_impl.cc(85)] VizNullHypothesis is disabled (not a warning) diff --git a/1800 b/1800 deleted file mode 100644 index a435dfc..0000000 --- a/1800 +++ /dev/null @@ -1 +0,0 @@ -[30756:1130/213041.896:WARNING:viz_main_impl.cc(85)] VizNullHypothesis is disabled (not a warning) diff --git a/1812 b/1812 deleted file mode 100644 index 8e6cf52..0000000 --- a/1812 +++ /dev/null @@ -1 +0,0 @@ -[4980:1130/214053.083:WARNING:viz_main_impl.cc(85)] VizNullHypothesis is disabled (not a warning) diff --git a/1816 b/1816 deleted file mode 100644 index c3faa37..0000000 --- a/1816 +++ /dev/null @@ -1,2 +0,0 @@ -[9764:1130/213807.644:WARNING:viz_main_impl.cc(85)] VizNullHypothesis is disabled (not a warning) -[8844:1130/214313.696:WARNING:viz_main_impl.cc(85)] VizNullHypothesis is disabled (not a warning) diff --git a/1836 b/1836 deleted file mode 100644 index a5f6cd9..0000000 --- a/1836 +++ /dev/null @@ -1 +0,0 @@ -[12908:1130/212744.465:WARNING:viz_main_impl.cc(85)] VizNullHypothesis is disabled (not a warning) diff --git a/1840 b/1840 deleted file mode 100644 index d247b29..0000000 --- a/1840 +++ /dev/null @@ -1 +0,0 @@ -[13704:1130/213900.024:WARNING:viz_main_impl.cc(85)] VizNullHypothesis is disabled (not a warning) diff --git a/2308 b/2308 deleted file mode 100644 index e69de29..0000000 diff --git a/2384 b/2384 deleted file mode 100644 index e69de29..0000000 diff --git a/2468 b/2468 deleted file mode 100644 index e69de29..0000000 diff --git a/2572 b/2572 deleted file mode 100644 index e69de29..0000000 diff --git a/2580 b/2580 deleted file mode 100644 index e69de29..0000000 diff --git a/2592 b/2592 deleted file mode 100644 index e69de29..0000000 diff --git a/2596 b/2596 deleted file mode 100644 index e69de29..0000000 diff --git a/2608 b/2608 deleted file mode 100644 index e69de29..0000000 diff --git a/2620 b/2620 deleted file mode 100644 index e69de29..0000000 diff --git a/2628 b/2628 deleted file mode 100644 index e69de29..0000000 diff --git a/2632 b/2632 deleted file mode 100644 index e69de29..0000000 diff --git a/2640 b/2640 deleted file mode 100644 index e69de29..0000000 diff --git a/2652 b/2652 deleted file mode 100644 index e69de29..0000000 diff --git a/2676 b/2676 deleted file mode 100644 index e69de29..0000000 diff --git a/2680 b/2680 deleted file mode 100644 index e69de29..0000000 diff --git a/2712 b/2712 deleted file mode 100644 index e69de29..0000000 diff --git a/2752 b/2752 deleted file mode 100644 index e69de29..0000000 diff --git a/2888 b/2888 deleted file mode 100644 index e69de29..0000000 diff --git a/2936 b/2936 deleted file mode 100644 index e69de29..0000000 diff --git a/3024 b/3024 deleted file mode 100644 index e69de29..0000000 diff --git a/3036 b/3036 deleted file mode 100644 index e69de29..0000000 diff --git a/3040 b/3040 deleted file mode 100644 index e69de29..0000000 diff --git a/3048 b/3048 deleted file mode 100644 index e69de29..0000000 diff --git a/3052 b/3052 deleted file mode 100644 index e69de29..0000000 diff --git a/3056 b/3056 deleted file mode 100644 index e69de29..0000000 diff --git a/3068 b/3068 deleted file mode 100644 index e69de29..0000000 diff --git a/3076 b/3076 deleted file mode 100644 index e69de29..0000000 diff --git a/3476 b/3476 deleted file mode 100644 index ebda67f..0000000 --- a/3476 +++ /dev/null @@ -1 +0,0 @@ -[4756:1130/212944.660:WARNING:viz_main_impl.cc(85)] VizNullHypothesis is disabled (not a warning) diff --git a/README.md b/README.md index 4bc551d..b02828b 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,10 @@ -# 小钠 · 化学元素拟人桌宠(SodiumPet) +# 小钠 · 化学元素拟人桌宠(SodiumPet) [![GitHub](https://img.shields.io/badge/GitHub-Tian--XiaRi%2FSodiumPet-181717?logo=github)](https://github.com/Tian-XiaRi/SodiumPet) [![Gitee](https://img.shields.io/badge/Gitee-TianXiaRi%2Fsodium--pet-C71D23?logo=gitee)](https://gitee.com/TianXiaRi/sodium-pet) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE) -一个跑在 Windows 桌面上的 Live2D 桌宠:化学元素拟人世界观、经济与任务系统、本地音乐播放器、成就、知识库、MOD 支持,以及可自定义的界面图标。 +一个跑在 Windows / Linux(Wayland、X11)桌面上的 Live2D 桌宠:化学元素拟人世界观、经济与任务系统、本地音乐播放器、成就、知识库、MOD 支持,以及可自定义的界面图标。 > 内置角色「小钠」= 钠(Na)拟人,来自 EL-Cross-Lab。也支持导入任意 Live2D 模型,并按「普通桌宠」风格使用。 > **仓库**:GitHub(主) · Gitee 国内镜像 · 欢迎 PR / issue @@ -33,6 +33,47 @@ > 额外素材:**藿藿 Live2D 模型**是单独附件(藿藿Live2D模型.zip),不是程序包,别下错了。 +--- + +## 原项目与致谢 + +- **原项目 / Original project**:**[Tian-XiaRi/SodiumPet](https://github.com/Tian-XiaRi/SodiumPet)** +- **原作者 / Author**:Tian_XiaRi(GitHub [@Tian-XiaRi](https://github.com/Tian-XiaRi)) +- 本仓库()是原项目的 **Linux / Wayland 移植分支**: + 保留全部原有功能,新增 Linux 桌面支持与安装脚本(见 [Linux / Wayland](#linux--wayland))。 + 当前已同步上游 **v0.1.1**(周期表 s/p/d/ds/f 五大分区与改色、全屏视线跟随、窗口表情包图标、 + 跨平台打包、人设提示词 v1.0)。 +- 代码遵循原项目 **MIT** 许可;内置 Live2D 模型、表情包等素材版权归原作者, + Live2D Cubism Core 遵循 Live2D Inc. 的许可(详见 `NOTICE`)。二次分发请保留以上署名。 + +## 快速安装 + +### Linux(本分支新增) + +```bash +git clone https://git.hinomori-minori.com/deepseek/SodiumPet.git +cd SodiumPet +npm install +npm run build +bash scripts/linux/install.sh --autostart # 装到 ~/.local/share/SodiumPet,并加入登录自启动 +``` + +装好后从应用菜单启动「SodiumPet / 小钠」,或执行 `~/.local/share/SodiumPet/bin/sodiumpet`。 +全程不需要 root;卸载用 `bash scripts/linux/uninstall.sh`(加 `--purge` 连存档一起删)。 + +> Wayland 桌面默认通过 **XWayland** 运行,以保留窗口定位 / 始终置顶 / 拖拽 / 鼠标穿透能力; +> 没有 XWayland 时会自动回退到原生 Wayland(位置与置顶由合成器决定,功能受限)。 + +### Windows(原项目方式) + +从 [原项目 Releases](https://github.com/Tian-XiaRi/SodiumPet/releases) 下载 `SodiumPet-*-win64.zip`, +解压后双击 `SodiumPet.exe`;或在源码目录执行 `npm install && npm run build && npm start`。 + +### 系统要求 + +- Windows 10/11 x64;或 Linux(X11 / Wayland,推荐带 XWayland 的 KDE Plasma、GNOME 等桌面)。 +- 从源码构建需要 Node.js 20+ 与 npm;Linux 运行库为发行版常见的 GTK3 / NSS / ALSA / GBM。 + ## 功能一览 - **Live2D 立绘**:透明置顶窗口、拖动、摸头、视线跟随、双击/右键菜单 @@ -50,14 +91,114 @@ - **编辑器**:改物品/活动(名称、图标、简介、价格、等级、奖励)、改等级描述与图标、周期表配色(可视化格子上取色、另存自定义方案)、底栏按钮图标(内置表情包或导入图片) - **MOD**:外挂 JSON 增加/覆盖物品与活动 -## 下载与运行 +## Windows 下载与运行 -1. 从 [Releases](../../releases) 下载 `SodiumPet-*-win64.zip`,解压后双击 `SodiumPet.exe` 即可运行(数据会生成在 exe 同级的 `data/`、`skins/` 目录)。 +1. 从 [原项目 Releases](https://github.com/Tian-XiaRi/SodiumPet/releases) 下载 `SodiumPet-*-win64.zip`,解压后双击 `SodiumPet.exe` 即可运行(数据会生成在 exe 同级的 `data/`、`skins/` 目录)。 2. 首次启动会在可执行文件旁或用户数据目录创建 `data/`(存档、皮肤、图库、知识库等)。 3. 右键桌宠 → 设置 → AI,填接口地址 / 模型 / 密钥即可对话(不填则用本地台词)。 > 需要 Windows 10/11 x64。桌宠窗口使用透明置顶,部分游戏全屏独占模式下可能被遮挡。 +## Linux / Wayland + +Linux 版本与 Windows 共用同一套代码,主进程里通过 `src/main/platform.ts` 做平台适配, +安装脚本在 `scripts/linux/`。 + +### 为什么默认走 XWayland + +Wayland 的 `xdg-toplevel` 协议**不允许客户端自己决定窗口位置**,也没有通用的 +「始终置顶 / 鼠标穿透 / 读取全局光标」协议——而桌宠的拖拽、贴边、气泡跟随、视线跟随 +全都依赖这些能力。因此: + +| 后端 | 窗口定位 | 始终置顶 | 拖拽 | 视线跟随 | 说明 | +| --- | --- | --- | --- | --- | --- | +| `x11`(XWayland,默认) | ✅ | ✅ | ✅ | ✅(KDE 全局) | 推荐,仍是同一个 Wayland 桌面 | +| `wayland`(原生) | ❌ 由合成器决定 | ❌ | ❌ | 仅窗口内 | 仅在没有 XWayland 时兜底 | + +启动时自动判断:只要会话里有 `WAYLAND_DISPLAY` 和 `DISPLAY`(KDE/GNOME 默认会带 +XWayland),就用 XWayland;只有 `WAYLAND_DISPLAY` 时才退回原生 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) + +```bash +npm install +npm run build +bash scripts/linux/install.sh # 安装到 ~/.local/share/SodiumPet +bash scripts/linux/install.sh --autostart # 顺便加入登录自启动 +``` + +安装脚本会: + +- 把 Electron 运行时和 `out/`、`assets/` 复制到 `~/.local/share/SodiumPet/{electron,app}`; +- 生成启动器 `~/.local/share/SodiumPet/bin/sodiumpet`,并软链到 `~/.local/bin/sodiumpet`; +- 写入应用菜单项 `~/.local/share/applications/sodiumpet.desktop`(图标用 `assets/linux/sodiumpet.png`); +- 可选写入 `~/.config/autostart/sodiumpet.desktop`。 + +数据目录固定在 `~/.local/share/SodiumPet/home`(可用 `SODIUM_PET_HOME` 改), +升级只替换程序,不会动存档。卸载: + +```bash +bash scripts/linux/uninstall.sh # 保留存档 +bash scripts/linux/uninstall.sh --purge # 连存档一起删掉 +``` + +开发调试直接跑仓库里的构建产物: + +```bash +npm run build +npm run start:linux # 等价于 scripts/linux/run.sh +``` + +### 环境变量 + +| 变量 | 默认 | 作用 | +| --- | --- | --- | +| `SODIUM_PET_HOME` | `~/.local/share/SodiumPet` | 数据目录(存档、皮肤、缓存、日志) | +| `SODIUM_PET_OZONE` | `auto` | `auto` / `x11` / `wayland`,强制显示后端 | +| `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` | + +### 常见问题 + +- **窗口没有出现 / 日志里 `Missing X server or $DISPLAY`**:当前是纯 Wayland 且没有 + XWayland。装 `xwayland` 后重新登录,或临时 `SODIUM_PET_OZONE=wayland` 走原生模式。 +- **透明窗口黑底 / 花屏**:换用 `SODIUM_PET_DISABLE_GPU=1` 启动; + 虚拟机里的 llvmpipe 有时需要软件渲染。 +- **托盘没有图标**:托盘依赖 StatusNotifierItem,部分精简桌面/未装扩展的 GNOME 不显示, + 不影响右键菜单与面板。 +- **中文显示成方块**:安装一套中文字体,例如 `fonts-noto-cjk`。 +- **沙箱报错**:启动器检测到系统禁用非特权 user namespace 时会自动加 `--no-sandbox`; + 也可以手动 `SODIUM_PET_DISABLE_SANDBOX=1`。 +- **任务栏 / Alt-Tab 里看到小钠**:Electron 在 Linux 上对 `skipTaskbar` 支持有限 + (X11 窗口的 `_NET_WM_STATE_SKIP_TASKBAR` 不一定生效),不影响桌宠置顶与交互。 +- **登录后没有自动出现**:自启动由 `~/.config/autostart/sodiumpet.desktop` 驱动, + 启动器会等 XWayland 就绪;如果桌面环境延迟很大,可在日志 + `~/.local/share/SodiumPet/logs/sodiumpet.log` 里确认。 + ## 从源码构建 ```bash diff --git a/assets/kwin/sodiumpet-cursor.js b/assets/kwin/sodiumpet-cursor.js new file mode 100644 index 0000000..a0f53a6 --- /dev/null +++ b/assets/kwin/sodiumpet-cursor.js @@ -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) +})() diff --git a/assets/linux/sodiumpet-256.png b/assets/linux/sodiumpet-256.png new file mode 100644 index 0000000..142769e Binary files /dev/null and b/assets/linux/sodiumpet-256.png differ diff --git a/assets/linux/sodiumpet.png b/assets/linux/sodiumpet.png new file mode 100644 index 0000000..61671a2 Binary files /dev/null and b/assets/linux/sodiumpet.png differ diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 4818764..61d2825 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -1,5 +1,15 @@ # 变更记录 +## L4(跟进上游 v0.1.1) + +- 合并上游 v0.1.1:周期表 s/p/d/ds/f 五大分区与自定义改色、全屏视线跟随、窗口表情包图标、 + 跨平台打包(AppImage / deb / dmg / zip)、人设提示词对齐 v1.0 +- 保留本移植分支的 Linux 层:`src/main/platform.ts` 能力降级、KWin 全局光标桥接、`scripts/linux/install.sh` +- 合并后的视线跟随:33ms 主进程轮询 + KWin 桥接(指针在原生 Wayland 窗口上方也有效), + 没有桥接时退回 X11 光标;保留 NaN 复位(负数坐标是合法位置) +- 适配上游的点击穿透写法:Linux 不传 `forward` 选项;窗口图标沿用表情包方案 +- 上游 README 的「平台支持」表已收录本移植仓库;本 README 继续保留 Linux 安装、致谢与环境变量章节 + ## v0.1.1(周期表分区 / 全屏视线 / 跨平台 / 窗口图标) **人设提示词对齐 v1.0(补丁)** @@ -40,6 +50,50 @@ **其他** - 版本工作目录迁到 `E:\SodiumPet\WorkPlace\v0.1.0`(归档)与 `v0.1.1`(当前开发版) - 移除含本机窗口信息的截图,并在 `.gitignore` 忽略 `docs/shot-*.png` +## 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 sodiumpet-cursor` + `start`),注销后自动补装; + `SODIUM_PET_KWIN_CURSOR=0` 可关闭。非 KDE 桌面退回 X11 光标(行为同旧版)。 +- 顺带把视线复位的哨兵值从负数改成 NaN(负数在窗口外是合法坐标),避免误判复位。 +- 验证:在 Firefox(原生 Wayland)上方移动鼠标,日志中的光标坐标与辅助窗口位置持续更新; + 桌宠眼睛随光标左右移动。 + +## L2(修复:开启视线跟随后,鼠标移出窗口视线就不再跟随) + +- 根因:`src/renderer/src/pet/adapters/live2d.ts` 的 `lookAt()` 用「x < 0 或 y < 0」表示「复位正视」, + 但主进程送来的是**窗口相对坐标**——鼠标移到窗口左侧/上方时坐标本来就是负数, + 于是 50ms 一次的轮询全部被当成复位,视线永久回正(桌宠贴在右下角时几乎必然触发)。 +- 修复:复位改用 `NaN`(`Number.isFinite` 判断),负坐标按正常位置处理; + 关闭视线跟随时改为传 `NaN`,接口注释同步说明坐标可为负。 +- 验证:向渲染层注入 (-200, -200),`ParamAngleX` 稳定变为负值(看向左上方); + 注入 `NaN` 后回到 0 附近;两者行为符合预期。 +## L1(Linux / Wayland 支持) + +**平台适配层 `src/main/platform.ts`** +- 启动时判断会话类型:Wayland 会话优先 `--ozone-platform=x11`(XWayland),窗口定位、置顶、鼠标穿透、拖拽、视线跟随全部可用 +- 纯 Wayland(无 XWayland)自动退回 `--ozone-platform=wayland`,并对 setPosition / setAlwaysOnTop / getCursorScreenPoint 等不可用能力降级(不报错、不卡死) +- Ozone 后端在 JS 之前就已确定,`appendSwitch` 无效:启动参数缺失时用一次 relaunch 补上 +- 数据目录改用 XDG 规范:`$XDG_DATA_HOME/SodiumPet`(可用 `SODIUM_PET_HOME` 覆盖),不再创建 `E:\SodiumPet` 这种相对路径 + +**窗口 / 交互** +- 所有 `setBounds` / `setPosition` / `setAlwaysOnTop` / `setVisibleOnAllWorkspaces` 改走能力封装,原生 Wayland 下自动跳过 +- 托盘创建失败不再导致启动失败;Linux 窗口补上 PNG 图标、WM_CLASS(SodiumPet) +- `pet://` 协议对缺失文件直接返回 404,避免首次启动刷 `ERR_FILE_NOT_FOUND` 堆栈 + +**安装与文档** +- 新增 `scripts/linux/`:`install.sh`(安装到 `~/.local/share/SodiumPet`,生成启动器 / 菜单项 / 可选登录自启动)、`run.sh`(开发运行)、`uninstall.sh` +- 启动器负责选择后端、等待 XWayland 就绪、按需补 `--no-sandbox`、写日志 +- 新增 `assets/linux/sodiumpet.png` 应用图标;README 增补 Linux / Wayland 章节、环境变量与常见问题 +- 清理仓库根目录误提交的 Chromium 日志文件(1400、1428…) + +**验证环境**:Debian 13 + KDE Plasma 6(Wayland 会话),Electron 33.4.11,XWayland 下透明置顶、拖拽、气泡、面板、Live2D 均正常。 ## M42(修复:商店 / 互动 / 统计索引丢失) diff --git a/package.json b/package.json index b1bfc96..104d44b 100644 --- a/package.json +++ b/package.json @@ -13,7 +13,10 @@ "pack": "electron-builder --win dir --x64", "dist:win": "electron-builder --win zip --x64", "dist:linux": "electron-builder --linux AppImage deb --x64", - "dist:mac": "electron-builder --mac dmg zip --x64 --arm64" + "dist:mac": "electron-builder --mac dmg zip --x64 --arm64", + "start:linux": "bash scripts/linux/run.sh", + "install:linux": "bash scripts/linux/install.sh", + "uninstall:linux": "bash scripts/linux/uninstall.sh" }, "dependencies": { "live2dcubismcore": "^1.0.2", @@ -114,4 +117,4 @@ "category": "public.app-category.entertainment" } } -} \ No newline at end of file +} diff --git a/scripts/linux/install.sh b/scripts/linux/install.sh new file mode 100755 index 0000000..11a5bda --- /dev/null +++ b/scripts/linux/install.sh @@ -0,0 +1,124 @@ +#!/usr/bin/env bash +# 在 Linux 上把 SodiumPet 安装到当前用户目录(不需要 root) +# +# 用法: +# scripts/linux/install.sh [--prefix DIR] [--autostart] [--no-build] [--run] +# +# 默认安装位置:${XDG_DATA_HOME:-~/.local/share}/SodiumPet +# 数据目录: /home(卸载时保留,除非 --purge) +set -euo pipefail + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +PREFIX="${SODIUM_PET_PREFIX:-${XDG_DATA_HOME:-$HOME/.local/share}/SodiumPet}" +AUTOSTART=0 +DO_BUILD=1 +RUN_AFTER=0 + +while [ $# -gt 0 ]; do + case "$1" in + --prefix) PREFIX="$2"; shift 2 ;; + --autostart) AUTOSTART=1; shift ;; + --no-build) DO_BUILD=0; shift ;; + --run) RUN_AFTER=1; shift ;; + -h|--help) + sed -n '2,10p' "$0" | sed 's/^# \{0,1\}//' + exit 0 ;; + *) echo "未知参数:$1" >&2; exit 2 ;; + esac +done + +say() { printf '\033[1;32m[install]\033[0m %s\n' "$*"; } +warn() { printf '\033[1;33m[install]\033[0m %s\n' "$*" >&2; } +die() { printf '\033[1;31m[install]\033[0m %s\n' "$*" >&2; exit 1; } + +command -v node >/dev/null 2>&1 || die "找不到 node,请先安装 Node.js 20+" +command -v npm >/dev/null 2>&1 || die "找不到 npm" + +cd "$ROOT" + +if [ ! -d node_modules ]; then + say "首次安装依赖(npm install)…" + npm install --no-audit --no-fund +fi + +if [ ! -x node_modules/electron/dist/electron ]; then + say "下载 Electron 运行时…" + ELECTRON_MIRROR="${ELECTRON_MIRROR:-https://npmmirror.com/mirrors/electron/}" \ + node node_modules/electron/install.js +fi + +if [ "$DO_BUILD" = "1" ]; then + say "编译主进程 / 渲染进程…" + npm run build +fi + +[ -f out/main/index.js ] || die "缺少 out/main/index.js,请先 npm run build" + +say "安装到 $PREFIX" +mkdir -p "$PREFIX/bin" "$PREFIX/logs" "$PREFIX/home" +rm -rf "$PREFIX/app" "$PREFIX/electron" +mkdir -p "$PREFIX/app" +cp -a out assets package.json "$PREFIX/app/" +cp -a node_modules/electron/dist/. "$PREFIX/electron/" +install -m 0755 scripts/linux/sodiumpet-launcher.sh "$PREFIX/bin/sodiumpet" +cp -f assets/linux/sodiumpet.png "$PREFIX/icon.png" + +# ---- 应用菜单 ---- +APPS_DIR="${XDG_DATA_HOME:-$HOME/.local/share}/applications" +mkdir -p "$APPS_DIR" +cat > "$APPS_DIR/sodiumpet.desktop" < "$AUTOSTART_DIR/sodiumpet.desktop" </dev/null 2>&1; then + update-desktop-database "$APPS_DIR" >/dev/null 2>&1 || true +fi + +say "完成。启动方式:" +echo " 桌面菜单搜索 “SodiumPet / 小钠”" +echo " 或在终端执行 $PREFIX/bin/sodiumpet" +echo " 日志:$PREFIX/logs/sodiumpet.log" +echo " 数据:$PREFIX/home(存档 / 皮肤 / 音乐配置)" + +if [ "$RUN_AFTER" = "1" ]; then + say "启动 SodiumPet…" + setsid "$PREFIX/bin/sodiumpet" >/dev/null 2>&1 < /dev/null & +fi diff --git a/scripts/linux/run.sh b/scripts/linux/run.sh new file mode 100755 index 0000000..087bdd0 --- /dev/null +++ b/scripts/linux/run.sh @@ -0,0 +1,34 @@ +#!/usr/bin/env bash +# 开发模式在 Linux 上运行(不安装,直接用仓库里的 out/ + electron) +# scripts/linux/run.sh [electron 参数...] +set -euo pipefail + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +cd "$ROOT" + +ELECTRON="node_modules/electron/dist/electron" +if [ ! -x "$ELECTRON" ]; then + echo "[run] 先安装依赖…" + npm install --no-audit --no-fund + if [ ! -x "$ELECTRON" ]; then + ELECTRON_MIRROR="${ELECTRON_MIRROR:-https://npmmirror.com/mirrors/electron/}" \ + node node_modules/electron/install.js + fi +fi +[ -f out/main/index.js ] || npm run build + +ozone="${SODIUM_PET_OZONE:-auto}" +if [ "$ozone" = "auto" ]; then + if [ -n "${WAYLAND_DISPLAY:-}" ] || [ "${XDG_SESSION_TYPE:-}" = "wayland" ]; then + if [ -n "${DISPLAY:-}" ]; then ozone="x11"; else ozone="wayland"; fi + else + ozone="x11" + fi +fi +if [ "$ozone" = "x11" ] && [ -z "${DISPLAY:-}" ]; then + echo "[run] 没有 DISPLAY,改用原生 Wayland(窗口位置/置顶会受限)" >&2 + ozone="wayland" +fi + +echo "[run] backend=$ozone" +exec "$ELECTRON" --ozone-platform="$ozone" . "$@" diff --git a/scripts/linux/sodiumpet-launcher.sh b/scripts/linux/sodiumpet-launcher.sh new file mode 100755 index 0000000..ff57f8e --- /dev/null +++ b/scripts/linux/sodiumpet-launcher.sh @@ -0,0 +1,80 @@ +#!/bin/sh +# SodiumPet Linux 启动器 +# +# 由 scripts/linux/install.sh 安装到 /bin/sodiumpet。 +# 这里负责三件事: +# 1. 设置数据目录(SODIUM_PET_HOME,默认 /home); +# 2. 选择 Chromium 显示后端:Wayland 会话优先 XWayland(窗口可定位/置顶/穿透), +# 没有 XWayland 时才退回原生 Wayland; +# 3. 个别系统禁用了非特权 user namespace 时,自动补 --no-sandbox。 +set -eu + +SELF="$(readlink -f "$0")" +PREFIX="$(cd "$(dirname "$SELF")/.." && pwd)" +APP_DIR="$PREFIX/app" +ELECTRON="$PREFIX/electron/electron" + +if [ ! -x "$ELECTRON" ]; then + echo "SodiumPet: 找不到 $ELECTRON,请重新运行 scripts/linux/install.sh" >&2 + exit 1 +fi + +export SODIUM_PET_HOME="${SODIUM_PET_HOME:-$PREFIX/home}" +: "${XDG_RUNTIME_DIR:=/run/user/$(id -u)}" +export XDG_RUNTIME_DIR + +# ---- 显示后端 ---- +ozone="${SODIUM_PET_OZONE:-auto}" +if [ "$ozone" = "auto" ]; then + if [ -n "${WAYLAND_DISPLAY:-}" ] || [ "${XDG_SESSION_TYPE:-}" = "wayland" ]; then + if [ -n "${DISPLAY:-}" ]; then + ozone="x11" # XWayland:功能完整 + else + ozone="wayland" # 原生 Wayland:没有 XWayland 时的兜底 + fi + else + ozone="x11" + fi +fi +if [ "$ozone" = "x11" ] && [ -z "${DISPLAY:-}" ]; then + echo "SodiumPet: 当前没有 DISPLAY,改用原生 Wayland(窗口位置/置顶会受限)" >&2 + ozone="wayland" +fi + +# 登录自启动时 XWayland 可能还没就绪:等一小会儿 X socket,仍没有就退回原生 Wayland +if [ "$ozone" = "x11" ]; then + disp="${DISPLAY#*:}" + disp="${disp%%.*}" + xsock="/tmp/.X11-unix/X$disp" + i=0 + while [ ! -S "$xsock" ] && [ "$i" -lt 50 ]; do + sleep 0.1 + i=$((i + 1)) + done + if [ ! -S "$xsock" ] && [ -n "${WAYLAND_DISPLAY:-}" ]; then + echo "SodiumPet: X socket $xsock 未就绪,改用原生 Wayland" >&2 + ozone="wayland" + fi +fi + +EXTRA="--ozone-platform=$ozone" + +# ---- 沙箱兜底 ---- +if [ "${SODIUM_PET_DISABLE_SANDBOX:-0}" = "1" ]; then + EXTRA="$EXTRA --no-sandbox" +elif [ -e "$PREFIX/electron/chrome-sandbox" ] && [ ! -u "$PREFIX/electron/chrome-sandbox" ]; then + restrict="$(cat /proc/sys/kernel/apparmor_restrict_unprivileged_userns 2>/dev/null || echo 0)" + userns="$(cat /proc/sys/user/max_user_namespaces 2>/dev/null || echo 1)" + if [ "$restrict" = "1" ] || [ "$userns" = "0" ]; then + EXTRA="$EXTRA --no-sandbox" + fi +fi + +mkdir -p "$PREFIX/logs" +if [ "${SODIUM_PET_LOG:-1}" = "1" ]; then + LOG="$PREFIX/logs/sodiumpet.log" + : > "$LOG" + exec "$ELECTRON" $EXTRA "$APP_DIR" "$@" >>"$LOG" 2>&1 +else + exec "$ELECTRON" $EXTRA "$APP_DIR" "$@" +fi diff --git a/scripts/linux/uninstall.sh b/scripts/linux/uninstall.sh new file mode 100755 index 0000000..aeb5d9b --- /dev/null +++ b/scripts/linux/uninstall.sh @@ -0,0 +1,34 @@ +#!/usr/bin/env bash +# 卸载 SodiumPet(当前用户) +# scripts/linux/uninstall.sh # 保留存档 / 数据目录 +# scripts/linux/uninstall.sh --purge # 连存档一起删除 +set -euo pipefail + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +PREFIX="${SODIUM_PET_PREFIX:-${XDG_DATA_HOME:-$HOME/.local/share}/SodiumPet}" +PURGE=0 +[ "${1:-}" = "--purge" ] && PURGE=1 + +say() { printf '\033[1;32m[uninstall]\033[0m %s\n' "$*"; } + +# 先结束正在运行的实例 +pkill -f "$PREFIX/electron/electron" >/dev/null 2>&1 || true + +APPS_DIR="${XDG_DATA_HOME:-$HOME/.local/share}/applications" +AUTOSTART_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/autostart" +rm -f "$APPS_DIR/sodiumpet.desktop" "$AUTOSTART_DIR/sodiumpet.desktop" +rm -f "$HOME/.local/bin/sodiumpet" + +if [ "$PURGE" = "1" ]; then + rm -rf "$PREFIX" + say "已删除 $PREFIX(含存档)" +else + # 保留 home(存档 / 皮肤 / 配置),只删除程序本体 + find "$PREFIX" -mindepth 1 -maxdepth 1 ! -name home -exec rm -rf {} + + say "已删除程序本体,存档保留在 $PREFIX/home" +fi + +if command -v update-desktop-database >/dev/null 2>&1; then + update-desktop-database "$APPS_DIR" >/dev/null 2>&1 || true +fi +say "完成" diff --git a/src/main/index.ts b/src/main/index.ts index 6eaf79e..27b04a0 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -1,4 +1,4 @@ -import { +import { app, BrowserWindow, Tray, @@ -30,18 +30,36 @@ import { DESIGN_H, DESIGN_W, type PetConfig } from '../shared/petState' import { pickBark, pickClickBark, type BarkState } from '../shared/barks' import { ChatService } from './llm' import { chatEffect, suggestions } from '../shared/dialogue' +import { + bootstrapPlatform, + capabilities, + ensureOzoneBackend, + defaultHomeCandidates, + globalCursor, + placeWindow, + platformSummary, + raiseWindow, + showOnAllWorkspaces, + IS_LINUX +} from './platform' +import { startKwinCursorBridge } from './kwinCursor' + +// Linux 下需要在 app ready 前指定 Ozone 后端(Wayland 会话默认走 XWayland) +bootstrapPlatform() +// 启动参数里没带 --ozone-platform 时,用一次 relaunch 补上(否则原生 Wayland 会直接崩) +ensureOzoneBackend() // ---------------------------------------------------------------- 数据目录 -// 默认把「软件主体」放到 E:\SodiumPet,只有 Windows 临时/GPU 缓存留在 C 盘。 +// Windows:默认把「软件主体」放到 E:\SodiumPet,只有临时/GPU 缓存留在 C 盘。 +// Linux:放到 $XDG_DATA_HOME/SodiumPet(~/.local/share/SodiumPet)。 // 沙箱里写不进去时,逐级回退,保证开发时也能跑。 function resolveHome(): string { - const isWin = process.platform === 'win32' const candidates = [ process.env.SODIUM_PET_HOME, - // Windows 上沿用之前的固定目录;其他平台用系统标准数据目录 - isWin ? 'E:\\SodiumPet' : '', + ...defaultHomeCandidates(), + // Windows 上仍然保留「exe 同级目录」这个习惯 + ...(IS_LINUX ? [] : [path.dirname(app.getPath('exe'))]), path.join(app.getPath('appData'), 'SodiumPet'), - isWin ? path.dirname(app.getPath('exe')) : '', path.join(app.getAppPath(), '.devdata') ].filter(Boolean) as string[] @@ -241,6 +259,9 @@ function registerProtocol(): void { return new Response('not found', { status: 404 }) } if (!isInside(root, abs)) return new Response('forbidden', { status: 403 }) + // 文件不存在时直接返回 404:net.fetch(file://) 会对缺失文件抛 ERR_FILE_NOT_FOUND, + // 日志里会刷一堆红色堆栈(比如首次启动还没有 data/catalog.json) + if (!fs.existsSync(abs)) return new Response('not found', { status: 404 }) // 音频需要 Range 支持,才能拖动进度条 / 正常播放 if (url.host === 'music' && fs.existsSync(abs) && fs.statSync(abs).isFile()) { @@ -343,10 +364,12 @@ function createWindow(): void { const { workArea } = screen.getPrimaryDisplay() const width = 190 const height = 450 + const icon = appIcon() mainWindow = new BrowserWindow({ icon: stickerIcon('1.0.png'), width, height, + // 原生 Wayland 会忽略坐标,由合成器决定位置;这里只对 X11/XWayland 生效 x: Math.round(workArea.x + workArea.width - width - 24), y: Math.round(workArea.y + workArea.height - height), show: false, @@ -360,6 +383,7 @@ function createWindow(): void { skipTaskbar: true, hasShadow: false, alwaysOnTop: true, + ...(IS_LINUX ? { icon } : {}), webPreferences: { preload: path.join(__dirname, '../preload/index.js'), contextIsolation: true, @@ -368,8 +392,10 @@ function createWindow(): void { } }) - mainWindow.setAlwaysOnTop(true, 'screen-saver') - mainWindow.setVisibleOnAllWorkspaces(true, { visibleOnFullScreen: true }) + raiseWindow(mainWindow, true) + showOnAllWorkspaces(mainWindow) + // 部分 X11 窗口管理器不会在创建时应用 skipTaskbar,显式再设一次(Linux 桌宠不该出现在任务栏) + if (IS_LINUX) mainWindow.setSkipTaskbar(true) mainWindow.loadFile(path.join(__dirname, '../renderer/index.html')) @@ -377,19 +403,21 @@ function createWindow(): void { // 系统 DPI 缩放可能被带进页面,强制 1:1,避免内容被放大/裁切 mainWindow?.webContents.setZoomFactor(1) mainWindow?.show() - mainWindow?.setAlwaysOnTop(true, 'screen-saver') + raiseWindow(mainWindow, true) }) mainWindow.on('show', () => { - mainWindow?.setAlwaysOnTop(true, 'screen-saver') - mainWindow?.moveTop() + raiseWindow(mainWindow, true) + if (capabilities.topmost) mainWindow?.moveTop() }) // 有些全屏程序会抢置顶,定期重新申明一次(很轻,不影响性能) - setInterval(() => { - if (!mainWindow?.isVisible()) return - mainWindow.setAlwaysOnTop(true, 'screen-saver') - }, 15000) + if (capabilities.topmost) { + setInterval(() => { + if (!mainWindow?.isVisible()) return + raiseWindow(mainWindow, true) + }, 15000) + } if (process.env.PET_CAPTURE_PET) { setTimeout(() => { @@ -712,18 +740,21 @@ function applyConfig(cfg: PetConfig): void { const height = Math.max(80, Math.round(DESIGN_H * cfg.scale - cfg.cropTop - cfg.cropBottom)) const b = mainWindow.getBounds() // 右下角锚定,缩放/裁剪时不会跑位 - mainWindow.setBounds({ + placeWindow(mainWindow, { x: Math.round(b.x + (b.width - width)), y: Math.round(b.y + (b.height - height)), width, height }) console.log('[config] bounds', mainWindow.getBounds(), 'dpr', screen.getPrimaryDisplay().scaleFactor) - mainWindow.setAlwaysOnTop(cfg.topmost, 'screen-saver') - mainWindow.setIgnoreMouseEvents( - cfg.clickThrough, - process.platform === 'linux' ? undefined : { forward: true } - ) + raiseWindow(mainWindow, cfg.topmost) + if (capabilities.clickThrough) { + // Linux 上 setIgnoreMouseEvents 不支持 forward 选项 + mainWindow.setIgnoreMouseEvents( + cfg.clickThrough, + process.platform === 'linux' ? undefined : { forward: true } + ) + } for (const w of BrowserWindow.getAllWindows()) { if (!w.isDestroyed()) w.webContents.send('pet:config:update', cfg) } @@ -757,8 +788,8 @@ function createBubbleWindow(): void { sandbox: false } }) - bubbleWindow.setIgnoreMouseEvents(true, { forward: true }) - bubbleWindow.setAlwaysOnTop(true, 'screen-saver') + if (capabilities.clickThrough) bubbleWindow.setIgnoreMouseEvents(true, { forward: true }) + raiseWindow(bubbleWindow, true) bubbleWindow.loadFile(path.join(__dirname, '../renderer/index.html'), { query: { view: 'bubble' } }) @@ -786,7 +817,7 @@ function positionBubble(): void { if (!mainWindow || !bubbleWindow) return const b = mainWindow.getBounds() const h = bubbleWindow.getBounds().height - bubbleWindow.setBounds({ + placeWindow(bubbleWindow, { x: Math.round(b.x + (b.width - 440) / 2), y: b.y - (h - 10), width: 440, @@ -796,7 +827,7 @@ function positionBubble(): void { function say(text: string, duration = 6500): void { createBubbleWindow() - bubbleWindow?.setBounds({ width: 440, height: 96 }) + if (bubbleWindow) placeWindow(bubbleWindow, { ...bubbleWindow.getBounds(), width: 440, height: 96 }) positionBubble() const payload = { text, duration } currentBubble = { text, duration, at: Date.now() } @@ -826,7 +857,7 @@ function bubbleStreamStart(): void { createBubbleWindow() bubbleStreamLen = 0 if (bubbleTimer) clearTimeout(bubbleTimer) - bubbleWindow?.setBounds({ width: 440, height: 96 }) + if (bubbleWindow) placeWindow(bubbleWindow, { ...bubbleWindow.getBounds(), width: 440, height: 96 }) positionBubble() bubbleWindow?.showInactive() sendBubbleStream('pet:bubble:stream:start') @@ -839,7 +870,7 @@ function bubbleStreamChunk(chunk: string): void { const h = Math.min(300, Math.max(96, 44 + lines * 26)) const b = mainWindow?.getBounds() if (b) { - bubbleWindow.setBounds({ + placeWindow(bubbleWindow, { x: Math.round(b.x + (b.width - 440) / 2), y: b.y - (h - 10), width: 440, @@ -1105,7 +1136,7 @@ function createMenuWindow(): void { sandbox: false } }) - menuWindow.setAlwaysOnTop(true, 'screen-saver') + raiseWindow(menuWindow, true) menuWindow.loadFile(path.join(__dirname, '../renderer/index.html'), { query: { view: 'menu' } }) @@ -1282,8 +1313,8 @@ function createLyricWindow(): void { sandbox: false } }) - lyricWindow.setAlwaysOnTop(true, 'screen-saver') - lyricWindow.setIgnoreMouseEvents(false) + raiseWindow(lyricWindow, true) + if (capabilities.clickThrough) lyricWindow.setIgnoreMouseEvents(false) lyricWindow.loadFile(path.join(__dirname, '../renderer/index.html'), { query: { view: 'lyric' } }) @@ -1522,7 +1553,7 @@ function currentFlavor(): string { function positionMenu(): void { if (!mainWindow || !menuWindow) return const b = mainWindow.getBounds() - menuWindow.setBounds({ + placeWindow(menuWindow, { x: Math.round(b.x + b.width / 2 - 200), y: Math.round(b.y + b.height - 388), width: 400, @@ -1571,7 +1602,7 @@ function createChatBar(): void { sandbox: false } }) - chatBar.setAlwaysOnTop(true, 'screen-saver') + raiseWindow(chatBar, true) chatBar.loadFile(path.join(__dirname, '../renderer/index.html'), { query: { view: 'chat' } }) @@ -1594,7 +1625,7 @@ function positionChatBar(): void { if (!mainWindow || !chatBar) return const b = mainWindow.getBounds() const h = chatExpanded ? 274 : 54 - chatBar.setBounds({ + placeWindow(chatBar, { x: Math.round(b.x + b.width / 2 - 210), y: Math.max(0, b.y - 118) + 54 - h, width: 420, @@ -1638,24 +1669,34 @@ function createPanel(tab?: string, arg?: string): void { }) // 面板放在宠物左边,避免挡住她 - const saved = store.getConfig().panelPos - if (saved) { - panelWindow.setPosition(saved.x, saved.y) - } else if (mainWindow) { - const b = mainWindow.getBounds() - panelWindow.setPosition(Math.max(20, b.x - 420), Math.max(20, b.y - 100)) - } + if (capabilities.positionWindows) { + const saved = store.getConfig().panelPos + if (saved) { + panelWindow.setPosition(saved.x, saved.y) + } else if (mainWindow) { + const b = mainWindow.getBounds() + panelWindow.setPosition(Math.max(20, b.x - 420), Math.max(20, b.y - 100)) + } - panelWindow.on('moved', () => { - if (!panelWindow) return - const [x, y] = panelWindow.getPosition() - store.setConfig({ panelPos: { x, y } }) - }) + // 原生 Wayland 下窗口位置由合成器决定,记录「移动」没有意义 + panelWindow.on('moved', () => { + if (!panelWindow) return + const [x, y] = panelWindow.getPosition() + store.setConfig({ panelPos: { x, y } }) + }) + } } // ---------------------------------------------------------------- 托盘 function createTray(): void { - tray = new Tray(buildTrayIcon()) + // Linux 下托盘依赖 StatusNotifierItem(KDE/GNOME 扩展),个别精简桌面可能不可用, + // 失败时不要让整个应用起不来——右键菜单依然可以打开面板/退出。 + try { + tray = new Tray(buildTrayIcon()) + } catch (err) { + console.warn('[tray] 当前桌面不支持托盘,已跳过:', err) + return + } tray.setToolTip('小钠 · 桌宠') tray.setContextMenu( Menu.buildFromTemplate([ @@ -2316,8 +2357,11 @@ let dragStartWin: [number, number] = [0, 0] function startDrag(): void { if (!mainWindow) return + // 原生 Wayland 下既读不到全局光标,也不能由客户端移动窗口,拖拽只能禁用 + if (!capabilities.positionWindows || !capabilities.cursor) return dragStartWin = mainWindow.getPosition() as [number, number] - const p = screen.getCursorScreenPoint() + const p = globalCursor() + if (!p) return dragStartCursor = [p.x, p.y] if (dragTimer) clearInterval(dragTimer) @@ -2326,7 +2370,8 @@ function startDrag(): void { let lastY = dragStartWin[1] dragTimer = setInterval(() => { if (!mainWindow) return - const c = screen.getCursorScreenPoint() + const c = globalCursor() + if (!c) return const x = Math.round(dragStartWin[0] + (c.x - dragStartCursor[0])) const y = Math.round(dragStartWin[1] + (c.y - dragStartCursor[1])) if (x === lastX && y === lastY) return // 没动就不调用,减少无效 setPosition @@ -2354,9 +2399,12 @@ if (!gotLock) { app.on('second-instance', () => mainWindow?.show()) app.whenReady().then(() => { + console.log('[pet] platform =', platformSummary()) console.log('[pet] home =', HOME) registerProtocol() registerIpc() + // KDE/Wayland:用 KWin 脚本桥接真实的全局光标(否则指针离开 X11 窗口后就读不到位置) + startKwinCursorBridge(path.join(bundledDir('kwin'), 'sodiumpet-cursor.js')) createWindow() createTray() applyConfig(store.getConfig()) @@ -2380,21 +2428,33 @@ if (!gotLock) { } }, 3000) - // 全屏视线跟随:主进程按 33ms 轮询光标(屏幕坐标,跨窗口 / 跨显示器都有效) - setInterval(() => { - const cfgNow = store.getConfig() - const forceLook = !!process.env.PET_FORCE_EYE_FOLLOW - if (!(cfgNow.eyeFollow || forceLook) || !mainWindow || mainWindow.isDestroyed()) return - if (mainWindow.isMinimized()) return - const p = screen.getCursorScreenPoint() - const b = mainWindow.getBounds() - mainWindow.webContents.send('pet:look', { - x: p.x - b.x + cfgNow.cropLeft, - y: p.y - b.y + cfgNow.cropTop, - // 光标是否在窗口内(渲染层可用于复位/弱化) - inside: p.x >= b.x && p.x <= b.x + b.width && p.y >= b.y && p.y <= b.y + b.height - }) - }, 33) + // 全屏视线跟随:主进程按 33ms 轮询光标(跨窗口 / 跨显示器都有效) + // KDE/Wayland 下用 KWin 桥接取真实光标;没有桥接时退回 X11 光标 + let lastLookLogAt = 0 + if (capabilities.cursor) { + setInterval(() => { + const cfgNow = store.getConfig() + const forceLook = !!process.env.PET_FORCE_EYE_FOLLOW + if (!(cfgNow.eyeFollow || forceLook) || !mainWindow || mainWindow.isDestroyed()) return + if (mainWindow.isMinimized()) return + const p = globalCursor() + 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() + mainWindow.webContents.send('pet:look', { + x: p.x - b.x + cfgNow.cropLeft, + y: p.y - b.y + cfgNow.cropTop, + // 光标是否在窗口内(渲染层可用于复位 / 弱化) + inside: p.x >= b.x && p.x <= b.x + b.width && p.y >= b.y && p.y <= b.y + b.height + }) + }, 33) + } app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) createWindow() diff --git a/src/main/kwinCursor.ts b/src/main/kwinCursor.ts new file mode 100644 index 0000000..189abd3 --- /dev/null +++ b/src/main/kwinCursor.ts @@ -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 +} diff --git a/src/main/platform.ts b/src/main/platform.ts new file mode 100644 index 0000000..86afd5e --- /dev/null +++ b/src/main/platform.ts @@ -0,0 +1,171 @@ +/** + * 桌面平台适配层(Linux / Wayland 支持) + * + * 这个项目最初只面向 Windows。要在 Linux(尤其是 Wayland 会话)上运行, + * 需要处理几处平台差异: + * + * 1. **窗口后端**:Wayland 原生协议(xdg-toplevel)不允许客户端自己决定窗口位置, + * 也没有「始终置顶 / 鼠标穿透 / 读取全局光标」的通用协议——而桌宠恰恰全都依赖它们。 + * 因此默认在 Wayland 会话里通过 XWayland(`--ozone-platform=x11`)运行: + * 窗口位置、置顶、穿透、拖拽、视线跟随都能正常工作,并仍然是同一个 Wayland 桌面。 + * 也可以用 `SODIUM_PET_OZONE=wayland` 强制走原生 Wayland(功能会受限,见 README)。 + * 2. **数据目录**:Windows 习惯把数据放在 exe 旁边(E:\SodiumPet),Linux 遵循 + * XDG 规范放到 `$XDG_DATA_HOME/SodiumPet`。 + * 3. **能力降级**:原生 Wayland 下 setPosition/setAlwaysOnTop/getCursorScreenPoint + * 都会被合成器忽略,所以要提前判断并跳过这些调用,避免窗口「看起来没反应」。 + */ +import { app, screen, type BrowserWindow } from 'electron' +import * as os from 'node:os' +import * as path from 'node:path' +import { kwinCursorPoint } from './kwinCursor' + +export type OzoneMode = 'x11' | 'wayland' | '' + +export const IS_LINUX = process.platform === 'linux' +export const IS_WINDOWS = process.platform === 'win32' +export const IS_MAC = process.platform === 'darwin' + +const sessionType = (process.env.XDG_SESSION_TYPE || '').toLowerCase() +const hasX11 = Boolean(process.env.DISPLAY) +const hasWayland = Boolean(process.env.WAYLAND_DISPLAY) + +/** 当前是否运行在 Wayland 会话(无论后端是 XWayland 还是原生 Wayland) */ +export const IS_WAYLAND_SESSION = IS_LINUX && (sessionType === 'wayland' || hasWayland) + +/** 实际使用的 Chromium Ozone 后端 */ +export const OZONE_MODE: OzoneMode = decideOzoneMode() + +function decideOzoneMode(): OzoneMode { + if (!IS_LINUX) return '' + const forced = (process.env.SODIUM_PET_OZONE || 'auto').toLowerCase() + if (forced === 'x11') return hasX11 ? 'x11' : hasWayland ? 'wayland' : 'x11' + if (forced === 'wayland') return hasWayland ? 'wayland' : hasX11 ? 'x11' : 'wayland' + // auto:Wayland 会话下优先 XWayland(功能完整);没有 XWayland 才用原生 Wayland + if (IS_WAYLAND_SESSION) return hasX11 ? 'x11' : 'wayland' + return hasX11 ? 'x11' : '' +} + +/** 原生 Wayland 下很多窗口操作是空操作,这里集中声明能力,便于上层降级 */ +export const capabilities = { + /** 能否由程序指定窗口坐标(原生 Wayland:否) */ + positionWindows: !IS_LINUX || OZONE_MODE !== 'wayland', + /** 能否置顶 / 跨虚拟桌面(原生 Wayland:否) */ + topmost: !IS_LINUX || OZONE_MODE !== 'wayland', + /** 能否读取全局鼠标坐标(原生 Wayland:否) */ + cursor: !IS_LINUX || OZONE_MODE !== 'wayland', + /** 能否设置鼠标穿透(原生 Wayland:否) */ + clickThrough: !IS_LINUX || OZONE_MODE !== 'wayland' +} + +/** + * 在 app ready 之前调用:设置应用名、Ozone 后端等启动参数。 + * 注意必须早于 app.whenReady(),Chromium 在初始化 UI 平台时会读取这些开关。 + */ +export function bootstrapPlatform(): void { + if (!IS_LINUX) return + // WM_CLASS / 托盘 / 通知里显示的名字 + app.setName('SodiumPet') + // 注意:Ozone 后端在 JS 运行之前就已确定,appendSwitch('ozone-platform') 是无效的, + // 必须保证启动参数里带上它 —— 见 ensureOzoneBackend()。 + // 部分 X11 合成器(含 XWayland)需要显式声明才能拿到 ARGB 视觉,否则透明窗口会黑底 + if (OZONE_MODE === 'x11' && !app.commandLine.hasSwitch('enable-transparent-visuals')) { + app.commandLine.appendSwitch('enable-transparent-visuals') + } + // 软件渲染兜底:虚拟机 / 无 GPU 环境下可通过环境变量关闭硬件加速 + if (process.env.SODIUM_PET_DISABLE_GPU === '1') app.disableHardwareAcceleration() + if (process.env.SODIUM_PET_GPU_COMPOSITING === 'off') { + app.disableHardwareAcceleration() + app.commandLine.appendSwitch('disable-gpu-compositing') + } +} + +/** + * 确保当前进程使用了正确的 Ozone 后端。 + * + * Chromium 在选择 Wayland/X11 后端时早于主进程 JS,`app.commandLine.appendSwitch` + * 对它无效,所以启动参数里没有 `--ozone-platform` 时,用一次极短的 relaunch 补上。 + * 正常安装后由启动脚本直接带参数,不会触发这里。 + */ +export function ensureOzoneBackend(): void { + if (!IS_LINUX || !OZONE_MODE) return + if (app.commandLine.hasSwitch('ozone-platform')) return + console.log(`[platform] 缺少 --ozone-platform,重启为 ${OZONE_MODE} 后端`) + app.relaunch({ args: [...process.argv.slice(1), `--ozone-platform=${OZONE_MODE}`] }) + app.exit(0) +} + +/** 各平台默认的数据目录候选(第一个可写的会被使用) */ +export function defaultHomeCandidates(): string[] { + if (IS_WINDOWS) { + return ['E:\\SodiumPet'] + } + if (IS_MAC) { + return [path.join(os.homedir(), 'Library', 'Application Support', 'SodiumPet')] + } + // Linux:遵循 XDG 规范,避免往 /opt、/usr 这类只读目录里写数据 + const dataHome = process.env.XDG_DATA_HOME || path.join(os.homedir(), '.local', 'share') + return [path.join(dataHome, 'SodiumPet')] +} + +/** 把窗口放到指定位置;原生 Wayland 下只调整大小(合成器决定位置) */ +export function placeWindow( + win: BrowserWindow | null, + bounds: { x: number; y: number; width: number; height: number } +): void { + if (!win || win.isDestroyed()) return + if (capabilities.positionWindows) { + win.setBounds(bounds) + } else { + win.setSize(Math.max(1, Math.round(bounds.width)), Math.max(1, Math.round(bounds.height))) + } +} + +/** 置顶 / 取消置顶;原生 Wayland 下没有该能力,直接跳过 */ +export function raiseWindow(win: BrowserWindow | null, onTop: boolean): void { + if (!win || win.isDestroyed()) return + if (!capabilities.topmost) return + win.setAlwaysOnTop(onTop, 'screen-saver') +} + +/** 在所有虚拟桌面 / 全屏窗口上方可见 */ +export function showOnAllWorkspaces(win: BrowserWindow | null): void { + if (!win || win.isDestroyed()) return + if (!capabilities.topmost) return + win.setVisibleOnAllWorkspaces(true, { visibleOnFullScreen: true }) +} + +/** + * 读取全局鼠标位置。 + * + * 优先使用 KDE 的 KWin 桥接(能拿到 Wayland 原生窗口上方的真实光标); + * 没有桥接时退回 XQueryPointer —— 注意后者在指针离开 X11 窗口后会停住。 + */ +export function globalCursor(): { x: number; y: number } | null { + const bridged = kwinCursorPoint() + if (bridged) return bridged + if (!capabilities.cursor) return null + try { + return screen.getCursorScreenPoint() + } catch { + return null + } +} + +/** 主窗口右下角默认位置(按工作区计算,多显示器也适用) */ +export function bottomRightPosition(width: number, height: number, margin = 24): { + x: number + y: number +} { + const { workArea } = screen.getPrimaryDisplay() + return { + x: Math.round(workArea.x + workArea.width - width - margin), + y: Math.round(workArea.y + workArea.height - height) + } +} + +/** 当前平台的一句话描述,写进日志方便排查 */ +export function platformSummary(): string { + if (!IS_LINUX) return `${process.platform} (${process.arch})` + const backend = OZONE_MODE === 'wayland' ? 'wayland(原生)' : 'x11(XWayland)' + return `linux (${process.arch}) session=${sessionType || 'unknown'} backend=${backend}` +} diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsx index d84182d..da12f4f 100644 --- a/src/renderer/src/App.tsx +++ b/src/renderer/src/App.tsx @@ -117,7 +117,8 @@ export default function App(): React.ReactElement { const w = DESIGN_W * cfg.scale const h = DESIGN_H * cfg.scale adapterRef.current?.resize(w, h) - if (!cfg.eyeFollow) adapterRef.current?.lookAt?.(-1, -1) + // NaN = 复位看向正前方(负数坐标是合法位置,不能当复位信号) + if (!cfg.eyeFollow) adapterRef.current?.lookAt?.(Number.NaN, Number.NaN) // 只有模型已经挂载完成(记录过皮肤)且皮肤确实变了才重载,避免启动时的无限重载循环 if (loadedSkinRef.current && (cfg.currentSkin || 'xiaona') !== loadedSkinRef.current) { window.location.reload() diff --git a/src/renderer/src/pet/adapters/live2d.ts b/src/renderer/src/pet/adapters/live2d.ts index a1cd33f..026ed87 100644 --- a/src/renderer/src/pet/adapters/live2d.ts +++ b/src/renderer/src/pet/adapters/live2d.ts @@ -1,4 +1,4 @@ -import type { AvatarAdapter, AvatarContext } from '../types' +import type { AvatarAdapter, AvatarContext } from '../types' /** * Live2D(Cubism 4/5)渲染器。 @@ -257,7 +257,10 @@ export class Live2DAdapter implements AvatarAdapter { lookAt(x: number, y: number): void { try { - if (x < 0 || y < 0) { + // 复位用 NaN 表示。注意不能用「负数」当复位信号: + // 主进程送来的是窗口相对坐标,鼠标移到窗口左侧/上方时本来就是负数, + // 旧写法会把「看向左边的鼠标」误判成复位,导致鼠标一离开窗口视线就回正。 + if (!Number.isFinite(x) || !Number.isFinite(y)) { // 复位:直接把 FocusController 归零(正视前方) const fc = this.model?.internalModel?.focusController if (fc && typeof fc.focus === 'function') { diff --git a/src/renderer/src/pet/types.ts b/src/renderer/src/pet/types.ts index 459feeb..ceb4a96 100644 --- a/src/renderer/src/pet/types.ts +++ b/src/renderer/src/pet/types.ts @@ -1,4 +1,4 @@ -import type { SkinManifest } from '../../../shared/types' +import type { SkinManifest } from '../../../shared/types' /** 所有形象渲染器的统一接口:Live2D / Q 版序列帧 / 静态图都实现它 */ export interface AvatarAdapter { @@ -13,7 +13,7 @@ export interface AvatarAdapter { lipSync?(value: number): void /** 预留:情绪驱动(后续接状态条) */ setMood?(mood: string): void - /** Live2D:视线看向画布内某点(CSS 坐标,相对画布左上角) */ + /** Live2D:视线看向画布内某点(CSS 坐标,相对画布左上角;可为负数;NaN 表示复位正视) */ lookAt?(x: number, y: number): void /** 无校准值的导入模型:自动测量包围盒 */ tryAutoCalibrate?(): void