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 8da6681..8429218 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,48 @@ -# 小钠 · 化学元素拟人桌宠(SodiumPet) +# 小钠 · 化学元素拟人桌宠(SodiumPet) -一个跑在 Windows 桌面上的 Live2D 桌宠:化学元素拟人世界观、经济与任务系统、本地音乐播放器、成就、知识库、MOD 支持,以及可自定义的界面图标。 +一个跑在 Windows / Linux(Wayland、X11)桌面上的 Live2D 桌宠:化学元素拟人世界观、经济与任务系统、本地音乐播放器、成就、知识库、MOD 支持,以及可自定义的界面图标。 > 内置角色「小钠」= 钠(Na)拟人,来自 EL-Cross-Lab。也支持导入任意 Live2D 模型,并按「普通桌宠」风格使用。 +--- + +## 原项目与致谢 + +- **原项目 / 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))。 +- 代码遵循原项目 **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 立绘**:透明置顶窗口、拖动、摸头、视线跟随、双击/右键菜单 @@ -21,14 +60,91 @@ - **编辑器**:改物品/活动(名称、图标、简介、价格、等级、奖励)、改等级描述与图标、周期表配色(可视化格子上取色、另存自定义方案)、底栏按钮图标(内置表情包或导入图片) - **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,默认) | ✅ | ✅ | ✅ | ✅ | 推荐,仍是同一个 Wayland 桌面 | +| `wayland`(原生) | ❌ 由合成器决定 | ❌ | ❌ | 仅窗口内 | 仅在没有 XWayland 时兜底 | + +启动时自动判断:只要会话里有 `WAYLAND_DISPLAY` 和 `DISPLAY`(KDE/GNOME 默认会带 +XWayland),就用 XWayland;只有 `WAYLAND_DISPLAY` 时才退回原生 Wayland,并在日志里提示。 +可以用 `SODIUM_PET_OZONE=wayland` 强制原生 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_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/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 3264223..ed92f4d 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -1,4 +1,25 @@ -# 变更记录 +# 变更记录 + +## 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 7c524fb..93f1277 100644 --- a/package.json +++ b/package.json @@ -11,7 +11,10 @@ "start": "electron .", "dev": "node scripts/dev.mjs", "dist": "electron-builder --win portable --x64", - "pack": "electron-builder --win dir --x64" + "pack": "electron-builder --win dir --x64", + "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", @@ -76,4 +79,4 @@ } ] } -} \ 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 0087789..d6dda3e 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -1,4 +1,4 @@ -import { +import { app, BrowserWindow, Tray, @@ -30,15 +30,34 @@ 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' + +// 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 candidates = [ process.env.SODIUM_PET_HOME, - 'E:\\SodiumPet', - path.dirname(app.getPath('exe')), + ...defaultHomeCandidates(), + // Windows 上仍然保留「exe 同级目录」这个习惯 + ...(IS_LINUX ? [] : [path.dirname(app.getPath('exe'))]), path.join(app.getPath('appData'), 'SodiumPet'), path.join(app.getAppPath(), '.devdata') ].filter(Boolean) as string[] @@ -239,6 +258,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()) { @@ -331,10 +353,12 @@ function createWindow(): void { const { workArea } = screen.getPrimaryDisplay() const width = 190 const height = 450 + const icon = appIcon() mainWindow = new BrowserWindow({ width, height, + // 原生 Wayland 会忽略坐标,由合成器决定位置;这里只对 X11/XWayland 生效 x: Math.round(workArea.x + workArea.width - width - 24), y: Math.round(workArea.y + workArea.height - height), show: false, @@ -348,6 +372,7 @@ function createWindow(): void { skipTaskbar: true, hasShadow: false, alwaysOnTop: true, + ...(IS_LINUX ? { icon } : {}), webPreferences: { preload: path.join(__dirname, '../preload/index.js'), contextIsolation: true, @@ -356,8 +381,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')) @@ -365,19 +392,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_ONCE) { @@ -669,15 +698,17 @@ 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, { forward: true }) + raiseWindow(mainWindow, cfg.topmost) + if (capabilities.clickThrough) { + mainWindow.setIgnoreMouseEvents(cfg.clickThrough, { forward: true }) + } for (const w of BrowserWindow.getAllWindows()) { if (!w.isDestroyed()) w.webContents.send('pet:config:update', cfg) } @@ -711,8 +742,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' } }) @@ -740,7 +771,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, @@ -750,7 +781,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() } @@ -780,7 +811,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') @@ -793,7 +824,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, @@ -1059,7 +1090,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' } }) @@ -1236,8 +1267,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' } }) @@ -1476,7 +1507,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, @@ -1525,7 +1556,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' } }) @@ -1548,7 +1579,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, @@ -1592,24 +1623,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([ @@ -2270,8 +2311,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) @@ -2280,7 +2324,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 @@ -2308,6 +2353,7 @@ if (!gotLock) { app.on('second-instance', () => mainWindow?.show()) app.whenReady().then(() => { + console.log('[pet] platform =', platformSummary()) console.log('[pet] home =', HOME) registerProtocol() registerIpc() @@ -2335,16 +2381,20 @@ if (!gotLock) { }, 3000) // 全屏视线跟随:主进程按 50ms 轮询光标位置,发给宠物窗口 - setInterval(() => { - const cfgNow = store.getConfig() - if (!cfgNow.eyeFollow || !mainWindow || !mainWindow.isVisible()) 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 - }) - }, 50) + // 原生 Wayland 读不到全局光标,改为只跟随窗口内的鼠标(渲染层已处理) + if (capabilities.cursor) { + setInterval(() => { + const cfgNow = store.getConfig() + if (!cfgNow.eyeFollow || !mainWindow || !mainWindow.isVisible()) return + const p = globalCursor() + if (!p) return + const b = mainWindow.getBounds() + mainWindow.webContents.send('pet:look', { + x: p.x - b.x + cfgNow.cropLeft, + y: p.y - b.y + cfgNow.cropTop + }) + }, 50) + } app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) createWindow() diff --git a/src/main/platform.ts b/src/main/platform.ts new file mode 100644 index 0000000..cbb98bc --- /dev/null +++ b/src/main/platform.ts @@ -0,0 +1,163 @@ +/** + * 桌面平台适配层(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' + +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 }) +} + +/** 读取全局鼠标位置;原生 Wayland 下返回 null */ +export function globalCursor(): { x: number; y: number } | null { + 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}` +}