Compare commits
136
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0bec173396 | ||
|
|
fd9b8068cb | ||
|
|
edcab5c72c | ||
|
|
abf958e2a6 | ||
|
|
f4d2916f0d | ||
|
|
6068d5bc65 | ||
|
|
3e08e9314e | ||
|
|
3e2acc5a17 | ||
|
|
19990fc9de | ||
|
|
20a5b3ebf1 | ||
|
|
c957cecee4 | ||
|
|
d19baec90b | ||
|
|
900eb90b42 | ||
|
|
2246e3f68e | ||
|
|
0e851ff920 | ||
|
|
6c09525834 | ||
|
|
462b49b5c4 | ||
|
|
6ce93ee962 | ||
|
|
ddec5c59c0 | ||
|
|
fdf859c4c9 | ||
|
|
b819912733 | ||
|
|
3f366651bd | ||
|
|
f863b1022c | ||
|
|
5df305e2f9 | ||
|
|
4a2f1c120c | ||
|
|
b30df83c8b | ||
|
|
b83d3e54f3 | ||
|
|
303dbf24e6 | ||
|
|
54a783b80e | ||
|
|
d06989622f | ||
|
|
c8d4972cf0 | ||
|
|
90cc6b0bb1 | ||
|
|
ff65f6f3c9 | ||
|
|
27fc535301 | ||
|
|
f6cdab7ec7 | ||
|
|
2065514d16 | ||
|
|
a67b966de3 | ||
|
|
b3c565fdc7 | ||
|
|
91563f05cb | ||
|
|
6ab941a086 | ||
|
|
28aa6ec971 | ||
|
|
752346d877 | ||
|
|
1c32dc71b0 | ||
|
|
f470585136 | ||
|
|
7d29723f0d | ||
|
|
bfb97de6c7 | ||
|
|
a634a59976 | ||
|
|
99c59551fd | ||
|
|
442b9a1c32 | ||
|
|
b63b45fabd | ||
|
|
8ee5ca66b2 | ||
|
|
7d05d25b94 | ||
|
|
1ce54df4c0 | ||
|
|
ff755ce551 | ||
|
|
4e62508335 | ||
|
|
09973884ae | ||
|
|
5b75dd5c59 | ||
|
|
2b1c300203 | ||
|
|
a6f37418e6 | ||
|
|
7da47bffa3 | ||
|
|
19be0d2443 | ||
|
|
f8735e5ca5 | ||
|
|
8febf2d94e | ||
|
|
1803cc00da | ||
|
|
d5df921d7f | ||
|
|
c17c3d3384 | ||
|
|
901f504dc6 | ||
|
|
101c7260a2 | ||
|
|
7f570c85c3 | ||
|
|
b1392c0512 | ||
|
|
16b5d3cab1 | ||
|
|
6a189513b0 | ||
|
|
aa272fc82b | ||
|
|
81e3add520 | ||
|
|
9a495e6a0f | ||
|
|
64b11d56bf | ||
|
|
b15cece581 | ||
|
|
2d9ac527fb | ||
|
|
55846a91e9 | ||
|
|
66d8cd6efe | ||
|
|
44adec01f6 | ||
|
|
1b86da28d2 | ||
|
|
8b63cb5211 | ||
|
|
4c2aa876b6 | ||
|
|
d7fc94e551 | ||
|
|
c01ee8ae5a | ||
|
|
b6964658d7 | ||
|
|
885966aa7e | ||
|
|
9e759197d0 | ||
|
|
7ef442271f | ||
|
|
533a263d6e | ||
|
|
3e21c2c993 | ||
|
|
f4bb5ccf46 | ||
|
|
2b123194e1 | ||
|
|
ec2d3ffbc4 | ||
|
|
26fd6b51b7 | ||
|
|
a09ac41299 | ||
|
|
d609188acc | ||
|
|
cf08034060 | ||
|
|
8012cf7954 | ||
|
|
0b604c76f1 | ||
|
|
58241a513f | ||
|
|
929e4b1e78 | ||
|
|
2e2c4a5234 | ||
|
|
3cacb34422 | ||
|
|
cfa6c04aa6 | ||
|
|
d95a5d8f0c | ||
|
|
6e11156b90 | ||
|
|
afb22c4f08 | ||
|
|
ae6958f291 | ||
|
|
76670121a9 | ||
|
|
c971dad167 | ||
|
|
71c44a085d | ||
|
|
81d33f3048 | ||
|
|
391082278f | ||
|
|
c6c8f85ddd | ||
|
|
8692a13577 | ||
|
|
56731efa76 | ||
|
|
7a08fff85e | ||
|
|
8b31277c58 | ||
|
|
2fc28dd7a5 | ||
|
|
40af06edad | ||
|
|
6ed498e4d0 | ||
|
|
c3c5f583ad | ||
|
|
ce389c2154 | ||
|
|
5a1fd594e0 | ||
|
|
18f63bf33e | ||
|
|
5421268fbf | ||
|
|
0117c02677 | ||
|
|
65f9377f24 | ||
|
|
e094131a7a | ||
|
|
b6d72f4792 | ||
|
|
8fa50b7804 | ||
|
|
c9e10b0db7 | ||
|
|
3dac2ca6ed | ||
|
|
b26de2651b |
No files matched your search
@@ -1,29 +0,0 @@
|
||||
## 简体中文
|
||||
|
||||
`v0.1.0` 是 WTOffline 启动器的首个公开版本。
|
||||
|
||||
### 主要功能
|
||||
|
||||
- **本地人机对局。** 在支持的陆战、空战和海战模式中与 AI 队友和对手交战。对局结束后可以查看结算和回放。
|
||||
- **离线机库与成长。** 组建编队、研发载具和改装件、训练乘员,并使用本地商店与交易所。
|
||||
- **客户端、存档和数值。** 管理多个离线客户端,备份、恢复和迁移存档,调整对局、收益和研发数值。
|
||||
- **内置更新检查。** 在「关于」检查启动器和适配包更新。启动器会验证下载的适配包签名,通过后启用。
|
||||
|
||||
### 客户端兼容性
|
||||
|
||||
已在 `2.61.0.37`、`2.61.0.43` 和 `2.61.0.55` 上实机验证。补丁会根据客户端文件内容查找匹配位置,因此也可能适配之后的其他小版本更新。
|
||||
|
||||
## English
|
||||
|
||||
`v0.1.0` is the first public release of the WTOffline Launcher.
|
||||
|
||||
### Highlights
|
||||
|
||||
- **Local battles with AI.** Play supported ground, air, and naval modes with AI teammates and opponents. View your results and replays after a battle.
|
||||
- **Offline hangar and progression.** Build lineups, research vehicles and modifications, train crews, and use the local store and marketplace.
|
||||
- **Clients, saves, and tuning.** Manage multiple offline clients, back up, restore, and transfer saves, and adjust battle, reward, and research settings.
|
||||
- **Built-in update checks.** Check for launcher and adaptation pack updates under **About**. The launcher verifies each downloaded pack's signature before enabling it.
|
||||
|
||||
### Client compatibility
|
||||
|
||||
Tested in-game with client versions `2.61.0.37`, `2.61.0.43`, and `2.61.0.55`. The patches match patterns in the client files, so they may also work with other later minor updates.
|
||||
@@ -1,35 +0,0 @@
|
||||
## 简体中文
|
||||
|
||||
> **重要升级提示:** 所有使用 **Gaijin 官方独立版客户端**,或者 **Steam 版但曾经通过官方启动器(更新器)启动过游戏** 的用户,**必须更新到 `v0.1.1` 启动器**(更新后请对已有离线副本重新执行一次「构建客户端」)。旧版启动器在存在官方清单 `content/warthunder.blk` 时会触发游戏拉起官方启动器并还原离线补丁,导致启动闪退、弹出官服更新或报原版备份不一致。
|
||||
|
||||
`v0.1.1` 是 WTOffline 启动器的重要维护更新,重点修复官方客户端/官方启动器用户无法正常启动的问题、修复对局中非本机载具受损提示串台,并增强启动稳定性与故障诊断能力。
|
||||
|
||||
### 修复与改进
|
||||
|
||||
- **解决官方独立版 / 官方启动器拉起官服更新的问题。** 启动参数新增 `-skip_pkg_validation`,跳过 `aces.exe` 启动时对官方 `content/warthunder.blk` 的文件体积校验;同时新增可执行文件隔离补丁,阻止游戏在异常情况下拉起官方 `launcher.exe -fullcheck` 联网覆盖离线文件,修复“启动数秒后以退出码 `1` 退出 → 弹出官服更新 → 离线文件被还原/报备份不一致”的死循环。
|
||||
- **局内受损提示与敌方部件归属。** 修复空战与现代陆战中 AI 载具航电、传感器、雷达、红外干扰和瞄准吊舱受损时错误向玩家弹出白字提示(及误退光电视角)的问题;过滤陆战与海战右侧敌方部件损毁列表及特殊命中反馈中的非本机攻击记录,保留本机在途弹药与观战视角显示。
|
||||
- **启动与写盘稳定性。** 游戏补丁文件写入改为临时文件原子替换并带短暂占用重试,降低安全软件实时扫描导致写入失败的风险;优化 `wto_ws.dll` 加载时的钩子批量启用流程,减少初始化期的线程冻结次数并记录详细错误码。
|
||||
- **原版备份检测与报错。** 修复旧版 `wtoffline\stock` 备份在客户端更新后遮蔽实际版本、无法自动刷新的问题;启动时区分「原版文件备份缺失/损坏」与「版本不一致」,并在日志中记录双方实际版本号。
|
||||
- **启动前检查与诊断导出。** 启动游戏前核对核心文件是否可读(提前提示可能被安全软件隔离);异常退出时在启动器日志记录现场文件状态与带十六进制的系统退出码;导出的诊断 ZIP 自动附带 `wto_ws.log`、最新一份游戏 `.clog` 日志和环境摘要(不含玩家存档)。
|
||||
|
||||
### 客户端兼容性
|
||||
|
||||
支持已核对版本 `2.61.0.37`、`2.61.0.43` 和 `2.61.0.55`(自带补丁集 `2026.12.02`),并支持按特征码自动尝试适配后续小版本更新。
|
||||
|
||||
## English
|
||||
|
||||
> **Important upgrade notice:** All users on the **standalone Gaijin client**, as well as **Steam users who have ever launched the game through the official Gaijin launcher/updater**, **must upgrade to `v0.1.1`** (and rebuild existing offline copies after updating). On earlier launcher versions, the presence of `content/warthunder.blk` causes `aces.exe` to spawn the official launcher and overwrite patched offline files, resulting in startup exit code `1`, official updater popups, or stock-backup version mismatches.
|
||||
|
||||
`v0.1.1` is an important maintenance release of the WTOffline Launcher that fixes startup failures on standalone/official-launcher clients, fixes cross-unit battle damage notices, improves launch reliability, and strengthens crash diagnostics.
|
||||
|
||||
### Fixes and improvements
|
||||
|
||||
- **Skip startup package validation and block official launcher spawns.** Added `-skip_pkg_validation` to offline launch arguments so `aces.exe` skips the startup `content/warthunder.blk` file-size integrity check, and added an executable isolation patch that blocks `aces.exe` from spawning the official `launcher.exe -fullcheck` updater. This eliminates the loop where the game exits with code `1`, opens the official launcher, and overwrites offline files back to the online build.
|
||||
- **In-battle damage notices and enemy parts feedback.** Fixed AI avionics, sensor, radar, RWR/countermeasures, and targeting-pod failures in air and modern ground battles incorrectly showing white damage notices (or forcing the player out of optic view). Filtered non-local AI-on-AI hits out of the ground/naval enemy damaged-parts list and special hit-camera events while preserving in-flight player munitions and spectator views.
|
||||
- **Launch and file-write reliability.** Rebuilt game files are now written via temporary files with atomic rename and brief retry on transient antivirus locks. Batched MinHook activation in `wto_ws.dll` into two passes to cut startup thread-freeze cycles and log detailed `MH_STATUS` diagnostics on failure.
|
||||
- **Stock backup detection and errors.** Fixed stale `wtoffline\stock` backups masking an externally updated client and blocking backup refresh. Launch checks now distinguish missing/unreadable backups from version mismatches and log the exact copy and backup versions.
|
||||
- **Pre-launch checks and richer diagnostics.** Verify core launch files before starting `aces.exe` (flagging possible antivirus quarantine early), log post-exit file snapshots and hex-annotated Windows exit codes, and include `wto_ws.log`, the latest `.clog`, and a metadata summary (without player saves) in exported diagnostic ZIPs.
|
||||
|
||||
### Client compatibility
|
||||
|
||||
Verified with client versions `2.61.0.37`, `2.61.0.43`, and `2.61.0.55` (bundled patch set `2026.12.02`), with pattern-based matching for later minor updates.
|
||||
@@ -1,27 +0,0 @@
|
||||
## 简体中文
|
||||
|
||||
`v0.1.2` 是 WTOffline 启动器的维护更新,重点放开「节省空间的复制」对游戏版本的硬锁定、修复维护页更新客户端时的路径校验误报,并内置 `2.61.0.58` 版本核对记录。
|
||||
|
||||
### 修复与改进
|
||||
|
||||
- **省空间复制改为跨版本规则。** 取消原先绑定单一版本号(`2.61.0.43`)与 8 MiB 体积门槛的静态哈希清单,改为基于只读资源规则自动共用 `content/` 与 `content.hq/` 下的 `.dxp.bin` 和 `.grp` 资源包;小版本更新后无需等待新清单即可继续省空间安装或转换,且同卷省空间客户端执行「从在线版更新」时会保持或重建硬链接,不再拆分为完整复制。
|
||||
- **修复维护页「从在线版更新」误报路径越界。** 扫描安装来源时排除顶层残留的 `wtoffline` 目录;安装向导第 3 步与后台同步拦截将数据目录设为客户端目录或其父目录的配置,并解除旧安装把数据目录放在客户端父目录时的误报;所有路径安全校验失败均在启动器日志中记录具体原因与路径以便排查。
|
||||
- **「关于」页快速导出日志与关闭日志开关。** 在「关于」页新增「保存日志 ZIP…」快捷按钮(导出内容同时纳入最新一份内置浏览器 `-browser.log`,仍不含玩家存档),并在「设置 → 诊断」新增「生成运行日志」开关,允许关闭启动器日志、本地服务器流量日志及 `wto_ws.log` 的磁盘写入。
|
||||
|
||||
### 客户端兼容性
|
||||
|
||||
支持已核对版本 `2.61.0.37`、`2.61.0.43`、`2.61.0.55` 和 `2.61.0.58`(自带补丁集 `2026.12.02`),并支持按特征码自动尝试适配后续小版本更新。
|
||||
|
||||
## English
|
||||
|
||||
`v0.1.2` is a maintenance release of the WTOffline Launcher that makes space-saving copies resilient across minor game updates, fixes false path-scope errors during client updates, and bundles the `2.61.0.58` version check record.
|
||||
|
||||
### Fixes and improvements
|
||||
|
||||
- **Version-independent space-saving copies.** Replaced the single-version (`2.61.0.43`) SHA-256 manifest and 8 MiB cutoff with declarative read-only asset rules covering `.dxp.bin` and `.grp` archives under `content/` and `content.hq/`. Space-saving installs and conversions now keep working across minor updates, and updating a same-volume space-saving client preserves or recreates hard links instead of detaching them into full copies.
|
||||
- **Fix false `maintenance_location` errors when updating.** Ignore stray top-level `wtoffline` folders when scanning a stock source, prevent picking a data folder that equals or contains the client folder during installation (with inline Step 3 validation), stop blocking updates when an existing installation placed `dataPath` at an ancestor of the client folder, and log the exact reason and paths on every path-scope rejection.
|
||||
- **Quick log ZIP export on About and runtime logging toggle.** Added a quick "Save log ZIP…" button on the About page (now also bundling the latest embedded browser `-browser.log`, still excluding saves), and added a "Record runtime logs" toggle under Settings → Diagnostics to stop writing launcher logs, local server traffic logs, and `wto_ws.log`.
|
||||
|
||||
### Client compatibility
|
||||
|
||||
Verified with client versions `2.61.0.37`, `2.61.0.43`, `2.61.0.55`, and `2.61.0.58` (bundled patch set `2026.12.02`), with pattern-based matching for later minor updates.
|
||||
@@ -1,97 +0,0 @@
|
||||
## 简体中文
|
||||
|
||||
`v0.1.3` 是 WTOffline的一次大型功能更新,正式引入**第一版模组系统(开放社区模组制作)**、初步接通**原子雷霆**模式,并包含多项对局机制、存档容量、贴花导入与更新链路修复。
|
||||
|
||||
### 该下载哪一个文件?
|
||||
|
||||
- **绝大多数玩家**:下载 **`wtoffline-launcher-0.1.3-win-x64.exe`** ,下载后安装即可。
|
||||
- **想要免安装 / 解压即用**:下载 **`wtoffline-launcher-0.1.3-win-x64-portable.zip`** ,解压到任意目录后运行其中的启动器即可。
|
||||
|
||||
### 重点新功能
|
||||
|
||||
- **第一版模组系统与开放模组制作(实验性)。**
|
||||
- 启动器新增「模组」管理页:支持为每个客户端独立开关模组、调整加载顺序、保存/切换模组方案以及自定义模组目录,并可直接一键打开完整模组开发文档。
|
||||
- 支持客户端数据包增量覆写(BLK / CSV / 附加包挂载,且核心隔离补丁受保护不可被误覆盖)、服务端 JS/TS 脚本钩子与独立模组数据存储,以及数值列表增量修改。
|
||||
- 内置并首次自动生成 3 套官方示例模组模板(含可直接使用的「官方地图选择器」、服务端脚本示例与载具参数微调示例),配套完整中英文 `mod-dev-docs` 开发手册,欢迎玩家与创作者制作并分享自己的模组。
|
||||
- **接通「原子雷霆」模式。**
|
||||
- 完整接入空战历史子模式「原子雷霆」的专用 HUD、阶段推进门槛、不限出击次数与机场独立冷却机制,并按 10 国与房间权重自动分配战术核弹载机(5 kt / 30 kt)。
|
||||
- 在启动器「数值 → 对局」新增「原子雷霆战略核轰炸机」开关(默认开启),可在阶段 3 追加战略核轰炸机(`B-52H` / `Tu-95M`)。
|
||||
|
||||
### 修复与改进
|
||||
|
||||
- **对局与战斗体验**:
|
||||
- 恢复陆战街机空中支援事件(呼叫战斗机 / 攻击机 / 轰炸机);
|
||||
- 修复本地主机下玩家乘员技能与专家 / 王牌资格在战局内未生效的问题;
|
||||
- 恢复空战街机模式下的空中重新装填弹药;
|
||||
- 修复部分载具出生时改装件效果反转,以及单弹链航空武器被未选中的隐身弹链覆盖导致无曳光弹的问题;
|
||||
- 恢复对战模式飞机有限燃油消耗与油量倒计时,并修复局内小队黄色标记;
|
||||
- 支持在机库切换并保存载具的可选分房权重(如部分直升机 / 挂载升档),开局按所选权重参与匹配;
|
||||
- 修复空战街机等多槽模式下 AI 飞机重生次数受限,以及坦克 AI 重生次数配置未对全部模式生效的问题(感谢 `duduyagame`);
|
||||
- 修复新手教程完成进度未保存的问题:通关后重启不再反复提示教程,并按原版规则发放首次通关的贴花、基础教程金鹰及各难度银狮奖励(感谢 `duduyagame`)。
|
||||
- **启动器、存档与更新链路**:
|
||||
- 修复新版在线客户端贴花与可下载涂装缓存导入失败的问题(兼容现行 `regional.vromfs.bin` + `.ddsx` 及旧版缓存格式);
|
||||
- 修复全车库改装件总数超过 65,535 个时的存档溢出问题;
|
||||
- 将启动器「存档 → 载具和研发」中的「全部研发」与「获得常规载具」合并为一步到位的「全部研发并购买」;
|
||||
- 优化默认更新线路并保留 GitHub 自动回退,全流程继续保持 Ed25519 签名校验;
|
||||
- 「关于」页改版为双栏布局,新增「项目主页」与「Discord」快捷入口,修复切换页面时维护进度丢失的问题。
|
||||
|
||||
### 社区交流与模组分享
|
||||
|
||||
欢迎加入 WTOffline 官方 Discord 服务器,一起交流玩法、反馈 Bug、分享你的调参或自制模组,并关注最新客户端适配进度:
|
||||
|
||||
- **Discord 社区**:https://discord.gg/P566xWNpEs
|
||||
- **项目主页**:https://wto-project.net
|
||||
|
||||
### 客户端兼容性
|
||||
|
||||
支持已核对版本 `2.61.0.37`、`2.61.0.43`、`2.61.0.55` 和 `2.61.0.58`,并支持按特征码自动尝试适配后续小版本更新。
|
||||
|
||||
---
|
||||
|
||||
## English
|
||||
|
||||
`v0.1.3` is a major feature release of WTOffline introducing the **first version of the experimental Mod System** (opening up community mod authoring), Add support for **Nuclear Escalation**, and a broad set of battle, save, decal import, and launcher fixes.
|
||||
|
||||
### Which file should I download?
|
||||
|
||||
- **Most players (Recommended)**: Download **`wtoffline-launcher-0.1.3-win-x64.exe`** — the standard Windows installer with built-in automatic update checks.
|
||||
- **No-install / Portable**: Download **`wtoffline-launcher-0.1.3-win-x64-portable.zip`** — extract anywhere and run the launcher directly.
|
||||
|
||||
### Highlights
|
||||
|
||||
- **Experimental Mod System v1 & Mod Authoring.**
|
||||
- New **Mods** page in the launcher with per-client enablement, load-order management, presets, custom mod repository folder, and a quick-open button for the mod developer handbook.
|
||||
- Supports additive client archive overlays (BLK / CSV / addon mounts while protecting essential isolation patches), server-side JS/TS lifecycle hooks with isolated mod storage, and tuning list operations.
|
||||
- Ships with 3 bundled example mod templates (including a ready-to-use **Official Map Selector**, a server script example, and a vehicle tweak example) plus full bilingual documentation in `mod-dev-docs/`.
|
||||
- **Nuclear Escalation mode.**
|
||||
- Full support for Air Realistic sub-mode **Nuclear Escalation**, including custom HUD, stage thresholds, unlimited respawns, per-airfield cooldowns, and nation-matched tactical nuclear carriers (5 kt / 30 kt) scaled to room BR.
|
||||
- Added a **Nuclear Escalation strategic bombers** toggle under **Tuning → Battle** (enabled by default) to unlock stage-3 strategic nuclear bombers (`B-52H` / `Tu-95M`).
|
||||
|
||||
### Fixes and improvements
|
||||
|
||||
- **Battles & gameplay**:
|
||||
- Restored Ground Arcade air support events (fighters, attackers, bombers).
|
||||
- Fixed player crew skills and Expert / Ace qualifications not applying on the local host.
|
||||
- Restored in-flight ammunition reload in Air Arcade.
|
||||
- Fixed inverted modification effects on spawn and single-belt aircraft tracers being overwritten by unselected stealth belts.
|
||||
- Restored limited fuel consumption / HUD fuel timer in versus modes and yellow squad target markers.
|
||||
- Persisted selectable battle ratings for units with BR-changing modifications and applied them during matchmaking.
|
||||
- Fixed AI aircraft respawn limits in Air Arcade and other multi-slot modes, and applied configured ground AI respawn counts across all modes (thanks to `duduyagame`).
|
||||
- Persisted stock training/tutorial completion progress so finished tutorials no longer re-prompt after restart, and granted one-time first-completion decals, basic tutorial Golden Eagles, and per-difficulty Silver Lions rewards (thanks to `duduyagame`).
|
||||
- **Launcher, saves & updates**:
|
||||
- Fixed online decal and downloadable skin cache import on modern 2.61 clients (supports both `regional.vromfs.bin` + `.ddsx` and legacy cache layouts).
|
||||
- Fixed save overflow when total owned modifications exceed 65,535 by splitting across native sibling blocks.
|
||||
- Merged "Research all" and "Grant regular vehicles" into a single **Research and buy all** action in the launcher.
|
||||
- Improved default release update routing with automatic GitHub fallback and continued Ed25519 signature verification.
|
||||
- Updated the About page to a two-column layout with **Project homepage** and **Discord** buttons, and preserved copy maintenance progress across tab switches.
|
||||
|
||||
### Community & Mod Sharing
|
||||
|
||||
Join the official WTOffline Discord server to chat, report issues, share tuning presets or custom mods, and follow client adaptation updates:
|
||||
|
||||
- **Discord**: https://discord.gg/P566xWNpEs
|
||||
- **Homepage**: https://wto-project.net
|
||||
|
||||
### Client compatibility
|
||||
|
||||
Verified with client versions `2.61.0.37`, `2.61.0.43`, `2.61.0.55`, and `2.61.0.58`, with signature-based matching for later minor updates.
|
||||
@@ -1,97 +0,0 @@
|
||||
# Build, sign, and publish a Windows installer of the WTOffline Launcher as a GitHub release
|
||||
# tagged v<version>. The launcher's update check reads v<version> releases and expects the three
|
||||
# signed files (installer, manifest, signature); a release missing any of them breaks the check
|
||||
# for already-installed launchers. The workflow also packages and signs the portable zip with its
|
||||
# own manifest and signature so portable installations can update in place.
|
||||
#
|
||||
# Start it either way:
|
||||
# - push a tag: git tag v0.1.0 && git push origin v0.1.0
|
||||
# - from the Actions page (Run workflow), giving the version; the tag is created on the chosen
|
||||
# branch's latest commit.
|
||||
# The release note comes from .github/release-notes/v<version>.md. The signing key comes from the
|
||||
# repository secret PATCH_SIGNING_KEY (the same Ed25519 key used for adaptation packs).
|
||||
name: Launcher release
|
||||
|
||||
on:
|
||||
push:
|
||||
tags: ['v*']
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
version:
|
||||
description: 'Launcher version, e.g. 0.1.0 (must match apps/launcher/package.json)'
|
||||
required: true
|
||||
type: string
|
||||
draft:
|
||||
description: 'Keep the release as a draft for editing before publication'
|
||||
type: boolean
|
||||
default: true
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
release:
|
||||
runs-on: windows-latest
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 24
|
||||
cache: npm
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: Download the Electron runtime
|
||||
run: node node_modules/electron/install.js
|
||||
|
||||
- name: Resolve and verify the version
|
||||
run: |
|
||||
if [ "${{ github.event_name }}" = 'workflow_dispatch' ]; then
|
||||
VERSION="${{ inputs.version }}"
|
||||
else
|
||||
VERSION="${GITHUB_REF_NAME#v}"
|
||||
fi
|
||||
PKG_VERSION=$(node -p "require('./apps/launcher/package.json').version")
|
||||
if [ "$VERSION" != "$PKG_VERSION" ]; then
|
||||
echo "Version $VERSION does not match apps/launcher/package.json ($PKG_VERSION)" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "VERSION=$VERSION" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Typecheck
|
||||
run: |
|
||||
npm run typecheck
|
||||
npm run typecheck --workspace "@wto/launcher"
|
||||
|
||||
- name: Build and package the Windows installer and portable archive
|
||||
run: npm --workspace "@wto/launcher" run package:win
|
||||
|
||||
- name: Sign the release
|
||||
env:
|
||||
PATCH_SIGNING_KEY: ${{ secrets.PATCH_SIGNING_KEY }}
|
||||
run: node scripts/sign-launcher-release.ts
|
||||
|
||||
- name: Create the release
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
flags=(--draft)
|
||||
if [ "${{ github.event_name }}" = 'workflow_dispatch' ] && [ "${{ inputs.draft }}" = 'false' ]; then
|
||||
flags=()
|
||||
fi
|
||||
gh release create "v$VERSION" \
|
||||
"build/windows-installer/wtoffline-launcher-$VERSION-win-x64.exe" \
|
||||
"build/windows-installer/wtoffline-launcher-$VERSION-win-x64.manifest.json" \
|
||||
"build/windows-installer/wtoffline-launcher-$VERSION-win-x64.manifest.json.sig" \
|
||||
"build/windows-installer/wtoffline-launcher-$VERSION-win-x64-portable.zip" \
|
||||
"build/windows-installer/wtoffline-launcher-$VERSION-win-x64-portable.manifest.json" \
|
||||
"build/windows-installer/wtoffline-launcher-$VERSION-win-x64-portable.manifest.json.sig" \
|
||||
"${flags[@]}" \
|
||||
--title "WTOffline Launcher $VERSION" \
|
||||
--notes-file ".github/release-notes/v$VERSION.md" \
|
||||
--target "$GITHUB_SHA"
|
||||
@@ -1,5 +1,5 @@
|
||||
# Release an adaptation pack (packages/patcher/src/patch-pack/): pack and sign patches/ and publish
|
||||
# it as a GitHub prerelease tagged patches-<version>, where the launcher looks for it.
|
||||
# it as a GitHub release tagged patches-<version>, where the launcher looks for it.
|
||||
#
|
||||
# Start it either way:
|
||||
# - push a tag: git tag patches-2026.11.29 && git push origin patches-2026.11.29
|
||||
@@ -18,10 +18,6 @@ on:
|
||||
description: 'Pack version, YYYY.MM.DD or YYYY.MM.DD.N'
|
||||
required: true
|
||||
type: string
|
||||
draft:
|
||||
description: 'Keep the signed prerelease as a draft for editing before publication'
|
||||
type: boolean
|
||||
default: false
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
@@ -54,25 +50,19 @@ jobs:
|
||||
node scripts/build-patch-pack.ts --out dist
|
||||
fi
|
||||
|
||||
- name: Create the prerelease
|
||||
- name: Publish the release
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
DRAFT: ${{ inputs.draft || false }}
|
||||
run: |
|
||||
manifest=$(ls dist/*.manifest.json)
|
||||
field() { node -e "const m=JSON.parse(require('fs').readFileSync(process.argv[1],'utf8'));const v=m[process.argv[2]];process.stdout.write(Array.isArray(v)?v.join(', '):String(v))" "$manifest" "$1"; }
|
||||
version=$(field version)
|
||||
printf 'Adaptation pack %s.\n\nChecked game versions: %s\nNeeds offline version %s or newer.\n' \
|
||||
"$version" "$(field game_versions)" "$(field min_app_version)" > dist/notes.md
|
||||
release_flags=(--prerelease)
|
||||
if [ "$DRAFT" = 'true' ]; then
|
||||
release_flags+=(--draft)
|
||||
fi
|
||||
gh release create "patches-$version" \
|
||||
"dist/wtoffline-patches-$version.zip" \
|
||||
"dist/wtoffline-patches-$version.zip.sig" \
|
||||
"dist/wtoffline-patches-$version.manifest.json" \
|
||||
"${release_flags[@]}" \
|
||||
--title "Adaptation pack $version" \
|
||||
--notes-file dist/notes.md \
|
||||
--target "$GITHUB_SHA"
|
||||
+1
-5
@@ -1,8 +1,5 @@
|
||||
# Never commit game files (copyright, size). The build reads them from a game folder.
|
||||
*.vromfs.bin
|
||||
# Allow additive patch directories named after target packs inside mod templates (never binary archives).
|
||||
!mod-dev-docs/templates/**/client/packs/*.vromfs.bin/
|
||||
!mod-dev-docs/templates/**/client/packs/ui/*.vromfs.bin/
|
||||
*.vromfs.bin.orig
|
||||
aces.exe
|
||||
aces*.exe
|
||||
@@ -28,11 +25,10 @@ __pycache__/
|
||||
*.pyc
|
||||
.venv/
|
||||
|
||||
# Saves, logs, local runtime data, local secrets
|
||||
# Saves, logs, local runtime data
|
||||
/data/
|
||||
/saves/
|
||||
*.log
|
||||
.env*.local
|
||||
|
||||
# Editors / OS
|
||||
.vscode/
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
<a id="zh-cn"></a>
|
||||
|
||||
简体中文 · [English](#english) · [Discord](https://discord.gg/P566xWNpEs)
|
||||
简体中文 · [English](#english)
|
||||
|
||||
------
|
||||
|
||||
@@ -21,10 +21,6 @@ WTOffline 是《战争雷霆》(War Thunder)Windows 客户端的单机离线
|
||||
|
||||
`patches/versions/` 中每份核对记录对应一个检查通过并在游戏中验证过的客户端版本。补丁和 native 模块按特征码、字符串引用和从代码中读出的值定位,不依赖固定地址,小版本更新后通常仍能命中,但没有核对记录的版本不保证功能正确。
|
||||
|
||||
## 开发讨论、交流与求助
|
||||
|
||||
欢迎加入 [WTOffline Discord 服务器](https://discord.gg/P566xWNpEs),用于日常交流、使用求助、问题反馈、调参分享以及开发和版本适配讨论。
|
||||
|
||||
## 功能
|
||||
|
||||
| 领域 | 已实现 |
|
||||
@@ -77,8 +73,8 @@ AI 的驾驶、寻路和战术使用游戏自带的 AI,目前仍有明显不
|
||||
|
||||
- **服务地址**:`config/network.blk`(`char.vromfs.bin`)和 `config/settings.blk`(`aces.vromfs.bin`)中所有 Gaijin 地址改写为 `127.0.0.1:<端口>`。端口在构建时写入,因此服务器必须使用相同的端口。
|
||||
- **配置表**:开启离线需要的功能开关,放出隐藏载具,写入贴花索引,为本地商店的礼包登记 GUID。
|
||||
- **exe 补丁**:`patches/exe/` 下共 13 项,见下表。
|
||||
- **界面脚本补丁**:`patches/gui/` 下共 40 项,用于本地账号注册、本地对局的开局与结算、本地商店的购买回执,以及库存签名公钥等。
|
||||
- **exe 补丁**:`patches/exe/` 下共 12 项,见下表。
|
||||
- **界面脚本补丁**:`patches/gui/` 下共 35 项,用于本地对局的开局与结算、本地商店的购买回执,以及库存签名公钥等。
|
||||
- **网络钩子库**:exe 的导入表把 `WS2_32.dll` 改为同长度的 `wto_ws.dll`。该库转发系统 `ws2_32.dll` 的全部导出,并用 MinHook 挂钩域名解析(`getaddrinfo` 等)、连接(`connect`、`ConnectEx` 等)和 UDP 发送,把所有外部连接重定向到本地服务器端口。端口从 exe 旁的 `wto_ws.cfg` 读取。
|
||||
|
||||
| exe 补丁 | 作用 |
|
||||
@@ -88,7 +84,6 @@ AI 的驾驶、寻路和战术使用游戏自带的 AI,目前仍有明显不
|
||||
| `isolation/registry-key` | 注册表位置改为 `Software\WTOffline` |
|
||||
| `isolation/never-load-battleye` | 不加载 BattlEye |
|
||||
| `isolation/never-upload-crash-reports` | 不上传崩溃报告 |
|
||||
| `isolation/never-launch-official-launcher` | 不拉起官方启动器 `launcher.exe` |
|
||||
| `online/network-hook-library` | 加载 `wto_ws.dll` 代替 `WS2_32.dll` |
|
||||
| `online/accept-local-tls-certificate` | 让 libcurl 接受本地服务器的自签名证书 |
|
||||
| `online/matching-server-public-key` | 匹配服务器公钥替换为本地服务器的公钥,用于解出会话密钥 |
|
||||
@@ -126,7 +121,7 @@ AI 的驾驶、寻路和战术使用游戏自带的 AI,目前仍有明显不
|
||||
| 路径 | 内容 |
|
||||
|---|---|
|
||||
| `accounts.json` | 本地账号 |
|
||||
| `saves/` | 每个本地账号的存档 |
|
||||
| `saves/` | 每个账号的存档。存档格式变更时,旧存档在读取时自动升级 |
|
||||
| `clans.json` | 本地联队 |
|
||||
| `cache/` | 从游戏文件提取的数据集缓存 |
|
||||
| `logs/` | 流量日志,服务器每次启动新建一个子目录 |
|
||||
@@ -155,8 +150,6 @@ AI 的驾驶、寻路和战术使用游戏自带的 AI,目前仍有明显不
|
||||
|
||||
## 开发
|
||||
|
||||
开发规范、补丁指南和 PR 自查清单见 [Dev Docs](dev-docs/README.md#zh-cn),开发与版本适配讨论欢迎前往 [Discord](https://discord.gg/P566xWNpEs)。
|
||||
|
||||
### 环境要求
|
||||
|
||||
- Windows x64
|
||||
@@ -185,16 +178,13 @@ node scripts/build-game-copy.ts --game "<原版目录>" --out "<副本目录>" -
|
||||
node apps/server/src/cli.ts --game "<副本目录>" --data "<数据目录>" --port 27015
|
||||
```
|
||||
|
||||
第一次登录前,在游戏登录界面点击「注册」,或在启动器的「存档」页创建本地账号。已有本地账号可以直接登录。
|
||||
|
||||
`build-game-copy.ts` 的可选参数:
|
||||
|
||||
| 参数 | 说明 |
|
||||
|---|---|
|
||||
| `--decal-cache <目录>` | 线上版安装的 `cache/content`,复制到副本以显示真实贴花;不指定时使用占位贴图 |
|
||||
| `--skip-unavailable` | 非必需补丁不可用时继续构建 |
|
||||
| `--patches <目录>` | 指定补丁集根目录,包含 `exe/`、`gui/`、`native/` 和 `versions/` |
|
||||
| `--native <目录>` | 指定 `wto_ws.dll` 所在目录 |
|
||||
| `--patches`、`--gui-patches`、`--native` | 替换默认的补丁目录和 `wto_ws.dll` 所在目录 |
|
||||
| `--verbose` | 输出每个补丁的定位结果 |
|
||||
|
||||
### 辅助命令
|
||||
@@ -223,8 +213,6 @@ wtotools check-patches --exe "<原版目录>\win64\aces.exe" # 定位并核
|
||||
wtotools check-gui --gui "<原版目录>\gui.vromfs.bin" --sq "<sq.exe 路径>" # 应用界面补丁并用 Quirrel 编译器编译
|
||||
```
|
||||
|
||||
GUI 检查需要 Quirrel 编译器,准备方式见 [Dev Docs](dev-docs/contributing.md#quirrel)。
|
||||
|
||||
检查全部补丁和 native 模块并写入该客户端版本的核对记录:`node scripts/record-game-version.ts --game "<原版目录>"`。
|
||||
|
||||
## 目录结构
|
||||
@@ -269,7 +257,7 @@ tools/ wtotools,补丁检查工具(Python)
|
||||
|
||||
# WTOffline (English)
|
||||
|
||||
[简体中文](#zh-cn) · English · [Discord](https://discord.gg/P566xWNpEs)
|
||||
[简体中文](#zh-cn) · English
|
||||
|
||||
WTOffline is a single-player offline project for the Windows client of War Thunder. A local server emulates Gaijin's online services, and the client sends all of its requests to the local machine. The client logs in, loads its profile, enters the hangar, and submits player actions as usual. Game rules, saves, and battle settlement run on the local server, and all allies and opponents are AI.
|
||||
|
||||
@@ -286,10 +274,6 @@ The repository contains source code and patch definitions only. It does not cont
|
||||
|
||||
Each check record in `patches/versions/` stands for a client version that passed the checks and was verified in game. Patches and native modules are located by signatures, string references and values read from the code rather than fixed addresses, so they usually still match after a minor update, but correct behavior is not guaranteed for a version without a check record.
|
||||
|
||||
## Community
|
||||
|
||||
Join the [WTOffline Discord server](https://discord.gg/P566xWNpEs) for general discussion, troubleshooting, bug reports, and development or patch adaptation discussions.
|
||||
|
||||
## Features
|
||||
|
||||
| Area | Implemented |
|
||||
@@ -342,8 +326,8 @@ Static data such as vehicles, tech trees, prices, and reward factors is extracte
|
||||
|
||||
- **Service addresses**: every Gaijin address in `config/network.blk` (`char.vromfs.bin`) and `config/settings.blk` (`aces.vromfs.bin`) is rewritten to `127.0.0.1:<port>`. The port is written at build time, so the server must use the same port.
|
||||
- **Config tables**: enables feature flags the offline copy needs, reveals hidden vehicles, adds a decal index, and registers GUIDs for local store packs.
|
||||
- **exe patches**: 13 patches under `patches/exe/`, listed below.
|
||||
- **UI script patches**: 40 patches under `patches/gui/`, covering local account registration, battle start and settlement, store purchase receipts, and the inventory signing key.
|
||||
- **exe patches**: 12 patches under `patches/exe/`, listed below.
|
||||
- **UI script patches**: 35 patches under `patches/gui/`, covering local battle start and settlement, local store purchase receipts, and the inventory signing key, among others.
|
||||
- **Network hook library**: the import table entry `WS2_32.dll` is renamed to `wto_ws.dll`, which has the same length. The library forwards every export of the system `ws2_32.dll` and uses MinHook to hook name resolution (`getaddrinfo` and others), connections (`connect`, `ConnectEx`, and others), and UDP sends, redirecting every external connection to the local server port. The port is read from `wto_ws.cfg` next to the exe.
|
||||
|
||||
| exe patch | Purpose |
|
||||
@@ -353,7 +337,6 @@ Static data such as vehicles, tech trees, prices, and reward factors is extracte
|
||||
| `isolation/registry-key` | Moves registry settings to `Software\WTOffline` |
|
||||
| `isolation/never-load-battleye` | Never loads BattlEye |
|
||||
| `isolation/never-upload-crash-reports` | Never uploads crash reports |
|
||||
| `isolation/never-launch-official-launcher` | Never launches the official `launcher.exe` |
|
||||
| `online/network-hook-library` | Loads `wto_ws.dll` instead of `WS2_32.dll` |
|
||||
| `online/accept-local-tls-certificate` | Makes libcurl accept the local server's self-signed certificate |
|
||||
| `online/matching-server-public-key` | Replaces the matching server public key with the local server's, so it can decrypt the session key |
|
||||
@@ -391,7 +374,7 @@ The server and the build script share one data folder (`--data`):
|
||||
| Path | Contents |
|
||||
|---|---|
|
||||
| `accounts.json` | Local accounts |
|
||||
| `saves/` | One save per local account |
|
||||
| `saves/` | One save per account. When the save format changes, older saves are upgraded on load |
|
||||
| `clans.json` | Local squadrons |
|
||||
| `cache/` | Dataset cache extracted from the game files |
|
||||
| `logs/` | Traffic logs, one subfolder per server run |
|
||||
@@ -420,8 +403,6 @@ To override defaults, create `tuning/<same file name>.jsonc` in the data folder
|
||||
|
||||
## Development
|
||||
|
||||
See [Dev Docs](dev-docs/README.md#english) for development rules, patch templates, and the PR checklist, or join [Discord](https://discord.gg/P566xWNpEs) for development and patch adaptation discussions.
|
||||
|
||||
### Requirements
|
||||
|
||||
- Windows x64
|
||||
@@ -450,16 +431,13 @@ node scripts/build-game-copy.ts --game "<stock folder>" --out "<copy folder>" --
|
||||
node apps/server/src/cli.ts --game "<copy folder>" --data "<data folder>" --port 27015
|
||||
```
|
||||
|
||||
Before the first sign-in, select **Register** on the game login screen or create a local account on the launcher's **Saves** page. Existing local accounts can sign in directly.
|
||||
|
||||
Optional arguments for `build-game-copy.ts`:
|
||||
|
||||
| Argument | Description |
|
||||
|---|---|
|
||||
| `--decal-cache <folder>` | The online installation's `cache/content`, copied into the copy to show real decals. Without it, placeholder images are used |
|
||||
| `--skip-unavailable` | Continue when non-essential patches are unavailable |
|
||||
| `--patches <folder>` | Override the patch set root containing `exe/`, `gui/`, `native/`, and `versions/` |
|
||||
| `--native <folder>` | Override the folder containing `wto_ws.dll` |
|
||||
| `--patches`, `--gui-patches`, `--native` | Override the default patch folders and the folder containing `wto_ws.dll` |
|
||||
| `--verbose` | Print the locate result of every patch |
|
||||
|
||||
### Helper commands
|
||||
@@ -488,8 +466,6 @@ wtotools check-patches --exe "<stock folder>\win64\aces.exe" # locate and ve
|
||||
wtotools check-gui --gui "<stock folder>\gui.vromfs.bin" --sq "<path to sq.exe>" # apply UI patches and compile them with the Quirrel compiler
|
||||
```
|
||||
|
||||
The GUI check requires the Quirrel compiler. See [the build steps](dev-docs/contributing.md#quirrel).
|
||||
|
||||
To check every patch and native module and write the check record of that client version: `node scripts/record-game-version.ts --game "<stock folder>"`.
|
||||
|
||||
## Repository layout
|
||||
|
||||
@@ -15,7 +15,6 @@ export default defineConfig({
|
||||
input: {
|
||||
index: resolve('src/main/index.ts'),
|
||||
'build-worker': resolve('src/main/workers/build-worker.ts'),
|
||||
'server-worker': resolve('src/main/workers/server-worker.ts'),
|
||||
'save-worker': resolve('src/main/workers/save-worker.ts'),
|
||||
'patch-check-worker': resolve('src/main/workers/patch-check-worker.ts'),
|
||||
},
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@wto/launcher",
|
||||
"productName": "WTOffline Launcher",
|
||||
"version": "0.1.3",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"description": "Installer and launcher of the War Thunder offline project.",
|
||||
"type": "module",
|
||||
@@ -9,12 +9,10 @@
|
||||
"scripts": {
|
||||
"dev": "electron-vite dev",
|
||||
"build": "electron-vite build",
|
||||
"package:win": "npm run build && node ../../scripts/build-windows-installer.ts",
|
||||
"typecheck": "tsc --noEmit -p tsconfig.node.json && tsc --noEmit -p tsconfig.web.json"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fontsource/roboto-condensed": "^5.3.0",
|
||||
"@wto/mods": "*",
|
||||
"@wto/patcher": "*",
|
||||
"@wto/server": "*",
|
||||
"fflate": "^0.8.2",
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 107 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 7.6 KiB |
@@ -1,37 +1,21 @@
|
||||
import { app, BrowserWindow, dialog, shell } from 'electron';
|
||||
import { isInSteamLibrary, patchFeatures, recordedGameVersions } from '@wto/patcher';
|
||||
import { patchFeatures, recordedGameVersions } from '@wto/patcher';
|
||||
import { AppError } from '@shared/errors.ts';
|
||||
import { appUpdatesSupported, checkAppUpdate, downloadAppUpdate, installAppUpdate } from '../services/app-update/app-update.ts';
|
||||
import { listBackgroundPictures } from '../services/background-art/art-catalog.ts';
|
||||
import { getCopyTuning, updateCopyTuning } from '../services/config/copy-tuning.ts';
|
||||
import { getSettings, updateSettings } from '../services/config/settings-store.ts';
|
||||
import { cancelMaintenance, maintainCopy, maintenanceInfo, maintenanceInProgress, maintenanceState } from '../services/copies/copy-maintenance.ts';
|
||||
import { relocateCopy } from '../services/copies/relocate-copy.ts';
|
||||
import { cancelMaintenance, maintainCopy, maintenanceInfo, maintenanceInProgress } from '../services/copies/copy-maintenance.ts';
|
||||
import { exportDiagnostics, openLogsFolder } from '../services/diagnostics/diagnostics.ts';
|
||||
import { measureFolder } from '../services/game-folder/folder-size.ts';
|
||||
import { inspectGameFolder, requireFolder } from '../services/game-folder/inspect-game-folder.ts';
|
||||
import { inspectPickedTargetFolder } from '../services/game-folder/inspect-target-folder.ts';
|
||||
import { changeDecalSource, decalImportInProgress } from '../services/install/decals.ts';
|
||||
import { cancelInstall, checkGameFolder, dataFolderProblem, installGame, installationInProgress } from '../services/install/install-game.ts';
|
||||
import { canonicalCopyPath, copyFolderMissing, createCopyDraft, hydrateCopiesStatus, listCopies, readInstallRecord, renameCopy, setCurrentCopy } from '../services/install/install-record.ts';
|
||||
import { inspectTargetFolder } from '../services/game-folder/inspect-target-folder.ts';
|
||||
import { cancelInstall, checkGameFolder, installGame } from '../services/install/install-game.ts';
|
||||
import { createCopyDraft, listCopies, readInstallRecord, renameCopy, setCurrentCopy } from '../services/install/install-record.ts';
|
||||
import { readInstalledLab } from '../services/launch/lab-handoff.ts';
|
||||
import { getLaunchState, launchInProgress, openServerStatus, startLaunch, stopLaunch } from '../services/launch/launch-controller.ts';
|
||||
import { getLaunchState, openServerStatus, startLaunch, stopLaunch } from '../services/launch/launch-controller.ts';
|
||||
import { activePatchSet, applyPackUpdate, checkPackUpdate, revertToBundledPatchSet } from '../services/patch-pack/pack-update.ts';
|
||||
import {
|
||||
applyModPreset,
|
||||
autoSortMods,
|
||||
deleteModPreset,
|
||||
exportModPreset,
|
||||
getModsState,
|
||||
importModPreset,
|
||||
openModsFolder,
|
||||
saveModPreset,
|
||||
setModEnabled,
|
||||
setModsFolder,
|
||||
setModsOrder,
|
||||
} from '../services/mods/mods-service.ts';
|
||||
import { resourcePaths } from '../services/resources/resource-paths.ts';
|
||||
import { changeSaveAccount, changeSaveResearch, copyOnlineData, createSave, discoverOnlineData, exportSave, getSaveAvatarChoices, getSaveAvatarPreview, getSaveDetails, getSaveList, getSaveResearch, importSelectedBackups, listSaveBackups, pickOfficialBackups, pickSaveArchive, previewSelectedBackups, removeSave, restoreSaveBackup, saveWriteInProgress, selectSave, setSaveCurrencies, takeSaveBackup, transferSave } from '../services/saves/manage-saves.ts';
|
||||
import { changeSaveResearch, createSave, exportSave, getSaveDetails, getSaveList, getSaveResearch, importSelectedBackups, listSaveBackups, pickOfficialBackups, pickSaveArchive, previewSelectedBackups, removeSave, restoreSaveBackup, saveWriteInProgress, selectSave, setSaveCurrencies, takeSaveBackup, transferSave } from '../services/saves/manage-saves.ts';
|
||||
import { broadcast, handle } from './register.ts';
|
||||
|
||||
/** Registers the handler of every contract channel. One line per channel; the work is in services/. */
|
||||
@@ -42,7 +26,6 @@ export function registerIpcHandlers(): void {
|
||||
version: app.getVersion(),
|
||||
electron: process.versions.electron,
|
||||
development: !app.isPackaged,
|
||||
appUpdatesSupported: appUpdatesSupported(),
|
||||
systemLocale: app.getLocale(),
|
||||
userDataPath: app.getPath('userData'),
|
||||
supportedGameVersions: recordedGameVersions(resources.patches),
|
||||
@@ -77,21 +60,7 @@ export function registerIpcHandlers(): void {
|
||||
|
||||
handle('install:prepareCopy', () => createCopyDraft());
|
||||
handle('install:inspectGameFolder', ({ path }) => inspectGameFolder(path));
|
||||
handle('install:inspectTargetFolder', ({ path, stockPath, version }) =>
|
||||
inspectPickedTargetFolder(path, stockPath, version ?? null));
|
||||
handle('install:inspectDataFolder', async ({ path, copyPath, sourcePath, stockSourcePath }) => {
|
||||
const [resolved, resolvedCopy, resolvedSource, resolvedStock] = await Promise.all([
|
||||
canonicalCopyPath(path),
|
||||
copyPath ? canonicalCopyPath(copyPath) : Promise.resolve(null),
|
||||
sourcePath ? canonicalCopyPath(sourcePath) : Promise.resolve(null),
|
||||
stockSourcePath ? canonicalCopyPath(stockSourcePath) : Promise.resolve(null),
|
||||
]);
|
||||
return {
|
||||
path: resolved,
|
||||
inSteam: isInSteamLibrary(path) || isInSteamLibrary(resolved),
|
||||
problem: dataFolderProblem(resolved, resolvedCopy, resolvedSource, resolvedStock),
|
||||
};
|
||||
});
|
||||
handle('install:inspectTargetFolder', ({ path, stockPath }) => inspectTargetFolder(path, stockPath));
|
||||
handle('install:measureFolder', async ({ path }) => {
|
||||
await requireFolder(path);
|
||||
try {
|
||||
@@ -102,56 +71,36 @@ export function registerIpcHandlers(): void {
|
||||
}
|
||||
});
|
||||
|
||||
handle('install:checkPatches', ({ gamePath, dataPath, stockSourcePath }) =>
|
||||
checkGameFolder(gamePath, dataPath, stockSourcePath));
|
||||
handle('install:checkPatches', ({ gamePath, dataPath }) => checkGameFolder(gamePath, dataPath));
|
||||
handle('install:start', async (request) => {
|
||||
if (maintenanceInProgress()) throw new AppError('maintenance_busy');
|
||||
const record = await installGame(request, (progress) => broadcast('event:install-progress', progress));
|
||||
broadcast('event:copies-changed', await hydrateCopiesStatus(await listCopies()));
|
||||
broadcast('event:copies-changed', await listCopies());
|
||||
return record;
|
||||
});
|
||||
handle('install:cancel', () => ({ cancelled: cancelInstall() }));
|
||||
handle('install:getRecord', async () => {
|
||||
const record = await readInstallRecord();
|
||||
if (!record) return { record: null };
|
||||
return { record: (await copyFolderMissing(record.copyPath)) ? { ...record, folderMissing: true } : record };
|
||||
});
|
||||
handle('install:getRecord', async () => ({ record: await readInstallRecord() }));
|
||||
handle('install:listFeatures', () => {
|
||||
const resources = resourcePaths();
|
||||
return patchFeatures(resources.patches).map((feature) => ({ ...feature, patchIds: [...feature.patchIds] }));
|
||||
});
|
||||
|
||||
handle('copies:list', async () => hydrateCopiesStatus(await listCopies()));
|
||||
handle('copies:list', () => listCopies());
|
||||
handle('copies:setCurrent', async ({ id }) => {
|
||||
const registry = await hydrateCopiesStatus(await setCurrentCopy(id));
|
||||
const registry = await setCurrentCopy(id);
|
||||
broadcast('event:copies-changed', registry);
|
||||
return registry;
|
||||
});
|
||||
handle('copies:rename', async ({ id, name }) => {
|
||||
const registry = await hydrateCopiesStatus(await renameCopy(id, name));
|
||||
broadcast('event:copies-changed', registry);
|
||||
return registry;
|
||||
});
|
||||
handle('copies:relocate', async ({ id, path }) => {
|
||||
if (launchInProgress() || maintenanceInProgress() || installationInProgress() || saveWriteInProgress() || decalImportInProgress()) {
|
||||
throw new AppError('maintenance_busy');
|
||||
}
|
||||
const registry = await relocateCopy(id, path);
|
||||
const registry = await renameCopy(id, name);
|
||||
broadcast('event:copies-changed', registry);
|
||||
return registry;
|
||||
});
|
||||
|
||||
handle('copies:setDecalSource', async ({ id, path }) => {
|
||||
if (launchInProgress() || maintenanceInProgress() || installationInProgress()) throw new AppError('maintenance_busy');
|
||||
const updated = await hydrateCopiesStatus(await changeDecalSource(id, path));
|
||||
broadcast('event:copies-changed', updated);
|
||||
return updated;
|
||||
});
|
||||
handle('copies:maintenanceInfo', ({ id }) => maintenanceInfo(id));
|
||||
handle('copies:maintenanceState', () => maintenanceState());
|
||||
handle('copies:maintain', async (request) => {
|
||||
if (saveWriteInProgress() || decalImportInProgress()) throw new AppError('maintenance_busy');
|
||||
const updated = await hydrateCopiesStatus(await maintainCopy(request, (progress) => broadcast('event:copy-maintenance', progress)));
|
||||
if (saveWriteInProgress()) throw new AppError('maintenance_busy');
|
||||
const updated = await maintainCopy(request, (progress) => broadcast('event:copy-maintenance', progress));
|
||||
broadcast('event:copies-changed', updated);
|
||||
return updated;
|
||||
});
|
||||
@@ -161,9 +110,6 @@ export function registerIpcHandlers(): void {
|
||||
handle('saves:details', ({ copyId, userId }) => getSaveDetails(copyId, userId));
|
||||
handle('saves:setCurrent', ({ copyId, userId }) => selectSave(copyId, userId));
|
||||
handle('saves:create', (request) => createSave(request));
|
||||
handle('saves:avatars', ({ copyId }) => getSaveAvatarChoices(copyId));
|
||||
handle('saves:avatarPreview', ({ copyId, avatar }) => getSaveAvatarPreview(copyId, avatar));
|
||||
handle('saves:editAccount', ({ copyId, userId, edits }) => changeSaveAccount(copyId, userId, edits));
|
||||
handle('saves:editCurrencies', ({ copyId, userId, values }) => setSaveCurrencies(copyId, userId, values));
|
||||
|
||||
handle('saves:pickArchive', (_input, sender) => pickSaveArchive(BrowserWindow.fromWebContents(sender)));
|
||||
@@ -174,11 +120,9 @@ export function registerIpcHandlers(): void {
|
||||
handle('saves:takeBackup', ({ copyId, userId }) => takeSaveBackup(copyId, userId));
|
||||
handle('saves:restoreBackup', ({ copyId, userId, name }) => restoreSaveBackup(copyId, userId, name));
|
||||
|
||||
handle('saves:discoverOnlineData', () => discoverOnlineData());
|
||||
handle('saves:copyOnlineData', ({ copyId, userId, accountId }) => copyOnlineData(copyId, userId, accountId));
|
||||
handle('saves:pickOfficialBackups', (_input, sender) => pickOfficialBackups(BrowserWindow.fromWebContents(sender)));
|
||||
handle('saves:previewOfficial', ({ copyId, userId, paths }) =>
|
||||
previewSelectedBackups(copyId, userId, paths));
|
||||
handle('saves:previewOfficial', ({ copyId, userId, paths, includeUsedVehicles }) =>
|
||||
previewSelectedBackups(copyId, userId, paths, includeUsedVehicles));
|
||||
handle('saves:importOfficial', ({ copyId, userId, paths, options }) =>
|
||||
importSelectedBackups(copyId, userId, paths, options));
|
||||
|
||||
@@ -188,52 +132,10 @@ export function registerIpcHandlers(): void {
|
||||
handle('tuning:get', ({ copyId }) => getCopyTuning(copyId));
|
||||
handle('tuning:update', ({ copyId, patch }) => updateCopyTuning(copyId, patch));
|
||||
|
||||
const requireModsWritable = (): void => {
|
||||
if (launchInProgress() || maintenanceInProgress()) throw new AppError('mods_read_only');
|
||||
};
|
||||
handle('mods:getState', ({ copyId }) => getModsState(copyId));
|
||||
handle('mods:setEnabled', ({ copyId, modId, enabled }) => {
|
||||
requireModsWritable();
|
||||
return setModEnabled(copyId, modId, enabled);
|
||||
});
|
||||
handle('mods:setOrder', ({ copyId, order }) => {
|
||||
requireModsWritable();
|
||||
return setModsOrder(copyId, order);
|
||||
});
|
||||
handle('mods:autoSort', ({ copyId }) => {
|
||||
requireModsWritable();
|
||||
return autoSortMods(copyId);
|
||||
});
|
||||
handle('mods:savePreset', ({ copyId, name, overwriteId }) => {
|
||||
requireModsWritable();
|
||||
return saveModPreset(copyId, name, overwriteId);
|
||||
});
|
||||
handle('mods:applyPreset', ({ copyId, presetId }) => {
|
||||
requireModsWritable();
|
||||
return applyModPreset(copyId, presetId);
|
||||
});
|
||||
handle('mods:deletePreset', ({ copyId, presetId }) => {
|
||||
requireModsWritable();
|
||||
return deleteModPreset(copyId, presetId);
|
||||
});
|
||||
handle('mods:exportPreset', ({ copyId, presetId }, sender) =>
|
||||
exportModPreset(copyId, presetId, BrowserWindow.fromWebContents(sender)));
|
||||
handle('mods:importPreset', ({ copyId }, sender) => {
|
||||
requireModsWritable();
|
||||
return importModPreset(copyId, BrowserWindow.fromWebContents(sender));
|
||||
});
|
||||
handle('mods:openFolder', () => openModsFolder());
|
||||
handle('mods:setFolder', async ({ copyId, path }) => {
|
||||
requireModsWritable();
|
||||
const state = await setModsFolder(copyId, path);
|
||||
broadcast('event:settings-changed', await getSettings());
|
||||
return state;
|
||||
});
|
||||
|
||||
handle('launch:getState', () => getLaunchState());
|
||||
handle('launch:getLabInfo', () => readInstalledLab().catch(() => null));
|
||||
handle('launch:start', () => {
|
||||
if (maintenanceInProgress() || saveWriteInProgress() || decalImportInProgress()) throw new AppError('maintenance_busy');
|
||||
if (maintenanceInProgress() || saveWriteInProgress()) throw new AppError('maintenance_busy');
|
||||
return startLaunch((state) => broadcast('event:launch-state', state));
|
||||
});
|
||||
handle('launch:stop', async () => { await stopLaunch(); });
|
||||
@@ -241,10 +143,10 @@ export function registerIpcHandlers(): void {
|
||||
|
||||
handle('patches:active', () => activePatchSet());
|
||||
handle('patches:check', () => checkPackUpdate());
|
||||
handle('patches:apply', async ({ version }) => {
|
||||
handle('patches:apply', async () => {
|
||||
// A build reads the patch set while it runs; switch only between builds.
|
||||
if (maintenanceInProgress()) throw new AppError('maintenance_busy');
|
||||
const result = await applyPackUpdate(version);
|
||||
const result = await applyPackUpdate();
|
||||
if (result.ok) broadcast('event:patch-set-changed', result.active);
|
||||
return result;
|
||||
});
|
||||
@@ -255,11 +157,6 @@ export function registerIpcHandlers(): void {
|
||||
return active;
|
||||
});
|
||||
|
||||
handle('updates:check', () => checkAppUpdate());
|
||||
handle('updates:download', ({ version }) => downloadAppUpdate(version, (progress) => broadcast('event:app-update-progress', progress)));
|
||||
handle('updates:install', ({ version }) => installAppUpdate(version, () =>
|
||||
launchInProgress() || installationInProgress() || maintenanceInProgress() || saveWriteInProgress() || decalImportInProgress()));
|
||||
|
||||
handle('settings:get', () => getSettings());
|
||||
handle('settings:update', async (patch) => {
|
||||
const settings = await updateSettings(patch);
|
||||
|
||||
@@ -1,231 +0,0 @@
|
||||
import { spawn } from 'node:child_process';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { once } from 'node:events';
|
||||
import { createWriteStream } from 'node:fs';
|
||||
import { mkdir, rename, unlink } from 'node:fs/promises';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { Transform } from 'node:stream';
|
||||
import { pipeline } from 'node:stream/promises';
|
||||
import { app } from 'electron';
|
||||
import { compareAppVersions, packSigningPublicKey, PatchPackError, patchPackTuning, verifyEd25519 } from '@wto/patcher';
|
||||
import { AppError } from '@shared/errors.ts';
|
||||
import {
|
||||
LauncherReleaseManifest,
|
||||
PortableReleaseManifest,
|
||||
type AppUpdateCheck, type AppUpdateProgress,
|
||||
} from '@shared/schemas/app-update.ts';
|
||||
import { gameProcessRunning } from '../launch/game-process.ts';
|
||||
import {
|
||||
newestProjectRelease, projectReleaseVersion, ReleasePageLimitError, sameReleaseSource, withReleaseSources, type LauncherRelease,
|
||||
} from '../patch-pack/release-feed.ts';
|
||||
import {
|
||||
FeedUnreachableError, readReleaseAsset, releaseAssetChunks, RELEASE_MANIFEST_MAX_BYTES, RELEASE_SIGNATURE_MAX_BYTES, requestReleaseAsset,
|
||||
} from '../patch-pack/release-assets.ts';
|
||||
import { installerDigest, launcherSignaturePayload, portableSignaturePayload } from './installer-integrity.ts';
|
||||
import { isPortableLauncher, launchPortableUpdater, preparePortableInstall } from './portable-update.ts';
|
||||
|
||||
type UpdateMode = 'installer' | 'portable';
|
||||
|
||||
interface OfferedUpdate {
|
||||
readonly mode: UpdateMode;
|
||||
readonly release: LauncherRelease;
|
||||
readonly manifest: LauncherReleaseManifest | PortableReleaseManifest;
|
||||
}
|
||||
|
||||
class ManifestSignatureError extends Error {}
|
||||
let offered: OfferedUpdate | null = null;
|
||||
let updating = false;
|
||||
|
||||
export function appUpdatesSupported(): boolean {
|
||||
return app.isPackaged && process.platform === 'win32' && process.arch === 'x64';
|
||||
}
|
||||
|
||||
async function exclusively<T>(action: () => Promise<T>): Promise<T> {
|
||||
if (!appUpdatesSupported()) throw new AppError('app_update_unavailable');
|
||||
if (updating) throw new AppError('app_update_busy');
|
||||
updating = true;
|
||||
try {
|
||||
return await action();
|
||||
} finally {
|
||||
updating = false;
|
||||
}
|
||||
}
|
||||
|
||||
function updatesRoot(): string {
|
||||
return join(app.getPath('userData'), 'launcher-updates');
|
||||
}
|
||||
|
||||
function stagedArtifact(mode: UpdateMode): string {
|
||||
return join(updatesRoot(), mode === 'portable' ? 'portable.zip' : 'installer.exe');
|
||||
}
|
||||
|
||||
async function matchesArtifact(path: string, manifest: LauncherReleaseManifest | PortableReleaseManifest): Promise<boolean> {
|
||||
try {
|
||||
const digest = await installerDigest(path, manifest.size);
|
||||
return digest.size === manifest.size && digest.sha256 === manifest.sha256;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function offerResult(offer: OfferedUpdate, ready: boolean): AppUpdateCheck {
|
||||
return {
|
||||
status: 'available',
|
||||
release: { version: offer.manifest.version, size: offer.manifest.size, notes: offer.release.notes },
|
||||
ready,
|
||||
};
|
||||
}
|
||||
|
||||
function selectedOffer(version: string): OfferedUpdate {
|
||||
if (!offered || version !== offered.manifest.version || compareAppVersions(version, app.getVersion()) <= 0) {
|
||||
throw new AppError('app_update_unavailable');
|
||||
}
|
||||
return offered;
|
||||
}
|
||||
|
||||
async function signedOffer(release: LauncherRelease, key: string): Promise<OfferedUpdate> {
|
||||
const deadline = AbortSignal.timeout(patchPackTuning().requestTimeoutMs);
|
||||
if (isPortableLauncher(app.isPackaged) && release.portable) {
|
||||
const [bytes, signature] = await Promise.all([
|
||||
readReleaseAsset(release.portable.manifest, RELEASE_MANIFEST_MAX_BYTES, deadline, release.source),
|
||||
readReleaseAsset(release.portable.signature, RELEASE_SIGNATURE_MAX_BYTES, deadline, release.source),
|
||||
]);
|
||||
if (!verifyEd25519(portableSignaturePayload(bytes), new TextDecoder().decode(signature), key)) {
|
||||
throw new ManifestSignatureError('The portable release manifest signature does not match.');
|
||||
}
|
||||
const manifest = PortableReleaseManifest.parse(JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)));
|
||||
if (manifest.version !== release.version) throw new Error('The signed portable manifest version does not match the release tag.');
|
||||
return { mode: 'portable', release, manifest };
|
||||
}
|
||||
const [bytes, signature] = await Promise.all([
|
||||
readReleaseAsset(release.manifest, RELEASE_MANIFEST_MAX_BYTES, deadline, release.source),
|
||||
readReleaseAsset(release.signature, RELEASE_SIGNATURE_MAX_BYTES, deadline, release.source),
|
||||
]);
|
||||
if (!verifyEd25519(launcherSignaturePayload(bytes), new TextDecoder().decode(signature), key)) {
|
||||
throw new ManifestSignatureError('The release manifest signature does not match.');
|
||||
}
|
||||
const manifest = LauncherReleaseManifest.parse(JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)));
|
||||
if (manifest.version !== release.version) throw new Error('The signed manifest version does not match the release tag.');
|
||||
return { mode: 'installer', release, manifest };
|
||||
}
|
||||
|
||||
export function checkAppUpdate(): Promise<AppUpdateCheck> {
|
||||
return exclusively(async () => {
|
||||
offered = null;
|
||||
try {
|
||||
const key = packSigningPublicKey();
|
||||
if (!key) return { status: 'failed', problem: 'no_signing_key' };
|
||||
const installedVersion = app.getVersion();
|
||||
const offer = await withReleaseSources(async (source) => {
|
||||
const latest = await newestProjectRelease('launcher', installedVersion, source);
|
||||
if (!latest || compareAppVersions(latest.version, installedVersion) <= 0) return null;
|
||||
return signedOffer(latest, key);
|
||||
});
|
||||
if (!offer) return { status: 'current' };
|
||||
offered = offer;
|
||||
return offerResult(offer, await matchesArtifact(stagedArtifact(offer.mode), offer.manifest));
|
||||
} catch (error) {
|
||||
console.warn('[app-update] checking the release failed:', error);
|
||||
if (error instanceof ReleasePageLimitError) return { status: 'failed', problem: 'page_limit' };
|
||||
if (error instanceof ManifestSignatureError) return { status: 'failed', problem: 'signature' };
|
||||
if (error instanceof FeedUnreachableError || (error instanceof Error && error.name === 'TimeoutError')) {
|
||||
return { status: 'failed', problem: 'network' };
|
||||
}
|
||||
if (error instanceof PatchPackError && error.problem === 'key') return { status: 'failed', problem: 'no_signing_key' };
|
||||
return { status: 'failed', problem: 'contents' };
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export function downloadAppUpdate(
|
||||
version: string, report: (progress: AppUpdateProgress) => void,
|
||||
): Promise<AppUpdateCheck> {
|
||||
return exclusively(async () => {
|
||||
const offer = selectedOffer(version);
|
||||
const target = stagedArtifact(offer.mode);
|
||||
if (await matchesArtifact(target, offer.manifest)) return offerResult(offer, true);
|
||||
try {
|
||||
await withReleaseSources(async (source) => {
|
||||
const release = sameReleaseSource(source, offer.release.source)
|
||||
? offer.release : await projectReleaseVersion('launcher', version, source);
|
||||
const assetUrl = offer.mode === 'portable' ? release.portable?.archive : release.installer;
|
||||
if (!assetUrl) throw new FeedUnreachableError(`This update source does not have the ${offer.mode} asset for ${version}.`);
|
||||
await stageArtifact(assetUrl, release.source, offer.manifest, target, report);
|
||||
}, offer.release.source);
|
||||
return offerResult(offer, true);
|
||||
} catch (error) {
|
||||
console.warn('[app-update] preparing the update asset failed:', error);
|
||||
throw new AppError('app_update_download_failed');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function stageArtifact(
|
||||
assetUrl: URL, source: LauncherRelease['source'], manifest: LauncherReleaseManifest | PortableReleaseManifest, target: string,
|
||||
report: (progress: AppUpdateProgress) => void,
|
||||
): Promise<void> {
|
||||
const partial = `${target}.partial`;
|
||||
const deadline = AbortSignal.timeout(30 * 60_000);
|
||||
let size = 0;
|
||||
let reportedAt = 0;
|
||||
const hash = createHash('sha256');
|
||||
try {
|
||||
await mkdir(dirname(target), { recursive: true });
|
||||
await unlink(partial).catch((error: NodeJS.ErrnoException) => {
|
||||
if (error.code !== 'ENOENT') throw error;
|
||||
});
|
||||
const response = await requestReleaseAsset(assetUrl, deadline, source);
|
||||
const monitor = new Transform({
|
||||
transform(chunk: Buffer, _encoding, done) {
|
||||
size += chunk.length;
|
||||
if (size > manifest.size) {
|
||||
done(new Error('The download is larger than the signed release size.'));
|
||||
return;
|
||||
}
|
||||
hash.update(chunk);
|
||||
if (size === manifest.size || Date.now() - reportedAt >= 200) {
|
||||
reportedAt = Date.now();
|
||||
report({ received: size, total: manifest.size });
|
||||
}
|
||||
done(null, chunk);
|
||||
},
|
||||
});
|
||||
await pipeline(releaseAssetChunks(response), monitor, createWriteStream(partial, { flags: 'wx' }), { signal: deadline });
|
||||
if (size !== manifest.size) throw new FeedUnreachableError('The update download is incomplete.');
|
||||
if (hash.digest('hex') !== manifest.sha256) throw new Error('The update download does not match the signed release.');
|
||||
await rename(partial, target);
|
||||
} catch (error) {
|
||||
if (deadline.aborted) throw new FeedUnreachableError('The update download timed out.', { cause: error });
|
||||
throw error;
|
||||
} finally {
|
||||
await unlink(partial).catch((error: NodeJS.ErrnoException) => {
|
||||
if (error.code !== 'ENOENT') console.warn('[app-update] removing a partial download failed:', error);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export function installAppUpdate(version: string, launcherBusy: () => boolean): Promise<void> {
|
||||
return exclusively(async () => {
|
||||
const offer = selectedOffer(version);
|
||||
if (launcherBusy()) throw new AppError('app_update_launcher_busy');
|
||||
const path = stagedArtifact(offer.mode);
|
||||
if (!await matchesArtifact(path, offer.manifest)) throw new AppError('app_update_installer_invalid');
|
||||
const signal = AbortSignal.timeout(5000);
|
||||
if (await gameProcessRunning(signal) || launcherBusy()) throw new AppError('app_update_launcher_busy');
|
||||
try {
|
||||
if (offer.mode === 'portable') {
|
||||
const prepared = await preparePortableInstall(path, offer.manifest.version, updatesRoot());
|
||||
launchPortableUpdater(prepared);
|
||||
app.quit();
|
||||
return;
|
||||
}
|
||||
const installer = spawn(path, [], { cwd: dirname(path), detached: true, stdio: 'ignore', shell: false });
|
||||
await once(installer, 'spawn');
|
||||
installer.unref();
|
||||
app.quit();
|
||||
} catch (error) {
|
||||
console.warn('[app-update] starting the update failed:', error);
|
||||
throw new AppError('app_update_install_failed');
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { createReadStream } from 'node:fs';
|
||||
import { MAX_INSTALLER_BYTES } from '../../../shared/schemas/app-update.ts';
|
||||
|
||||
const SIGNATURE_DOMAIN = Buffer.from('WTOffline launcher release v1\n', 'utf8');
|
||||
const PORTABLE_SIGNATURE_DOMAIN = Buffer.from('WTOffline launcher portable release v1\n', 'utf8');
|
||||
|
||||
export function launcherSignaturePayload(manifest: Uint8Array): Uint8Array {
|
||||
return Buffer.concat([SIGNATURE_DOMAIN, manifest]);
|
||||
}
|
||||
|
||||
export function portableSignaturePayload(manifest: Uint8Array): Uint8Array {
|
||||
return Buffer.concat([PORTABLE_SIGNATURE_DOMAIN, manifest]);
|
||||
}
|
||||
|
||||
export async function installerDigest(path: string, limit = MAX_INSTALLER_BYTES): Promise<{ size: number; sha256: string }> {
|
||||
const hash = createHash('sha256');
|
||||
let size = 0;
|
||||
for await (const chunk of createReadStream(path)) {
|
||||
size += (chunk as Buffer).length;
|
||||
if (size > limit) throw new Error('The installer is larger than expected.');
|
||||
hash.update(chunk as Buffer);
|
||||
}
|
||||
return { size, sha256: hash.digest('hex') };
|
||||
}
|
||||
@@ -1,283 +0,0 @@
|
||||
/**
|
||||
* In-place updater for portable (unpacked ZIP) launcher builds on Windows.
|
||||
*
|
||||
* Extraction and path validation happen while the launcher is still running so a bad archive or
|
||||
* read-only folder fails cleanly before quitting. Once staged, a detached PowerShell helper waits
|
||||
* for this process to exit, overwrites only files listed in the new portable inventory, removes
|
||||
* only obsolete files listed in the previous portable inventory (never touching unrelated user
|
||||
* files in the same folder), and restarts the updated executable.
|
||||
*/
|
||||
import { execFile, spawn } from 'node:child_process';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { existsSync } from 'node:fs';
|
||||
import { lstat, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
|
||||
import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
|
||||
import { promisify } from 'node:util';
|
||||
import { z } from 'zod';
|
||||
|
||||
const execute = promisify(execFile);
|
||||
|
||||
export const PORTABLE_MARKER_FILE = 'portable-mode';
|
||||
export const PORTABLE_FILES_MANIFEST = 'portable-files.json';
|
||||
const LAUNCHER_EXECUTABLE = 'WTOffline Launcher.exe';
|
||||
const UNINSTALLER_EXECUTABLE = 'Uninstall WTOffline Launcher.exe';
|
||||
|
||||
const PortableInventorySchema = z.object({
|
||||
format: z.literal(1),
|
||||
version: z.string().min(1),
|
||||
files: z.array(z.string().min(1)).min(1),
|
||||
});
|
||||
|
||||
export interface PreparedPortableUpdate {
|
||||
readonly scriptPath: string;
|
||||
readonly planPath: string;
|
||||
readonly stagingDir: string;
|
||||
}
|
||||
|
||||
export interface PortableUpdatePlan {
|
||||
readonly pid: number;
|
||||
readonly installDir: string;
|
||||
readonly stagingDir: string;
|
||||
readonly archivePath: string;
|
||||
readonly logPath: string;
|
||||
readonly executable: string;
|
||||
readonly newFiles: readonly string[];
|
||||
readonly staleFiles: readonly string[];
|
||||
}
|
||||
|
||||
export function isPortableLauncher(isPackaged: boolean): boolean {
|
||||
if (!isPackaged || process.platform !== 'win32') return false;
|
||||
if (existsSync(join(process.resourcesPath, PORTABLE_MARKER_FILE))) return true;
|
||||
return !existsSync(join(dirname(process.execPath), UNINSTALLER_EXECUTABLE));
|
||||
}
|
||||
|
||||
/** Validate a POSIX-style relative path from a portable inventory against traversal or drive prefixes. */
|
||||
export function isSafePortableRelativePath(entry: string): boolean {
|
||||
if (!entry || entry.includes('\\') || entry.includes(':') || entry.startsWith('/')) return false;
|
||||
if (/[\0-\x1f]/.test(entry)) return false;
|
||||
const parts = entry.split('/');
|
||||
return parts.every((part) => part.length > 0 && part !== '.' && part !== '..');
|
||||
}
|
||||
|
||||
function resolveInside(root: string, relPosix: string): string {
|
||||
if (!isSafePortableRelativePath(relPosix)) throw new Error(`Unsafe portable path: ${relPosix}`);
|
||||
const target = resolve(root, ...relPosix.split('/'));
|
||||
const rel = relative(root, target);
|
||||
if (!rel || rel.startsWith('..') || isAbsolute(rel)) {
|
||||
throw new Error(`Portable path escapes root: ${relPosix}`);
|
||||
}
|
||||
return target;
|
||||
}
|
||||
|
||||
async function readPortableInventory(resourcesDir: string): Promise<readonly string[] | null> {
|
||||
try {
|
||||
const raw = await readFile(join(resourcesDir, PORTABLE_FILES_MANIFEST), 'utf8');
|
||||
const parsed = PortableInventorySchema.parse(JSON.parse(raw));
|
||||
return parsed.files.filter(isSafePortableRelativePath);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function assertWritableFolder(folder: string): Promise<void> {
|
||||
const probe = join(folder, `.wto-update-probe-${randomUUID()}.tmp`);
|
||||
await writeFile(probe, '', { flag: 'wx' });
|
||||
await rm(probe, { force: true });
|
||||
}
|
||||
|
||||
async function extractPortableArchive(zipPath: string, stagingDir: string, updatesRoot: string): Promise<void> {
|
||||
const extractScriptPath = join(updatesRoot, `extract-portable-${randomUUID()}.ps1`);
|
||||
const script = [
|
||||
'param([string]$ZipPath, [string]$DestDir)',
|
||||
"$ErrorActionPreference = 'Stop'",
|
||||
'Add-Type -AssemblyName System.IO.Compression.FileSystem',
|
||||
'$destFull = [System.IO.Path]::GetFullPath($DestDir)',
|
||||
'if (-not $destFull.EndsWith([System.IO.Path]::DirectorySeparatorChar)) { $destFull += [System.IO.Path]::DirectorySeparatorChar }',
|
||||
'$zip = [System.IO.Compression.ZipFile]::OpenRead($ZipPath)',
|
||||
'try {',
|
||||
' foreach ($entry in $zip.Entries) {',
|
||||
' $name = $entry.FullName',
|
||||
' if ([string]::IsNullOrEmpty($name) -or $name.EndsWith("/") -or $name.EndsWith("\\")) { continue }',
|
||||
' if ($name.Contains("..") -or $name.StartsWith("/") -or $name.StartsWith("\\") -or $name.Contains(":")) {',
|
||||
' throw "Unsafe zip entry: $name"',
|
||||
' }',
|
||||
' $target = [System.IO.Path]::GetFullPath([System.IO.Path]::Combine($destFull, $name))',
|
||||
' if (-not $target.StartsWith($destFull, [System.StringComparison]::OrdinalIgnoreCase)) {',
|
||||
' throw "Zip entry escapes destination: $name"',
|
||||
' }',
|
||||
' $parent = [System.IO.Path]::GetDirectoryName($target)',
|
||||
' if ($parent) { [System.IO.Directory]::CreateDirectory($parent) | Out-Null }',
|
||||
' [System.IO.Compression.ZipFileExtensions]::ExtractToFile($entry, $target, $true)',
|
||||
' }',
|
||||
'} finally {',
|
||||
' $zip.Dispose()',
|
||||
'}',
|
||||
].join('\r\n');
|
||||
// UTF-8 BOM ensures Windows PowerShell 5.1 decodes non-ASCII paths properly.
|
||||
await writeFile(extractScriptPath, `\uFEFF${script}\r\n`, 'utf8');
|
||||
try {
|
||||
await execute('powershell.exe', [
|
||||
'-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass',
|
||||
'-File', extractScriptPath, zipPath, stagingDir,
|
||||
], { windowsHide: true, timeout: 180_000 });
|
||||
} finally {
|
||||
await rm(extractScriptPath, { force: true }).catch(() => undefined);
|
||||
}
|
||||
}
|
||||
|
||||
export function buildPortableApplyScript(): string {
|
||||
return [
|
||||
'param([string]$PlanPath)',
|
||||
"$ErrorActionPreference = 'Stop'",
|
||||
'$utf8 = New-Object System.Text.UTF8Encoding($false)',
|
||||
'$plan = [System.IO.File]::ReadAllText($PlanPath, $utf8) | ConvertFrom-Json',
|
||||
'function Write-Log([string]$msg) {',
|
||||
' try {',
|
||||
' $line = "$(Get-Date -Format o) $msg`r`n"',
|
||||
' [System.IO.File]::AppendAllText($plan.logPath, $line, $utf8)',
|
||||
' } catch {}',
|
||||
'}',
|
||||
'try {',
|
||||
' Write-Log "Starting portable update in $($plan.installDir) (waiting for pid $($plan.pid))"',
|
||||
' $deadline = (Get-Date).AddSeconds(30)',
|
||||
' while ((Get-Date) -lt $deadline) {',
|
||||
' if (-not (Get-Process -Id $plan.pid -ErrorAction SilentlyContinue)) { break }',
|
||||
' Start-Sleep -Milliseconds 200',
|
||||
' }',
|
||||
' Start-Sleep -Milliseconds 400',
|
||||
' foreach ($rel in $plan.newFiles) {',
|
||||
' $winRel = $rel -replace "/", "\\"',
|
||||
' $src = [System.IO.Path]::Combine($plan.stagingDir, $winRel)',
|
||||
' $dst = [System.IO.Path]::Combine($plan.installDir, $winRel)',
|
||||
' $parent = [System.IO.Path]::GetDirectoryName($dst)',
|
||||
' if ($parent) { [System.IO.Directory]::CreateDirectory($parent) | Out-Null }',
|
||||
' $copied = $false',
|
||||
' for ($attempt = 1; $attempt -le 20; $attempt++) {',
|
||||
' try {',
|
||||
' if ([System.IO.File]::Exists($dst)) { [System.IO.File]::SetAttributes($dst, [System.IO.FileAttributes]::Normal) }',
|
||||
' [System.IO.File]::Copy($src, $dst, $true)',
|
||||
' $copied = $true',
|
||||
' break',
|
||||
' } catch {',
|
||||
' if ($attempt -eq 20) { throw }',
|
||||
' Start-Sleep -Milliseconds 300',
|
||||
' }',
|
||||
' }',
|
||||
' if (-not $copied) { throw "Failed to copy $rel" }',
|
||||
' }',
|
||||
' $installRoot = [System.IO.Path]::GetFullPath($plan.installDir).TrimEnd("\\")',
|
||||
' foreach ($rel in $plan.staleFiles) {',
|
||||
' $winRel = $rel -replace "/", "\\"',
|
||||
' $old = [System.IO.Path]::Combine($plan.installDir, $winRel)',
|
||||
' if ([System.IO.File]::Exists($old)) {',
|
||||
' try {',
|
||||
' [System.IO.File]::SetAttributes($old, [System.IO.FileAttributes]::Normal)',
|
||||
' [System.IO.File]::Delete($old)',
|
||||
' } catch { Write-Log "Could not remove stale file ${rel}: $_" }',
|
||||
' }',
|
||||
' $dir = [System.IO.Path]::GetDirectoryName($old)',
|
||||
' while ($dir -and ($dir.TrimEnd("\\") -ne $installRoot)) {',
|
||||
' if (-not [System.IO.Directory]::Exists($dir)) { break }',
|
||||
' $entries = [System.IO.Directory]::GetFileSystemEntries($dir)',
|
||||
' if ($entries.Length -gt 0) { break }',
|
||||
' try { [System.IO.Directory]::Delete($dir) } catch { break }',
|
||||
' $dir = [System.IO.Path]::GetDirectoryName($dir)',
|
||||
' }',
|
||||
' }',
|
||||
' Write-Log "Replaced $($plan.newFiles.Count) files and cleaned $($plan.staleFiles.Count) obsolete files."',
|
||||
' if ($plan.stagingDir -and [System.IO.Directory]::Exists($plan.stagingDir)) {',
|
||||
' try { Remove-Item -LiteralPath $plan.stagingDir -Recurse -Force } catch {}',
|
||||
' }',
|
||||
' if ($plan.archivePath -and [System.IO.File]::Exists($plan.archivePath)) {',
|
||||
' try { Remove-Item -LiteralPath $plan.archivePath -Force } catch {}',
|
||||
' }',
|
||||
' if ([System.IO.File]::Exists($PlanPath)) {',
|
||||
' try { Remove-Item -LiteralPath $PlanPath -Force } catch {}',
|
||||
' }',
|
||||
' $exe = [System.IO.Path]::Combine($plan.installDir, $plan.executable)',
|
||||
' if ([System.IO.File]::Exists($exe)) {',
|
||||
' Start-Process -FilePath $exe -WorkingDirectory $plan.installDir',
|
||||
' Write-Log "Relaunched $exe"',
|
||||
' }',
|
||||
'} catch {',
|
||||
' Write-Log "Portable update failed: $_"',
|
||||
' exit 1',
|
||||
'}',
|
||||
].join('\r\n');
|
||||
}
|
||||
|
||||
export async function preparePortableInstall(
|
||||
archivePath: string,
|
||||
expectedVersion: string,
|
||||
updatesRoot: string,
|
||||
installDir = dirname(process.execPath),
|
||||
resourcesDir = process.resourcesPath,
|
||||
parentPid = process.pid,
|
||||
): Promise<PreparedPortableUpdate> {
|
||||
await assertWritableFolder(installDir);
|
||||
await mkdir(updatesRoot, { recursive: true });
|
||||
const stagingDir = join(updatesRoot, `portable-staging-${randomUUID()}`);
|
||||
await mkdir(stagingDir, { recursive: true });
|
||||
try {
|
||||
await extractPortableArchive(archivePath, stagingDir, updatesRoot);
|
||||
|
||||
const stagedInventoryRaw = await readFile(join(stagingDir, 'resources', PORTABLE_FILES_MANIFEST), 'utf8');
|
||||
const stagedInventory = PortableInventorySchema.parse(JSON.parse(stagedInventoryRaw));
|
||||
if (stagedInventory.version !== expectedVersion) {
|
||||
throw new Error(`Portable archive inventory version ${stagedInventory.version} does not match ${expectedVersion}.`);
|
||||
}
|
||||
const newFiles = stagedInventory.files;
|
||||
const newSet = new Set(newFiles);
|
||||
const requiredEntries = [
|
||||
LAUNCHER_EXECUTABLE,
|
||||
`resources/${PORTABLE_MARKER_FILE}`,
|
||||
`resources/${PORTABLE_FILES_MANIFEST}`,
|
||||
];
|
||||
for (const required of requiredEntries) {
|
||||
if (!newSet.has(required)) throw new Error(`Portable archive inventory is missing ${required}.`);
|
||||
}
|
||||
for (const rel of newFiles) {
|
||||
const stagedPath = resolveInside(stagingDir, rel);
|
||||
const stats = await lstat(stagedPath);
|
||||
if (!stats.isFile()) throw new Error(`Staged portable entry is not a file: ${rel}`);
|
||||
}
|
||||
|
||||
const oldFiles = await readPortableInventory(resourcesDir);
|
||||
const staleFiles = oldFiles
|
||||
? oldFiles.filter((rel) => !newSet.has(rel) && isSafePortableRelativePath(rel))
|
||||
: [];
|
||||
|
||||
const planPath = join(updatesRoot, `portable-plan-${randomUUID()}.json`);
|
||||
const scriptPath = join(updatesRoot, 'apply-portable-update.ps1');
|
||||
const plan: PortableUpdatePlan = {
|
||||
pid: parentPid,
|
||||
installDir: resolve(installDir),
|
||||
stagingDir,
|
||||
archivePath,
|
||||
logPath: join(updatesRoot, 'portable-update.log'),
|
||||
executable: LAUNCHER_EXECUTABLE,
|
||||
newFiles,
|
||||
staleFiles,
|
||||
};
|
||||
await writeFile(planPath, `${JSON.stringify(plan, null, 2)}\n`, 'utf8');
|
||||
await writeFile(scriptPath, `\uFEFF${buildPortableApplyScript()}\r\n`, 'utf8');
|
||||
return { scriptPath, planPath, stagingDir };
|
||||
} catch (error) {
|
||||
await rm(stagingDir, { recursive: true, force: true }).catch(() => undefined);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export function launchPortableUpdater(prepared: PreparedPortableUpdate): void {
|
||||
const child = spawn('powershell.exe', [
|
||||
'-NoProfile', '-NonInteractive', '-WindowStyle', 'Hidden', '-ExecutionPolicy', 'Bypass',
|
||||
'-File', prepared.scriptPath, prepared.planPath,
|
||||
], {
|
||||
cwd: dirname(prepared.scriptPath),
|
||||
detached: true,
|
||||
stdio: 'ignore',
|
||||
windowsHide: true,
|
||||
shell: false,
|
||||
});
|
||||
child.unref();
|
||||
}
|
||||
@@ -4,7 +4,6 @@ import { app } from 'electron';
|
||||
import { AppError } from '@shared/errors.ts';
|
||||
import { defaultSettings, SettingsSchema, type Settings, type SettingsPatch } from '@shared/schemas/settings.ts';
|
||||
import { readJsonOr, writeJsonAtomic } from '../../util/atomic-json.ts';
|
||||
import { setLauncherLoggingEnabled } from '../diagnostics/launcher-log.ts';
|
||||
|
||||
/**
|
||||
* The launcher's settings file, `<user data>/settings.json`. Read once and cached; every change is
|
||||
@@ -12,7 +11,6 @@ import { setLauncherLoggingEnabled } from '../diagnostics/launcher-log.ts';
|
||||
*/
|
||||
|
||||
let cached: Settings | null = null;
|
||||
let pending: Promise<void> = Promise.resolve();
|
||||
|
||||
function settingsPath(): string {
|
||||
return join(app.getPath('userData'), 'settings.json');
|
||||
@@ -37,22 +35,17 @@ export async function getSettings(): Promise<Settings> {
|
||||
return cached;
|
||||
}
|
||||
|
||||
export function updateSettings(patch: SettingsPatch): Promise<Settings> {
|
||||
const operation = pending.then(async () => {
|
||||
const current = await getSettings();
|
||||
const merged = SettingsSchema.parse({ ...current, ...definedFields(patch) });
|
||||
try {
|
||||
await writeJsonAtomic(settingsPath(), merged);
|
||||
} catch (error) {
|
||||
console.error('[settings] write failed:', error);
|
||||
throw new AppError('settings_write_failed');
|
||||
}
|
||||
cached = merged;
|
||||
setLauncherLoggingEnabled(merged.loggingEnabled);
|
||||
return merged;
|
||||
});
|
||||
pending = operation.then(() => undefined, () => undefined);
|
||||
return operation;
|
||||
export async function updateSettings(patch: SettingsPatch): Promise<Settings> {
|
||||
const current = await getSettings();
|
||||
const merged = SettingsSchema.parse({ ...current, ...definedFields(patch) });
|
||||
try {
|
||||
await writeJsonAtomic(settingsPath(), merged);
|
||||
} catch (error) {
|
||||
console.error('[settings] write failed:', error);
|
||||
throw new AppError('settings_write_failed');
|
||||
}
|
||||
cached = merged;
|
||||
return merged;
|
||||
}
|
||||
|
||||
/** The patch without the fields it leaves out, so they do not overwrite current values. */
|
||||
|
||||
@@ -1,294 +0,0 @@
|
||||
import type { BigIntStats } from 'node:fs';
|
||||
import { copyFile, lstat, mkdir } from 'node:fs/promises';
|
||||
import { dirname, join, normalize, relative, sep } from 'node:path';
|
||||
import { compareVersions, GAME_FILES, isHardlinkableResource } from '@wto/patcher';
|
||||
import { AppError } from '@shared/errors.ts';
|
||||
import type { Copies, GameFolderInspection, InstallRecord } from '@shared/schemas/install.ts';
|
||||
import type { MaintenanceProgress } from '@shared/schemas/maintenance.ts';
|
||||
import { inspectGameFolder } from '../game-folder/inspect-game-folder.ts';
|
||||
import { sameVolume } from '../game-folder/inspect-target-folder.ts';
|
||||
import { copyPlannedFiles, planCopy, type CopyPlan } from '../install/copy-game.ts';
|
||||
import {
|
||||
fileHash,
|
||||
linkVerifiedResource,
|
||||
sameInode,
|
||||
sameResource,
|
||||
statFile,
|
||||
statHardlinkResource,
|
||||
verifyMatchingResource,
|
||||
} from '../install/hardlink-files.ts';
|
||||
import { canonicalCopyPath, copyPathContains, listCopies, updateCopyRecord } from '../install/install-record.ts';
|
||||
import { checkPatches } from '../install/patch-check.ts';
|
||||
import { STOCK_BACKUP_FOLDER } from '../install/stock-backup.ts';
|
||||
import { changeCopyFiles, fileInfo, stagedPath } from './change-copy-files.ts';
|
||||
|
||||
export type Report = (phase: MaintenanceProgress['phase'], doneBytes?: number, totalBytes?: number) => void;
|
||||
|
||||
export async function readSource(record: InstallRecord): Promise<GameFolderInspection | null> {
|
||||
if (!record.sourcePath) return null;
|
||||
try {
|
||||
const game = await inspectGameFolder(record.sourcePath);
|
||||
return game.missingFiles.length > 0 ? null : game;
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) return null;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export function isNewer(source: GameFolderInspection | null, version: string | null): boolean {
|
||||
return !!source?.version && !!version && compareVersions(source.version, version) > 0;
|
||||
}
|
||||
|
||||
export async function repair(record: InstallRecord, root: string, applying: () => void): Promise<Copies> {
|
||||
return changeCopyFiles(root, async (incoming) => {
|
||||
const files = Object.values(GAME_FILES);
|
||||
for (const file of files) await stageBackup(record.stockBackupPath, file, join(incoming, file));
|
||||
applying();
|
||||
return { replace: files, remove: [] };
|
||||
}, listCopies);
|
||||
}
|
||||
|
||||
export async function updatePreservesSpaceSaving(
|
||||
record: InstallRecord,
|
||||
source: GameFolderInspection,
|
||||
root: string,
|
||||
): Promise<boolean> {
|
||||
return (record.hardlinkedFiles?.length ?? 0) > 0 && await canShareVolume(source.path, root);
|
||||
}
|
||||
|
||||
export async function updateFromSource(record: InstallRecord, root: string, signal: AbortSignal, report: Report): Promise<Copies> {
|
||||
const game = await readSource(record);
|
||||
if (!game || !isNewer(game, record.gameVersion)) throw new AppError('maintenance_no_update');
|
||||
|
||||
const dataPath = await canonicalCopyPath(record.dataPath);
|
||||
const plan = await planCopy(game.path);
|
||||
const inventory = plan.files.map((entry) => entry.relativePath);
|
||||
const found = new Set(inventory.map(key));
|
||||
const linked = record.hardlinkedFiles ?? [];
|
||||
const linkedPaths = new Set(linked.map(key));
|
||||
const preserveHardlinks = await updatePreservesSpaceSaving(record, game, root);
|
||||
const remove = [...new Set([...(record.sourceFiles ?? []), ...linked])].filter((name) => !found.has(key(name)));
|
||||
const { copy, linksToStage, hardlinkedFiles } = await planUpdateFiles(
|
||||
game.path, root, dataPath, plan, linkedPaths, preserveHardlinks, signal,
|
||||
);
|
||||
for (const file of remove) await scopedInstallFile(dataPath, root, file);
|
||||
|
||||
signal.throwIfAborted();
|
||||
const check = await checkPatches(game.path, record.dataPath);
|
||||
signal.throwIfAborted();
|
||||
return changeCopyFiles(root, async (incoming) => {
|
||||
report('copying', 0, copy.totalBytes);
|
||||
let lastReport = 0;
|
||||
await copyPlannedFiles(game.path, incoming, copy, signal, ({ doneBytes }) => {
|
||||
if (doneBytes === copy.totalBytes || Date.now() - lastReport >= 250) {
|
||||
lastReport = Date.now();
|
||||
report('copying', doneBytes, copy.totalBytes);
|
||||
}
|
||||
});
|
||||
const stagedLinks = new Map<string, BigIntStats>();
|
||||
for (const [relativePath, sourceStamp] of linksToStage) {
|
||||
signal.throwIfAborted();
|
||||
const staged = join(incoming, relativePath);
|
||||
await mkdir(dirname(staged), { recursive: true });
|
||||
const linkedStamp = await linkVerifiedResource(join(game.path, relativePath), staged, sourceStamp);
|
||||
stagedLinks.set(staged, linkedStamp);
|
||||
}
|
||||
const stockFiles = Object.values(GAME_FILES).map((file) => join(STOCK_BACKUP_FOLDER, file));
|
||||
for (const file of Object.values(GAME_FILES)) {
|
||||
signal.throwIfAborted();
|
||||
await stageBackup(game.path, file, join(incoming, STOCK_BACKUP_FOLDER, file));
|
||||
}
|
||||
await verifySourceFiles(game.path, plan, signal);
|
||||
if (stagedLinks.size > 0) await verifyStagedLinks(record, game.version, stagedLinks, signal);
|
||||
signal.throwIfAborted();
|
||||
report('applying', copy.totalBytes, copy.totalBytes);
|
||||
return {
|
||||
replace: [...copy.files.map(({ relativePath }) => relativePath), ...linksToStage.keys(), ...stockFiles],
|
||||
remove,
|
||||
};
|
||||
}, () => updateCopyRecord(record.id, (latest) => ({
|
||||
...latest, gameVersion: game.version, unavailablePatches: check.unavailable,
|
||||
lastCheckedAt: new Date().toISOString(), sourceFiles: inventory,
|
||||
...(preserveHardlinks ? { hardlinkedFiles } : linked.length ? { hardlinkedFiles: [] } : {}),
|
||||
})));
|
||||
}
|
||||
|
||||
interface UpdateFilePlan {
|
||||
readonly copy: CopyPlan;
|
||||
readonly linksToStage: ReadonlyMap<string, BigIntStats>;
|
||||
readonly hardlinkedFiles: string[];
|
||||
}
|
||||
|
||||
async function planUpdateFiles(
|
||||
source: string,
|
||||
root: string,
|
||||
dataPath: string,
|
||||
plan: CopyPlan,
|
||||
linked: ReadonlySet<string>,
|
||||
preserveHardlinks: boolean,
|
||||
signal: AbortSignal,
|
||||
): Promise<UpdateFilePlan> {
|
||||
const changed: CopyPlan['files'][number][] = [];
|
||||
const linksToStage = new Map<string, BigIntStats>();
|
||||
const hardlinkedFiles: string[] = [];
|
||||
for (const file of plan.files) {
|
||||
signal.throwIfAborted();
|
||||
const target = await scopedInstallFile(dataPath, root, file.relativePath);
|
||||
const sourceFile = join(source, file.relativePath);
|
||||
const old = await statFile(target);
|
||||
if (preserveHardlinks && isHardlinkableResource(file.relativePath, file.bytes)) {
|
||||
const sourceStamp = await statHardlinkResource(sourceFile, file.bytes, signal);
|
||||
if (!sourceStamp) throw new AppError('maintenance_source_changed');
|
||||
if (!old || !sameResource(old, sourceStamp)) linksToStage.set(file.relativePath, sourceStamp);
|
||||
hardlinkedFiles.push(file.relativePath);
|
||||
continue;
|
||||
}
|
||||
const sourceStamp = await statFile(sourceFile);
|
||||
if (!sourceStamp?.isFile() || sourceStamp.size !== BigInt(file.bytes)) {
|
||||
throw new AppError('maintenance_source_changed');
|
||||
}
|
||||
if (linked.has(key(file.relativePath)) || !old?.isFile() || sameInode(old, sourceStamp) ||
|
||||
old.size !== BigInt(file.bytes)) {
|
||||
changed.push(file);
|
||||
} else if (Math.trunc(Number(old.mtimeMs)) !== Math.trunc(file.modifiedAt)) {
|
||||
const [targetHash, sourceHash] = await Promise.all([
|
||||
fileHash(target, signal), fileHash(sourceFile, signal),
|
||||
]);
|
||||
if (targetHash !== sourceHash) changed.push(file);
|
||||
}
|
||||
}
|
||||
return {
|
||||
copy: {
|
||||
files: changed,
|
||||
folders: [...new Set(changed.map(({ relativePath }) => dirname(relativePath)))],
|
||||
totalBytes: changed.reduce((total, file) => total + file.bytes, 0),
|
||||
},
|
||||
linksToStage,
|
||||
hardlinkedFiles,
|
||||
};
|
||||
}
|
||||
|
||||
async function verifySourceFiles(source: string, plan: CopyPlan, signal: AbortSignal): Promise<void> {
|
||||
for (const file of plan.files) {
|
||||
signal.throwIfAborted();
|
||||
const info = await fileInfo(join(source, file.relativePath));
|
||||
if (!info?.isFile() || info.size !== file.bytes || info.mtimeMs !== file.modifiedAt) {
|
||||
throw new AppError('maintenance_source_changed');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function convertibleCopy(record: InstallRecord, source: GameFolderInspection, root: string): Promise<boolean> {
|
||||
return record.method === 'copy' && source.version !== null &&
|
||||
source.version === record.gameVersion && await canShareVolume(source.path, root);
|
||||
}
|
||||
|
||||
export async function compactCopy(record: InstallRecord, root: string, signal: AbortSignal, report: Report): Promise<Copies> {
|
||||
const source = await readSource(record);
|
||||
if (!source || !await convertibleCopy(record, source, root) ||
|
||||
(await inspectGameFolder(root)).version !== source.version) {
|
||||
throw new AppError('hardlink_unavailable');
|
||||
}
|
||||
|
||||
const plan = await planCopy(source.path);
|
||||
const candidates = plan.files.filter(({ relativePath, bytes }) => isHardlinkableResource(relativePath, bytes));
|
||||
const total = candidates.reduce((bytes, file) => bytes + file.bytes, 0);
|
||||
const dataPath = await canonicalCopyPath(record.dataPath);
|
||||
const linked = new Map((record.hardlinkedFiles ?? []).map((path) => [key(path), path]));
|
||||
return changeCopyFiles(root, async (incoming) => {
|
||||
const replacements: string[] = [];
|
||||
const unchanged = new Map<string, BigIntStats>();
|
||||
let checked = 0;
|
||||
let matches = 0;
|
||||
let lastReport = 0;
|
||||
report('checking', 0, total);
|
||||
for (const { relativePath, bytes } of candidates) {
|
||||
const target = await scopedInstallFile(dataPath, root, relativePath);
|
||||
const original = join(source.path, relativePath);
|
||||
const match = await verifyMatchingResource(target, original, bytes, signal);
|
||||
if (match.status === 'already-linked') {
|
||||
linked.set(key(relativePath), relativePath);
|
||||
matches += 1;
|
||||
} else if (match.status === 'matched') {
|
||||
const staged = join(incoming, relativePath);
|
||||
await mkdir(dirname(staged), { recursive: true });
|
||||
const stagedStamp = await linkVerifiedResource(original, staged, match.sourceStamp);
|
||||
unchanged.set(target, match.copyStamp);
|
||||
unchanged.set(staged, stagedStamp);
|
||||
replacements.push(relativePath);
|
||||
linked.set(key(relativePath), relativePath);
|
||||
matches += 1;
|
||||
}
|
||||
checked += bytes;
|
||||
if (checked === total || Date.now() - lastReport >= 250) {
|
||||
lastReport = Date.now();
|
||||
report('checking', checked, total);
|
||||
}
|
||||
}
|
||||
if (!matches) throw new AppError('hardlink_no_match');
|
||||
|
||||
await verifyStagedLinks(record, source.version, unchanged, signal);
|
||||
signal.throwIfAborted();
|
||||
report('applying', total, total);
|
||||
return { replace: replacements, remove: [] };
|
||||
}, () => updateCopyRecord(record.id, (latest) => ({ ...latest, hardlinkedFiles: [...linked.values()] })));
|
||||
}
|
||||
|
||||
async function canShareVolume(sourcePath: string, root: string): Promise<boolean> {
|
||||
return await sameVolume(sourcePath, root) && await sameVolume(sourcePath, dirname(root));
|
||||
}
|
||||
|
||||
async function verifyStagedLinks(
|
||||
record: InstallRecord, version: string | null, unchanged: ReadonlyMap<string, BigIntStats>, signal: AbortSignal,
|
||||
): Promise<void> {
|
||||
signal.throwIfAborted();
|
||||
if ((await readSource(record))?.version !== version) throw new AppError('hardlink_file_changed');
|
||||
for (const [path, stamp] of unchanged) {
|
||||
signal.throwIfAborted();
|
||||
if (!sameResource(stamp, await lstat(path, { bigint: true }))) throw new AppError('hardlink_file_changed');
|
||||
}
|
||||
}
|
||||
|
||||
function key(path: string): string {
|
||||
const name = normalize(path);
|
||||
return process.platform === 'win32' ? name.toLowerCase() : name;
|
||||
}
|
||||
|
||||
const OFFLINE_DATA_ENTRIES = new Set(['accounts.json', 'saves', 'tuning', 'logs', 'asset-pack', 'decals', 'cache']);
|
||||
|
||||
function failLocation(reason: string, details: Record<string, unknown>): never {
|
||||
console.warn('[copies] maintenance_location:', reason, details);
|
||||
throw new AppError('maintenance_location');
|
||||
}
|
||||
|
||||
async function scopedInstallFile(dataPath: string, root: string, name: string): Promise<string> {
|
||||
const target = await stagedPath(root, name);
|
||||
if (copyPathContains(join(root, dirname(STOCK_BACKUP_FOLDER)), target)) {
|
||||
failLocation('target_inside_wtoffline', { root, target, name });
|
||||
}
|
||||
// Protect the data folder when it is nested inside the client folder. If an older installation
|
||||
// placed dataPath at an ancestor of the client folder, files inside the client folder do not
|
||||
// overlap data files stored at the ancestor root.
|
||||
if (copyPathContains(root, dataPath)) {
|
||||
if (relative(root, dataPath) !== '') {
|
||||
if (copyPathContains(dataPath, target)) {
|
||||
failLocation('target_inside_nested_data_folder', { root, dataPath, target, name });
|
||||
}
|
||||
} else {
|
||||
const topSegment = normalize(name).split(sep)[0]?.toLowerCase() ?? '';
|
||||
if (OFFLINE_DATA_ENTRIES.has(topSegment)) {
|
||||
failLocation('target_collides_with_data_entry', { root, dataPath, target, name });
|
||||
}
|
||||
}
|
||||
}
|
||||
return target;
|
||||
}
|
||||
|
||||
async function stageBackup(folder: string, file: string, target: string): Promise<void> {
|
||||
await mkdir(dirname(target), { recursive: true });
|
||||
const source = join(folder, file);
|
||||
if (!(await fileInfo(source))?.isFile()) {
|
||||
failLocation('stock_backup_source_missing', { folder, file, source });
|
||||
}
|
||||
await copyFile(source, target);
|
||||
}
|
||||
@@ -1,34 +1,28 @@
|
||||
import { readdir, rm } from 'node:fs/promises';
|
||||
import { isAbsolute, join, parse, relative } from 'node:path';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { createReadStream } from 'node:fs';
|
||||
import { copyFile, mkdir, readdir, rm } from 'node:fs/promises';
|
||||
import { dirname, isAbsolute, join, normalize, parse, relative } from 'node:path';
|
||||
import { app } from 'electron';
|
||||
import { isInSteamLibrary } from '@wto/patcher';
|
||||
import { compareVersions, GAME_FILES, isInSteamLibrary } from '@wto/patcher';
|
||||
import { AppError } from '@shared/errors.ts';
|
||||
import type { Copies, InstallRecord } from '@shared/schemas/install.ts';
|
||||
import type { Copies, GameFolderInspection, InstallRecord } from '@shared/schemas/install.ts';
|
||||
import type { MaintenanceInfo, MaintenanceProgress, MaintenanceRequest } from '@shared/schemas/maintenance.ts';
|
||||
import { inspectGameFolder } from '../game-folder/inspect-game-folder.ts';
|
||||
import { copyPlannedFiles, planCopy, type CopyPlan } from '../install/copy-game.ts';
|
||||
import { installationInProgress } from '../install/install-game.ts';
|
||||
import { canonicalCopyPath, copyPathContains, listCopies, removeCopyRecord, steamLibraryNeedsConfirmation, updateCopyRecord } from '../install/install-record.ts';
|
||||
import { canonicalCopyPath, copyPathContains, listCopies, removeCopyRecord, updateCopyRecord } from '../install/install-record.ts';
|
||||
import { checkPatches } from '../install/patch-check.ts';
|
||||
import { STOCK_BACKUP_FOLDER } from '../install/stock-backup.ts';
|
||||
import { gameProcessRunning, launchInProgress } from '../launch/launch-controller.ts';
|
||||
import { readInstalledLab } from '../launch/lab-handoff.ts';
|
||||
import { localServerReady } from '../launch/local-server.ts';
|
||||
import { fileInfo } from './change-copy-files.ts';
|
||||
import { compactCopy, convertibleCopy, isNewer, readSource, repair, updateFromSource, updatePreservesSpaceSaving, type Report } from './copy-file-maintenance.ts';
|
||||
import { labStatusUrl, readInstalledLab } from '../launch/lab-handoff.ts';
|
||||
import { changeCopyFiles, fileInfo, stagedPath } from './change-copy-files.ts';
|
||||
|
||||
let current: {
|
||||
stop: AbortController;
|
||||
interruptible: boolean;
|
||||
progress: MaintenanceProgress;
|
||||
} | null = null;
|
||||
let current: { stop: AbortController; interruptible: boolean } | null = null;
|
||||
|
||||
export function maintenanceInProgress(): boolean {
|
||||
return current !== null;
|
||||
}
|
||||
|
||||
export function maintenanceState(): MaintenanceProgress | null {
|
||||
return current ? { ...current.progress } : null;
|
||||
}
|
||||
|
||||
export function cancelMaintenance(): void {
|
||||
if (current?.interruptible) current.stop.abort();
|
||||
}
|
||||
@@ -36,48 +30,40 @@ export function cancelMaintenance(): void {
|
||||
export async function maintenanceInfo(id: string): Promise<MaintenanceInfo> {
|
||||
const record = await requireCopy(id);
|
||||
const source = await readSource(record);
|
||||
const [copyPath, dataPath] = await Promise.all([canonicalCopyPath(record.copyPath), canonicalCopyPath(record.dataPath)]);
|
||||
const copyInSteam = isInSteamLibrary(record.copyPath) || isInSteamLibrary(copyPath);
|
||||
const dataInSteam = isInSteamLibrary(record.dataPath) || isInSteamLibrary(dataPath);
|
||||
return {
|
||||
sourceVersion: source?.version ?? null,
|
||||
updateAvailable: isNewer(source, record.gameVersion),
|
||||
updatePreservesSpaceSaving: source !== null && await updatePreservesSpaceSaving(record, source, record.copyPath),
|
||||
spaceSavingAvailable: source !== null && await convertibleCopy(record, source, record.copyPath),
|
||||
steamConfirmationRequired: steamLibraryNeedsConfirmation(record, copyPath, dataPath),
|
||||
steamLocations: copyInSteam || dataInSteam ? { copyPath, dataPath, copyInSteam, dataInSteam } : null,
|
||||
};
|
||||
return { sourceVersion: source?.version ?? null, updateAvailable: isNewer(source, record.gameVersion) };
|
||||
}
|
||||
|
||||
export async function maintainCopy(
|
||||
request: MaintenanceRequest,
|
||||
publish: (progress: MaintenanceProgress | null) => void,
|
||||
publish: (progress: MaintenanceProgress) => void,
|
||||
): Promise<Copies> {
|
||||
if (current || launchInProgress() || installationInProgress()) throw new AppError('maintenance_busy');
|
||||
const initial: MaintenanceProgress = {
|
||||
id: request.id,
|
||||
operation: request.operation,
|
||||
phase: 'checking',
|
||||
doneBytes: 0,
|
||||
totalBytes: 0,
|
||||
};
|
||||
const job = {
|
||||
stop: new AbortController(),
|
||||
interruptible: request.operation === 'update' || request.operation === 'compact',
|
||||
progress: initial,
|
||||
};
|
||||
const job = { stop: new AbortController(), interruptible: request.operation === 'update' };
|
||||
current = job;
|
||||
const signal = job.stop.signal;
|
||||
const report: Report = (phase, doneBytes = 0, totalBytes = 0) => {
|
||||
const report = (phase: MaintenanceProgress['phase'], doneBytes = 0, totalBytes = 0): void => {
|
||||
if (phase === 'applying') job.interruptible = false;
|
||||
const next: MaintenanceProgress = { id: request.id, operation: request.operation, phase, doneBytes, totalBytes };
|
||||
job.progress = next;
|
||||
publish(next);
|
||||
publish({ id: request.id, operation: request.operation, phase, doneBytes, totalBytes });
|
||||
};
|
||||
report('checking');
|
||||
|
||||
try {
|
||||
report('checking');
|
||||
return await performMaintenance(request, signal, report);
|
||||
const record = await requireCopy(request.id);
|
||||
const root = await checkedRoot(record);
|
||||
if (await gameProcessRunning(signal) || await labServerUses(root)) throw new AppError('maintenance_busy');
|
||||
signal.throwIfAborted();
|
||||
|
||||
switch (request.operation) {
|
||||
case 'check':
|
||||
return await recordCheck(record, record.stockBackupPath);
|
||||
case 'repair':
|
||||
return await repair(record, root, () => report('applying'));
|
||||
case 'update':
|
||||
return await updateFromSource(record, root, signal, report);
|
||||
case 'delete':
|
||||
report('applying');
|
||||
return await remove(record, root, request.deleteData);
|
||||
}
|
||||
} catch (error) {
|
||||
if (signal.aborted) throw new AppError('maintenance_cancelled');
|
||||
if (error instanceof AppError) throw error;
|
||||
@@ -85,44 +71,6 @@ export async function maintainCopy(
|
||||
throw new AppError('maintenance_failed');
|
||||
} finally {
|
||||
current = null;
|
||||
publish(null);
|
||||
}
|
||||
}
|
||||
|
||||
async function performMaintenance(request: MaintenanceRequest, signal: AbortSignal, report: Report): Promise<Copies> {
|
||||
const { id, operation, steamLocations } = request;
|
||||
const record = await requireCopy(id);
|
||||
const root = await checkedRoot(record);
|
||||
const dataPath = await canonicalCopyPath(record.dataPath);
|
||||
const needsConfirmation = steamLibraryNeedsConfirmation(record, root, dataPath);
|
||||
if (await gameProcessRunning(signal) || await labServerUses(root)) throw new AppError('maintenance_busy');
|
||||
signal.throwIfAborted();
|
||||
|
||||
if (operation !== 'confirm-steam' && operation !== 'delete' && needsConfirmation) {
|
||||
throw new AppError('launch_steam_confirmation_required');
|
||||
}
|
||||
|
||||
switch (operation) {
|
||||
case 'confirm-steam':
|
||||
if (!steamLocations || !isAbsolute(steamLocations.copyPath) || !isAbsolute(steamLocations.dataPath) ||
|
||||
relative(root, steamLocations.copyPath) !== '' || relative(dataPath, steamLocations.dataPath) !== '') {
|
||||
failLocation('steam_confirmation_mismatch', { root, dataPath, steamLocations });
|
||||
}
|
||||
if (!needsConfirmation) return listCopies();
|
||||
return updateCopyRecord(id, (copy) => ({
|
||||
...copy, steamLibraryConfirmation: { copyPath: root, dataPath },
|
||||
}));
|
||||
case 'check':
|
||||
return recordCheck(record, record.stockBackupPath);
|
||||
case 'repair':
|
||||
return repair(record, root, () => report('applying'));
|
||||
case 'update':
|
||||
return updateFromSource(record, root, signal, report);
|
||||
case 'compact':
|
||||
return compactCopy(record, root, signal, report);
|
||||
case 'delete':
|
||||
report('applying');
|
||||
return remove(record, root, request.deleteData);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -132,46 +80,52 @@ async function requireCopy(id: string): Promise<InstallRecord> {
|
||||
return record;
|
||||
}
|
||||
|
||||
function failLocation(reason: string, details: Record<string, unknown>): never {
|
||||
console.warn('[copies] maintenance_location:', reason, details);
|
||||
throw new AppError('maintenance_location');
|
||||
async function readSource(record: InstallRecord): Promise<GameFolderInspection | null> {
|
||||
if (!record.sourcePath) return null;
|
||||
try {
|
||||
const game = await inspectGameFolder(record.sourcePath);
|
||||
return game.missingFiles.length > 0 ? null : game;
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) return null;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function isNewer(source: GameFolderInspection | null, version: string | null): boolean {
|
||||
return !!source?.version && !!version && compareVersions(source.version, version) > 0;
|
||||
}
|
||||
|
||||
async function checkedRoot(record: InstallRecord): Promise<string> {
|
||||
const root = await safeFolder(record.copyPath, true);
|
||||
const root = await safeFolder(record.copyPath);
|
||||
const backup = await canonicalCopyPath(record.stockBackupPath);
|
||||
const expectedBackup = join(root, STOCK_BACKUP_FOLDER);
|
||||
if (relative(expectedBackup, backup) !== '') {
|
||||
failLocation('stock_backup_outside_copy', { root, expectedBackup, backup, recordedBackup: record.stockBackupPath });
|
||||
}
|
||||
if (relative(join(root, STOCK_BACKUP_FOLDER), backup) !== '') throw new AppError('maintenance_location');
|
||||
if (record.sourcePath) {
|
||||
const source = await canonicalCopyPath(record.sourcePath);
|
||||
if (copyPathContains(source, root) || copyPathContains(root, source)) {
|
||||
failLocation('copy_overlaps_source', { root, source, sourcePath: record.sourcePath });
|
||||
}
|
||||
if (copyPathContains(source, root) || copyPathContains(root, source)) throw new AppError('maintenance_location');
|
||||
}
|
||||
return root;
|
||||
}
|
||||
|
||||
async function safeFolder(path: string, steamAllowed = false): Promise<string> {
|
||||
async function safeFolder(path: string): Promise<string> {
|
||||
const root = await canonicalCopyPath(path);
|
||||
const inSteam = isInSteamLibrary(path) || isInSteamLibrary(root);
|
||||
const appPath = await canonicalCopyPath(app.getAppPath());
|
||||
const userDataPath = await canonicalCopyPath(app.getPath('userData'));
|
||||
if (!isAbsolute(path) || root === parse(root).root || (!steamAllowed && inSteam) ||
|
||||
copyPathContains(root, appPath) || copyPathContains(root, userDataPath)) {
|
||||
failLocation('unsafe_folder', { path, root, inSteam, steamAllowed, appPath, userDataPath });
|
||||
}
|
||||
if ((!steamAllowed || !inSteam) && (await fileInfo(path))?.isSymbolicLink()) {
|
||||
failLocation('folder_is_symlink', { path, root });
|
||||
if (!isAbsolute(path) || root === parse(root).root || isInSteamLibrary(root) ||
|
||||
copyPathContains(root, await canonicalCopyPath(app.getAppPath())) ||
|
||||
copyPathContains(root, await canonicalCopyPath(app.getPath('userData')))) {
|
||||
throw new AppError('maintenance_location');
|
||||
}
|
||||
if ((await fileInfo(path))?.isSymbolicLink()) throw new AppError('maintenance_location');
|
||||
return root;
|
||||
}
|
||||
|
||||
async function labServerUses(root: string): Promise<boolean> {
|
||||
const lab = await readInstalledLab().catch(() => null);
|
||||
if (!lab || relative(lab.copyPath, root) !== '') return false;
|
||||
return localServerReady(lab.port);
|
||||
try {
|
||||
const response = await fetch(labStatusUrl(lab.port), { signal: AbortSignal.timeout(800) });
|
||||
return response.ok && (await response.json() as { app?: string }).app === 'wto-server';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function recordCheck(record: InstallRecord, folder: string): Promise<Copies> {
|
||||
@@ -181,17 +135,113 @@ async function recordCheck(record: InstallRecord, folder: string): Promise<Copie
|
||||
}));
|
||||
}
|
||||
|
||||
async function remove(record: InstallRecord, root: string, deleteData: boolean): Promise<Copies> {
|
||||
if (isInSteamLibrary(record.copyPath) || isInSteamLibrary(root)) {
|
||||
if (deleteData) failLocation('delete_data_blocked_in_steam', { copyPath: record.copyPath, root });
|
||||
return removeCopyRecord(record.id);
|
||||
}
|
||||
async function repair(record: InstallRecord, root: string, applying: () => void): Promise<Copies> {
|
||||
return changeCopyFiles(root, async (incoming) => {
|
||||
const files = Object.values(GAME_FILES);
|
||||
for (const file of files) await stageBackup(record.stockBackupPath, file, join(incoming, file));
|
||||
applying();
|
||||
return { replace: files, remove: [] };
|
||||
}, listCopies);
|
||||
}
|
||||
|
||||
type Report = (phase: MaintenanceProgress['phase'], doneBytes?: number, totalBytes?: number) => void;
|
||||
|
||||
async function updateFromSource(record: InstallRecord, root: string, signal: AbortSignal, report: Report): Promise<Copies> {
|
||||
const game = await readSource(record);
|
||||
if (!game || !isNewer(game, record.gameVersion)) throw new AppError('maintenance_no_update');
|
||||
|
||||
const dataPath = await canonicalCopyPath(record.dataPath);
|
||||
const plan = await planCopy(game.path);
|
||||
const inventory = plan.files.map((entry) => entry.relativePath);
|
||||
const found = new Set(inventory.map(key));
|
||||
const remove = (record.sourceFiles ?? []).filter((name) => !found.has(key(name)));
|
||||
const changed: CopyPlan['files'][number][] = [];
|
||||
for (const file of plan.files) {
|
||||
signal.throwIfAborted();
|
||||
const target = await scopedInstallFile(dataPath, root, file.relativePath);
|
||||
const old = await fileInfo(target);
|
||||
if (!old?.isFile() || old.size !== file.bytes) {
|
||||
changed.push(file);
|
||||
} else if (Math.trunc(old.mtimeMs) !== Math.trunc(file.modifiedAt)) {
|
||||
const [targetHash, sourceHash] = await Promise.all([
|
||||
fileHash(target, signal), fileHash(join(game.path, file.relativePath), signal),
|
||||
]);
|
||||
if (targetHash !== sourceHash) changed.push(file);
|
||||
}
|
||||
}
|
||||
for (const file of remove) await scopedInstallFile(dataPath, root, file);
|
||||
|
||||
signal.throwIfAborted();
|
||||
const check = await checkPatches(game.path, record.dataPath);
|
||||
signal.throwIfAborted();
|
||||
const copy: CopyPlan = {
|
||||
files: changed,
|
||||
folders: [...new Set(changed.map(({ relativePath }) => dirname(relativePath)))],
|
||||
totalBytes: changed.reduce((total, file) => total + file.bytes, 0),
|
||||
};
|
||||
return changeCopyFiles(root, async (incoming) => {
|
||||
report('copying', 0, copy.totalBytes);
|
||||
let lastReport = 0;
|
||||
await copyPlannedFiles(game.path, incoming, copy, signal, ({ doneBytes }) => {
|
||||
if (doneBytes === copy.totalBytes || Date.now() - lastReport >= 250) {
|
||||
lastReport = Date.now();
|
||||
report('copying', doneBytes, copy.totalBytes);
|
||||
}
|
||||
});
|
||||
const stockFiles = Object.values(GAME_FILES).map((file) => join(STOCK_BACKUP_FOLDER, file));
|
||||
for (const file of Object.values(GAME_FILES)) {
|
||||
signal.throwIfAborted();
|
||||
await stageBackup(game.path, file, join(incoming, STOCK_BACKUP_FOLDER, file));
|
||||
}
|
||||
for (const file of plan.files) {
|
||||
signal.throwIfAborted();
|
||||
const info = await fileInfo(join(game.path, file.relativePath));
|
||||
if (!info?.isFile() || info.size !== file.bytes || info.mtimeMs !== file.modifiedAt) {
|
||||
throw new AppError('maintenance_source_changed');
|
||||
}
|
||||
}
|
||||
signal.throwIfAborted();
|
||||
report('applying', copy.totalBytes, copy.totalBytes);
|
||||
return { replace: [...changed.map(({ relativePath }) => relativePath), ...stockFiles], remove };
|
||||
}, () => updateCopyRecord(record.id, (latest) => ({
|
||||
...latest, gameVersion: game.version, unavailablePatches: check.unavailable,
|
||||
lastCheckedAt: new Date().toISOString(), sourceFiles: inventory,
|
||||
})));
|
||||
}
|
||||
|
||||
function key(path: string): string {
|
||||
const name = normalize(path);
|
||||
return process.platform === 'win32' ? name.toLowerCase() : name;
|
||||
}
|
||||
|
||||
async function scopedInstallFile(dataPath: string, root: string, name: string): Promise<string> {
|
||||
const target = await stagedPath(root, name);
|
||||
if (copyPathContains(join(root, dirname(STOCK_BACKUP_FOLDER)), target) ||
|
||||
copyPathContains(dataPath, target)) {
|
||||
throw new AppError('maintenance_location');
|
||||
}
|
||||
return target;
|
||||
}
|
||||
|
||||
async function fileHash(path: string, signal: AbortSignal): Promise<string> {
|
||||
const hash = createHash('sha256');
|
||||
for await (const bytes of createReadStream(path, { signal })) hash.update(bytes as Buffer);
|
||||
return hash.digest('hex');
|
||||
}
|
||||
|
||||
async function stageBackup(folder: string, file: string, target: string): Promise<void> {
|
||||
await mkdir(dirname(target), { recursive: true });
|
||||
const source = join(folder, file);
|
||||
if (!(await fileInfo(source))?.isFile()) throw new AppError('maintenance_location');
|
||||
await copyFile(source, target);
|
||||
}
|
||||
|
||||
async function remove(record: InstallRecord, root: string, deleteData: boolean): Promise<Copies> {
|
||||
const data = deleteData ? await safeFolder(record.dataPath) : await canonicalCopyPath(record.dataPath);
|
||||
const source = record.sourcePath ? await canonicalCopyPath(record.sourcePath) : null;
|
||||
if (deleteData && ((source && (copyPathContains(data, source) || copyPathContains(source, data))) ||
|
||||
(relative(data, root) !== '' && copyPathContains(data, root)))) {
|
||||
failLocation('delete_data_overlaps_source_or_copy', { root, data, source });
|
||||
throw new AppError('maintenance_location');
|
||||
}
|
||||
if (!deleteData && copyPathContains(root, data)) {
|
||||
await removeExcept(root, data);
|
||||
@@ -208,7 +258,7 @@ async function removeExcept(folder: string, kept: string): Promise<void> {
|
||||
for (const entry of await readdir(folder, { withFileTypes: true })) {
|
||||
const path = join(folder, entry.name);
|
||||
if (copyPathContains(path, kept)) {
|
||||
if (!entry.isDirectory()) failLocation('kept_data_ancestor_not_directory', { folder, kept, path });
|
||||
if (!entry.isDirectory()) throw new AppError('maintenance_location');
|
||||
await removeExcept(path, kept);
|
||||
} else {
|
||||
await rm(path, { recursive: true, force: true });
|
||||
|
||||
@@ -1,25 +0,0 @@
|
||||
import { AppError } from '@shared/errors.ts';
|
||||
import type { Copies } from '@shared/schemas/install.ts';
|
||||
import { inspectGameFolder } from '../game-folder/inspect-game-folder.ts';
|
||||
import { hydrateCopiesStatus, relocateCopyRecord } from '../install/install-record.ts';
|
||||
import { backUpStockFiles, installStockSource, refreshStockBackup } from '../install/stock-backup.ts';
|
||||
|
||||
/**
|
||||
* Re-point an existing registered client to its moved folder while keeping its id, name, saves,
|
||||
* and data folder intact.
|
||||
*/
|
||||
export async function relocateCopy(id: string, newPath: string): Promise<Copies> {
|
||||
const game = await inspectGameFolder(newPath);
|
||||
if (game.missingFiles.length) throw new AppError('not_a_game_folder', { path: newPath });
|
||||
if (game.needsStockSource) throw new AppError('stock_source_invalid');
|
||||
const stock = await installStockSource(game.resolvedPath, game.version);
|
||||
const stockBackupPath = stock.refresh
|
||||
? await refreshStockBackup(game.resolvedPath)
|
||||
: await backUpStockFiles(game.resolvedPath);
|
||||
const updated = await relocateCopyRecord(id, {
|
||||
copyPath: newPath,
|
||||
stockBackupPath,
|
||||
gameVersion: game.version,
|
||||
});
|
||||
return hydrateCopiesStatus(updated);
|
||||
}
|
||||
@@ -1,31 +1,15 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { lstat, mkdir, readdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
|
||||
import { release } from 'node:os';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { join } from 'node:path';
|
||||
import { app, dialog, shell, type BrowserWindow } from 'electron';
|
||||
import { zipSync } from 'fflate';
|
||||
import { GAME_FILES } from '@wto/patcher';
|
||||
import { AppError } from '@shared/errors.ts';
|
||||
import type { InstallRecord } from '@shared/schemas/install.ts';
|
||||
import { getSettings } from '../config/settings-store.ts';
|
||||
import { COPIES_FILENAME, readInstallRecord } from '../install/install-record.ts';
|
||||
import { LAUNCHER_LOG_FILES, launcherLogFolder } from './launcher-log.ts';
|
||||
|
||||
type ArchiveFiles = Record<string, Uint8Array>;
|
||||
|
||||
/** Bound individual client log files so a huge crash dump or session log cannot exhaust memory. */
|
||||
const MAX_CLIENT_LOG_BYTES = 16 * 1024 * 1024;
|
||||
/** Number of recent .game_logs entries listed in client-logs/summary.json. */
|
||||
const RECENT_GAME_LOGS_LIMIT = 10;
|
||||
const HOOK_LOG_FILENAME = 'wto_ws.log';
|
||||
const HOOK_CONFIG_FILENAME = 'wto_ws.cfg';
|
||||
|
||||
interface ListedFile {
|
||||
readonly name: string;
|
||||
readonly size: number;
|
||||
readonly modifiedAt: string;
|
||||
}
|
||||
|
||||
export async function openLogsFolder(): Promise<void> {
|
||||
const path = launcherLogFolder();
|
||||
try {
|
||||
@@ -61,7 +45,6 @@ export async function exportDiagnostics(window: BrowserWindow | null): Promise<{
|
||||
const [record, settings] = await Promise.all([readInstallRecord(), getSettings()]);
|
||||
const dataPath = (settings.developerMode ? settings.labDataPath : null) ?? record?.dataPath;
|
||||
if (dataPath) await addServerLogs(files, dataPath);
|
||||
if (record) await addClientLogs(files, record, settings.loggingEnabled);
|
||||
|
||||
const temporary = `${result.filePath}.${randomUUID()}.tmp`;
|
||||
try {
|
||||
@@ -90,173 +73,6 @@ async function addServerLogs(files: ArchiveFiles, dataPath: string): Promise<voi
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Include the hook library log, the latest game .clog and embedded browser log, and a small
|
||||
* metadata summary for the active client so crashes and web-UI issues can be diagnosed without
|
||||
* touching player saves.
|
||||
*/
|
||||
async function addClientLogs(files: ArchiveFiles, record: InstallRecord, loggingEnabled: boolean): Promise<void> {
|
||||
const exeFolder = join(record.copyPath, dirname(GAME_FILES.executable));
|
||||
const hookLogPath = join(exeFolder, HOOK_LOG_FILENAME);
|
||||
const hookConfigPath = join(exeFolder, HOOK_CONFIG_FILENAME);
|
||||
const gameLogsFolder = join(record.copyPath, '.game_logs');
|
||||
|
||||
const [hookLogStat, hookConfigStat] = await Promise.all([
|
||||
readRegularFileStat(hookLogPath),
|
||||
readRegularFileStat(hookConfigPath),
|
||||
]);
|
||||
|
||||
let hookLogIncluded = false;
|
||||
let hookLogOmittedReason: string | null = null;
|
||||
if (hookLogStat) {
|
||||
const added = await addBoundedClientFile(files, `client-logs/${HOOK_LOG_FILENAME}`, hookLogPath, hookLogStat.size);
|
||||
hookLogIncluded = added.included;
|
||||
hookLogOmittedReason = added.omittedReason;
|
||||
}
|
||||
|
||||
const recentGameLogs: ListedFile[] = [];
|
||||
let latestClog: ListedFile | null = null;
|
||||
let latestClogIncluded = false;
|
||||
let latestClogOmittedReason: string | null = null;
|
||||
let latestBrowserLog: ListedFile | null = null;
|
||||
let latestBrowserLogIncluded = false;
|
||||
let latestBrowserLogOmittedReason: string | null = null;
|
||||
|
||||
const gameLogsDirStat = await safeStat(gameLogsFolder);
|
||||
if (gameLogsDirStat?.isDirectory()) {
|
||||
const entries = await safeReadDir(gameLogsFolder);
|
||||
const inspected: Array<ListedFile & { readonly mtimeMs: number }> = [];
|
||||
for (const entry of entries) {
|
||||
if (!entry.isFile()) continue;
|
||||
const stats = await readRegularFileStat(join(gameLogsFolder, entry.name));
|
||||
if (!stats) continue;
|
||||
inspected.push({
|
||||
name: entry.name,
|
||||
size: stats.size,
|
||||
modifiedAt: new Date(stats.mtimeMs).toISOString(),
|
||||
mtimeMs: stats.mtimeMs,
|
||||
});
|
||||
}
|
||||
inspected.sort((left, right) => right.mtimeMs - left.mtimeMs);
|
||||
for (const item of inspected.slice(0, RECENT_GAME_LOGS_LIMIT)) {
|
||||
recentGameLogs.push({ name: item.name, size: item.size, modifiedAt: item.modifiedAt });
|
||||
}
|
||||
const newestClog = inspected.find((item) => item.name.toLowerCase().endsWith('.clog')) ?? null;
|
||||
if (newestClog) {
|
||||
latestClog = { name: newestClog.name, size: newestClog.size, modifiedAt: newestClog.modifiedAt };
|
||||
const added = await addBoundedClientFile(
|
||||
files,
|
||||
`client-logs/game-logs/${newestClog.name}`,
|
||||
join(gameLogsFolder, newestClog.name),
|
||||
newestClog.size,
|
||||
);
|
||||
latestClogIncluded = added.included;
|
||||
latestClogOmittedReason = added.omittedReason;
|
||||
}
|
||||
const newestBrowserLog = inspected.find((item) => item.name.toLowerCase().endsWith('-browser.log')) ?? null;
|
||||
if (newestBrowserLog) {
|
||||
latestBrowserLog = {
|
||||
name: newestBrowserLog.name,
|
||||
size: newestBrowserLog.size,
|
||||
modifiedAt: newestBrowserLog.modifiedAt,
|
||||
};
|
||||
const added = await addBoundedClientFile(
|
||||
files,
|
||||
`client-logs/game-logs/${newestBrowserLog.name}`,
|
||||
join(gameLogsFolder, newestBrowserLog.name),
|
||||
newestBrowserLog.size,
|
||||
);
|
||||
latestBrowserLogIncluded = added.included;
|
||||
latestBrowserLogOmittedReason = added.omittedReason;
|
||||
}
|
||||
}
|
||||
|
||||
const summary = {
|
||||
exportedAt: new Date().toISOString(),
|
||||
launcherVersion: app.getVersion(),
|
||||
loggingEnabled,
|
||||
platform: process.platform,
|
||||
arch: process.arch,
|
||||
osRelease: release(),
|
||||
copyId: record.id,
|
||||
gameVersion: record.gameVersion,
|
||||
hookConfig: hookConfigStat
|
||||
? { present: true, size: hookConfigStat.size, modifiedAt: new Date(hookConfigStat.mtimeMs).toISOString() }
|
||||
: { present: false },
|
||||
hookLog: hookLogStat
|
||||
? {
|
||||
present: true,
|
||||
size: hookLogStat.size,
|
||||
modifiedAt: new Date(hookLogStat.mtimeMs).toISOString(),
|
||||
included: hookLogIncluded,
|
||||
...(hookLogOmittedReason ? { omittedReason: hookLogOmittedReason } : {}),
|
||||
}
|
||||
: { present: false },
|
||||
gameLogsFolderPresent: gameLogsDirStat?.isDirectory() ?? false,
|
||||
recentGameLogs,
|
||||
latestClog: latestClog
|
||||
? {
|
||||
...latestClog,
|
||||
included: latestClogIncluded,
|
||||
...(latestClogOmittedReason ? { omittedReason: latestClogOmittedReason } : {}),
|
||||
}
|
||||
: null,
|
||||
latestBrowserLog: latestBrowserLog
|
||||
? {
|
||||
...latestBrowserLog,
|
||||
included: latestBrowserLogIncluded,
|
||||
...(latestBrowserLogOmittedReason ? { omittedReason: latestBrowserLogOmittedReason } : {}),
|
||||
}
|
||||
: null,
|
||||
};
|
||||
files['client-logs/summary.json'] = new TextEncoder().encode(`${JSON.stringify(summary, null, 2)}\n`);
|
||||
}
|
||||
|
||||
async function addBoundedClientFile(
|
||||
files: ArchiveFiles,
|
||||
entry: string,
|
||||
path: string,
|
||||
size: number,
|
||||
): Promise<{ readonly included: boolean; readonly omittedReason: string | null }> {
|
||||
if (size > MAX_CLIENT_LOG_BYTES) return { included: false, omittedReason: 'too-large' };
|
||||
try {
|
||||
const bytes = await readFile(path);
|
||||
if (bytes.byteLength > MAX_CLIENT_LOG_BYTES) return { included: false, omittedReason: 'too-large' };
|
||||
files[entry] = bytes;
|
||||
return { included: true, omittedReason: null };
|
||||
} catch (error) {
|
||||
console.warn('[diagnostics] could not read client log:', path, error);
|
||||
return { included: false, omittedReason: 'unreadable' };
|
||||
}
|
||||
}
|
||||
|
||||
async function readRegularFileStat(path: string) {
|
||||
const stats = await safeStat(path);
|
||||
return stats?.isFile() ? stats : null;
|
||||
}
|
||||
|
||||
async function safeStat(path: string) {
|
||||
try {
|
||||
return await lstat(path);
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
|
||||
console.warn('[diagnostics] could not inspect path:', path, error);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function safeReadDir(path: string) {
|
||||
try {
|
||||
return await readdir(path, { withFileTypes: true });
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
|
||||
console.warn('[diagnostics] could not read folder:', path, error);
|
||||
}
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
async function addFile(files: ArchiveFiles, entry: string, path: string): Promise<void> {
|
||||
if (!(await ifPresent(() => lstat(path)))?.isFile()) return;
|
||||
const bytes = await ifPresent(() => readFile(path));
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Console } from 'node:console';
|
||||
import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
|
||||
import { appendFileSync, existsSync, mkdirSync, renameSync, writeFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { Writable } from 'node:stream';
|
||||
import { app } from 'electron';
|
||||
@@ -12,26 +12,13 @@ export const LAUNCHER_LOG_FILES = [
|
||||
'launcher.4.log',
|
||||
] as const;
|
||||
|
||||
let loggingEnabled = true;
|
||||
let activeLogPath: string | null = null;
|
||||
let fileFailed = false;
|
||||
let originalConsole = console;
|
||||
|
||||
export function launcherLogFolder(): string {
|
||||
return join(app.getPath('userData'), 'logs');
|
||||
}
|
||||
|
||||
function readInitialLoggingEnabled(): boolean {
|
||||
try {
|
||||
const raw = JSON.parse(readFileSync(join(app.getPath('userData'), 'settings.json'), 'utf8')) as { loggingEnabled?: unknown };
|
||||
return raw?.loggingEnabled !== false;
|
||||
} catch {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
function ensureLogFileReady(): boolean {
|
||||
if (activeLogPath) return !fileFailed;
|
||||
/** Rotate after taking the single-instance lock and keep the original console destinations. */
|
||||
export function startLauncherLogging(): void {
|
||||
const originalConsole = console;
|
||||
const folder = launcherLogFolder();
|
||||
const active = join(folder, LAUNCHER_LOG_FILES[0]);
|
||||
try {
|
||||
@@ -41,37 +28,17 @@ function ensureLogFileReady(): boolean {
|
||||
if (existsSync(previous)) renameSync(previous, join(folder, LAUNCHER_LOG_FILES[index]!));
|
||||
}
|
||||
writeFileSync(active, '', { flag: 'wx' });
|
||||
activeLogPath = active;
|
||||
fileFailed = false;
|
||||
return true;
|
||||
} catch (error) {
|
||||
fileFailed = true;
|
||||
originalConsole.error('[logs] opening the launcher log failed:', error);
|
||||
return false;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
/** Enable or disable writing launcher console output to launcher.log at runtime. */
|
||||
export function setLauncherLoggingEnabled(enabled: boolean): void {
|
||||
loggingEnabled = enabled;
|
||||
if (enabled && !activeLogPath && !fileFailed) {
|
||||
if (ensureLogFileReady()) {
|
||||
console.info(`WTOffline Launcher ${app.getVersion()} logging enabled.`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Rotate after taking the single-instance lock and keep the original console destinations. */
|
||||
export function startLauncherLogging(): void {
|
||||
originalConsole = console;
|
||||
loggingEnabled = readInitialLoggingEnabled();
|
||||
if (loggingEnabled) ensureLogFileReady();
|
||||
|
||||
let fileFailed = false;
|
||||
const mirror = (destination: NodeJS.WriteStream, stream: string): Writable => new Writable({
|
||||
write(chunk: Buffer, _encoding, done) {
|
||||
if (loggingEnabled && activeLogPath && !fileFailed) {
|
||||
if (!fileFailed) {
|
||||
try {
|
||||
appendFileSync(activeLogPath, `${new Date().toISOString()} [${stream}] ${chunk.toString('utf8')}`);
|
||||
appendFileSync(active, `${new Date().toISOString()} [${stream}] ${chunk.toString('utf8')}`);
|
||||
} catch (error) {
|
||||
fileFailed = true;
|
||||
originalConsole.error('[logs] writing the launcher log failed:', error);
|
||||
|
||||
@@ -1,11 +1,26 @@
|
||||
import { isHardlinkableResource } from '@wto/patcher';
|
||||
import { lstat, readdir } from 'node:fs/promises';
|
||||
import { join } from 'node:path';
|
||||
import type { FolderSize } from '@shared/schemas/install.ts';
|
||||
import { planCopy } from '../install/copy-game.ts';
|
||||
|
||||
/** Estimate the installation size and the bytes eligible for space-saving hard links. */
|
||||
/**
|
||||
* The size of a folder tree, counted the way the copy will copy it: regular files only. Links
|
||||
* and junctions are not followed. Asynchronous, so the window stays responsive on a large
|
||||
* installation.
|
||||
*/
|
||||
export async function measureFolder(root: string): Promise<FolderSize> {
|
||||
const plan = await planCopy(root);
|
||||
const linkableBytes = plan.files.reduce((total, file) =>
|
||||
total + (isHardlinkableResource(file.relativePath, file.bytes) ? file.bytes : 0), 0);
|
||||
return { bytes: plan.totalBytes, files: plan.files.length, linkableBytes };
|
||||
let bytes = 0;
|
||||
let files = 0;
|
||||
const pending = [root];
|
||||
while (pending.length) {
|
||||
const folder = pending.pop()!;
|
||||
for (const entry of await readdir(folder, { withFileTypes: true })) {
|
||||
const path = join(folder, entry.name);
|
||||
if (entry.isDirectory()) pending.push(path);
|
||||
else if (entry.isFile()) {
|
||||
bytes += (await lstat(path)).size;
|
||||
files += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
return { bytes, files };
|
||||
}
|
||||
@@ -1,90 +1,34 @@
|
||||
import { access, readFile, realpath, stat } from 'node:fs/promises';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { access, readFile, stat } from 'node:fs/promises';
|
||||
import { join } from 'node:path';
|
||||
import { executableVersion, GAME_FILES, isInSteamLibrary, recordedGameVersions } from '@wto/patcher';
|
||||
import { AppError } from '@shared/errors.ts';
|
||||
import type { GameFolderInspection } from '@shared/schemas/install.ts';
|
||||
import { STOCK_BACKUP_FOLDER } from '../install/stock-backup.ts';
|
||||
import { resourcePaths } from '../resources/resource-paths.ts';
|
||||
|
||||
const PATCH_MARKER_FILES = ['wto_ws.dll', 'wto_ws.cfg'] as const;
|
||||
const PATCHED_EXE_MARKER = Buffer.from('wto_ws.dll', 'ascii');
|
||||
|
||||
/**
|
||||
* Look at a folder the player chose as their War Thunder installation: is it one, which version,
|
||||
* whether it already has an offline stock backup, whether it is already patched without one,
|
||||
* and whether it is inside a Steam library. Only reads.
|
||||
* and is it a Steam library. Only reads.
|
||||
*/
|
||||
export async function inspectGameFolder(path: string): Promise<GameFolderInspection> {
|
||||
await requireFolder(path);
|
||||
const resolved = await realpath(path);
|
||||
const required = Object.values(GAME_FILES);
|
||||
const missingFiles: string[] = [];
|
||||
for (const file of required) {
|
||||
if (!(await exists(join(resolved, file)))) missingFiles.push(file);
|
||||
}
|
||||
const stockRoot = join(resolved, STOCK_BACKUP_FOLDER);
|
||||
let hasStockFiles = true;
|
||||
for (const file of required) {
|
||||
if (!(await exists(join(stockRoot, file)))) {
|
||||
hasStockFiles = false;
|
||||
break;
|
||||
}
|
||||
if (!(await exists(join(path, file)))) missingFiles.push(file);
|
||||
}
|
||||
const resources = resourcePaths();
|
||||
const liveExeBytes = missingFiles.includes(GAME_FILES.executable)
|
||||
? null
|
||||
: await readBytes(join(resolved, GAME_FILES.executable));
|
||||
const liveVersion = liveExeBytes ? readVersionFromBytes(liveExeBytes) : null;
|
||||
const backupExeBytes = hasStockFiles
|
||||
? await readBytes(join(stockRoot, GAME_FILES.executable))
|
||||
: null;
|
||||
const backupVersion = backupExeBytes ? readVersionFromBytes(backupExeBytes) : null;
|
||||
|
||||
// Always report the live executable's version when readable so an externally updated client
|
||||
// (for example, an in-place folder updated by the official launcher) is never masked by a stale
|
||||
// wtoffline/stock backup.
|
||||
const version = liveVersion ?? backupVersion;
|
||||
const hasOfflineBackup = hasStockFiles && backupVersion !== null && (liveVersion === null || backupVersion === liveVersion);
|
||||
const liveExePatched = liveExeBytes !== null && liveExeBytes.includes(PATCHED_EXE_MARKER);
|
||||
|
||||
let needsStockSource = false;
|
||||
if (!hasOfflineBackup && missingFiles.length === 0) {
|
||||
if (hasStockFiles && backupVersion !== null && liveVersion !== null && backupVersion !== liveVersion) {
|
||||
// A stale stock backup only needs an external stock source if the live executable is already
|
||||
// patched; an unpatched live executable can refresh wtoffline/stock directly during install.
|
||||
needsStockSource = liveExePatched;
|
||||
} else {
|
||||
const exeDir = join(resolved, dirname(GAME_FILES.executable));
|
||||
const hasMarkerFile = (await Promise.all(
|
||||
PATCH_MARKER_FILES.map((file) => exists(join(exeDir, file))),
|
||||
)).some(Boolean);
|
||||
needsStockSource = hasMarkerFile || liveExePatched;
|
||||
}
|
||||
}
|
||||
return {
|
||||
path,
|
||||
resolvedPath: resolved,
|
||||
missingFiles,
|
||||
version,
|
||||
version: missingFiles.includes(GAME_FILES.executable) ? null : await readVersion(join(path, GAME_FILES.executable)),
|
||||
verifiedVersions: recordedGameVersions(resources.patches),
|
||||
inSteamLibrary: isInSteamLibrary(path) || isInSteamLibrary(resolved),
|
||||
hasOfflineBackup,
|
||||
needsStockSource,
|
||||
inSteamLibrary: isInSteamLibrary(path),
|
||||
};
|
||||
}
|
||||
|
||||
async function readBytes(filePath: string): Promise<Buffer | null> {
|
||||
async function readVersion(executablePath: string): Promise<string | null> {
|
||||
try {
|
||||
return await readFile(filePath);
|
||||
} catch (error) {
|
||||
console.warn('[game-folder] reading the executable failed:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function readVersionFromBytes(bytes: Buffer): string | null {
|
||||
try {
|
||||
return executableVersion(bytes);
|
||||
return executableVersion(await readFile(executablePath));
|
||||
} catch (error) {
|
||||
// Not a PE file, or unreadable: the folder is then not a usable installation, which the
|
||||
// missing version already says.
|
||||
|
||||
@@ -1,99 +1,24 @@
|
||||
import { readdir, stat, statfs } from 'node:fs/promises';
|
||||
import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';
|
||||
import { readdir, realpath, stat, statfs } from 'node:fs/promises';
|
||||
import { dirname, parse, relative, resolve, isAbsolute } from 'node:path';
|
||||
import { isInSteamLibrary } from '@wto/patcher';
|
||||
import type { TargetFolderInspection } from '@shared/schemas/install.ts';
|
||||
import { canonicalCopyPath, listCopies } from '../install/install-record.ts';
|
||||
|
||||
const DEFAULT_SUBFOLDER = 'WTOffline';
|
||||
const SUBFOLDER_PATTERN = /^wtoffline(?:[-_].+)?$/i;
|
||||
const MAX_DUPLICATE_SUFFIX = 99;
|
||||
|
||||
/**
|
||||
* Look at the exact folder for the game copy (install by copying): it must be new or
|
||||
* Look at the folder the player chose for the game copy (install by copying): it must be new or
|
||||
* empty, must not overlap the stock installation, and the drive must have room. Only reads.
|
||||
*/
|
||||
export async function inspectTargetFolder(path: string, stockPath: string): Promise<TargetFolderInspection> {
|
||||
const [target, stock] = await Promise.all([canonicalCopyPath(path), canonicalCopyPath(stockPath)]);
|
||||
const target = await canonical(path);
|
||||
const stock = await canonical(stockPath);
|
||||
return {
|
||||
path,
|
||||
resolvedPath: target,
|
||||
problem: await targetProblem(target, stock),
|
||||
inSteamLibrary: isInSteamLibrary(path) || isInSteamLibrary(target),
|
||||
inSteamLibrary: isInSteamLibrary(target),
|
||||
freeBytes: await freeBytes(target),
|
||||
sameDriveAsStock: await sameVolume(target, stock),
|
||||
sameDriveAsStock: parse(target).root.toLowerCase() === parse(stock).root.toLowerCase(),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a player-picked parent folder into a dedicated `WTOffline` subfolder (falling back to
|
||||
* `WTOffline-<version>` and `WTOffline-2`, `WTOffline-3`, ... when an earlier folder already has
|
||||
* files or is registered), unless the picked folder is already an empty `WTOffline*` directory.
|
||||
*/
|
||||
export async function inspectPickedTargetFolder(
|
||||
pickedPath: string,
|
||||
stockPath: string,
|
||||
version: string | null,
|
||||
): Promise<TargetFolderInspection> {
|
||||
const [picked, stock] = await Promise.all([canonicalCopyPath(pickedPath), canonicalCopyPath(stockPath)]);
|
||||
if (contains(stock, picked) || contains(picked, stock)) {
|
||||
return inspectTargetFolder(pickedPath, stockPath);
|
||||
}
|
||||
try {
|
||||
const info = await stat(picked);
|
||||
if (!info.isDirectory()) return inspectTargetFolder(pickedPath, stockPath);
|
||||
} catch {
|
||||
// Picked folder does not exist yet; still check it directly if it already looks like WTOffline*.
|
||||
}
|
||||
|
||||
const registered = await registeredCopyPaths();
|
||||
if (SUBFOLDER_PATTERN.test(basename(pickedPath)) && !registered.has(picked.toLowerCase())) {
|
||||
const directProblem = await targetProblem(picked, stock);
|
||||
if (directProblem === null) return inspectTargetFolder(pickedPath, stockPath);
|
||||
}
|
||||
|
||||
const candidateNames = [DEFAULT_SUBFOLDER];
|
||||
const safeVersion = version?.replace(/[^0-9A-Za-z._-]/g, '').trim();
|
||||
if (safeVersion) candidateNames.push(`${DEFAULT_SUBFOLDER}-${safeVersion}`);
|
||||
for (let i = 2; i <= MAX_DUPLICATE_SUFFIX; i += 1) {
|
||||
candidateNames.push(`${DEFAULT_SUBFOLDER}-${i}`);
|
||||
}
|
||||
|
||||
for (const name of candidateNames) {
|
||||
const candidate = join(pickedPath, name);
|
||||
const resolvedCandidate = await canonicalCopyPath(candidate);
|
||||
if (registered.has(resolvedCandidate.toLowerCase())) continue;
|
||||
const problem = await targetProblem(resolvedCandidate, stock);
|
||||
if (problem === null) return inspectTargetFolder(candidate, stockPath);
|
||||
}
|
||||
return inspectTargetFolder(join(pickedPath, DEFAULT_SUBFOLDER), stockPath);
|
||||
}
|
||||
|
||||
async function registeredCopyPaths(): Promise<Set<string>> {
|
||||
try {
|
||||
const { copies } = await listCopies();
|
||||
const resolved = await Promise.all(copies.map((entry) => canonicalCopyPath(entry.copyPath).catch(() => entry.copyPath)));
|
||||
return new Set(resolved.map((folder) => folder.toLowerCase()));
|
||||
} catch {
|
||||
return new Set();
|
||||
}
|
||||
}
|
||||
|
||||
/** Compare actual volumes, including directories reached through junctions. */
|
||||
export async function sameVolume(left: string, right: string): Promise<boolean> {
|
||||
const [first, second] = await Promise.all([volumeDevice(left), volumeDevice(right)]);
|
||||
return first !== null && first === second;
|
||||
}
|
||||
|
||||
async function volumeDevice(path: string): Promise<bigint | null> {
|
||||
for (let folder = resolve(path); ; folder = dirname(folder)) {
|
||||
try {
|
||||
return (await stat(folder, { bigint: true })).dev || null;
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code !== 'ENOENT' || dirname(folder) === folder) return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function targetProblem(target: string, stock: string): Promise<TargetFolderInspection['problem']> {
|
||||
if (contains(stock, target) || contains(target, stock)) return 'overlaps_stock';
|
||||
let entries: string[];
|
||||
@@ -114,7 +39,7 @@ function contains(outer: string, inner: string): boolean {
|
||||
}
|
||||
|
||||
/** Free bytes on the drive of the nearest existing folder at or above `path`. */
|
||||
export async function freeBytes(path: string): Promise<number | null> {
|
||||
async function freeBytes(path: string): Promise<number | null> {
|
||||
for (let folder = path; ; folder = dirname(folder)) {
|
||||
try {
|
||||
const info = await statfs(folder);
|
||||
@@ -124,3 +49,15 @@ export async function freeBytes(path: string): Promise<number | null> {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The real path of the nearest existing part, with the rest appended as given. */
|
||||
async function canonical(path: string): Promise<string> {
|
||||
const absolute = resolve(path);
|
||||
try {
|
||||
return await realpath(absolute);
|
||||
} catch {
|
||||
const parent = dirname(absolute);
|
||||
if (parent === absolute) return absolute;
|
||||
return resolve(await canonical(parent), relative(parent, absolute));
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,8 @@
|
||||
import { createReadStream, createWriteStream, type BigIntStats } from 'node:fs';
|
||||
import { createReadStream, createWriteStream } from 'node:fs';
|
||||
import { lstat, mkdir, readdir, rm, utimes } from 'node:fs/promises';
|
||||
import { join, relative } from 'node:path';
|
||||
import { Transform } from 'node:stream';
|
||||
import { pipeline } from 'node:stream/promises';
|
||||
import { AppError } from '@shared/errors.ts';
|
||||
import { linkVerifiedResource, sameResource } from './hardlink-files.ts';
|
||||
|
||||
/**
|
||||
* Copy a War Thunder installation into a new or empty folder (install method "copy"). The stock
|
||||
@@ -17,9 +15,7 @@ import { linkVerifiedResource, sameResource } from './hardlink-files.ts';
|
||||
* own missions. The offline copy does not take the online game's data (working rules 18); the
|
||||
* game creates these folders again when it needs them.
|
||||
*/
|
||||
export const PLAYER_DATA_FOLDERS = new Set(['.game_logs', 'cache', 'replays', 'screenshots', 'usermissions']);
|
||||
/** Top-level folders ignored when scanning a stock source, including any stray offline backup directory. */
|
||||
const SKIPPED_SOURCE_FOLDERS = new Set([...PLAYER_DATA_FOLDERS, 'wtoffline']);
|
||||
const PLAYER_DATA_FOLDERS = new Set(['.game_logs', 'cache', 'replays', 'screenshots', 'usermissions']);
|
||||
|
||||
interface CopyEntry {
|
||||
readonly relativePath: string;
|
||||
@@ -48,7 +44,7 @@ export async function planCopy(source: string): Promise<CopyPlan> {
|
||||
const folder = pending.pop()!;
|
||||
for (const entry of await readdir(folder, { withFileTypes: true })) {
|
||||
const path = join(folder, entry.name);
|
||||
if (folder === source && SKIPPED_SOURCE_FOLDERS.has(entry.name.toLowerCase())) continue;
|
||||
if (folder === source && PLAYER_DATA_FOLDERS.has(entry.name.toLowerCase())) continue;
|
||||
if (entry.isDirectory()) {
|
||||
folders.push(relative(source, path));
|
||||
pending.push(path);
|
||||
@@ -76,11 +72,9 @@ export async function copyPlannedFiles(
|
||||
plan: CopyPlan,
|
||||
signal: AbortSignal,
|
||||
onProgress: (progress: CopyProgress) => void,
|
||||
hardlinks?: ReadonlyMap<string, BigIntStats>,
|
||||
): Promise<void> {
|
||||
await mkdir(target, { recursive: true });
|
||||
for (const folder of plan.folders) await mkdir(join(target, folder), { recursive: true });
|
||||
const linkedTargets = hardlinks ? new Map<string, BigIntStats>() : undefined;
|
||||
let next = 0;
|
||||
let doneBytes = 0;
|
||||
let doneFiles = 0;
|
||||
@@ -100,24 +94,15 @@ export async function copyPlannedFiles(
|
||||
while (next < plan.files.length) {
|
||||
stopSignal.throwIfAborted();
|
||||
const file = plan.files[next++]!;
|
||||
const from = join(source, file.relativePath);
|
||||
const to = join(target, file.relativePath);
|
||||
const verified = hardlinks?.get(file.relativePath);
|
||||
if (verified) {
|
||||
const linked = await linkVerifiedResource(from, to, verified);
|
||||
linkedTargets?.set(to, linked);
|
||||
doneBytes += file.bytes;
|
||||
} else {
|
||||
await pipeline(
|
||||
createReadStream(from),
|
||||
countBytes(),
|
||||
// 'wx': fail instead of overwriting a file that is already there.
|
||||
createWriteStream(to, { flags: 'wx' }),
|
||||
{ signal: stopSignal },
|
||||
);
|
||||
const modified = new Date(file.modifiedAt);
|
||||
await utimes(to, modified, modified);
|
||||
}
|
||||
await pipeline(
|
||||
createReadStream(join(source, file.relativePath)),
|
||||
countBytes(),
|
||||
// 'wx': fail instead of overwriting a file that is already there.
|
||||
createWriteStream(join(target, file.relativePath), { flags: 'wx' }),
|
||||
{ signal: stopSignal },
|
||||
);
|
||||
const modified = new Date(file.modifiedAt);
|
||||
await utimes(join(target, file.relativePath), modified, modified);
|
||||
doneFiles += 1;
|
||||
onProgress({ doneBytes, doneFiles });
|
||||
}
|
||||
@@ -129,12 +114,6 @@ export async function copyPlannedFiles(
|
||||
const results = await Promise.allSettled(Array.from({ length: PARALLEL_COPIES }, copyNext));
|
||||
const failed = results.find((result): result is PromiseRejectedResult => result.status === 'rejected');
|
||||
if (failed) throw failed.reason;
|
||||
if (linkedTargets) {
|
||||
for (const [path, stamp] of linkedTargets) {
|
||||
signal.throwIfAborted();
|
||||
if (!sameResource(stamp, await lstat(path, { bigint: true }))) throw new AppError('hardlink_file_changed');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
import { readdir } from 'node:fs/promises';
|
||||
import { join } from 'node:path';
|
||||
import { AppError } from '@shared/errors.ts';
|
||||
|
||||
/** A data tree must keep the server's saves, logs and caches inside the selected folder. */
|
||||
export async function requireUnredirectedData(root: string): Promise<void> {
|
||||
const folders = [root];
|
||||
for (let folder = folders.pop(); folder !== undefined; folder = folders.pop()) {
|
||||
const entries = await readdir(folder, { withFileTypes: true }).catch((error: NodeJS.ErrnoException) => {
|
||||
if (folder === root && error.code === 'ENOENT') return [];
|
||||
throw error;
|
||||
});
|
||||
for (const entry of entries) {
|
||||
if (entry.isSymbolicLink()) throw new AppError('launch_location');
|
||||
if (entry.isDirectory()) folders.push(join(folder, entry.name));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,122 +0,0 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { cp, lstat, mkdir, realpath, rm } from 'node:fs/promises';
|
||||
import { dirname, isAbsolute, join, relative } from 'node:path';
|
||||
import {
|
||||
isInSteamLibrary,
|
||||
playerDecalCacheProblem,
|
||||
resolvePlayerDecalCacheFolder,
|
||||
writeDecalCacheIndexSnapshot,
|
||||
} from '@wto/patcher';
|
||||
import { AppError } from '@shared/errors.ts';
|
||||
import type { Copies } from '@shared/schemas/install.ts';
|
||||
import { canonicalCopyPath, copyPathContains, listCopies, steamLibraryNeedsConfirmation, updateCopyRecord } from './install-record.ts';
|
||||
|
||||
const CACHE_FOLDER = 'decal-cache';
|
||||
let changing = false;
|
||||
|
||||
export function decalImportInProgress(): boolean {
|
||||
return changing;
|
||||
}
|
||||
|
||||
export function decalCachePath(dataPath: string, cacheId: string): string {
|
||||
return join(dataPath, CACHE_FOLDER, cacheId);
|
||||
}
|
||||
|
||||
async function cacheRoot(dataPath: string, steamDataConfirmed: boolean): Promise<string> {
|
||||
if (!isAbsolute(dataPath)) throw new AppError('decal_import_failed');
|
||||
const data = await canonicalCopyPath(dataPath);
|
||||
const root = join(data, CACHE_FOLDER);
|
||||
if ((isInSteamLibrary(data) && (!steamDataConfirmed || relative(dataPath, data) !== '')) ||
|
||||
relative(root, await canonicalCopyPath(root)) !== '') {
|
||||
throw new AppError('decal_import_failed');
|
||||
}
|
||||
return root;
|
||||
}
|
||||
|
||||
/** Import the selected cache as its own snapshot so a later build can use the copy's data alone. */
|
||||
export async function importDecalCache(
|
||||
dataPath: string, sourcePath: string, signal?: AbortSignal, steamDataConfirmed = false,
|
||||
): Promise<string> {
|
||||
if (!isAbsolute(sourcePath)) throw new AppError('decal_source_invalid');
|
||||
const rawSource = await realpath(sourcePath).catch(() => null);
|
||||
const source = rawSource ? await realpath(resolvePlayerDecalCacheFolder(rawSource)).catch(() => null) : null;
|
||||
const problem = source ? playerDecalCacheProblem(source) : 'selected folder could not be resolved';
|
||||
if (!source || problem) {
|
||||
console.warn('[decals] invalid decal cache source:', sourcePath, '->', problem);
|
||||
throw new AppError('decal_source_invalid');
|
||||
}
|
||||
|
||||
const root = await cacheRoot(dataPath, steamDataConfirmed);
|
||||
if (copyPathContains(source, root) || copyPathContains(root, source)) {
|
||||
throw new AppError('decal_source_invalid');
|
||||
}
|
||||
const id = randomUUID();
|
||||
const target = join(root, id);
|
||||
try {
|
||||
await mkdir(root, { recursive: true });
|
||||
await cp(source, target, {
|
||||
recursive: true,
|
||||
force: false,
|
||||
errorOnExist: true,
|
||||
filter: async (path) => {
|
||||
signal?.throwIfAborted();
|
||||
const entry = await lstat(path);
|
||||
if (!entry.isDirectory() && !entry.isFile()) throw new AppError('decal_source_invalid');
|
||||
return true;
|
||||
},
|
||||
});
|
||||
signal?.throwIfAborted();
|
||||
writeDecalCacheIndexSnapshot(source, target);
|
||||
const copiedProblem = playerDecalCacheProblem(target);
|
||||
if (copiedProblem) {
|
||||
console.warn('[decals] copied decal cache failed validation:', copiedProblem);
|
||||
throw new AppError('decal_source_invalid');
|
||||
}
|
||||
return id;
|
||||
} catch (error) {
|
||||
await discardDecalCache(dataPath, id, steamDataConfirmed);
|
||||
if (signal?.aborted || error instanceof AppError) throw error;
|
||||
console.error('[decals] could not import the cache:', error);
|
||||
throw new AppError('decal_import_failed');
|
||||
}
|
||||
}
|
||||
|
||||
export async function discardDecalCache(dataPath: string, id: string, steamDataConfirmed = false): Promise<void> {
|
||||
try {
|
||||
const root = await cacheRoot(dataPath, steamDataConfirmed);
|
||||
const target = decalCachePath(dataPath, id);
|
||||
const actual = await realpath(target).catch(() => null);
|
||||
if (actual && relative(root, dirname(actual)) === '' && relative(join(root, id), actual) === '') {
|
||||
await rm(actual, { recursive: true, force: true });
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('[decals] could not remove the replaced cache:', error);
|
||||
}
|
||||
}
|
||||
|
||||
export async function changeDecalSource(id: string, source: string | null): Promise<Copies> {
|
||||
if (changing) throw new AppError('maintenance_busy');
|
||||
changing = true;
|
||||
try {
|
||||
const record = (await listCopies()).copies.find((copy) => copy.id === id);
|
||||
if (!record) throw new AppError('copy_not_found');
|
||||
const [copyPath, dataPath] = await Promise.all([canonicalCopyPath(record.copyPath), canonicalCopyPath(record.dataPath)]);
|
||||
if (steamLibraryNeedsConfirmation(record, copyPath, dataPath)) throw new AppError('launch_steam_confirmation_required');
|
||||
const dataInSteam = isInSteamLibrary(dataPath);
|
||||
const cacheId = source === null ? undefined : await importDecalCache(dataPath, source, undefined, dataInSteam);
|
||||
let copies: Copies;
|
||||
try {
|
||||
copies = await updateCopyRecord(id, (current) => {
|
||||
const { decalCacheId, ...other } = current;
|
||||
return cacheId === undefined ? other : { ...other, decalCacheId: cacheId };
|
||||
});
|
||||
} catch (error) {
|
||||
if (cacheId) await discardDecalCache(dataPath, cacheId, dataInSteam);
|
||||
throw error;
|
||||
}
|
||||
if (record.decalCacheId) await discardDecalCache(dataPath, record.decalCacheId, dataInSteam);
|
||||
return copies;
|
||||
} finally {
|
||||
changing = false;
|
||||
}
|
||||
}
|
||||
@@ -1,85 +0,0 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { createReadStream, type BigIntStats } from 'node:fs';
|
||||
import { link, lstat } from 'node:fs/promises';
|
||||
import { AppError } from '@shared/errors.ts';
|
||||
|
||||
export type ResourceMatchResult =
|
||||
| { readonly status: 'already-linked'; readonly copyStamp: BigIntStats; readonly sourceStamp: BigIntStats }
|
||||
| { readonly status: 'matched'; readonly copyStamp: BigIntStats; readonly sourceStamp: BigIntStats }
|
||||
| { readonly status: 'mismatch' };
|
||||
|
||||
export async function fileHash(path: string, signal: AbortSignal): Promise<string> {
|
||||
const hash = createHash('sha256');
|
||||
for await (const chunk of createReadStream(path, { signal })) hash.update(chunk as Buffer);
|
||||
return hash.digest('hex');
|
||||
}
|
||||
|
||||
export async function statFile(path: string): Promise<BigIntStats | null> {
|
||||
return lstat(path, { bigint: true }).catch((error: NodeJS.ErrnoException) => {
|
||||
if (error.code === 'ENOENT') return null;
|
||||
throw error;
|
||||
});
|
||||
}
|
||||
|
||||
/** Capture the file identity of a stock asset right before hardlinking it. */
|
||||
export async function statHardlinkResource(
|
||||
path: string,
|
||||
expectedBytes: number,
|
||||
signal: AbortSignal,
|
||||
): Promise<BigIntStats | null> {
|
||||
signal.throwIfAborted();
|
||||
const stats = await statFile(path);
|
||||
if (!stats?.isFile() || stats.size !== BigInt(expectedBytes)) return null;
|
||||
return stats;
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify that an existing copy file and stock file have identical contents before replacing the
|
||||
* copy file with a hard link. Already-linked pairs return immediately without re-hashing.
|
||||
*/
|
||||
export async function verifyMatchingResource(
|
||||
copyPath: string,
|
||||
sourcePath: string,
|
||||
expectedBytes: number,
|
||||
signal: AbortSignal,
|
||||
): Promise<ResourceMatchResult> {
|
||||
signal.throwIfAborted();
|
||||
const [copyBefore, sourceBefore] = await Promise.all([statFile(copyPath), statFile(sourcePath)]);
|
||||
const size = BigInt(expectedBytes);
|
||||
if (!copyBefore?.isFile() || !sourceBefore?.isFile() || copyBefore.size !== size || sourceBefore.size !== size) {
|
||||
return { status: 'mismatch' };
|
||||
}
|
||||
if (sameResource(copyBefore, sourceBefore)) {
|
||||
return { status: 'already-linked', copyStamp: copyBefore, sourceStamp: sourceBefore };
|
||||
}
|
||||
const [copyHash, sourceHash] = await Promise.all([fileHash(copyPath, signal), fileHash(sourcePath, signal)]);
|
||||
const [copyAfter, sourceAfter] = await Promise.all([statFile(copyPath), statFile(sourcePath)]);
|
||||
if (!copyAfter || !sourceAfter || !sameResource(copyBefore, copyAfter) || !sameResource(sourceBefore, sourceAfter)) {
|
||||
throw new AppError('hardlink_file_changed');
|
||||
}
|
||||
return copyHash === sourceHash
|
||||
? { status: 'matched', copyStamp: copyAfter, sourceStamp: sourceAfter }
|
||||
: { status: 'mismatch' };
|
||||
}
|
||||
|
||||
export function sameInode(left: BigIntStats, right: BigIntStats): boolean {
|
||||
return left.isFile() && right.isFile() && left.dev === right.dev && left.ino === right.ino;
|
||||
}
|
||||
|
||||
export function sameResource(left: BigIntStats, right: BigIntStats): boolean {
|
||||
return sameIdentityAndContents(left, right) && left.ctimeNs === right.ctimeNs;
|
||||
}
|
||||
|
||||
export async function linkVerifiedResource(source: string, target: string, verified: BigIntStats): Promise<BigIntStats> {
|
||||
if (!sameResource(verified, await lstat(source, { bigint: true }))) throw new AppError('hardlink_file_changed');
|
||||
await link(source, target);
|
||||
// Linking may change ctime. The inode, contents and modification time must stay the same.
|
||||
const linked = await lstat(target, { bigint: true });
|
||||
if (!sameIdentityAndContents(verified, linked)) throw new AppError('hardlink_file_changed');
|
||||
return linked;
|
||||
}
|
||||
|
||||
function sameIdentityAndContents(left: BigIntStats, right: BigIntStats): boolean {
|
||||
return right.isFile() && left.dev === right.dev && left.ino === right.ino &&
|
||||
left.size === right.size && left.mtimeNs === right.mtimeNs;
|
||||
}
|
||||
@@ -1,18 +1,12 @@
|
||||
import type { BigIntStats } from 'node:fs';
|
||||
import { access, mkdir } from 'node:fs/promises';
|
||||
import { dirname, isAbsolute, join, relative } from 'node:path';
|
||||
import { isHardlinkableResource, isInSteamLibrary } from '@wto/patcher';
|
||||
import { AppError } from '@shared/errors.ts';
|
||||
import type { DataFolderProblem, InstallProgress, InstallRecord, InstallRequest, PatchCheck } from '@shared/schemas/install.ts';
|
||||
import type { InstallProgress, InstallRecord, InstallRequest, PatchCheck } from '@shared/schemas/install.ts';
|
||||
import { inspectGameFolder } from '../game-folder/inspect-game-folder.ts';
|
||||
import { freeBytes, inspectTargetFolder, sameVolume } from '../game-folder/inspect-target-folder.ts';
|
||||
import { copyPlannedFiles, planCopy, removeInterruptedCopy, type CopyPlan } from './copy-game.ts';
|
||||
import { requireUnredirectedData } from './data-location.ts';
|
||||
import { discardDecalCache, importDecalCache } from './decals.ts';
|
||||
import { statHardlinkResource } from './hardlink-files.ts';
|
||||
import { canonicalCopyPath, copyPathContains, requireAvailableCopy, writeInstallRecord } from './install-record.ts';
|
||||
import { inspectTargetFolder } from '../game-folder/inspect-target-folder.ts';
|
||||
import { copyPlannedFiles, planCopy, removeInterruptedCopy } from './copy-game.ts';
|
||||
import { requireAvailableCopy, writeInstallRecord } from './install-record.ts';
|
||||
import { checkPatches } from './patch-check.ts';
|
||||
import { backUpStockFiles, installStockSource, refreshStockBackup, refreshStockBackupFrom, requireStockBackupLocation, STOCK_BACKUP_FOLDER } from './stock-backup.ts';
|
||||
import { backUpStockFiles, stockBackupPath } from './stock-backup.ts';
|
||||
|
||||
/**
|
||||
* Install the offline version: check the patches against the player's game,
|
||||
@@ -41,9 +35,6 @@ export async function installGame(request: InstallRequest, onProgress: (progress
|
||||
running = controller;
|
||||
try {
|
||||
return await install(request, controller.signal, throttled(onProgress));
|
||||
} catch (error) {
|
||||
if (controller.signal.aborted) throw new AppError('install_cancelled');
|
||||
throw error;
|
||||
} finally {
|
||||
running = null;
|
||||
}
|
||||
@@ -56,214 +47,97 @@ export function cancelInstall(): boolean {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* The stock files a check of `gameFolder` starts from: its backup folder when it already has one
|
||||
* (a folder installed before, whose own files may be patched), otherwise its own files.
|
||||
*/
|
||||
export async function stockFolderOf(gameFolder: string): Promise<string> {
|
||||
const backup = stockBackupPath(gameFolder);
|
||||
try {
|
||||
await access(backup);
|
||||
return backup;
|
||||
} catch {
|
||||
return gameFolder;
|
||||
}
|
||||
}
|
||||
|
||||
/** Which patches fit the game in `gameFolder`, for the window to show before installing. */
|
||||
export async function checkGameFolder(gameFolder: string, dataPath: string, stockSourcePath?: string): Promise<PatchCheck> {
|
||||
const game = await requireGameFolder(gameFolder);
|
||||
const stock = stockSourcePath
|
||||
? await resolveExternalStockSource(stockSourcePath, game.version)
|
||||
: game.needsStockSource
|
||||
? (() => { throw new AppError('stock_source_invalid'); })()
|
||||
: await installStockSource(game.resolvedPath, game.version);
|
||||
const data = await canonicalCopyPath(dataPath);
|
||||
await requireUnredirectedData(data);
|
||||
return checkPatches(stock.path, data);
|
||||
export async function checkGameFolder(gameFolder: string, dataPath: string): Promise<PatchCheck> {
|
||||
await requireGameFolder(gameFolder);
|
||||
return checkPatches(await stockFolderOf(gameFolder), dataPath);
|
||||
}
|
||||
|
||||
async function install(request: InstallRequest, signal: AbortSignal, report: (progress: InstallProgress) => void): Promise<InstallRecord> {
|
||||
const { version, requestedCopyPath, copyPath, dataPath, sourcePath, externalStockPath, target, useHardLinks, copyInSteam, dataInSteam } =
|
||||
await inspectInstallation(request);
|
||||
const gameFolder = request.method === 'copy' ? request.sourcePath : request.gamePath;
|
||||
const game = await requireGameFolder(gameFolder);
|
||||
const copyPath = request.method === 'copy' ? request.copyPath : request.gamePath;
|
||||
await requireAvailableCopy(request.id, copyPath, request.dataPath);
|
||||
|
||||
const target = request.method === 'copy' ? await inspectTargetFolder(copyPath, gameFolder) : null;
|
||||
if (target?.problem) throw new AppError('target_not_usable', { problem: target.problem });
|
||||
const inSteamLibrary = target ? target.inSteamLibrary : game.inSteamLibrary;
|
||||
if (inSteamLibrary && !request.steamLibraryConfirmed) throw new AppError('steam_library_not_confirmed');
|
||||
|
||||
report({ phase: 'checking', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 });
|
||||
const stock = externalStockPath
|
||||
? { path: externalStockPath, refresh: false }
|
||||
: await installStockSource(sourcePath, version);
|
||||
await mkdir(dataPath, { recursive: true });
|
||||
const check = await checkPatches(stock.path, dataPath);
|
||||
await mkdir(request.dataPath, { recursive: true });
|
||||
const check = await checkPatches(await stockFolderOf(gameFolder), request.dataPath);
|
||||
const essential = check.unavailable.filter((patch) => patch.essential);
|
||||
if (essential.length) throw new AppError('essential_patches_unavailable', { patches: essential.map((patch) => patch.patchId).join(', ') });
|
||||
if (check.unavailable.length && !request.missingFeaturesAccepted) throw new AppError('missing_features_not_accepted');
|
||||
signal.throwIfAborted();
|
||||
|
||||
let decalCacheId: string | undefined;
|
||||
if (request.decalSourcePath) {
|
||||
report({ phase: 'importing-decals', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 });
|
||||
decalCacheId = await importDecalCache(dataPath, request.decalSourcePath, signal, dataInSteam);
|
||||
}
|
||||
try {
|
||||
const copied = request.method === 'copy'
|
||||
? await copyGame(sourcePath, copyPath, target!.freeBytes, useHardLinks, version, signal, report)
|
||||
: undefined;
|
||||
const sourceFiles = request.method === 'copy'
|
||||
? await copyGame(request.sourcePath, copyPath, target!.freeBytes, signal, report)
|
||||
: undefined;
|
||||
|
||||
report({ phase: 'backing-up', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 });
|
||||
const stockBackup = externalStockPath
|
||||
? await refreshStockBackupFrom(copyPath, externalStockPath)
|
||||
: (request.method === 'in-place' || request.method === 'existing') && stock.refresh
|
||||
? await refreshStockBackup(copyPath)
|
||||
: await backUpStockFiles(copyPath);
|
||||
report({ phase: 'backing-up', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 });
|
||||
const stockBackup = await backUpStockFiles(copyPath);
|
||||
|
||||
report({ phase: 'recording', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 });
|
||||
const record: InstallRecord = {
|
||||
id: request.id,
|
||||
name: request.name,
|
||||
sourcePath: request.method === 'copy' ? sourcePath : null,
|
||||
method: request.method,
|
||||
copyPath: requestedCopyPath,
|
||||
dataPath: request.dataPath,
|
||||
...(copyInSteam || dataInSteam ? { steamLibraryConfirmation: { copyPath, dataPath } } : {}),
|
||||
stockBackupPath: stockBackup,
|
||||
gameVersion: version,
|
||||
unavailablePatches: check.unavailable,
|
||||
installedAt: new Date().toISOString(),
|
||||
lastCheckedAt: new Date().toISOString(),
|
||||
...(decalCacheId ? { decalCacheId } : {}),
|
||||
...copied,
|
||||
};
|
||||
await writeInstallRecord(record);
|
||||
return record;
|
||||
} catch (error) {
|
||||
if (decalCacheId) await discardDecalCache(dataPath, decalCacheId, dataInSteam);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async function inspectInstallation(request: InstallRequest) {
|
||||
const gameFolder = request.method === 'copy' ? request.sourcePath : request.gamePath;
|
||||
const game = await requireGameFolder(gameFolder);
|
||||
let externalStockPath: string | null = null;
|
||||
if (request.method === 'copy') {
|
||||
if (game.needsStockSource) throw new AppError('stock_source_invalid');
|
||||
} else if (request.stockSourcePath) {
|
||||
externalStockPath = (await resolveExternalStockSource(request.stockSourcePath, game.version)).path;
|
||||
} else if (game.needsStockSource) {
|
||||
throw new AppError('stock_source_invalid');
|
||||
}
|
||||
const requestedCopyPath = request.method === 'copy' ? request.copyPath : request.gamePath;
|
||||
const [copyPath, dataPath, sourcePath] = await Promise.all([
|
||||
canonicalCopyPath(requestedCopyPath), canonicalCopyPath(request.dataPath), canonicalCopyPath(gameFolder),
|
||||
]);
|
||||
await requireAvailableCopy(request.id, copyPath, dataPath);
|
||||
const dataProblem = dataFolderProblem(
|
||||
dataPath,
|
||||
report({ phase: 'recording', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 });
|
||||
const record: InstallRecord = {
|
||||
id: request.id,
|
||||
name: request.name,
|
||||
sourcePath: request.method === 'copy' ? request.sourcePath : null,
|
||||
method: request.method,
|
||||
copyPath,
|
||||
request.method === 'copy' ? sourcePath : null,
|
||||
externalStockPath,
|
||||
);
|
||||
if (!isAbsolute(request.dataPath) || dataProblem !== null) {
|
||||
throw new AppError('target_not_usable', { problem: dataProblem ?? 'overlaps_stock' });
|
||||
}
|
||||
|
||||
const target = request.method === 'copy' ? await inspectTargetFolder(copyPath, sourcePath) : null;
|
||||
if (target?.problem) throw new AppError('target_not_usable', { problem: target.problem });
|
||||
const useHardLinks = request.method === 'copy' && request.useHardLinks === true;
|
||||
if (useHardLinks && !target?.sameDriveAsStock) {
|
||||
throw new AppError('hardlink_unavailable');
|
||||
}
|
||||
const copyInSteam = isInSteamLibrary(requestedCopyPath) || isInSteamLibrary(copyPath);
|
||||
const dataInSteam = isInSteamLibrary(request.dataPath) || isInSteamLibrary(dataPath);
|
||||
const { confirmedSteamCopyPath, confirmedSteamDataPath } = request;
|
||||
const copyConfirmed = confirmedSteamCopyPath !== undefined && relative(copyPath, confirmedSteamCopyPath) === '';
|
||||
const dataConfirmed = confirmedSteamDataPath !== undefined && relative(dataPath, confirmedSteamDataPath) === '';
|
||||
if ((copyInSteam && !copyConfirmed) || (dataInSteam && !dataConfirmed)) {
|
||||
throw new AppError('steam_library_not_confirmed');
|
||||
}
|
||||
await Promise.all([requireStockBackupLocation(copyPath), requireUnredirectedData(dataPath)]);
|
||||
return { version: game.version, requestedCopyPath, copyPath, dataPath, sourcePath, externalStockPath, target, useHardLinks, copyInSteam, dataInSteam };
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate where the offline data folder sits relative to the client and stock folders.
|
||||
* A subfolder inside the client (outside wtoffline/) is allowed, while setting dataPath to the
|
||||
* client folder itself or an ancestor of it would mix game files into the data root.
|
||||
*/
|
||||
export function dataFolderProblem(
|
||||
dataPath: string,
|
||||
copyPath: string | null,
|
||||
sourcePath: string | null,
|
||||
externalStockPath: string | null,
|
||||
): DataFolderProblem | null {
|
||||
if (copyPath && (copyPathContains(dataPath, copyPath) ||
|
||||
copyPathContains(join(copyPath, dirname(STOCK_BACKUP_FOLDER)), dataPath))) {
|
||||
return 'overlaps_client';
|
||||
}
|
||||
if ((sourcePath && copyPathContains(sourcePath, dataPath)) ||
|
||||
(externalStockPath && copyPathContains(externalStockPath, dataPath))) {
|
||||
return 'overlaps_stock';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
async function resolveExternalStockSource(stockSourcePath: string, expectedVersion: string | null) {
|
||||
const stockGame = await requireGameFolder(stockSourcePath);
|
||||
if (stockGame.needsStockSource) throw new AppError('stock_source_invalid');
|
||||
if (expectedVersion !== null && stockGame.version !== null && expectedVersion !== stockGame.version) {
|
||||
throw new AppError('stock_source_version_mismatch', { expected: expectedVersion, actual: stockGame.version });
|
||||
}
|
||||
return installStockSource(stockGame.resolvedPath, stockGame.version);
|
||||
dataPath: request.dataPath,
|
||||
stockBackupPath: stockBackup,
|
||||
gameVersion: game.version,
|
||||
unavailablePatches: check.unavailable,
|
||||
installedAt: new Date().toISOString(),
|
||||
lastCheckedAt: new Date().toISOString(),
|
||||
...(sourceFiles ? { sourceFiles } : {}),
|
||||
};
|
||||
await writeInstallRecord(record);
|
||||
return record;
|
||||
}
|
||||
|
||||
async function copyGame(
|
||||
source: string,
|
||||
target: string,
|
||||
initialFreeBytes: number | null,
|
||||
useHardLinks: boolean,
|
||||
sourceVersion: string | null,
|
||||
freeBytes: number | null,
|
||||
signal: AbortSignal,
|
||||
report: (progress: InstallProgress) => void,
|
||||
): Promise<Pick<InstallRecord, 'sourceFiles' | 'hardlinkedFiles'>> {
|
||||
): Promise<string[]> {
|
||||
report({ phase: 'measuring', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 });
|
||||
const plan = await planCopy(source);
|
||||
const hardlinks = useHardLinks ? await prepareHardlinks(source, plan, signal, report) : undefined;
|
||||
const linkedBytes = hardlinks ? [...hardlinks.values()].reduce((total, file) => total + Number(file.size), 0) : 0;
|
||||
const neededBytes = plan.totalBytes - linkedBytes + SPARE_BYTES;
|
||||
if (hardlinks && (!await sameVolume(source, target) || (await inspectGameFolder(source)).version !== sourceVersion)) {
|
||||
throw new AppError('hardlink_file_changed');
|
||||
}
|
||||
const available = hardlinks ? await freeBytes(target) : initialFreeBytes;
|
||||
if (available !== null && available < neededBytes) {
|
||||
throw new AppError('not_enough_space', { neededGb: gigabytes(neededBytes), freeGb: gigabytes(available) });
|
||||
if (freeBytes !== null && freeBytes < plan.totalBytes + SPARE_BYTES) {
|
||||
throw new AppError('not_enough_space', { neededGb: gigabytes(plan.totalBytes + SPARE_BYTES), freeGb: gigabytes(freeBytes) });
|
||||
}
|
||||
const targetExisted = await exists(target);
|
||||
const totals = { totalBytes: plan.totalBytes, totalFiles: plan.files.length };
|
||||
report({ phase: 'copying', doneBytes: 0, doneFiles: 0, ...totals });
|
||||
try {
|
||||
await copyPlannedFiles(source, target, plan, signal,
|
||||
(done) => report({ phase: 'copying', ...done, ...totals }), hardlinks);
|
||||
if (hardlinks && (await inspectGameFolder(source)).version !== sourceVersion) throw new AppError('hardlink_file_changed');
|
||||
return {
|
||||
sourceFiles: plan.files.map((file) => file.relativePath),
|
||||
...(hardlinks ? { hardlinkedFiles: [...hardlinks.keys()] } : {}),
|
||||
};
|
||||
await copyPlannedFiles(source, target, plan, signal, (done) => report({ phase: 'copying', ...done, ...totals }));
|
||||
return plan.files.map((file) => file.relativePath);
|
||||
} catch (error) {
|
||||
await removeInterruptedCopy(target, targetExisted).catch((cleanup) => console.error('[install] removing the interrupted copy failed:', cleanup));
|
||||
if (signal.aborted) throw new AppError('install_cancelled');
|
||||
if (error instanceof AppError) throw error;
|
||||
console.error('[install] copying failed:', error);
|
||||
throw new AppError('copy_failed');
|
||||
}
|
||||
}
|
||||
|
||||
async function prepareHardlinks(
|
||||
source: string,
|
||||
plan: CopyPlan,
|
||||
signal: AbortSignal,
|
||||
report: (progress: InstallProgress) => void,
|
||||
): Promise<ReadonlyMap<string, BigIntStats>> {
|
||||
const candidates = plan.files.filter((file) => isHardlinkableResource(file.relativePath, file.bytes));
|
||||
const totalBytes = candidates.reduce((total, file) => total + file.bytes, 0);
|
||||
const links = new Map<string, BigIntStats>();
|
||||
let doneBytes = 0;
|
||||
let doneFiles = 0;
|
||||
report({ phase: 'verifying', doneBytes, totalBytes, doneFiles, totalFiles: candidates.length });
|
||||
for (const file of candidates) {
|
||||
const verified = await statHardlinkResource(join(source, file.relativePath), file.bytes, signal);
|
||||
if (verified) links.set(file.relativePath, verified);
|
||||
doneBytes += file.bytes;
|
||||
doneFiles += 1;
|
||||
report({ phase: 'verifying', doneBytes, totalBytes, doneFiles, totalFiles: candidates.length });
|
||||
}
|
||||
if (!links.size) throw new AppError('hardlink_no_match');
|
||||
return links;
|
||||
}
|
||||
|
||||
async function requireGameFolder(path: string) {
|
||||
const game = await inspectGameFolder(path);
|
||||
if (game.missingFiles.length) throw new AppError('not_a_game_folder', { path });
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { access, realpath } from 'node:fs/promises';
|
||||
import { realpath } from 'node:fs/promises';
|
||||
import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
|
||||
import { app } from 'electron';
|
||||
import { GAME_FILES, isInSteamLibrary } from '@wto/patcher';
|
||||
import { AppError } from '@shared/errors.ts';
|
||||
import { CopiesSchema, type Copies, type InstallRecord } from '@shared/schemas/install.ts';
|
||||
import { readJsonOr, writeJsonAtomic } from '../../util/atomic-json.ts';
|
||||
@@ -75,72 +74,11 @@ export function renameCopy(id: string, name: string): Promise<Copies> {
|
||||
return updateCopyRecord(id, (record) => ({ ...record, name }));
|
||||
}
|
||||
|
||||
export async function copyFolderMissing(copyPath: string): Promise<boolean> {
|
||||
for (const file of Object.values(GAME_FILES)) {
|
||||
try {
|
||||
await access(join(copyPath, file));
|
||||
} catch {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Attach live `folderMissing` status to each registered copy without modifying `copies.json`. */
|
||||
export async function hydrateCopiesStatus(registry: Copies): Promise<Copies> {
|
||||
const copies = await Promise.all(registry.copies.map(async (copy) => {
|
||||
const missing = await copyFolderMissing(copy.copyPath);
|
||||
const { folderMissing: _old, ...base } = copy;
|
||||
return missing ? { ...base, folderMissing: true } : base;
|
||||
}));
|
||||
return { ...registry, copies };
|
||||
}
|
||||
|
||||
export function relocateCopyRecord(
|
||||
id: string,
|
||||
next: { readonly copyPath: string; readonly stockBackupPath: string; readonly gameVersion: string | null },
|
||||
): Promise<Copies> {
|
||||
return changeRegistry(async (registry) => {
|
||||
const current = registry.copies.find((copy) => copy.id === id);
|
||||
if (!current) throw new AppError('copy_not_found');
|
||||
const resolvedCopy = await canonicalCopyPath(next.copyPath);
|
||||
const resolvedData = await canonicalCopyPath(current.dataPath);
|
||||
if (overlaps(resolvedCopy, resolvedData) && copyPathContains(next.stockBackupPath, resolvedData)) {
|
||||
throw new AppError('copy_location_in_use');
|
||||
}
|
||||
for (const existing of registry.copies) {
|
||||
if (existing.id === id) continue;
|
||||
const used = await Promise.all([canonicalCopyPath(existing.copyPath), canonicalCopyPath(existing.dataPath)]);
|
||||
if (used.some((other) => overlaps(resolvedCopy, other))) {
|
||||
throw new AppError('copy_location_in_use');
|
||||
}
|
||||
}
|
||||
return {
|
||||
...registry,
|
||||
copies: registry.copies.map((record) => {
|
||||
if (record.id !== id) return record;
|
||||
const { steamLibraryConfirmation: _staleSteam, folderMissing: _staleMissing, ...rest } = record;
|
||||
return {
|
||||
...rest,
|
||||
copyPath: next.copyPath,
|
||||
stockBackupPath: next.stockBackupPath,
|
||||
gameVersion: next.gameVersion,
|
||||
};
|
||||
}),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/** Serialize writes so switching, renaming and completing an installation preserve each other. */
|
||||
function changeRegistry(change: (registry: Copies) => Promise<Copies> | Copies): Promise<Copies> {
|
||||
const operation = pending.then(async () => {
|
||||
try {
|
||||
const next = await change(await readRegistry());
|
||||
const sanitized: Copies = {
|
||||
...next,
|
||||
copies: next.copies.map(({ folderMissing: _ignored, ...rest }) => rest),
|
||||
};
|
||||
const updated = CopiesSchema.parse(sanitized);
|
||||
const updated = CopiesSchema.parse(await change(await readRegistry()));
|
||||
await writeJsonAtomic(recordPath(), updated);
|
||||
return updated;
|
||||
} catch (error) {
|
||||
@@ -168,12 +106,6 @@ export function copyPathContains(parent: string, child: string): boolean {
|
||||
return !isAbsolute(remainder) && remainder !== '..' && !remainder.startsWith('..' + sep);
|
||||
}
|
||||
|
||||
export function steamLibraryNeedsConfirmation(record: InstallRecord, copyPath: string, dataPath: string): boolean {
|
||||
if (![record.copyPath, record.dataPath, copyPath, dataPath].some(isInSteamLibrary)) return false;
|
||||
const confirmed = record.steamLibraryConfirmation;
|
||||
return !confirmed || relative(confirmed.copyPath, copyPath) !== '' || relative(confirmed.dataPath, dataPath) !== '';
|
||||
}
|
||||
|
||||
function overlaps(left: string, right: string): boolean {
|
||||
return copyPathContains(left, right) || copyPathContains(right, left);
|
||||
}
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
import { constants } from 'node:fs';
|
||||
import { access, copyFile, mkdir, readFile } from 'node:fs/promises';
|
||||
import { dirname, join, relative } from 'node:path';
|
||||
import { executableVersion, GAME_FILES } from '@wto/patcher';
|
||||
import { AppError } from '@shared/errors.ts';
|
||||
import { changeCopyFiles } from '../copies/change-copy-files.ts';
|
||||
import { canonicalCopyPath } from './install-record.ts';
|
||||
import { access, copyFile, mkdir } from 'node:fs/promises';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { GAME_FILES } from '@wto/patcher';
|
||||
|
||||
/**
|
||||
* The stock files every build starts from, kept inside the game copy: the three data packs and
|
||||
@@ -18,73 +15,21 @@ export function stockBackupPath(copyFolder: string): string {
|
||||
return join(copyFolder, STOCK_BACKUP_FOLDER);
|
||||
}
|
||||
|
||||
export async function requireStockBackupLocation(copyFolder: string): Promise<string> {
|
||||
const backup = stockBackupPath(await canonicalCopyPath(copyFolder));
|
||||
for (const file of Object.values(GAME_FILES)) {
|
||||
const path = join(backup, file);
|
||||
if (relative(path, await canonicalCopyPath(path)) !== '') throw new AppError('launch_location');
|
||||
}
|
||||
return backup;
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies each stock file from the copy into the backup folder, unless the backup already has it:
|
||||
* a backed-up file is never replaced, because the copy's own file may be a patched one by then.
|
||||
*/
|
||||
export async function backUpStockFiles(copyFolder: string): Promise<string> {
|
||||
return backUpStockFilesFrom(copyFolder, copyFolder);
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies the four stock files from `sourceFolder` (read-only) into `<copyFolder>/wtoffline/stock`,
|
||||
* keeping any file that is already backed up.
|
||||
*/
|
||||
export async function backUpStockFilesFrom(copyFolder: string, sourceFolder: string): Promise<string> {
|
||||
const backup = await requireStockBackupLocation(copyFolder);
|
||||
const backup = stockBackupPath(copyFolder);
|
||||
for (const file of Object.values(GAME_FILES)) {
|
||||
const kept = join(backup, file);
|
||||
if (await exists(kept)) continue;
|
||||
await mkdir(dirname(kept), { recursive: true });
|
||||
await copyFile(join(sourceFolder, file), kept, constants.COPYFILE_EXCL);
|
||||
await copyFile(join(copyFolder, file), kept, constants.COPYFILE_EXCL);
|
||||
}
|
||||
return backup;
|
||||
}
|
||||
|
||||
/** A new game version or damaged backup must pass the patch checks before replacing wtoffline/stock. */
|
||||
export async function installStockSource(copyFolder: string, version: string | null) {
|
||||
const backup = await requireStockBackupLocation(copyFolder);
|
||||
const backupExe = join(backup, GAME_FILES.executable);
|
||||
if (!await exists(backupExe)) return { path: copyFolder, refresh: await exists(backup) };
|
||||
let backedUpVersion: string | null = null;
|
||||
try {
|
||||
backedUpVersion = executableVersion(await readFile(backupExe));
|
||||
} catch (error) {
|
||||
console.warn('[stock-backup] unreadable backed-up executable, will refresh:', backupExe, error);
|
||||
return { path: copyFolder, refresh: true };
|
||||
}
|
||||
return backedUpVersion === null || (version !== null && backedUpVersion !== version)
|
||||
? { path: copyFolder, refresh: true }
|
||||
: { path: backup, refresh: false };
|
||||
}
|
||||
|
||||
export async function refreshStockBackup(copyFolder: string): Promise<string> {
|
||||
return refreshStockBackupFrom(copyFolder, copyFolder);
|
||||
}
|
||||
|
||||
/** Replace wtoffline/stock atomically with the four stock files from `sourceFolder`. */
|
||||
export async function refreshStockBackupFrom(copyFolder: string, sourceFolder: string): Promise<string> {
|
||||
const backup = await requireStockBackupLocation(copyFolder);
|
||||
return await changeCopyFiles(copyFolder, async (incoming) => {
|
||||
const replace = Object.values(GAME_FILES).map((file) => join(STOCK_BACKUP_FOLDER, file));
|
||||
for (const file of Object.values(GAME_FILES)) {
|
||||
const target = join(incoming, STOCK_BACKUP_FOLDER, file);
|
||||
await mkdir(dirname(target), { recursive: true });
|
||||
await copyFile(join(sourceFolder, file), target);
|
||||
}
|
||||
return { replace, remove: [] };
|
||||
}, async () => backup);
|
||||
}
|
||||
|
||||
async function exists(path: string): Promise<boolean> {
|
||||
try {
|
||||
await access(path);
|
||||
|
||||
@@ -1,172 +0,0 @@
|
||||
import { execFile, spawn } from 'node:child_process';
|
||||
import { constants } from 'node:fs';
|
||||
import { access, lstat, open, readdir } from 'node:fs/promises';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { promisify } from 'node:util';
|
||||
import { GAME_FILES } from '@wto/patcher';
|
||||
import { AppError } from '@shared/errors.ts';
|
||||
import offlineGameArguments from '@shared/offline-game-arguments.json';
|
||||
import { formatExitCode, type GameExit } from '@shared/schemas/launch.ts';
|
||||
|
||||
const execute = promisify(execFile);
|
||||
const HOOK_DLL_FILENAME = 'wto_ws.dll';
|
||||
const HOOK_CFG_FILENAME = 'wto_ws.cfg';
|
||||
const HOOK_LOG_FILENAME = 'wto_ws.log';
|
||||
const HOOK_LOG_TAIL_BYTES = 8 * 1024;
|
||||
const HOOK_LOG_TAIL_LINES = 8;
|
||||
const HOOK_LOG_LINE_LIMIT = 200;
|
||||
/** Allow small filesystem timestamp skew when matching newly created .game_logs entries. */
|
||||
const MTIME_SKEW_MS = 2000;
|
||||
|
||||
export async function gameProcessRunning(signal: AbortSignal): Promise<boolean> {
|
||||
if (process.platform !== 'win32') return false;
|
||||
const games = await execute('tasklist.exe', ['/FI', 'IMAGENAME eq aces.exe', '/FO', 'CSV', '/NH'], { windowsHide: true, signal });
|
||||
return /^"aces\.exe",/im.test(games.stdout);
|
||||
}
|
||||
|
||||
export async function runGameProcess(
|
||||
copyPath: string, additionalArguments: readonly string[], signal: AbortSignal, onStart: () => void,
|
||||
): Promise<GameExit> {
|
||||
if (await gameProcessRunning(signal)) throw new AppError('launch_game_running');
|
||||
await verifyLaunchFiles(copyPath);
|
||||
signal.throwIfAborted();
|
||||
const executable = join(copyPath, GAME_FILES.executable);
|
||||
const args = [...offlineGameArguments, ...additionalArguments];
|
||||
const startedAt = Date.now();
|
||||
console.info('[game] starting:', executable, args);
|
||||
const child = spawn(executable, args, {
|
||||
cwd: copyPath, shell: false, stdio: 'ignore',
|
||||
});
|
||||
const stop = (): void => { child.kill(); };
|
||||
|
||||
try {
|
||||
return await new Promise<GameExit>((resolve, reject) => {
|
||||
child.once('spawn', () => {
|
||||
console.info('[game] process started, pid:', child.pid ?? 'unknown');
|
||||
if (signal.aborted) stop();
|
||||
else onStart();
|
||||
});
|
||||
child.once('error', (error) => {
|
||||
console.error('[game] process error:', error);
|
||||
reject(new AppError('launch_game_failed'));
|
||||
});
|
||||
child.once('close', (code, reason) => {
|
||||
const logFolder = join(copyPath, '.game_logs');
|
||||
const elapsedMs = Date.now() - startedAt;
|
||||
const summary = code !== null ? formatExitCode(code) : (reason ?? 'unknown');
|
||||
if (code !== 0 && !signal.aborted) {
|
||||
console.warn('[game] process exited:', summary, `after ${elapsedMs} ms`, logFolder);
|
||||
void logAbnormalExitContext(copyPath, startedAt)
|
||||
.catch((error: unknown) => console.warn('[game] inspecting post-exit files failed:', error))
|
||||
.finally(() => resolve({ code, signal: reason, logFolder }));
|
||||
return;
|
||||
}
|
||||
console.info('[game] process exited:', summary, `after ${elapsedMs} ms`);
|
||||
resolve({ code, signal: reason, logFolder });
|
||||
});
|
||||
signal.addEventListener('abort', stop, { once: true });
|
||||
});
|
||||
} finally {
|
||||
signal.removeEventListener('abort', stop);
|
||||
}
|
||||
}
|
||||
|
||||
/** Verify the patched executable and hook files are still present and readable right before spawn. */
|
||||
async function verifyLaunchFiles(copyPath: string): Promise<void> {
|
||||
const exeFolder = dirname(GAME_FILES.executable);
|
||||
const required = [
|
||||
GAME_FILES.executable,
|
||||
join(exeFolder, HOOK_DLL_FILENAME),
|
||||
join(exeFolder, HOOK_CFG_FILENAME),
|
||||
];
|
||||
const missing: string[] = [];
|
||||
for (const relativePath of required) {
|
||||
const fullPath = join(copyPath, relativePath);
|
||||
try {
|
||||
const stats = await lstat(fullPath);
|
||||
if (!stats.isFile() || stats.size === 0) {
|
||||
missing.push(`${relativePath} (not a non-empty file)`);
|
||||
continue;
|
||||
}
|
||||
await access(fullPath, constants.R_OK);
|
||||
} catch (error) {
|
||||
const code = (error as NodeJS.ErrnoException).code ?? 'error';
|
||||
missing.push(`${relativePath} (${code})`);
|
||||
}
|
||||
}
|
||||
if (missing.length > 0) {
|
||||
console.error('[game] required launch files unavailable before start:', missing.join(', '));
|
||||
throw new AppError('launch_game_files_missing');
|
||||
}
|
||||
}
|
||||
|
||||
/** Record a compact read-only snapshot of hook and game log files after an unexpected non-zero exit. */
|
||||
async function logAbnormalExitContext(copyPath: string, startedAt: number): Promise<void> {
|
||||
const exeFolder = join(copyPath, dirname(GAME_FILES.executable));
|
||||
const [dllState, cfgState, hookLogStat, newGameLogs] = await Promise.all([
|
||||
describeFile(join(exeFolder, HOOK_DLL_FILENAME)),
|
||||
describeFile(join(exeFolder, HOOK_CFG_FILENAME)),
|
||||
safeRegularStat(join(exeFolder, HOOK_LOG_FILENAME)),
|
||||
listNewGameLogs(join(copyPath, '.game_logs'), startedAt),
|
||||
]);
|
||||
const hookLogDesc = hookLogStat
|
||||
? `${hookLogStat.size} bytes (${hookLogStat.mtimeMs >= startedAt - MTIME_SKEW_MS ? 'updated' : 'stale'})`
|
||||
: 'missing';
|
||||
console.warn(
|
||||
`[game] post-exit check: ${HOOK_DLL_FILENAME}=${dllState}, ${HOOK_CFG_FILENAME}=${cfgState}, ` +
|
||||
`${HOOK_LOG_FILENAME}=${hookLogDesc}, newGameLogs=${newGameLogs}`,
|
||||
);
|
||||
if (hookLogStat && hookLogStat.size > 0) {
|
||||
const tail = await readTailLines(join(exeFolder, HOOK_LOG_FILENAME), hookLogStat.size);
|
||||
if (tail.length > 0) {
|
||||
console.warn(`[game] ${HOOK_LOG_FILENAME} tail:\n ${tail.join('\n ')}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function describeFile(path: string): Promise<string> {
|
||||
const stats = await safeRegularStat(path);
|
||||
return stats ? `${stats.size} bytes` : 'missing';
|
||||
}
|
||||
|
||||
async function safeRegularStat(path: string) {
|
||||
try {
|
||||
const stats = await lstat(path);
|
||||
return stats.isFile() ? stats : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function listNewGameLogs(folder: string, startedAt: number): Promise<string> {
|
||||
try {
|
||||
const entries = await readdir(folder, { withFileTypes: true });
|
||||
const recent: string[] = [];
|
||||
for (const entry of entries) {
|
||||
if (!entry.isFile()) continue;
|
||||
const stats = await safeRegularStat(join(folder, entry.name));
|
||||
if (!stats || stats.mtimeMs < startedAt - MTIME_SKEW_MS) continue;
|
||||
recent.push(`${entry.name} (${stats.size} bytes)`);
|
||||
}
|
||||
return recent.length > 0 ? recent.slice(0, 6).join(', ') : 'none';
|
||||
} catch {
|
||||
return 'unavailable';
|
||||
}
|
||||
}
|
||||
|
||||
async function readTailLines(path: string, fileSize: number): Promise<string[]> {
|
||||
const length = Math.min(fileSize, HOOK_LOG_TAIL_BYTES);
|
||||
const start = fileSize - length;
|
||||
const handle = await open(path, 'r');
|
||||
try {
|
||||
const buffer = Buffer.alloc(length);
|
||||
const { bytesRead } = await handle.read(buffer, 0, length, start);
|
||||
const text = buffer.subarray(0, bytesRead).toString('utf8');
|
||||
const lines = text.split(/\r?\n/).filter((line) => line.length > 0);
|
||||
return lines.slice(-HOOK_LOG_TAIL_LINES).map((line) => (
|
||||
line.length > HOOK_LOG_LINE_LIMIT ? `${line.slice(0, HOOK_LOG_LINE_LIMIT)}…` : line
|
||||
));
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
}
|
||||
@@ -3,9 +3,8 @@ import { lstat, readFile, realpath, writeFile } from 'node:fs/promises';
|
||||
import { isAbsolute, join, relative, resolve } from 'node:path';
|
||||
import { app } from 'electron';
|
||||
import { z } from 'zod';
|
||||
import { HEALTH_PATH } from '@wto/server';
|
||||
import { AppError } from '@shared/errors.ts';
|
||||
import offlineGameArguments from '@shared/offline-game-arguments.json';
|
||||
import { localServerReady } from './local-server.ts';
|
||||
import { forwardProcessOutput } from './process-output.ts';
|
||||
|
||||
const Configuration = z.object({
|
||||
@@ -13,13 +12,13 @@ const Configuration = z.object({
|
||||
copy: z.string().min(1),
|
||||
port: z.number().int().min(1).max(65535),
|
||||
labUser: z.literal('wto-lab'),
|
||||
gameArguments: z.array(z.string()),
|
||||
});
|
||||
const Status = z.object({
|
||||
state: z.string(),
|
||||
message: z.string(),
|
||||
guardExitCode: z.number().nullable().optional(),
|
||||
});
|
||||
const Health = z.object({ app: z.literal('wto-server'), pid: z.number() });
|
||||
|
||||
export interface Lab {
|
||||
readonly installPath: string;
|
||||
@@ -35,10 +34,6 @@ export async function readInstalledLab(): Promise<Lab> {
|
||||
const installPath = join(programData, 'WTOffline-lab');
|
||||
try {
|
||||
const config = Configuration.parse(JSON.parse(await readFile(join(installPath, 'lab.json'), 'utf8')));
|
||||
if (config.gameArguments.length !== offlineGameArguments.length ||
|
||||
offlineGameArguments.some((argument, index) => config.gameArguments[index] !== argument)) {
|
||||
throw new Error('The installed lab launch arguments are out of date.');
|
||||
}
|
||||
const root = await realpath(config.lab);
|
||||
const copyPath = await realpath(resolve(root, config.copy));
|
||||
const relation = relative(root, copyPath);
|
||||
@@ -63,6 +58,10 @@ export async function readInstalledLab(): Promise<Lab> {
|
||||
}
|
||||
}
|
||||
|
||||
export function labStatusUrl(port: number): string {
|
||||
return `http://127.0.0.1:${port}${HEALTH_PATH}`;
|
||||
}
|
||||
|
||||
async function readStatus(lab: Lab): Promise<z.output<typeof Status> | null> {
|
||||
try {
|
||||
return Status.parse(JSON.parse(await readFile(join(lab.controlPath, 'status.json'), 'utf8')));
|
||||
@@ -71,6 +70,15 @@ async function readStatus(lab: Lab): Promise<z.output<typeof Status> | null> {
|
||||
}
|
||||
}
|
||||
|
||||
async function isReady(port: number, pid: number): Promise<boolean> {
|
||||
try {
|
||||
const response = await fetch(labStatusUrl(port), { signal: AbortSignal.timeout(900) });
|
||||
return response.ok && Health.parse(await response.json()).pid === pid;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function stopGame(lab: Lab): Promise<void> {
|
||||
await writeFile(join(lab.controlPath, 'stop-request'), '', { flag: 'wx' }).catch((error: NodeJS.ErrnoException) => {
|
||||
if (error.code !== 'EEXIST') throw error;
|
||||
@@ -137,7 +145,7 @@ export async function runLab(
|
||||
return;
|
||||
}
|
||||
checking = true;
|
||||
void localServerReady(lab.port, serverPid).then((ready) => {
|
||||
void isReady(lab.port, serverPid).then((ready) => {
|
||||
if (!running || processClosed) return;
|
||||
failures = ready ? 0 : failures + 1;
|
||||
if (failures < 3) return;
|
||||
|
||||
@@ -1,26 +1,21 @@
|
||||
import { execFile } from 'node:child_process';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { createServer } from 'node:net';
|
||||
import { isAbsolute, join } from 'node:path';
|
||||
import { app, BrowserWindow, shell } from 'electron';
|
||||
import { AccountStore, LOOPBACK } from '@wto/server';
|
||||
import { isAbsolute, join, relative } from 'node:path';
|
||||
import { promisify } from 'node:util';
|
||||
import { BrowserWindow, shell } from 'electron';
|
||||
import { AccountStore } from '@wto/server';
|
||||
import { executableVersion, GAME_FILES, isInSteamLibrary } from '@wto/patcher';
|
||||
import { AppError } from '@shared/errors.ts';
|
||||
import type { InstallRecord } from '@shared/schemas/install.ts';
|
||||
import type { GameExit, LaunchState } from '@shared/schemas/launch.ts';
|
||||
import type { Settings } from '@shared/schemas/settings.ts';
|
||||
import type { LaunchState } from '@shared/schemas/launch.ts';
|
||||
import { getSettings } from '../config/settings-store.ts';
|
||||
import { decalCachePath } from '../install/decals.ts';
|
||||
import { canonicalCopyPath, copyPathContains, readInstallRecord } from '../install/install-record.ts';
|
||||
import { resolveEnabledModsForLaunch } from '../mods/mods-service.ts';
|
||||
import { readInstallRecord } from '../install/install-record.ts';
|
||||
import { resourcePaths } from '../resources/resource-paths.ts';
|
||||
import { saveBackup } from '../saves/save-archive.ts';
|
||||
import { buildCopy } from './build-copy.ts';
|
||||
import { gameProcessRunning } from './game-process.ts';
|
||||
import { readInstalledLab, runLab, type Lab } from './lab-handoff.ts';
|
||||
import { localServerStatusUrl } from './local-server.ts';
|
||||
import { ordinaryLaunchPaths, runOrdinaryLaunch } from './ordinary-launch.ts';
|
||||
import { labStatusUrl, readInstalledLab, runLab } from './lab-handoff.ts';
|
||||
|
||||
export { gameProcessRunning } from './game-process.ts';
|
||||
const execute = promisify(execFile);
|
||||
|
||||
interface LaunchJob {
|
||||
readonly stop: AbortController;
|
||||
@@ -36,31 +31,30 @@ export function launchInProgress(): boolean {
|
||||
return active !== null;
|
||||
}
|
||||
|
||||
export async function gameProcessRunning(signal: AbortSignal): Promise<boolean> {
|
||||
if (process.platform !== 'win32') return false;
|
||||
const games = await execute('tasklist.exe', ['/FI', 'IMAGENAME eq aces.exe', '/FO', 'CSV', '/NH'], { windowsHide: true, signal });
|
||||
return /^"aces\.exe",/im.test(games.stdout);
|
||||
}
|
||||
|
||||
export function getLaunchState(): LaunchState {
|
||||
return state;
|
||||
}
|
||||
|
||||
export function startLaunch(report: LaunchJob['report']): LaunchState {
|
||||
const previous = active;
|
||||
if (previous && state.phase !== 'server-running') throw new AppError('launch_busy');
|
||||
if (active) throw new AppError('launch_busy');
|
||||
const job: LaunchJob = { stop: new AbortController(), report, done: Promise.resolve() };
|
||||
active = job;
|
||||
previous?.stop.abort();
|
||||
update(job, { phase: 'checking' });
|
||||
job.done = (async () => {
|
||||
// A new build may only write after the server from the previous session has stopped.
|
||||
await previous?.done;
|
||||
job.stop.signal.throwIfAborted();
|
||||
await launch(job);
|
||||
})().catch((error: unknown) => {
|
||||
job.done = launch(job).catch((error: unknown) => {
|
||||
const port = state.port;
|
||||
const context = port === undefined ? {} : { port };
|
||||
if (job.stop.signal.aborted) {
|
||||
update(job, { phase: 'ready' });
|
||||
return;
|
||||
}
|
||||
const { port } = state;
|
||||
const context = port === undefined ? {} : { port };
|
||||
console.error('[launch] launch failed:', error);
|
||||
const code = error instanceof AppError ? error.code : 'launch_failed';
|
||||
const code = error instanceof AppError ? error.code : 'launch_lab_failed';
|
||||
switch (code) {
|
||||
case 'launch_port_busy':
|
||||
update(job, { phase: 'port-busy', ...context });
|
||||
@@ -73,7 +67,7 @@ export function startLaunch(report: LaunchJob['report']): LaunchState {
|
||||
break;
|
||||
}
|
||||
}).finally(() => {
|
||||
if (active === job) active = null;
|
||||
active = null;
|
||||
});
|
||||
return state;
|
||||
}
|
||||
@@ -89,120 +83,48 @@ export function stopLaunch(): Promise<void> | null {
|
||||
}
|
||||
|
||||
export async function openServerStatus(): Promise<void> {
|
||||
if ((state.phase !== 'running' && state.phase !== 'server-running') || state.port === undefined) {
|
||||
throw new AppError('launch_server_exited');
|
||||
}
|
||||
await shell.openExternal(localServerStatusUrl(state.port));
|
||||
if (state.phase !== 'running' || state.port === undefined) throw new AppError('launch_server_exited');
|
||||
await shell.openExternal(labStatusUrl(state.port));
|
||||
}
|
||||
|
||||
function update(job: LaunchJob, next: LaunchState): void {
|
||||
if (active !== job) return;
|
||||
state = job.copyId ? { ...next, copyId: job.copyId } : next;
|
||||
job.report(state);
|
||||
}
|
||||
|
||||
async function launch(job: LaunchJob): Promise<void> {
|
||||
if (process.platform !== 'win32') throw new AppError('launch_platform_unsupported');
|
||||
const signal = job.stop.signal;
|
||||
const [record, settings] = await Promise.all([readInstallRecord(), getSettings()]);
|
||||
if (!record) throw new AppError('launch_no_copy');
|
||||
job.copyId = record.id;
|
||||
const plan = await planLaunch(job, record, settings);
|
||||
if (plan === null) return;
|
||||
const { lab, copyPath, stockPath, dataPath, port, modsDir, enabledModIds } = plan;
|
||||
await buildForLaunch(job, record, plan, settings);
|
||||
|
||||
const publish = (phase: LaunchState['phase'], gameExit?: GameExit): void => {
|
||||
if (signal.aborted) return;
|
||||
update(job, { phase, port, gameExit });
|
||||
if (phase === 'running' && settings.afterGameStarts === 'minimize') {
|
||||
for (const window of BrowserWindow.getAllWindows()) window.minimize();
|
||||
}
|
||||
};
|
||||
if (lab) {
|
||||
await runLab(lab, stockPath, dataPath, signal, publish);
|
||||
update(job, { phase: 'ready' });
|
||||
return;
|
||||
}
|
||||
const gameExit = await runOrdinaryLaunch(
|
||||
copyPath,
|
||||
dataPath,
|
||||
port,
|
||||
settings,
|
||||
signal,
|
||||
publish,
|
||||
{ modsDir, enabledModIds },
|
||||
);
|
||||
update(job, { phase: 'game-exited', gameExit });
|
||||
}
|
||||
|
||||
interface LaunchPlan {
|
||||
readonly lab: Lab | null;
|
||||
readonly copyPath: string;
|
||||
readonly stockPath: string;
|
||||
readonly dataPath: string;
|
||||
readonly steamLibraryConfirmed: boolean;
|
||||
readonly port: number;
|
||||
readonly modsDir: string;
|
||||
readonly enabledModIds: readonly string[];
|
||||
}
|
||||
|
||||
async function planLaunch(job: LaunchJob, record: InstallRecord, settings: Settings): Promise<LaunchPlan | null> {
|
||||
const signal = job.stop.signal;
|
||||
const useLab = !app.isPackaged && settings.developerMode;
|
||||
if (useLab && (isInSteamLibrary(record.copyPath) || isInSteamLibrary(await canonicalCopyPath(record.copyPath)))) {
|
||||
throw new AppError('launch_copy_in_steam');
|
||||
}
|
||||
if (!settings.developerMode) throw new AppError('launch_lab_required');
|
||||
if (isInSteamLibrary(record.copyPath)) throw new AppError('launch_copy_in_steam');
|
||||
const currentVersion = await readVersion(record.copyPath, signal);
|
||||
if (!currentVersion || currentVersion !== record.gameVersion) {
|
||||
console.warn(
|
||||
`[launch] client version changed: recorded=${record.gameVersion ?? 'unknown'}, ` +
|
||||
`actual=${currentVersion ?? 'missing'} (${record.copyPath})`,
|
||||
);
|
||||
update(job, { phase: 'version-changed', actualVersion: currentVersion });
|
||||
return null;
|
||||
return;
|
||||
}
|
||||
|
||||
const lab = useLab ? await readInstalledLab() : null;
|
||||
const { copyPath, stockPath, dataPath, steamLibraryConfirmed } = lab ? {
|
||||
copyPath: lab.copyPath,
|
||||
stockPath: settings.labStockPath ?? record.stockBackupPath,
|
||||
dataPath: settings.labDataPath ?? record.dataPath,
|
||||
steamLibraryConfirmed: false,
|
||||
} : await ordinaryLaunchPaths(record);
|
||||
const lab = await readInstalledLab();
|
||||
const stockPath = settings.labStockPath ?? record.stockBackupPath;
|
||||
const dataPath = settings.labDataPath ?? record.dataPath;
|
||||
if (!isAbsolute(stockPath) || !isAbsolute(dataPath)) {
|
||||
throw new AppError('folder_unreadable', { path: !isAbsolute(stockPath) ? stockPath : dataPath });
|
||||
}
|
||||
if (lab && (isInSteamLibrary(copyPath) || isInSteamLibrary(dataPath) || isInSteamLibrary(await canonicalCopyPath(dataPath)))) {
|
||||
const relativeData = relative(stockPath, dataPath);
|
||||
if (isInSteamLibrary(dataPath) || (!isAbsolute(relativeData) && !relativeData.startsWith('..'))) {
|
||||
throw new AppError('launch_copy_in_steam');
|
||||
}
|
||||
if (copyPathContains(stockPath, dataPath)) throw new AppError('launch_location');
|
||||
const requestedPort = lab?.port ?? (settings.launchPortMode === 'fixed' ? settings.launchPort : 0);
|
||||
if (requestedPort) update(job, { phase: 'checking', port: requestedPort });
|
||||
const [copyVersion, stockVersion, games] = await Promise.all([
|
||||
lab ? readVersion(copyPath, signal) : currentVersion,
|
||||
update(job, { phase: 'checking', port: lab.port });
|
||||
const [labVersion, stockVersion, games] = await Promise.all([
|
||||
readVersion(lab.copyPath, signal),
|
||||
readVersion(stockPath, signal),
|
||||
gameProcessRunning(signal),
|
||||
]);
|
||||
signal.throwIfAborted();
|
||||
if (!copyVersion || copyVersion !== stockVersion) {
|
||||
console.warn(
|
||||
`[launch] copy/stock version mismatch: copy=${copyVersion ?? 'missing'} (${copyPath}), ` +
|
||||
`stock=${stockVersion ?? 'missing'} (${stockPath})`,
|
||||
);
|
||||
if (!lab && !stockVersion) throw new AppError('launch_stock_missing');
|
||||
throw new AppError(lab ? 'launch_lab_version' : 'launch_stock_version');
|
||||
}
|
||||
if (!labVersion || labVersion !== stockVersion) throw new AppError('launch_lab_version');
|
||||
if (games) throw new AppError('launch_game_running');
|
||||
const { modsDir, enabledMods } = await resolveEnabledModsForLaunch(dataPath, copyVersion);
|
||||
const enabledModIds = enabledMods.map((mod) => mod.manifest.id);
|
||||
const port = await selectPort(requestedPort);
|
||||
return { lab, copyPath, stockPath, dataPath, steamLibraryConfirmed, port, modsDir, enabledModIds };
|
||||
}
|
||||
|
||||
async function buildForLaunch(job: LaunchJob, record: InstallRecord, plan: LaunchPlan, settings: Settings): Promise<void> {
|
||||
const signal = job.stop.signal;
|
||||
const { lab, copyPath, stockPath, dataPath, port, steamLibraryConfirmed, modsDir, enabledModIds } = plan;
|
||||
await checkPort(lab.port);
|
||||
if (settings.autoSaveBackups) {
|
||||
for (const { userId } of new AccountStore(dataPath).all()) {
|
||||
signal.throwIfAborted();
|
||||
@@ -210,29 +132,28 @@ async function buildForLaunch(job: LaunchJob, record: InstallRecord, plan: Launc
|
||||
}
|
||||
}
|
||||
signal.throwIfAborted();
|
||||
update(job, { phase: 'building', port });
|
||||
const buildStart = Date.now();
|
||||
let writtenFiles = 0;
|
||||
update(job, { phase: 'building', port: lab.port });
|
||||
await buildCopy({
|
||||
kind: 'build',
|
||||
stockPath,
|
||||
copyPath,
|
||||
copyPath: lab.copyPath,
|
||||
dataPath,
|
||||
port,
|
||||
steamLibraryConfirmed,
|
||||
port: lab.port,
|
||||
...resourcePaths(),
|
||||
...(record.decalCacheId ? { decalCache: decalCachePath(lab ? record.dataPath : dataPath, record.decalCacheId) } : {}),
|
||||
hookLogging: settings.loggingEnabled,
|
||||
acceptedUnavailable: record.unavailablePatches.map(({ patchId }) => patchId),
|
||||
modsDir,
|
||||
enabledModIds,
|
||||
}, signal, (filesWritten, filesTotal, file) => {
|
||||
writtenFiles = filesWritten;
|
||||
if (!signal.aborted) update(job, {
|
||||
phase: 'building', port, filesWritten, filesTotal, ...(file === undefined ? {} : { file }),
|
||||
phase: 'building', port: lab.port, filesWritten, filesTotal, ...(file === undefined ? {} : { file }),
|
||||
});
|
||||
});
|
||||
console.info(`[launch] prepared ${writtenFiles} game files for port ${port} in ${Date.now() - buildStart} ms`);
|
||||
|
||||
await runLab(lab, stockPath, dataPath, signal, (phase) => {
|
||||
if (!signal.aborted) update(job, { phase, port: lab.port });
|
||||
if (phase === 'running' && !signal.aborted && settings.afterGameStarts === 'minimize') {
|
||||
for (const window of BrowserWindow.getAllWindows()) window.minimize();
|
||||
}
|
||||
});
|
||||
update(job, { phase: 'ready' });
|
||||
}
|
||||
|
||||
async function readVersion(folder: string, signal: AbortSignal): Promise<string | null> {
|
||||
@@ -245,19 +166,12 @@ async function readVersion(folder: string, signal: AbortSignal): Promise<string
|
||||
}
|
||||
}
|
||||
|
||||
async function selectPort(port: number): Promise<number> {
|
||||
return new Promise((resolve, reject) => {
|
||||
async function checkPort(port: number): Promise<void> {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const listener = createServer();
|
||||
listener.once('error', (error: NodeJS.ErrnoException) => reject(
|
||||
error.code === 'EADDRINUSE' ? new AppError('launch_port_busy') : error,
|
||||
));
|
||||
listener.listen(port, LOOPBACK, () => {
|
||||
const address = listener.address();
|
||||
listener.close((error) => {
|
||||
if (error) reject(error);
|
||||
else if (address && typeof address === 'object') resolve(address.port);
|
||||
else reject(new AppError('launch_server_failed'));
|
||||
});
|
||||
});
|
||||
listener.listen(port, '127.0.0.1', () => listener.close((error) => error ? reject(error) : resolve()));
|
||||
});
|
||||
}
|
||||
@@ -1,105 +0,0 @@
|
||||
import { once } from 'node:events';
|
||||
import { join } from 'node:path';
|
||||
import { setTimeout as delay } from 'node:timers/promises';
|
||||
import { utilityProcess } from 'electron';
|
||||
import { z } from 'zod';
|
||||
import { HEALTH_PATH, LOOPBACK, type ServerOptions } from '@wto/server';
|
||||
import { AppError } from '@shared/errors.ts';
|
||||
import type { ServerWorkerStatus } from '../../workers/server-worker.ts';
|
||||
import { forwardProcessOutput } from './process-output.ts';
|
||||
|
||||
const Health = z.object({ app: z.literal('wto-server'), pid: z.number() });
|
||||
|
||||
interface LocalServer {
|
||||
readonly exited: Promise<number>;
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
export function localServerStatusUrl(port: number): string {
|
||||
return `http://${LOOPBACK}:${port}${HEALTH_PATH}`;
|
||||
}
|
||||
|
||||
export async function localServerReady(port: number, pid?: number, signal?: AbortSignal): Promise<boolean> {
|
||||
const deadline = AbortSignal.timeout(900);
|
||||
try {
|
||||
const response = await fetch(localServerStatusUrl(port), {
|
||||
redirect: 'error', signal: signal ? AbortSignal.any([signal, deadline]) : deadline,
|
||||
});
|
||||
if (!response.ok) return false;
|
||||
const health = Health.parse(await response.json());
|
||||
return pid === undefined || health.pid === pid;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export interface StartLocalServerOptions extends Omit<ServerOptions, 'report' | 'mods'> {
|
||||
readonly modsDir?: string;
|
||||
readonly enabledModIds?: readonly string[];
|
||||
}
|
||||
|
||||
export async function startLocalServer(
|
||||
{ gameFolder, dataFolder, port, loggingEnabled = true, modsDir, enabledModIds }: StartLocalServerOptions, signal: AbortSignal,
|
||||
): Promise<LocalServer> {
|
||||
signal.throwIfAborted();
|
||||
const workerArgs = [gameFolder, dataFolder, String(port), loggingEnabled ? '1' : '0'];
|
||||
if (modsDir && enabledModIds && enabledModIds.length > 0) {
|
||||
workerArgs.push(modsDir, JSON.stringify(enabledModIds));
|
||||
}
|
||||
const worker = utilityProcess.fork(
|
||||
join(import.meta.dirname, 'server-worker.js'),
|
||||
workerArgs,
|
||||
{
|
||||
serviceName: 'WTOffline local server',
|
||||
stdio: 'pipe',
|
||||
},
|
||||
);
|
||||
forwardProcessOutput(worker.stdout, 'server', 'info');
|
||||
forwardProcessOutput(worker.stderr, 'server', 'error');
|
||||
|
||||
let ended = false;
|
||||
const exited = new Promise<number>((resolve) => worker.once('exit', (code) => {
|
||||
ended = true;
|
||||
resolve(code);
|
||||
}));
|
||||
worker.on('error', (type, location) => console.error('[server] utility process error:', type, location));
|
||||
|
||||
const stop = async (graceful: boolean): Promise<void> => {
|
||||
if (!ended && graceful) {
|
||||
worker.postMessage('close');
|
||||
await Promise.race([exited, delay(3000, undefined, { ref: false })]);
|
||||
}
|
||||
if (!ended && !worker.kill() && worker.pid === undefined) {
|
||||
worker.once('spawn', () => worker.kill());
|
||||
}
|
||||
await exited;
|
||||
};
|
||||
|
||||
const startup = AbortSignal.any([signal, AbortSignal.timeout(60_000)]);
|
||||
let listening = false;
|
||||
try {
|
||||
const reply: ServerWorkerStatus = await Promise.race([
|
||||
once(worker, 'message', { signal: startup }).then(([status]) => status as ServerWorkerStatus),
|
||||
exited.then(() => 'failed' as const),
|
||||
]);
|
||||
if (reply === 'port-busy') throw new AppError('launch_port_busy');
|
||||
const pid = worker.pid;
|
||||
if (reply !== 'listening' || pid === undefined) throw new AppError('launch_server_failed');
|
||||
listening = true;
|
||||
while (!ended) {
|
||||
startup.throwIfAborted();
|
||||
if (await localServerReady(port, pid, startup)) {
|
||||
startup.throwIfAborted();
|
||||
if (!ended) return { exited, close: () => stop(true) };
|
||||
break;
|
||||
}
|
||||
await delay(150, undefined, { signal: startup });
|
||||
}
|
||||
throw new AppError('launch_server_failed');
|
||||
} catch (error) {
|
||||
await stop(listening);
|
||||
signal.throwIfAborted();
|
||||
console.error('[server] startup failed:', error);
|
||||
throw error instanceof AppError ? error : new AppError('launch_server_failed');
|
||||
}
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
import { once } from 'node:events';
|
||||
import { isAbsolute, join, relative } from 'node:path';
|
||||
import { GAME_FILES, isInSteamLibrary } from '@wto/patcher';
|
||||
import { AppError } from '@shared/errors.ts';
|
||||
import { parseLaunchArguments } from '@shared/launch-arguments.ts';
|
||||
import type { InstallRecord } from '@shared/schemas/install.ts';
|
||||
import type { GameExit } from '@shared/schemas/launch.ts';
|
||||
import type { Settings } from '@shared/schemas/settings.ts';
|
||||
import { requireUnredirectedData } from '../install/data-location.ts';
|
||||
import { PLAYER_DATA_FOLDERS } from '../install/copy-game.ts';
|
||||
import { canonicalCopyPath, copyPathContains, steamLibraryNeedsConfirmation } from '../install/install-record.ts';
|
||||
import { requireStockBackupLocation, stockBackupPath } from '../install/stock-backup.ts';
|
||||
import { runGameProcess } from './game-process.ts';
|
||||
import { startLocalServer } from './local-server.ts';
|
||||
|
||||
export async function ordinaryLaunchPaths(record: InstallRecord) {
|
||||
const paths = [record.copyPath, record.stockBackupPath, record.dataPath] as const;
|
||||
if (paths.some((path) => !isAbsolute(path))) throw new AppError('launch_location');
|
||||
const [copyPath, stockPath, dataPath] = await Promise.all([
|
||||
canonicalCopyPath(record.copyPath), canonicalCopyPath(record.stockBackupPath), canonicalCopyPath(record.dataPath),
|
||||
]);
|
||||
const source = record.sourcePath === null ? null : await canonicalCopyPath(record.sourcePath);
|
||||
if (relative(stockBackupPath(copyPath), stockPath) !== '' ||
|
||||
copyPathContains(stockPath, dataPath) ||
|
||||
(source !== null && [copyPath, dataPath].some((path) => copyPathContains(source, path)))) {
|
||||
throw new AppError('launch_location');
|
||||
}
|
||||
await Promise.all([requireUnredirectedGamePaths(copyPath), requireStockBackupLocation(copyPath), requireUnredirectedData(dataPath)]);
|
||||
if (steamLibraryNeedsConfirmation(record, copyPath, dataPath)) throw new AppError('launch_steam_confirmation_required');
|
||||
return { copyPath, stockPath, dataPath, steamLibraryConfirmed: isInSteamLibrary(record.copyPath) || isInSteamLibrary(copyPath) };
|
||||
}
|
||||
|
||||
/** The game and build write to these copy-relative locations. */
|
||||
async function requireUnredirectedGamePaths(copyPath: string): Promise<void> {
|
||||
const paths = ['config.blk', join('cache', 'content'), ...PLAYER_DATA_FOLDERS, ...Object.values(GAME_FILES)];
|
||||
const checks = await Promise.all(paths.map(async (name) => {
|
||||
const intended = join(copyPath, name);
|
||||
return relative(intended, await canonicalCopyPath(intended)) === '';
|
||||
}));
|
||||
if (checks.includes(false)) throw new AppError('launch_location');
|
||||
}
|
||||
|
||||
type OrdinaryPhase = 'starting-server' | 'starting-game' | 'running' | 'server-running';
|
||||
|
||||
export async function runOrdinaryLaunch(
|
||||
copyPath: string, dataPath: string, port: number, settings: Settings, signal: AbortSignal,
|
||||
publish: (phase: OrdinaryPhase, gameExit?: GameExit) => void,
|
||||
mods?: { readonly modsDir: string; readonly enabledModIds: readonly string[] },
|
||||
): Promise<GameExit> {
|
||||
const args = parseLaunchArguments(settings.launchArguments);
|
||||
if (!args) throw new AppError('launch_game_failed');
|
||||
publish('starting-server');
|
||||
const server = await startLocalServer(
|
||||
{
|
||||
gameFolder: copyPath,
|
||||
dataFolder: dataPath,
|
||||
port,
|
||||
loggingEnabled: settings.loggingEnabled,
|
||||
...(mods && mods.enabledModIds.length > 0 ? { modsDir: mods.modsDir, enabledModIds: mods.enabledModIds } : {}),
|
||||
},
|
||||
signal,
|
||||
);
|
||||
const stop = new AbortController();
|
||||
const runSignal = AbortSignal.any([signal, stop.signal]);
|
||||
const serverExited = server.exited.then(() => { throw new AppError('launch_server_exited'); });
|
||||
publish('starting-game');
|
||||
const game = runGameProcess(copyPath, args, runSignal, () => publish('running'));
|
||||
try {
|
||||
const gameExit = await Promise.race([game, serverExited]);
|
||||
if (!runSignal.aborted && !settings.closeServerOnGameExit) {
|
||||
publish('server-running', gameExit);
|
||||
if (!runSignal.aborted) await Promise.race([once(runSignal, 'abort'), serverExited]);
|
||||
}
|
||||
return gameExit;
|
||||
} finally {
|
||||
stop.abort();
|
||||
await game.catch(() => undefined);
|
||||
await server.close();
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
import { join } from 'node:path';
|
||||
import { app, BrowserWindow, Menu, nativeImage, shell, Tray } from 'electron';
|
||||
import { app, BrowserWindow, Menu, shell, Tray } from 'electron';
|
||||
import { getSettings } from './config/settings-store.ts';
|
||||
import { bundledResourcePaths } from './resources/resource-paths.ts';
|
||||
|
||||
/**
|
||||
* The launcher's single window: a fixed size without the system frame, like the game's own
|
||||
@@ -26,9 +25,7 @@ export function beginWindowQuit(): void {
|
||||
|
||||
async function hideToTray(window: BrowserWindow): Promise<void> {
|
||||
if (!tray) {
|
||||
const customIcon = nativeImage.createFromPath(bundledResourcePaths().appIcon);
|
||||
const icon = customIcon.isEmpty() ? await app.getFileIcon(process.execPath, { size: 'small' }) : customIcon;
|
||||
tray = new Tray(icon);
|
||||
tray = new Tray(await app.getFileIcon(process.execPath, { size: 'small' }));
|
||||
tray.setToolTip(app.getName());
|
||||
tray.setContextMenu(Menu.buildFromTemplate([{ role: 'quit' }]));
|
||||
tray.on('click', () => showMainWindow());
|
||||
@@ -37,7 +34,6 @@ async function hideToTray(window: BrowserWindow): Promise<void> {
|
||||
}
|
||||
|
||||
export function createMainWindow(): BrowserWindow {
|
||||
const appIcon = nativeImage.createFromPath(bundledResourcePaths().appIcon);
|
||||
const window = new BrowserWindow({
|
||||
width: CONTENT_WIDTH,
|
||||
height: CONTENT_HEIGHT,
|
||||
@@ -48,7 +44,6 @@ export function createMainWindow(): BrowserWindow {
|
||||
frame: false,
|
||||
backgroundColor: BACKGROUND,
|
||||
show: false,
|
||||
...(!appIcon.isEmpty() ? { icon: appIcon } : {}),
|
||||
webPreferences: {
|
||||
preload: join(import.meta.dirname, '../preload/index.cjs'),
|
||||
sandbox: true,
|
||||
|
||||
@@ -1,428 +0,0 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { access, cp, mkdir, readdir, readFile, stat, writeFile } from 'node:fs/promises';
|
||||
import { isAbsolute, join } from 'node:path';
|
||||
import { app, BrowserWindow, dialog, shell } from 'electron';
|
||||
import {
|
||||
computeAutoSortOrder,
|
||||
discoverMods,
|
||||
emptyClientModsConfig,
|
||||
MOD_API_VERSION,
|
||||
normalizeClientModsConfig,
|
||||
resolveModLoadOrder,
|
||||
type ClientModsConfig,
|
||||
type DiscoveredMod,
|
||||
type ModPreset,
|
||||
} from '@wto/mods';
|
||||
import { AppError } from '@shared/errors.ts';
|
||||
import type { InstallRecord } from '@shared/schemas/install.ts';
|
||||
import { ModPresetTransferSchema, type ModListItem, type ModsStateView } from '@shared/schemas/mods.ts';
|
||||
import { readJsonOr, writeJsonAtomic } from '../../util/atomic-json.ts';
|
||||
import { getSettings, updateSettings } from '../config/settings-store.ts';
|
||||
import { listCopies } from '../install/install-record.ts';
|
||||
import { resourcePaths } from '../resources/resource-paths.ts';
|
||||
|
||||
const CLIENT_MODS_CONFIG_FILE = 'mods-config.json';
|
||||
const EXAMPLES_SEEDED_MARKER = '.wto-examples-seeded';
|
||||
const inFlightSeeds = new Map<string, Promise<void>>();
|
||||
|
||||
export function defaultModsFolder(): string {
|
||||
return join(app.getPath('userData'), 'mods');
|
||||
}
|
||||
|
||||
export async function resolveModsFolder(): Promise<{ readonly modsDir: string; readonly defaultModsDir: string; readonly isCustomModsDir: boolean }> {
|
||||
const settings = await getSettings();
|
||||
const defaultModsDir = defaultModsFolder();
|
||||
const isCustomModsDir = settings.modsFolder !== null;
|
||||
const modsDir = settings.modsFolder ?? defaultModsDir;
|
||||
await mkdir(modsDir, { recursive: true });
|
||||
await seedBundledExampleModsOnce(modsDir);
|
||||
return { modsDir, defaultModsDir, isCustomModsDir };
|
||||
}
|
||||
|
||||
/**
|
||||
* Copy newly shipped bundled template mods into the mods folder once each (disabled by default).
|
||||
* Tracks which template folder names have already been seeded in `.wto-examples-seeded` so
|
||||
* deleting a bundled template never restores it, while newly added official templates still
|
||||
* appear for existing users. Serialized per directory to prevent concurrent seeding races.
|
||||
*/
|
||||
async function seedBundledExampleModsOnce(modsDir: string): Promise<void> {
|
||||
const key = modsDir.toLowerCase();
|
||||
const pending = inFlightSeeds.get(key);
|
||||
if (pending) {
|
||||
await pending;
|
||||
return;
|
||||
}
|
||||
const task = (async () => {
|
||||
const markerPath = join(modsDir, EXAMPLES_SEEDED_MARKER);
|
||||
try {
|
||||
const templatesRoot = resourcePaths().modTemplates;
|
||||
if (!(await pathExists(templatesRoot))) return;
|
||||
const seeded = await readSeededTemplateNames(markerPath, modsDir);
|
||||
const templates = await readdir(templatesRoot, { withFileTypes: true });
|
||||
let changed = false;
|
||||
for (const entry of templates) {
|
||||
if (!entry.isDirectory()) continue;
|
||||
if (seeded.has(entry.name)) continue;
|
||||
const dest = join(modsDir, entry.name);
|
||||
if (!(await pathExists(dest))) {
|
||||
await cp(join(templatesRoot, entry.name), dest, { recursive: true });
|
||||
}
|
||||
seeded.add(entry.name);
|
||||
changed = true;
|
||||
}
|
||||
if (changed || !(await pathExists(markerPath))) {
|
||||
await writeFile(markerPath, JSON.stringify({ seeded: [...seeded].sort() }, null, 2) + '\n', 'utf8');
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('[mods] seeding bundled example mods skipped:', error);
|
||||
}
|
||||
})().finally(() => {
|
||||
inFlightSeeds.delete(key);
|
||||
});
|
||||
inFlightSeeds.set(key, task);
|
||||
await task;
|
||||
}
|
||||
|
||||
async function readSeededTemplateNames(markerPath: string, modsDir: string): Promise<Set<string>> {
|
||||
if (!(await pathExists(markerPath))) return new Set();
|
||||
try {
|
||||
const raw = (await readFile(markerPath, 'utf8')).trim();
|
||||
if (raw === '1') {
|
||||
// Legacy marker from initial 2-template version: mark existing folders as already seeded
|
||||
// so newly added official templates (e.g. official-map-selector) are still delivered once.
|
||||
const existing = await readdir(modsDir);
|
||||
const set = new Set(['example-vehicle-tweak', 'example-server-script']);
|
||||
for (const name of existing) set.add(name);
|
||||
return set;
|
||||
}
|
||||
const parsed = JSON.parse(raw) as { seeded?: unknown };
|
||||
if (Array.isArray(parsed.seeded)) {
|
||||
return new Set(parsed.seeded.filter((item): item is string => typeof item === 'string'));
|
||||
}
|
||||
} catch { /* ignore */ }
|
||||
return new Set();
|
||||
}
|
||||
|
||||
async function pathExists(path: string): Promise<boolean> {
|
||||
try {
|
||||
await access(path);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export async function openModsFolder(): Promise<void> {
|
||||
const { modsDir } = await resolveModsFolder();
|
||||
const failure = await shell.openPath(modsDir);
|
||||
if (failure) console.warn('[mods] opening the mods folder failed:', modsDir, failure);
|
||||
}
|
||||
|
||||
export async function getModsState(copyId: string): Promise<ModsStateView> {
|
||||
const copy = await requireCopy(copyId);
|
||||
return buildModsStateView(copy);
|
||||
}
|
||||
|
||||
export async function setModEnabled(copyId: string, modId: string, enabled: boolean): Promise<ModsStateView> {
|
||||
const copy = await requireCopy(copyId);
|
||||
const { modsDir } = await resolveModsFolder();
|
||||
const discovered = discoverMods(modsDir);
|
||||
const current = normalizeClientModsConfig(await readClientModsConfig(copy.dataPath), discovered.mods);
|
||||
const next: ClientModsConfig = {
|
||||
...current,
|
||||
activePresetId: null,
|
||||
enabled: { ...current.enabled, [modId]: enabled },
|
||||
};
|
||||
await writeClientModsConfig(copy.dataPath, next);
|
||||
return buildModsStateView(copy, next);
|
||||
}
|
||||
|
||||
export async function setModsOrder(copyId: string, order: readonly string[]): Promise<ModsStateView> {
|
||||
const copy = await requireCopy(copyId);
|
||||
const { modsDir } = await resolveModsFolder();
|
||||
const discovered = discoverMods(modsDir);
|
||||
const current = normalizeClientModsConfig(await readClientModsConfig(copy.dataPath), discovered.mods);
|
||||
const next = normalizeClientModsConfig({ ...current, activePresetId: null, order }, discovered.mods);
|
||||
await writeClientModsConfig(copy.dataPath, next);
|
||||
return buildModsStateView(copy, next);
|
||||
}
|
||||
|
||||
export async function autoSortMods(copyId: string): Promise<ModsStateView> {
|
||||
const copy = await requireCopy(copyId);
|
||||
const { modsDir } = await resolveModsFolder();
|
||||
const discovered = discoverMods(modsDir);
|
||||
const current = normalizeClientModsConfig(await readClientModsConfig(copy.dataPath), discovered.mods);
|
||||
const sortedOrder = computeAutoSortOrder(discovered.mods, current.order);
|
||||
const next: ClientModsConfig = {
|
||||
...current,
|
||||
activePresetId: null,
|
||||
order: sortedOrder,
|
||||
};
|
||||
await writeClientModsConfig(copy.dataPath, next);
|
||||
return buildModsStateView(copy, next);
|
||||
}
|
||||
|
||||
export async function saveModPreset(copyId: string, name: string, overwriteId?: string): Promise<ModsStateView> {
|
||||
const copy = await requireCopy(copyId);
|
||||
const { modsDir } = await resolveModsFolder();
|
||||
const discovered = discoverMods(modsDir);
|
||||
const current = normalizeClientModsConfig(await readClientModsConfig(copy.dataPath), discovered.mods);
|
||||
const now = new Date().toISOString();
|
||||
|
||||
let presets: ModPreset[];
|
||||
let presetId: string;
|
||||
if (overwriteId && current.presets.some((preset) => preset.id === overwriteId)) {
|
||||
presetId = overwriteId;
|
||||
presets = current.presets.map((preset) => (
|
||||
preset.id === overwriteId
|
||||
? { id: preset.id, name, order: [...current.order], enabled: { ...current.enabled }, updatedAt: now }
|
||||
: preset
|
||||
));
|
||||
} else {
|
||||
presetId = randomUUID();
|
||||
presets = [
|
||||
...current.presets,
|
||||
{ id: presetId, name, order: [...current.order], enabled: { ...current.enabled }, updatedAt: now },
|
||||
];
|
||||
}
|
||||
|
||||
const next: ClientModsConfig = {
|
||||
...current,
|
||||
activePresetId: presetId,
|
||||
presets,
|
||||
};
|
||||
await writeClientModsConfig(copy.dataPath, next);
|
||||
return buildModsStateView(copy, next);
|
||||
}
|
||||
|
||||
export async function applyModPreset(copyId: string, presetId: string): Promise<ModsStateView> {
|
||||
const copy = await requireCopy(copyId);
|
||||
const { modsDir } = await resolveModsFolder();
|
||||
const discovered = discoverMods(modsDir);
|
||||
const current = normalizeClientModsConfig(await readClientModsConfig(copy.dataPath), discovered.mods);
|
||||
const preset = current.presets.find((item) => item.id === presetId);
|
||||
if (!preset) throw new AppError('mods_preset_invalid');
|
||||
|
||||
const next = normalizeClientModsConfig({
|
||||
...current,
|
||||
order: preset.order,
|
||||
enabled: preset.enabled,
|
||||
activePresetId: preset.id,
|
||||
}, discovered.mods);
|
||||
await writeClientModsConfig(copy.dataPath, next);
|
||||
return buildModsStateView(copy, next);
|
||||
}
|
||||
|
||||
export async function deleteModPreset(copyId: string, presetId: string): Promise<ModsStateView> {
|
||||
const copy = await requireCopy(copyId);
|
||||
const current = await readClientModsConfig(copy.dataPath);
|
||||
const next: ClientModsConfig = {
|
||||
...current,
|
||||
activePresetId: current.activePresetId === presetId ? null : current.activePresetId,
|
||||
presets: current.presets.filter((preset) => preset.id !== presetId),
|
||||
};
|
||||
await writeClientModsConfig(copy.dataPath, next);
|
||||
return buildModsStateView(copy, next);
|
||||
}
|
||||
|
||||
export async function exportModPreset(
|
||||
copyId: string,
|
||||
presetId: string,
|
||||
window: BrowserWindow | null,
|
||||
): Promise<{ readonly path: string | null }> {
|
||||
const copy = await requireCopy(copyId);
|
||||
const current = await readClientModsConfig(copy.dataPath);
|
||||
const preset = current.presets.find((item) => item.id === presetId);
|
||||
if (!preset) throw new AppError('mods_preset_invalid');
|
||||
|
||||
const safeName = preset.name.replace(/[^A-Za-z0-9\u4e00-\u9fa5._-]+/g, '-').replace(/^-+|-+$/g, '') || 'preset';
|
||||
const dialogOptions = {
|
||||
defaultPath: `${safeName}.wto-mods-preset.json`,
|
||||
filters: [{ name: 'WTOffline Mod Preset', extensions: ['json'] }],
|
||||
};
|
||||
const choice = window
|
||||
? await dialog.showSaveDialog(window, dialogOptions)
|
||||
: await dialog.showSaveDialog(dialogOptions);
|
||||
if (choice.canceled || !choice.filePath) return { path: null };
|
||||
|
||||
const payload = {
|
||||
format: 1 as const,
|
||||
name: preset.name,
|
||||
order: [...preset.order],
|
||||
enabled: { ...preset.enabled },
|
||||
};
|
||||
await writeFile(choice.filePath, JSON.stringify(payload, null, 2) + '\n', 'utf8');
|
||||
return { path: choice.filePath };
|
||||
}
|
||||
|
||||
export async function importModPreset(
|
||||
copyId: string,
|
||||
window: BrowserWindow | null,
|
||||
): Promise<{ readonly imported: boolean; readonly state: ModsStateView }> {
|
||||
const copy = await requireCopy(copyId);
|
||||
const dialogOptions = {
|
||||
properties: ['openFile'] as Array<'openFile'>,
|
||||
filters: [{ name: 'WTOffline Mod Preset', extensions: ['json'] }],
|
||||
};
|
||||
const choice = window
|
||||
? await dialog.showOpenDialog(window, dialogOptions)
|
||||
: await dialog.showOpenDialog(dialogOptions);
|
||||
if (choice.canceled || !choice.filePaths[0]) {
|
||||
return { imported: false, state: await buildModsStateView(copy) };
|
||||
}
|
||||
|
||||
let parsedRaw: unknown;
|
||||
try {
|
||||
parsedRaw = JSON.parse(await readFile(choice.filePaths[0], 'utf8')) as unknown;
|
||||
} catch {
|
||||
throw new AppError('mods_preset_invalid');
|
||||
}
|
||||
const validated = ModPresetTransferSchema.safeParse(parsedRaw);
|
||||
if (!validated.success) throw new AppError('mods_preset_invalid');
|
||||
|
||||
const current = await readClientModsConfig(copy.dataPath);
|
||||
const newPreset: ModPreset = {
|
||||
id: randomUUID(),
|
||||
name: validated.data.name,
|
||||
order: validated.data.order,
|
||||
enabled: validated.data.enabled,
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
const next: ClientModsConfig = {
|
||||
...current,
|
||||
presets: [...current.presets, newPreset],
|
||||
};
|
||||
await writeClientModsConfig(copy.dataPath, next);
|
||||
return { imported: true, state: await buildModsStateView(copy, next) };
|
||||
}
|
||||
|
||||
export async function setModsFolder(copyId: string, folderPath: string | null): Promise<ModsStateView> {
|
||||
if (folderPath !== null) {
|
||||
if (!isAbsolute(folderPath)) throw new AppError('mods_folder_invalid');
|
||||
try {
|
||||
await mkdir(folderPath, { recursive: true });
|
||||
const info = await stat(folderPath);
|
||||
if (!info.isDirectory()) throw new AppError('mods_folder_invalid');
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) throw error;
|
||||
throw new AppError('mods_folder_invalid');
|
||||
}
|
||||
}
|
||||
await updateSettings({ modsFolder: folderPath });
|
||||
const copy = await requireCopy(copyId);
|
||||
return buildModsStateView(copy);
|
||||
}
|
||||
|
||||
/** Resolve ordered enabled mods for a launch; rejects when blocking dependency/conflict errors exist. */
|
||||
export async function resolveEnabledModsForLaunch(
|
||||
dataPath: string,
|
||||
gameVersion: string | null,
|
||||
): Promise<{ readonly modsDir: string; readonly enabledMods: readonly DiscoveredMod[] }> {
|
||||
const { modsDir } = await resolveModsFolder();
|
||||
const discovered = discoverMods(modsDir);
|
||||
const config = normalizeClientModsConfig(await readClientModsConfig(dataPath), discovered.mods);
|
||||
const resolved = resolveModLoadOrder(discovered.mods, config, gameVersion);
|
||||
if (resolved.hasBlockingErrors) {
|
||||
console.error('[mods] blocking mod issues prevented launch:', resolved.issues.filter((i) => i.severity === 'error'));
|
||||
throw new AppError('mods_blocking_issues');
|
||||
}
|
||||
return { modsDir, enabledMods: resolved.enabledMods };
|
||||
}
|
||||
|
||||
async function buildModsStateView(copy: InstallRecord, preloadedConfig?: ClientModsConfig): Promise<ModsStateView> {
|
||||
const { modsDir, defaultModsDir, isCustomModsDir } = await resolveModsFolder();
|
||||
const discovered = discoverMods(modsDir);
|
||||
const rawConfig = preloadedConfig ?? await readClientModsConfig(copy.dataPath);
|
||||
const config = normalizeClientModsConfig(rawConfig, discovered.mods);
|
||||
const resolved = resolveModLoadOrder(discovered.mods, config, copy.gameVersion);
|
||||
|
||||
const byId = new Map(discovered.mods.map((mod) => [mod.manifest.id, mod]));
|
||||
const orderedMods: ModListItem[] = config.order
|
||||
.map((id) => byId.get(id))
|
||||
.filter((mod): mod is DiscoveredMod => mod !== undefined)
|
||||
.map(toModListItem);
|
||||
|
||||
return {
|
||||
modsDir,
|
||||
defaultModsDir,
|
||||
isCustomModsDir,
|
||||
apiVersion: MOD_API_VERSION,
|
||||
mods: orderedMods,
|
||||
discoveryErrors: [...discovered.errors],
|
||||
order: [...config.order],
|
||||
enabled: { ...config.enabled },
|
||||
activePresetId: config.activePresetId,
|
||||
presets: config.presets.map((preset) => ({
|
||||
id: preset.id,
|
||||
name: preset.name,
|
||||
order: [...preset.order],
|
||||
enabled: { ...preset.enabled },
|
||||
updatedAt: preset.updatedAt,
|
||||
})),
|
||||
issues: [...resolved.issues],
|
||||
hasBlockingErrors: resolved.hasBlockingErrors,
|
||||
};
|
||||
}
|
||||
|
||||
function toModListItem(mod: DiscoveredMod): ModListItem {
|
||||
return {
|
||||
id: mod.manifest.id,
|
||||
folderName: mod.folderName,
|
||||
rootDir: mod.rootDir,
|
||||
name: mod.manifest.name,
|
||||
...(mod.manifest.description !== undefined ? { description: mod.manifest.description } : {}),
|
||||
version: mod.manifest.version,
|
||||
author: mod.manifest.author,
|
||||
apiVersion: mod.manifest.apiVersion,
|
||||
gameVersions: [...mod.manifest.gameVersions],
|
||||
requires: [...mod.manifest.requires],
|
||||
conflicts: [...mod.manifest.conflicts],
|
||||
loadAfter: [...mod.manifest.loadAfter],
|
||||
loadBefore: [...mod.manifest.loadBefore],
|
||||
badges: [...mod.content.badges],
|
||||
hasServerScript: mod.content.serverEntry !== undefined,
|
||||
serverTuningFiles: [...mod.content.serverTuningFiles],
|
||||
packOperations: [...mod.content.packOperations],
|
||||
guiPatchCount: mod.content.guiPatchDirs.length,
|
||||
exePatchCount: mod.content.exePatchDirs.length,
|
||||
hasClientAddon: mod.content.hasClientAddon,
|
||||
addonFileCount: mod.content.addonRelativeFiles.length,
|
||||
clientFileCount: mod.content.clientFiles.length,
|
||||
hasConfigBlkPatch: mod.content.configBlkPatch !== undefined,
|
||||
};
|
||||
}
|
||||
|
||||
async function requireCopy(copyId: string): Promise<InstallRecord> {
|
||||
const copies = await listCopies();
|
||||
const copy = copies.copies.find((entry) => entry.id === copyId);
|
||||
if (!copy) throw new AppError('copy_not_found');
|
||||
return copy;
|
||||
}
|
||||
|
||||
async function readClientModsConfig(dataPath: string): Promise<ClientModsConfig> {
|
||||
const path = join(dataPath, CLIENT_MODS_CONFIG_FILE);
|
||||
try {
|
||||
const raw = await readJsonOr(path, null);
|
||||
if (!raw || typeof raw !== 'object') return emptyClientModsConfig();
|
||||
const obj = raw as Partial<ClientModsConfig>;
|
||||
return {
|
||||
format: 1,
|
||||
order: Array.isArray(obj.order) ? obj.order.filter((item): item is string => typeof item === 'string') : [],
|
||||
enabled: obj.enabled && typeof obj.enabled === 'object' ? { ...obj.enabled } : {},
|
||||
activePresetId: typeof obj.activePresetId === 'string' ? obj.activePresetId : null,
|
||||
presets: Array.isArray(obj.presets) ? obj.presets : [],
|
||||
};
|
||||
} catch (error) {
|
||||
console.warn('[mods] unreadable client mods config, using defaults:', path, error);
|
||||
return emptyClientModsConfig();
|
||||
}
|
||||
}
|
||||
|
||||
async function writeClientModsConfig(dataPath: string, config: ClientModsConfig): Promise<void> {
|
||||
try {
|
||||
await writeJsonAtomic(join(dataPath, CLIENT_MODS_CONFIG_FILE), config);
|
||||
} catch (error) {
|
||||
console.error('[mods] writing client mods config failed:', error);
|
||||
throw new AppError('mods_write_failed');
|
||||
}
|
||||
}
|
||||
@@ -11,13 +11,12 @@
|
||||
* Only the active pack is kept.
|
||||
*/
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import { existsSync, readFileSync } from 'node:fs';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { mkdir, readdir, rename, rm, writeFile } from 'node:fs/promises';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { app } from 'electron';
|
||||
import {
|
||||
checkPatchSet,
|
||||
comparePackVersions,
|
||||
formatManifest,
|
||||
isPackVersion,
|
||||
manifestIncompatibility,
|
||||
@@ -45,31 +44,17 @@ function activeFile(): string {
|
||||
return join(storeFolder(), 'active.json');
|
||||
}
|
||||
|
||||
/** The version of a bundled set that carries a manifest (a packaged launcher's), else null. */
|
||||
export function bundledPatchVersion(bundledRoot: string): string | null {
|
||||
const path = join(bundledRoot, MANIFEST_FILE);
|
||||
if (!existsSync(path)) return null;
|
||||
try {
|
||||
return parseManifest(readFileSync(path, 'utf8')).version;
|
||||
} catch (error) {
|
||||
console.warn('[patch-pack] the bundled manifest is unreadable:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The active downloaded pack, when there is one this launcher can use and it is newer than the
|
||||
* bundled patch set. Synchronous, because the resource paths are; it reads two small files.
|
||||
* The active downloaded pack, when there is one this launcher can use. Synchronous, because the
|
||||
* resource paths are; it reads two small files.
|
||||
*/
|
||||
export function activeDownloadedPack(bundledRoot?: string): DownloadedPack | null {
|
||||
export function activeDownloadedPack(): DownloadedPack | null {
|
||||
try {
|
||||
const active = JSON.parse(readFileSync(activeFile(), 'utf8')) as { version?: unknown };
|
||||
if (typeof active.version !== 'string' || !isPackVersion(active.version)) return null;
|
||||
const root = join(storeFolder(), active.version);
|
||||
const manifest = parseManifest(readFileSync(join(root, MANIFEST_FILE), 'utf8'));
|
||||
if (manifest.version !== active.version || manifestIncompatibility(manifest, app.getVersion())) return null;
|
||||
const bundled = bundledRoot ? bundledPatchVersion(bundledRoot) : null;
|
||||
if (bundled && comparePackVersions(manifest.version, bundled) <= 0) return null;
|
||||
return { root, manifest };
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') console.warn('[patch-pack] the active pack is unusable:', error);
|
||||
|
||||
@@ -1,14 +1,17 @@
|
||||
/**
|
||||
* Adaptation pack updates: which patch set the builds use, whether a source has a newer pack, and
|
||||
* Adaptation pack updates: which patch set the builds use, whether GitHub has a newer pack, and
|
||||
* installing it. The launcher checks at start (when the setting allows) and from the About page;
|
||||
* a pack is installed only when the player confirms.
|
||||
*
|
||||
* A pack is newer when its version is above the active set's. A bundled set without a version
|
||||
* (a repository checkout) is older than every pack.
|
||||
*/
|
||||
import { existsSync, readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { app } from 'electron';
|
||||
import {
|
||||
comparePackVersions,
|
||||
MANIFEST_FILE,
|
||||
manifestIncompatibility,
|
||||
parseManifest,
|
||||
PatchPackError,
|
||||
@@ -19,24 +22,26 @@ import {
|
||||
} from '@wto/patcher';
|
||||
import type { ActivePatchSet, PackApplyResult, PackCheck, PackProblem, PackRelease } from '@shared/schemas/patch-pack.ts';
|
||||
import { bundledResourcePaths, usesDownloadedPacks } from '../resources/resource-paths.ts';
|
||||
import { activeDownloadedPack, bundledPatchVersion, installPack, useBundledPatchSet } from './pack-store.ts';
|
||||
import {
|
||||
newestProjectRelease, projectReleaseVersion, ReleasePageLimitError, withReleaseSources, type PackReleaseFiles, type ReleaseSource,
|
||||
} from './release-feed.ts';
|
||||
import { FeedUnreachableError, readReleaseAsset, RELEASE_MANIFEST_MAX_BYTES, RELEASE_SIGNATURE_MAX_BYTES } from './release-assets.ts';
|
||||
import { activeDownloadedPack, installPack, useBundledPatchSet } from './pack-store.ts';
|
||||
import { downloadReleaseFile, FeedUnreachableError, newestPackRelease, type PackReleaseFiles } from './release-feed.ts';
|
||||
|
||||
/** The manifest copy beside a release is a few hundred bytes. */
|
||||
const MANIFEST_COPY_MAX_BYTES = 64 * 1024;
|
||||
/** A signature file is 89 bytes. */
|
||||
const SIGNATURE_MAX_BYTES = 1024;
|
||||
|
||||
export function activePatchSet(): ActivePatchSet {
|
||||
const root = bundledResourcePaths().patches;
|
||||
const pack = usesDownloadedPacks() ? activeDownloadedPack(root) : null;
|
||||
const pack = usesDownloadedPacks() ? activeDownloadedPack() : null;
|
||||
if (pack) return { source: 'downloaded', version: pack.manifest.version, gameVersions: [...pack.manifest.gameVersions] };
|
||||
return { source: 'bundled', version: bundledPatchVersion(root), gameVersions: recordedGameVersions(root) };
|
||||
const root = bundledResourcePaths().patches;
|
||||
return { source: 'bundled', version: bundledVersion(root), gameVersions: recordedGameVersions(root) };
|
||||
}
|
||||
|
||||
export async function checkPackUpdate(): Promise<PackCheck> {
|
||||
const active = activePatchSet();
|
||||
if (!packSigningPublicKey()) return { status: 'failed', active, latest: null, problem: 'no_signing_key' };
|
||||
try {
|
||||
const found = await withReleaseSources((source) => newestRelease(active.version, source));
|
||||
const found = await newestRelease();
|
||||
if (!found || !isNewer(found.manifest.version, active.version)) return { status: 'up_to_date', active, latest: found ? release(found) : null, problem: null };
|
||||
const status = manifestIncompatibility(found.manifest, app.getVersion()) ? 'needs_app_update' : 'available';
|
||||
return { status, active, latest: release(found), problem: null };
|
||||
@@ -46,26 +51,18 @@ export async function checkPackUpdate(): Promise<PackCheck> {
|
||||
}
|
||||
}
|
||||
|
||||
/** Download and activate the selected pack when it is newer than the active set and usable. */
|
||||
export async function applyPackUpdate(version: string): Promise<PackApplyResult> {
|
||||
/** Download and activate the newest pack, when it is newer than the active set and usable. */
|
||||
export async function applyPackUpdate(): Promise<PackApplyResult> {
|
||||
if (!packSigningPublicKey()) return { ok: false, problem: 'no_signing_key' };
|
||||
if (!isNewer(version, activePatchSet().version)) return { ok: false, problem: 'up_to_date' };
|
||||
try {
|
||||
const downloaded = await withReleaseSources(async (source) => {
|
||||
const files = await projectReleaseVersion('pack', version, source);
|
||||
const manifest = await readPackManifest(files);
|
||||
if (manifestIncompatibility(manifest, app.getVersion())) return null;
|
||||
const tuning = patchPackTuning();
|
||||
const zip = await readReleaseAsset(files.zipUrl, tuning.maxPackBytes, AbortSignal.timeout(tuning.requestTimeoutMs), source);
|
||||
const signature = new TextDecoder().decode(await readReleaseAsset(
|
||||
files.signatureUrl, RELEASE_SIGNATURE_MAX_BYTES, AbortSignal.timeout(tuning.requestTimeoutMs), source,
|
||||
));
|
||||
return { zip, signature };
|
||||
});
|
||||
if (!downloaded) return { ok: false, problem: 'needs_app_update' };
|
||||
if (!isNewer(version, activePatchSet().version)) return { ok: false, problem: 'up_to_date' };
|
||||
await installPack(version, downloaded.zip, downloaded.signature);
|
||||
console.info(`[patch-pack] pack ${version} installed and active`);
|
||||
const found = await newestRelease();
|
||||
if (!found || !isNewer(found.manifest.version, activePatchSet().version)) return { ok: false, problem: 'up_to_date' };
|
||||
if (manifestIncompatibility(found.manifest, app.getVersion())) return { ok: false, problem: 'needs_app_update' };
|
||||
const tuning = patchPackTuning();
|
||||
const zip = await downloadReleaseFile(found.files.zipUrl, tuning.maxPackBytes);
|
||||
const signature = new TextDecoder().decode(await downloadReleaseFile(found.files.signatureUrl, SIGNATURE_MAX_BYTES));
|
||||
await installPack(found.files.version, zip, signature);
|
||||
console.info(`[patch-pack] pack ${found.files.version} installed and active`);
|
||||
return { ok: true, active: activePatchSet() };
|
||||
} catch (error) {
|
||||
console.warn('[patch-pack] update failed:', error);
|
||||
@@ -84,17 +81,13 @@ interface FoundRelease {
|
||||
readonly manifest: PatchPackManifest;
|
||||
}
|
||||
|
||||
async function newestRelease(installedVersion: string | null, source: ReleaseSource): Promise<FoundRelease | null> {
|
||||
const files = await newestProjectRelease('pack', installedVersion, source);
|
||||
return files ? { files, manifest: await readPackManifest(files) } : null;
|
||||
}
|
||||
|
||||
async function readPackManifest(files: PackReleaseFiles): Promise<PatchPackManifest> {
|
||||
const deadline = AbortSignal.timeout(patchPackTuning().requestTimeoutMs);
|
||||
const text = new TextDecoder().decode(await readReleaseAsset(files.manifestUrl, RELEASE_MANIFEST_MAX_BYTES, deadline, files.source));
|
||||
async function newestRelease(): Promise<FoundRelease | null> {
|
||||
const files = await newestPackRelease();
|
||||
if (!files) return null;
|
||||
const text = new TextDecoder().decode(await downloadReleaseFile(files.manifestUrl, MANIFEST_COPY_MAX_BYTES));
|
||||
const manifest = parseManifest(text);
|
||||
if (manifest.version !== files.version) throw new PatchPackError('contents', `release ${files.version} carries the manifest of ${manifest.version}`);
|
||||
return manifest;
|
||||
return { files, manifest };
|
||||
}
|
||||
|
||||
function release(found: FoundRelease): PackRelease {
|
||||
@@ -110,8 +103,19 @@ function isNewer(candidate: string, active: string | null): boolean {
|
||||
return active === null || comparePackVersions(candidate, active) > 0;
|
||||
}
|
||||
|
||||
/** The version of a bundled set that carries a manifest (a packaged launcher's), else null. */
|
||||
function bundledVersion(root: string): string | null {
|
||||
const path = join(root, MANIFEST_FILE);
|
||||
if (!existsSync(path)) return null;
|
||||
try {
|
||||
return parseManifest(readFileSync(path, 'utf8')).version;
|
||||
} catch (error) {
|
||||
console.warn('[patch-pack] the bundled manifest is unreadable:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function problemOf(error: unknown): PackProblem {
|
||||
if (error instanceof ReleasePageLimitError) return 'page_limit';
|
||||
if (error instanceof FeedUnreachableError) return 'network';
|
||||
if (error instanceof PatchPackError) {
|
||||
if (error.problem === 'signature') return 'signature';
|
||||
|
||||
@@ -1,87 +0,0 @@
|
||||
import type { Readable } from 'node:stream';
|
||||
import { net, type IncomingMessage } from 'electron';
|
||||
import { PatchPackError } from '@wto/patcher';
|
||||
import type { ReleaseSource } from './release-feed.ts';
|
||||
|
||||
const GITHUB_ASSET_HOSTS = new Set(['github.com', 'release-assets.githubusercontent.com', 'objects.githubusercontent.com']);
|
||||
export const UPDATE_USER_AGENT = 'WTOffline-Launcher';
|
||||
export const RELEASE_MANIFEST_MAX_BYTES = 64 * 1024;
|
||||
export const RELEASE_SIGNATURE_MAX_BYTES = 1024;
|
||||
|
||||
export class FeedUnreachableError extends Error {
|
||||
override readonly name = 'FeedUnreachableError';
|
||||
}
|
||||
|
||||
function isReleaseAsset(value: string, source: ReleaseSource): boolean {
|
||||
try {
|
||||
const url = new URL(value);
|
||||
if (url.protocol !== 'https:' || url.username || url.password) return false;
|
||||
return !source.githubDownloads || (!url.port && GITHUB_ASSET_HOSTS.has(url.hostname));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Download over HTTPS, including redirects, without sending session credentials. */
|
||||
export function requestReleaseAsset(
|
||||
url: URL, signal: AbortSignal, source: ReleaseSource,
|
||||
): Promise<IncomingMessage & Readable> {
|
||||
if (signal.aborted) return Promise.reject(new FeedUnreachableError('The release download timed out.'));
|
||||
if (!isReleaseAsset(url.href, source)) {
|
||||
return Promise.reject(new FeedUnreachableError('The release asset URL is not allowed.'));
|
||||
}
|
||||
return new Promise((resolve, reject) => {
|
||||
const request = net.request({ url: url.href, credentials: 'omit', redirect: 'manual' });
|
||||
request.setHeader('User-Agent', UPDATE_USER_AGENT);
|
||||
const cleanup = (): void => signal.removeEventListener('abort', abort);
|
||||
const fail = (error: FeedUnreachableError): void => {
|
||||
cleanup();
|
||||
reject(error);
|
||||
request.abort();
|
||||
};
|
||||
const abort = (): void => fail(new FeedUnreachableError('The release download timed out.'));
|
||||
signal.addEventListener('abort', abort, { once: true });
|
||||
|
||||
request.once('error', (error) => {
|
||||
cleanup();
|
||||
reject(new FeedUnreachableError('The release asset could not be downloaded.', { cause: error }));
|
||||
});
|
||||
request.on('redirect', (_status, _method, destination) => {
|
||||
if (isReleaseAsset(destination, source)) request.followRedirect();
|
||||
else fail(new FeedUnreachableError('The release asset redirected to a disallowed URL.'));
|
||||
});
|
||||
request.once('response', (response) => {
|
||||
if (response.statusCode !== 200) {
|
||||
fail(new FeedUnreachableError(`The update source answered HTTP ${response.statusCode} for a release asset.`));
|
||||
return;
|
||||
}
|
||||
const stream = response as IncomingMessage & Readable;
|
||||
stream.once('end', cleanup);
|
||||
stream.once('close', cleanup);
|
||||
resolve(stream);
|
||||
});
|
||||
request.end();
|
||||
});
|
||||
}
|
||||
|
||||
export async function* releaseAssetChunks(response: Readable): AsyncGenerator<Buffer> {
|
||||
try {
|
||||
for await (const chunk of response) yield chunk as Buffer;
|
||||
} catch (error) {
|
||||
throw new FeedUnreachableError('The release asset download was interrupted.', { cause: error });
|
||||
}
|
||||
}
|
||||
|
||||
export async function readReleaseAsset(
|
||||
url: URL, limit: number, signal: AbortSignal, source: ReleaseSource,
|
||||
): Promise<Uint8Array> {
|
||||
const response = await requestReleaseAsset(url, signal, source);
|
||||
const chunks: Buffer[] = [];
|
||||
let size = 0;
|
||||
for await (const chunk of releaseAssetChunks(response)) {
|
||||
size += chunk.length;
|
||||
if (size > limit) throw new PatchPackError('size', 'the release asset is larger than expected');
|
||||
chunks.push(chunk);
|
||||
}
|
||||
return Buffer.concat(chunks);
|
||||
}
|
||||
@@ -1,286 +1,80 @@
|
||||
/**
|
||||
* The launcher and adaptation pack channels share an anonymous, GitHub-compatible release list.
|
||||
* The primary release source is tried first, followed by any player-configured mirror and default fallbacks.
|
||||
* Adaptation pack releases on GitHub: the newest release tagged `patches-<version>` that carries
|
||||
* all three files (zip, signature, manifest copy), and downloads of those files.
|
||||
*
|
||||
* Requests send no account, no cookie and nothing about the player; GitHub sees an anonymous
|
||||
* request with a generic user agent.
|
||||
*/
|
||||
import { net } from 'electron';
|
||||
import {
|
||||
compareAppVersions, comparePackVersions, packFileNames, packVersionOfTag, PatchPackError, patchPackTuning,
|
||||
} from '@wto/patcher';
|
||||
import { z } from 'zod';
|
||||
import { AppReleaseVersionSchema, launcherReleaseFiles, portableLauncherReleaseFiles } from '@shared/schemas/app-update.ts';
|
||||
import { releaseRepositoryUrl } from '@shared/update-source.ts';
|
||||
import { getSettings } from '../config/settings-store.ts';
|
||||
import { FeedUnreachableError, UPDATE_USER_AGENT } from './release-assets.ts';
|
||||
|
||||
export interface ReleaseSource {
|
||||
readonly feed: URL;
|
||||
readonly githubDownloads: URL | null;
|
||||
}
|
||||
|
||||
export interface PortableReleaseAssets {
|
||||
readonly archive: URL;
|
||||
readonly manifest: URL;
|
||||
readonly signature: URL;
|
||||
}
|
||||
|
||||
export interface LauncherRelease {
|
||||
readonly source: ReleaseSource;
|
||||
readonly version: string;
|
||||
readonly notes: string;
|
||||
readonly installer: URL;
|
||||
readonly manifest: URL;
|
||||
readonly signature: URL;
|
||||
readonly portable?: PortableReleaseAssets;
|
||||
}
|
||||
import { comparePackVersions, packFileNames, packVersionOfTag, PatchPackError, patchPackTuning } from '@wto/patcher';
|
||||
|
||||
export interface PackReleaseFiles {
|
||||
readonly source: ReleaseSource;
|
||||
readonly version: string;
|
||||
readonly publishedAt: string | null;
|
||||
readonly zipUrl: URL;
|
||||
readonly signatureUrl: URL;
|
||||
readonly manifestUrl: URL;
|
||||
readonly zipUrl: string;
|
||||
readonly signatureUrl: string;
|
||||
readonly manifestUrl: string;
|
||||
}
|
||||
|
||||
interface ReleaseByChannel {
|
||||
launcher: LauncherRelease;
|
||||
pack: PackReleaseFiles;
|
||||
/** Thrown when GitHub cannot be reached or answers with an error. */
|
||||
export class FeedUnreachableError extends Error {
|
||||
override readonly name = 'FeedUnreachableError';
|
||||
}
|
||||
|
||||
type ReleaseChannel = keyof ReleaseByChannel;
|
||||
type ReleaseVersions = { [Channel in ReleaseChannel]: Map<string, ReleaseByChannel[Channel]> };
|
||||
const HEADERS = { Accept: 'application/vnd.github+json', 'User-Agent': 'WTOffline-Launcher', 'X-GitHub-Api-Version': '2022-11-28' };
|
||||
|
||||
interface ReleaseListing {
|
||||
readonly versions: ReleaseVersions;
|
||||
readonly incomplete: Readonly<Partial<Record<ReleaseChannel, string>>>;
|
||||
readonly pageLimit: number | null;
|
||||
}
|
||||
|
||||
/** Thrown when the list ends at the configured page limit without finding a newer release. */
|
||||
export class ReleasePageLimitError extends Error {
|
||||
override readonly name = 'ReleasePageLimitError';
|
||||
}
|
||||
|
||||
const GITHUB_HEADERS = { Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28' };
|
||||
const ReleaseAsset = z.object({ name: z.string(), browser_download_url: z.string().optional() });
|
||||
const LauncherReleaseEntry = z.object({
|
||||
draft: z.literal(false),
|
||||
prerelease: z.literal(false),
|
||||
assets: z.array(ReleaseAsset),
|
||||
body: z.string().nullable().optional(),
|
||||
});
|
||||
|
||||
const listings = new Map<string, Promise<ReleaseListing>>();
|
||||
|
||||
function releaseSource(repository: URL): ReleaseSource {
|
||||
const githubPath = repository.origin === 'https://github.com' ? repository.pathname
|
||||
: repository.origin === 'https://api.github.com'
|
||||
? /^\/repos(\/[\w.-]+\/[\w.-]+)(?:\/releases)?$/.exec(repository.pathname)?.[1]
|
||||
: null;
|
||||
if (githubPath) {
|
||||
return {
|
||||
feed: new URL(`https://api.github.com/repos${githubPath}/releases`),
|
||||
githubDownloads: new URL(`https://github.com${githubPath}/releases/download/`),
|
||||
};
|
||||
}
|
||||
const feed = new URL(repository);
|
||||
if (!feed.pathname.endsWith('/releases')) feed.pathname = `${feed.pathname.replace(/\/$/, '')}/releases`;
|
||||
return { feed, githubDownloads: null };
|
||||
}
|
||||
|
||||
export function sameReleaseSource(a: ReleaseSource, b: ReleaseSource): boolean {
|
||||
return a.githubDownloads && b.githubDownloads
|
||||
? a.feed.href.toLowerCase() === b.feed.href.toLowerCase()
|
||||
: a.feed.href === b.feed.href;
|
||||
}
|
||||
|
||||
/** Keep a check or download on its preferred source until that source becomes unavailable. */
|
||||
export async function withReleaseSources<T>(
|
||||
read: (source: ReleaseSource) => Promise<T>, preferred?: ReleaseSource,
|
||||
): Promise<T> {
|
||||
/** The newest complete pack release, or null when none is released (or the repository is not public yet). */
|
||||
export async function newestPackRelease(): Promise<PackReleaseFiles | null> {
|
||||
const tuning = patchPackTuning();
|
||||
const candidates: ReleaseSource[] = [];
|
||||
const add = (url: URL | null): void => {
|
||||
if (!url) return;
|
||||
const source = releaseSource(url);
|
||||
if (!candidates.some((existing) => sameReleaseSource(existing, source))) candidates.push(source);
|
||||
};
|
||||
add(releaseRepositoryUrl(tuning.primarySource));
|
||||
add(releaseRepositoryUrl((await getSettings()).updateMirrorUrl));
|
||||
for (const fallback of tuning.fallbackSources) add(releaseRepositoryUrl(fallback));
|
||||
if (candidates.length === 0) throw new FeedUnreachableError('No valid release sources are configured.');
|
||||
const url = `https://api.github.com/repos/${tuning.repository}/releases?per_page=${tuning.releasesPerCheck}`;
|
||||
const response = await request(url, HEADERS, tuning.requestTimeoutMs);
|
||||
if (response.status === 404) return null;
|
||||
if (!response.ok) throw new FeedUnreachableError(`GitHub answered HTTP ${response.status} for the release list`);
|
||||
const releases = (await response.json()) as unknown;
|
||||
if (!Array.isArray(releases)) throw new PatchPackError('contents', 'the release list is not a list');
|
||||
|
||||
const ordered = preferred
|
||||
? [preferred, ...candidates.filter((source) => !sameReleaseSource(source, preferred))]
|
||||
: candidates;
|
||||
const packs = releases.map(packRelease).filter((release): release is PackReleaseFiles => release !== null);
|
||||
packs.sort((a, b) => comparePackVersions(b.version, a.version));
|
||||
return packs[0] ?? null;
|
||||
}
|
||||
|
||||
let lastError: unknown;
|
||||
for (let index = 0; index < ordered.length; index += 1) {
|
||||
const current = ordered[index]!;
|
||||
try {
|
||||
return await read(current);
|
||||
} catch (error) {
|
||||
if (!(error instanceof FeedUnreachableError || error instanceof ReleasePageLimitError)) throw error;
|
||||
lastError = error;
|
||||
const next = ordered[index + 1];
|
||||
if (next) console.info(`[release-feed] ${current.feed.hostname} was unavailable, trying ${next.feed.hostname}.`);
|
||||
}
|
||||
function packRelease(value: unknown): PackReleaseFiles | null {
|
||||
if (typeof value !== 'object' || value === null) return null;
|
||||
const release = value as Record<string, unknown>;
|
||||
if (release['draft'] === true || release['prerelease'] === true || typeof release['tag_name'] !== 'string') return null;
|
||||
const version = packVersionOfTag(release['tag_name']);
|
||||
if (!version || !Array.isArray(release['assets'])) return null;
|
||||
const urls = new Map<string, string>();
|
||||
for (const asset of release['assets'] as unknown[]) {
|
||||
if (typeof asset !== 'object' || asset === null) continue;
|
||||
const { name, browser_download_url: download } = asset as Record<string, unknown>;
|
||||
if (typeof name === 'string' && typeof download === 'string' && download.startsWith('https://')) urls.set(name, download);
|
||||
}
|
||||
throw lastError;
|
||||
}
|
||||
|
||||
function listingFor(source: ReleaseSource): Promise<ReleaseListing> {
|
||||
const key = source.feed.href;
|
||||
const existing = listings.get(key);
|
||||
if (existing) return existing;
|
||||
const pending = readProjectReleases(source).finally(() => { listings.delete(key); });
|
||||
listings.set(key, pending);
|
||||
return pending;
|
||||
}
|
||||
|
||||
export async function newestProjectRelease<Channel extends ReleaseChannel>(
|
||||
channel: Channel, installedVersion: string | null, source: ReleaseSource,
|
||||
): Promise<ReleaseByChannel[Channel] | null> {
|
||||
const { versions, incomplete, pageLimit } = await listingFor(source);
|
||||
const compare = channel === 'launcher' ? compareAppVersions : comparePackVersions;
|
||||
let candidate: ReleaseByChannel[Channel] | null = null;
|
||||
for (const release of versions[channel].values()) {
|
||||
if (!candidate || compare(release.version, candidate.version) > 0) candidate = release;
|
||||
}
|
||||
if (candidate && (installedVersion === null || compare(candidate.version, installedVersion) > 0)) return candidate;
|
||||
if (pageLimit !== null) {
|
||||
throw new ReleasePageLimitError(`No newer ${channel} release was confirmed within ${pageLimit} pages.`);
|
||||
}
|
||||
const partial = incomplete[channel];
|
||||
if (partial && (!candidate || installedVersion === null || compare(partial, installedVersion) > 0)) {
|
||||
throw new PatchPackError('contents', `Release ${partial} for the ${channel} channel is missing required files.`);
|
||||
}
|
||||
return candidate;
|
||||
}
|
||||
|
||||
/** The fallback must supply the same release the player selected. */
|
||||
export async function projectReleaseVersion<Channel extends ReleaseChannel>(
|
||||
channel: Channel, version: string, source: ReleaseSource,
|
||||
): Promise<ReleaseByChannel[Channel]> {
|
||||
const release = (await listingFor(source)).versions[channel].get(version);
|
||||
if (!release) throw new FeedUnreachableError(`This update source does not have the files for ${version}.`);
|
||||
return release;
|
||||
}
|
||||
|
||||
async function readProjectReleases(source: ReleaseSource): Promise<ReleaseListing> {
|
||||
const tuning = patchPackTuning();
|
||||
const versions: ReleaseVersions = { launcher: new Map(), pack: new Map() };
|
||||
const incomplete: Partial<Record<ReleaseChannel, string>> = {};
|
||||
const url = new URL(source.feed);
|
||||
url.searchParams.set('per_page', String(tuning.releasePageSize));
|
||||
const headers = {
|
||||
Accept: 'application/json', 'User-Agent': UPDATE_USER_AGENT,
|
||||
...(source.githubDownloads ? GITHUB_HEADERS : {}),
|
||||
};
|
||||
for (let page = 1; page <= tuning.maxReleasePages; page += 1) {
|
||||
url.searchParams.set('page', String(page));
|
||||
const result = await requestReleasePage(url, headers, tuning.requestTimeoutMs);
|
||||
collectReleases(result.releases, versions, incomplete, source);
|
||||
// GitHub does not sort release pages by tag version.
|
||||
if (!result.hasNextPage) return { versions, incomplete, pageLimit: null };
|
||||
}
|
||||
console.info(`[release-feed] More releases exist after the configured limit of ${tuning.maxReleasePages} pages.`);
|
||||
return { versions, incomplete, pageLimit: tuning.maxReleasePages };
|
||||
}
|
||||
|
||||
async function requestReleasePage(url: URL, headers: Record<string, string>, timeoutMs: number) {
|
||||
try {
|
||||
const response = await net.fetch(url.href, { credentials: 'omit', headers, signal: AbortSignal.timeout(timeoutMs) });
|
||||
if (!response.ok) throw new FeedUnreachableError(`The update source answered HTTP ${response.status} for a release page.`);
|
||||
const releases: unknown = await response.json();
|
||||
if (!Array.isArray(releases)) throw new FeedUnreachableError('The update source did not return a release list.');
|
||||
const hasNextPage = /;\s*rel="next"\s*(?:,|$)/i.test(response.headers.get('link') ?? '');
|
||||
return { releases: releases as readonly unknown[], hasNextPage };
|
||||
} catch (error) {
|
||||
if (error instanceof FeedUnreachableError) throw error;
|
||||
throw new FeedUnreachableError('The update source could not be read.', { cause: error });
|
||||
}
|
||||
}
|
||||
|
||||
function collectReleases(
|
||||
entries: readonly unknown[], versions: ReleaseVersions, incomplete: Partial<Record<ReleaseChannel, string>>, source: ReleaseSource,
|
||||
): void {
|
||||
for (const entry of entries) {
|
||||
if (typeof entry !== 'object' || entry === null) continue;
|
||||
const release = entry as Record<string, unknown>;
|
||||
const tag = release['tag_name'];
|
||||
if (typeof tag !== 'string' || release['draft'] === true) continue;
|
||||
|
||||
if (tag.startsWith('v')) {
|
||||
if (release['prerelease'] === true) continue;
|
||||
const version = AppReleaseVersionSchema.safeParse(tag.slice(1));
|
||||
if (!version.success) continue;
|
||||
const launcher = launcherRelease(release, version.data, source);
|
||||
if (launcher) versions.launcher.set(launcher.version, launcher);
|
||||
else if (!incomplete.launcher || compareAppVersions(version.data, incomplete.launcher) > 0) incomplete.launcher = version.data;
|
||||
continue;
|
||||
}
|
||||
|
||||
const version = packVersionOfTag(tag);
|
||||
if (!version) continue;
|
||||
const pack = packRelease(release, version, tag, source);
|
||||
if (pack) versions.pack.set(pack.version, pack);
|
||||
else if (!incomplete.pack || comparePackVersions(version, incomplete.pack) > 0) incomplete.pack = version;
|
||||
}
|
||||
}
|
||||
|
||||
function assetUrls(assets: readonly unknown[], tag: string, source: ReleaseSource): Map<string, URL> {
|
||||
const urls = new Map<string, URL>();
|
||||
for (const asset of assets) {
|
||||
const parsed = ReleaseAsset.safeParse(asset);
|
||||
if (!parsed.success) continue;
|
||||
const { name, browser_download_url: download } = parsed.data;
|
||||
if (source.githubDownloads) {
|
||||
urls.set(name, new URL(`${tag}/${encodeURIComponent(name)}`, source.githubDownloads));
|
||||
continue;
|
||||
}
|
||||
const url = download ? URL.parse(download, source.feed.href) : null;
|
||||
if (url?.protocol === 'https:' && !url.username && !url.password) urls.set(name, url);
|
||||
}
|
||||
return urls;
|
||||
}
|
||||
|
||||
function launcherRelease(entry: Record<string, unknown>, version: string, source: ReleaseSource): LauncherRelease | null {
|
||||
const parsed = LauncherReleaseEntry.safeParse(entry);
|
||||
if (!parsed.success) return null;
|
||||
const { assets, body } = parsed.data;
|
||||
const names = launcherReleaseFiles(version);
|
||||
const portableNames = portableLauncherReleaseFiles(version);
|
||||
const urls = assetUrls(assets, `v${version}`, source);
|
||||
const installer = urls.get(names.installer);
|
||||
const manifest = urls.get(names.manifest);
|
||||
const signature = urls.get(names.signature);
|
||||
if (!installer || !manifest || !signature) return null;
|
||||
const portableArchive = urls.get(portableNames.archive);
|
||||
const portableManifest = urls.get(portableNames.manifest);
|
||||
const portableSignature = urls.get(portableNames.signature);
|
||||
const portable = portableArchive && portableManifest && portableSignature
|
||||
? { archive: portableArchive, manifest: portableManifest, signature: portableSignature }
|
||||
: undefined;
|
||||
return {
|
||||
source,
|
||||
version,
|
||||
notes: body?.trim().slice(0, 1600) ?? '',
|
||||
installer,
|
||||
manifest,
|
||||
signature,
|
||||
...(portable ? { portable } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function packRelease(release: Record<string, unknown>, version: string, tag: string, source: ReleaseSource): PackReleaseFiles | null {
|
||||
if (!Array.isArray(release['assets'])) return null;
|
||||
const urls = assetUrls(release['assets'], tag, source);
|
||||
const names = packFileNames(version);
|
||||
const zipUrl = urls.get(names.zip);
|
||||
const signatureUrl = urls.get(names.signature);
|
||||
const manifestUrl = urls.get(names.manifest);
|
||||
if (!zipUrl || !signatureUrl || !manifestUrl) return null;
|
||||
const publishedAt = typeof release['published_at'] === 'string' ? release['published_at'] : null;
|
||||
return { source, version, publishedAt, zipUrl, signatureUrl, manifestUrl };
|
||||
return { version, publishedAt, zipUrl, signatureUrl, manifestUrl };
|
||||
}
|
||||
|
||||
/** Download a release file, refusing anything larger than `maxBytes`. */
|
||||
export async function downloadReleaseFile(url: string, maxBytes: number): Promise<Uint8Array> {
|
||||
const tuning = patchPackTuning();
|
||||
const response = await request(url, { 'User-Agent': HEADERS['User-Agent'] }, tuning.requestTimeoutMs);
|
||||
if (!response.ok) throw new FeedUnreachableError(`HTTP ${response.status} for ${url}`);
|
||||
const declared = Number(response.headers.get('content-length') ?? '0');
|
||||
if (declared > maxBytes) throw new PatchPackError('size', `${url} is ${declared} bytes, more than ${maxBytes}`);
|
||||
const content = new Uint8Array(await response.arrayBuffer());
|
||||
if (content.length > maxBytes) throw new PatchPackError('size', `${url} is more than ${maxBytes} bytes`);
|
||||
return content;
|
||||
}
|
||||
|
||||
async function request(url: string, headers: Record<string, string>, timeoutMs: number): Promise<Response> {
|
||||
try {
|
||||
return await net.fetch(url, { credentials: 'omit', headers, signal: AbortSignal.timeout(timeoutMs) });
|
||||
} catch (error) {
|
||||
throw new FeedUnreachableError(`${url}: ${(error as Error).message}`);
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import { activeDownloadedPack } from '../patch-pack/pack-store.ts';
|
||||
|
||||
/**
|
||||
* Where the launcher finds what it ships besides its own code: the patch set (exe, GUI and native
|
||||
* definitions and version records, @wto/patcher patch-set.ts) and the network hook library.
|
||||
* definitions and version records, @wto/patcher patch-set.ts) and the network hook library. In development they are this repository's folders.
|
||||
*
|
||||
* The patch set is the active downloaded adaptation pack when there is a usable one
|
||||
* (services/patch-pack/), otherwise the bundled one. A repository checkout uses its own patches/
|
||||
@@ -15,35 +15,25 @@ export interface ResourcePaths {
|
||||
readonly patches: string;
|
||||
/** wto_ws.dll, built by native/wto-net/build.ps1. */
|
||||
readonly networkHookLibrary: string;
|
||||
/** Multi-resolution Windows icon for the window and system tray. */
|
||||
readonly appIcon: string;
|
||||
/** Bundled example mod templates seeded into an empty mods folder on first use. */
|
||||
readonly modTemplates: string;
|
||||
}
|
||||
|
||||
export function resourcePaths(): ResourcePaths {
|
||||
const bundled = bundledResourcePaths();
|
||||
const pack = usesDownloadedPacks() ? activeDownloadedPack(bundled.patches) : null;
|
||||
const pack = usesDownloadedPacks() ? activeDownloadedPack() : null;
|
||||
return pack ? { ...bundled, patches: pack.root } : bundled;
|
||||
}
|
||||
|
||||
/** The resources that ship with the launcher, ignoring downloaded packs. */
|
||||
export function bundledResourcePaths(): ResourcePaths {
|
||||
if (app.isPackaged) {
|
||||
return {
|
||||
patches: join(process.resourcesPath, 'patches'),
|
||||
networkHookLibrary: join(process.resourcesPath, 'native', 'wto_ws.dll'),
|
||||
appIcon: join(process.resourcesPath, 'icon.ico'),
|
||||
modTemplates: join(process.resourcesPath, 'mod-templates'),
|
||||
};
|
||||
// The packaged layout is decided with the installer build; nothing ships it yet.
|
||||
throw new Error('resource paths of a packaged launcher are not defined yet');
|
||||
}
|
||||
// The app path is apps/launcher; the repository is two levels up.
|
||||
const repository = resolve(app.getAppPath(), '..', '..');
|
||||
return {
|
||||
patches: join(repository, 'patches'),
|
||||
networkHookLibrary: join(repository, 'build', 'native', 'wto_ws.dll'),
|
||||
appIcon: join(repository, 'apps', 'launcher', 'resources', 'icon.ico'),
|
||||
modTemplates: join(repository, 'mod-dev-docs', 'templates'),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,16 +1,14 @@
|
||||
import { copyFile, lstat, mkdir, readdir, rm } from 'node:fs/promises';
|
||||
import { isAbsolute, join } from 'node:path';
|
||||
import { app, dialog, utilityProcess, type BrowserWindow } from 'electron';
|
||||
import { compareVersions, isInSteamLibrary } from '@wto/patcher';
|
||||
import { AppError } from '@shared/errors.ts';
|
||||
import type { InstallRecord } from '@shared/schemas/install.ts';
|
||||
import type { AccountEdits, CurrencyEdits, OfficialImportOptions, OfficialPreview, OnlineDataSource, SaveBackup, SaveDetails, SaveList, SaveRegistration, SaveTransfer, ResearchBranch, ResearchOperation, SaveAvatarChoices, SaveResearch } from '@shared/schemas/saves.ts';
|
||||
import type { CurrencyEdits, OfficialImportOptions, OfficialPreview, SaveBackup, SaveDetails, SaveList, SaveRegistration, SaveTransfer, ResearchBranch, ResearchOperation, SaveResearch } from '@shared/schemas/saves.ts';
|
||||
import type { SaveReply, SaveResult, SaveTask } from '../../workers/save-protocol.ts';
|
||||
import { maintenanceInProgress } from '../copies/copy-maintenance.ts';
|
||||
import { canonicalCopyPath, copyPathContains, listCopies, updateCopyRecord } from '../install/install-record.ts';
|
||||
import { gameProcessRunning, launchInProgress } from '../launch/launch-controller.ts';
|
||||
import { readInstalledLab } from '../launch/lab-handoff.ts';
|
||||
import { localServerReady } from '../launch/local-server.ts';
|
||||
import { labStatusUrl, readInstalledLab } from '../launch/lab-handoff.ts';
|
||||
import { forwardProcessOutput } from '../launch/process-output.ts';
|
||||
import { archivedBackup, backupList, captureSave, changeSaveFolder, readArchive, restoreDirectory, saveBackup, writeArchive, type SaveArchive } from './save-archive.ts';
|
||||
|
||||
@@ -57,35 +55,6 @@ export async function createSave({ copyId, login, password, nick }: SaveRegistra
|
||||
});
|
||||
}
|
||||
|
||||
export async function getSaveAvatarChoices(copyId: string): Promise<SaveAvatarChoices> {
|
||||
const copy = await requireCopy(copyId);
|
||||
return await run({ operation: 'avatars', ...location(copy) }) as SaveAvatarChoices;
|
||||
}
|
||||
|
||||
export async function getSaveAvatarPreview(copyId: string, avatar: string): Promise<string | null> {
|
||||
const copy = await requireCopy(copyId);
|
||||
return await run({ operation: 'avatarPreview', ...location(copy), avatar }) as string | null;
|
||||
}
|
||||
|
||||
export async function changeSaveAccount(copyId: string, userId: string, edits: AccountEdits): Promise<SaveDetails> {
|
||||
return write(async () => {
|
||||
const copy = await requireCopy(copyId);
|
||||
const changesProfile = edits.premiumDays !== undefined || edits.avatar !== undefined || edits.level !== undefined;
|
||||
const before = changesProfile ? await captureSave(copy, userId) : null;
|
||||
try {
|
||||
await run({ operation: 'editAccount', ...location(copy), userId, edits });
|
||||
} catch (error) {
|
||||
const rejectedEdit = error instanceof AppError &&
|
||||
['save_nick_invalid', 'save_avatar_invalid', 'save_level_invalid', 'save_not_found'].includes(error.code);
|
||||
if (before && !rejectedEdit) {
|
||||
await restoreDirectory(copy, userId, before);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
return getSaveDetails(copyId, userId);
|
||||
});
|
||||
}
|
||||
|
||||
export async function setSaveCurrencies(copyId: string, userId: string, values: CurrencyEdits): Promise<SaveDetails> {
|
||||
return write(async () => {
|
||||
const copy = await requireCopy(copyId);
|
||||
@@ -183,97 +152,6 @@ export async function restoreSaveBackup(copyId: string, userId: string, name: st
|
||||
});
|
||||
}
|
||||
|
||||
const ONLINE_DATA_FILES = ['global.blk', 'machine.blk', 'storage.blk'] as const;
|
||||
const ONLINE_DATA_MAX_BYTES = 32 * 1024 * 1024;
|
||||
|
||||
function onlineSavesRoot(): string {
|
||||
return join(app.getPath('documents'), 'My Games', 'WarThunder', 'Saves');
|
||||
}
|
||||
|
||||
async function offlineClientCacheFolders(userId: string): Promise<string[]> {
|
||||
if (!/^\d+$/.test(userId)) return [];
|
||||
const root = await canonicalCopyPath(join(app.getPath('documents'), 'My Games', 'WTOffline', 'Saves'));
|
||||
const candidates = [join(root, userId, 'production'), join(root, 'last', 'production')];
|
||||
const folders: string[] = [];
|
||||
for (const candidate of candidates) {
|
||||
const resolved = await canonicalCopyPath(candidate);
|
||||
if (copyPathContains(root, resolved)) folders.push(resolved);
|
||||
}
|
||||
return folders;
|
||||
}
|
||||
|
||||
/** Read-only discovery of local online client settings under Documents/My Games/WarThunder/Saves. */
|
||||
export async function discoverOnlineData(): Promise<OnlineDataSource[]> {
|
||||
const root = onlineSavesRoot();
|
||||
const entries = await readdir(root, { withFileTypes: true }).catch(() => []);
|
||||
const found: Array<OnlineDataSource & { readonly mtimeMs: number }> = [];
|
||||
|
||||
for (const entry of entries) {
|
||||
if (!entry.isDirectory() || !/^\d+$/.test(entry.name)) continue;
|
||||
const production = join(root, entry.name, 'production');
|
||||
const files: Array<(typeof ONLINE_DATA_FILES)[number]> = [];
|
||||
let latestMtime = 0;
|
||||
|
||||
for (const fileName of ONLINE_DATA_FILES) {
|
||||
const stats = await lstat(join(production, fileName)).catch(() => null);
|
||||
if (!stats || !stats.isFile() || stats.size === 0 || stats.size > ONLINE_DATA_MAX_BYTES) continue;
|
||||
files.push(fileName);
|
||||
if (stats.mtimeMs > latestMtime) latestMtime = stats.mtimeMs;
|
||||
}
|
||||
|
||||
if (files.length > 0) {
|
||||
found.push({
|
||||
accountId: entry.name,
|
||||
folder: production,
|
||||
files,
|
||||
updatedAt: new Date(latestMtime).toISOString(),
|
||||
mtimeMs: latestMtime,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return found
|
||||
.sort((a, b) => b.mtimeMs - a.mtimeMs || a.accountId.localeCompare(b.accountId))
|
||||
.map(({ mtimeMs: _ignored, ...item }) => item);
|
||||
}
|
||||
|
||||
/**
|
||||
* Copy the player's selected online settings files into the offline copy's own staging folder
|
||||
* without writing to or modifying the online directory.
|
||||
*/
|
||||
export async function copyOnlineData(copyId: string, userId: string, accountId: string): Promise<string[]> {
|
||||
if (!/^\d+$/.test(accountId) || !/^\d+$/.test(userId)) throw new AppError('save_official_invalid');
|
||||
const copy = await requireCopy(copyId);
|
||||
await getSaveDetails(copyId, userId);
|
||||
|
||||
const onlineRoot = await canonicalCopyPath(onlineSavesRoot());
|
||||
const sourceDir = await canonicalCopyPath(join(onlineRoot, accountId, 'production'));
|
||||
if (!copyPathContains(onlineRoot, sourceDir)) throw new AppError('save_official_location');
|
||||
|
||||
const dataRoot = await canonicalCopyPath(copy.dataPath);
|
||||
const stageDir = await canonicalCopyPath(join(dataRoot, 'imported-online-data', userId, accountId));
|
||||
if (!copyPathContains(dataRoot, stageDir)) throw new AppError('save_operation_failed');
|
||||
|
||||
const existingFiles: Array<(typeof ONLINE_DATA_FILES)[number]> = [];
|
||||
for (const fileName of ONLINE_DATA_FILES) {
|
||||
const sourcePath = join(sourceDir, fileName);
|
||||
const stats = await lstat(sourcePath).catch(() => null);
|
||||
if (!stats || !stats.isFile() || stats.size === 0 || stats.size > ONLINE_DATA_MAX_BYTES) continue;
|
||||
existingFiles.push(fileName);
|
||||
}
|
||||
if (existingFiles.length === 0) throw new AppError('save_official_invalid');
|
||||
|
||||
await rm(stageDir, { recursive: true, force: true });
|
||||
await mkdir(stageDir, { recursive: true });
|
||||
const copied: string[] = [];
|
||||
for (const fileName of existingFiles) {
|
||||
const targetPath = join(stageDir, fileName);
|
||||
await copyFile(join(sourceDir, fileName), targetPath);
|
||||
copied.push(targetPath);
|
||||
}
|
||||
return copied;
|
||||
}
|
||||
|
||||
export async function pickOfficialBackups(window: BrowserWindow | null): Promise<string[]> {
|
||||
const options = { properties: ['openFile' as const, 'multiSelections' as const], filters: [{ name: 'BLK', extensions: ['blk'] }] };
|
||||
const result = window ? await dialog.showOpenDialog(window, options) : await dialog.showOpenDialog(options);
|
||||
@@ -281,12 +159,12 @@ export async function pickOfficialBackups(window: BrowserWindow | null): Promise
|
||||
}
|
||||
|
||||
export async function previewSelectedBackups(
|
||||
copyId: string, userId: string, paths: readonly string[],
|
||||
copyId: string, userId: string, paths: readonly string[], includeUsedVehicles: boolean,
|
||||
): Promise<OfficialPreview> {
|
||||
const copy = await requireCopy(copyId);
|
||||
await getSaveDetails(copyId, userId);
|
||||
const selected = await verifyBackupLocations(copy, paths);
|
||||
return await run({ operation: 'previewOfficial', ...location(copy), paths: selected }) as OfficialPreview;
|
||||
return await run({ operation: 'previewOfficial', ...location(copy), paths: selected, includeUsedVehicles }) as OfficialPreview;
|
||||
}
|
||||
|
||||
export async function importSelectedBackups(
|
||||
@@ -296,18 +174,10 @@ export async function importSelectedBackups(
|
||||
const copy = await requireCopy(copyId);
|
||||
await getSaveDetails(copyId, userId);
|
||||
const selected = await verifyBackupLocations(copy, paths);
|
||||
const cacheFolders = await offlineClientCacheFolders(userId);
|
||||
const before = await captureSave(copy, userId);
|
||||
await saveBackup(copy, userId, 'import');
|
||||
try {
|
||||
return await run({
|
||||
operation: 'importOfficial',
|
||||
...location(copy),
|
||||
userId,
|
||||
paths: selected,
|
||||
options,
|
||||
...(cacheFolders.length > 0 ? { offlineClientCacheFolders: cacheFolders } : {}),
|
||||
}) as OfficialPreview;
|
||||
return await run({ operation: 'importOfficial', ...location(copy), userId, paths: selected, options }) as OfficialPreview;
|
||||
} catch (error) {
|
||||
await restoreDirectory(copy, userId, before);
|
||||
throw error;
|
||||
@@ -368,7 +238,12 @@ async function write<T>(operation: () => Promise<T>): Promise<T> {
|
||||
async function labServerRunning(): Promise<boolean> {
|
||||
const lab = await readInstalledLab().catch(() => null);
|
||||
if (!lab) return false;
|
||||
return localServerReady(lab.port);
|
||||
try {
|
||||
const response = await fetch(labStatusUrl(lab.port), { signal: AbortSignal.timeout(600) });
|
||||
return response.ok && (await response.json() as { app?: string }).app === 'wto-server';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function run(task: SaveTask): Promise<SaveResult> {
|
||||
|
||||
@@ -5,15 +5,10 @@ export interface BuildRequest {
|
||||
readonly stockPath: string;
|
||||
readonly copyPath: string;
|
||||
readonly dataPath: string;
|
||||
readonly steamLibraryConfirmed: boolean;
|
||||
readonly port: number;
|
||||
readonly patches: string;
|
||||
readonly networkHookLibrary: string;
|
||||
readonly decalCache?: string;
|
||||
readonly hookLogging: boolean;
|
||||
readonly acceptedUnavailable: readonly string[];
|
||||
readonly modsDir?: string;
|
||||
readonly enabledModIds?: readonly string[];
|
||||
}
|
||||
|
||||
export type BuildCommand = BuildRequest | { readonly kind: 'write' };
|
||||
|
||||
@@ -1,88 +1,24 @@
|
||||
import { readFileSync, realpathSync } from 'node:fs';
|
||||
import { relative } from 'node:path';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import type { MessageEvent } from 'electron';
|
||||
import { discoverMods, touchedClientPacks, type DiscoveredMod, type ModdableClientPack } from '@wto/mods';
|
||||
import {
|
||||
assertWritableCopy,
|
||||
buildGameCopy,
|
||||
computeModsBuildFingerprint,
|
||||
copyPlayerDecalCache,
|
||||
CORE_BUILD_PACKS,
|
||||
playerDecalCacheProblem,
|
||||
prepareOptionalStockPacks,
|
||||
readPlayerDecalIndexFiles,
|
||||
readStockGameFiles,
|
||||
syncExternalModFiles,
|
||||
writeGameCopy,
|
||||
type GameCopyFile,
|
||||
} from '@wto/patcher';
|
||||
import { assertWritableCopy, buildGameCopy, readStockGameFiles, writeGameCopy, type GameCopyFile } from '@wto/patcher';
|
||||
import { multiVehiclePackIds } from '@wto/server';
|
||||
import type { BuildCommand, BuildReply, BuildRequest } from './build-protocol.ts';
|
||||
|
||||
let prepared: {
|
||||
readonly request: BuildRequest;
|
||||
readonly files: readonly GameCopyFile[];
|
||||
readonly decalCache: string | undefined;
|
||||
readonly enabledMods: readonly DiscoveredMod[];
|
||||
readonly optionalPacksInBuild: readonly ModdableClientPack[];
|
||||
readonly fingerprint: string;
|
||||
} | null = null;
|
||||
|
||||
function checkBuildLocation({ stockPath, copyPath, steamLibraryConfirmed }: BuildRequest): void {
|
||||
if (relative(copyPath, realpathSync(copyPath)) !== '') throw new Error('The copy path changed during the build.');
|
||||
assertWritableCopy(stockPath, copyPath, { steamLibraryConfirmed });
|
||||
}
|
||||
let prepared: { readonly copyPath: string; readonly files: readonly GameCopyFile[] } | null = null;
|
||||
|
||||
function send(reply: BuildReply): void {
|
||||
process.parentPort.postMessage(reply);
|
||||
}
|
||||
|
||||
function importedDecals(path: string | undefined): string | undefined {
|
||||
if (!path) return undefined;
|
||||
try {
|
||||
const imported = realpathSync(path);
|
||||
if (relative(path, imported) === '' && !playerDecalCacheProblem(imported)) return imported;
|
||||
} catch (error) {
|
||||
console.warn('[build] the imported decal cache is unavailable:', error);
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function resolveOrderedMods(modsDir: string | undefined, enabledModIds: readonly string[] | undefined): DiscoveredMod[] {
|
||||
if (!modsDir || !enabledModIds || enabledModIds.length === 0) return [];
|
||||
const discovered = discoverMods(modsDir);
|
||||
const byId = new Map(discovered.mods.map((mod) => [mod.manifest.id, mod]));
|
||||
const ordered: DiscoveredMod[] = [];
|
||||
for (const id of enabledModIds) {
|
||||
const mod = byId.get(id);
|
||||
if (!mod) throw new Error(`enabled mod "${id}" was not found in ${modsDir}`);
|
||||
ordered.push(mod);
|
||||
}
|
||||
return ordered;
|
||||
}
|
||||
|
||||
function build(request: BuildRequest): void {
|
||||
checkBuildLocation(request);
|
||||
const decalCache = importedDecals(request.decalCache);
|
||||
const decalIndexFiles = decalCache ? readPlayerDecalIndexFiles(decalCache) : undefined;
|
||||
const enabledMods = resolveOrderedMods(request.modsDir, request.enabledModIds);
|
||||
const touchedPacks = touchedClientPacks(enabledMods);
|
||||
const optionalPacksInBuild = touchedPacks.filter((pack) => !CORE_BUILD_PACKS.has(pack));
|
||||
const extraStockPacks = optionalPacksInBuild.length > 0
|
||||
? prepareOptionalStockPacks(request.copyPath, request.stockPath, optionalPacksInBuild)
|
||||
: undefined;
|
||||
|
||||
assertWritableCopy(request.stockPath, request.copyPath);
|
||||
const result = buildGameCopy({
|
||||
stock: readStockGameFiles(request.stockPath),
|
||||
patches: request.patches,
|
||||
networkHookLibrary: readFileSync(request.networkHookLibrary),
|
||||
port: request.port,
|
||||
multiVehiclePackIds: multiVehiclePackIds(request.dataPath, console.info, enabledMods),
|
||||
placeholderDecals: decalCache === undefined,
|
||||
...(decalIndexFiles ? { decalIndexFiles } : {}),
|
||||
hookLogging: request.hookLogging,
|
||||
...(enabledMods.length > 0 ? { mods: enabledMods } : {}),
|
||||
...(extraStockPacks ? { extraStockPacks } : {}),
|
||||
multiVehiclePackIds: multiVehiclePackIds(request.dataPath, console.info),
|
||||
placeholderDecals: true,
|
||||
});
|
||||
const unavailable = [...result.exePatches.failures, ...result.guiPatches.failures, ...result.nativeModules.failures];
|
||||
const accepted = new Set(request.acceptedUnavailable);
|
||||
@@ -91,19 +27,7 @@ function build(request: BuildRequest): void {
|
||||
send({ kind: 'failed', error: 'launch_build_unavailable' });
|
||||
return;
|
||||
}
|
||||
if (result.mods.enabledModIds.length > 0) {
|
||||
console.info(
|
||||
`[build] applied ${result.mods.enabledModIds.length} mod(s): ${result.mods.enabledModIds.join(', ')} ` +
|
||||
`(pack overlays=${result.mods.packOverlays.length}, addons=${result.mods.addonMounts.length}, ` +
|
||||
`gui=${result.mods.guiPatches.applied.length} ok/${result.mods.guiPatches.failures.length} failed, ` +
|
||||
`exe=${result.mods.exePatches.applied.length} ok/${result.mods.exePatches.failures.length} failed)`,
|
||||
);
|
||||
for (const failure of [...result.mods.guiPatches.failures, ...result.mods.exePatches.failures]) {
|
||||
console.warn(`[build] mod "${failure.modId}" patch "${failure.patchId}" skipped: ${failure.reason}`);
|
||||
}
|
||||
}
|
||||
const fingerprint = computeModsBuildFingerprint(enabledMods, request.port, request.patches);
|
||||
prepared = { request, files: result.files, decalCache, enabledMods, optionalPacksInBuild, fingerprint };
|
||||
prepared = { copyPath: request.copyPath, files: result.files };
|
||||
send({ kind: 'prepared', total: prepared.files.length });
|
||||
}
|
||||
|
||||
@@ -115,22 +39,12 @@ process.parentPort.on('message', (event: MessageEvent) => {
|
||||
return;
|
||||
}
|
||||
if (!prepared) throw new Error('No build is ready to write.');
|
||||
const { request, files, decalCache, enabledMods, optionalPacksInBuild, fingerprint } = prepared;
|
||||
const { copyPath, files } = prepared;
|
||||
prepared = null;
|
||||
checkBuildLocation(request);
|
||||
const { copyPath, stockPath } = request;
|
||||
if (decalCache) copyPlayerDecalCache(decalCache, copyPath);
|
||||
for (const [index, file] of files.entries()) {
|
||||
writeGameCopy(copyPath, [file]);
|
||||
send({ kind: 'progress', written: index + 1, total: files.length, file: file.path });
|
||||
}
|
||||
const deployResult = syncExternalModFiles(copyPath, stockPath, enabledMods, optionalPacksInBuild, fingerprint);
|
||||
for (const warning of deployResult.warnings) {
|
||||
console.warn(`[mods] skipped "${warning.targetRelPath}" from "${warning.modId}": ${warning.reason}`);
|
||||
}
|
||||
if (deployResult.restoredOptionalPacks.length > 0) {
|
||||
console.info(`[mods] restored stock pack(s): ${deployResult.restoredOptionalPacks.join(', ')}`);
|
||||
}
|
||||
send({ kind: 'written' });
|
||||
} catch (error) {
|
||||
console.error('[build] preparing the game copy failed:', error);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { AppErrorCode } from '@shared/errors.ts';
|
||||
import type { AccountEdits, SaveAvatarChoices, CurrencyEdits, OfficialImportOptions, OfficialPreview, ResearchBranch, ResearchOperation, SaveDetails, SaveList, SaveResearch } from '@shared/schemas/saves.ts';
|
||||
import type { CurrencyEdits, OfficialImportOptions, OfficialPreview, ResearchBranch, ResearchOperation, SaveDetails, SaveList, SaveResearch } from '@shared/schemas/saves.ts';
|
||||
|
||||
interface Location {
|
||||
readonly gameFolder: string;
|
||||
@@ -9,23 +9,14 @@ interface Location {
|
||||
export type SaveTask = Location & (
|
||||
| { readonly operation: 'list' }
|
||||
| { readonly operation: 'details'; readonly userId: string }
|
||||
| { readonly operation: 'avatars' }
|
||||
| { readonly operation: 'avatarPreview'; readonly avatar: string }
|
||||
| { readonly operation: 'editAccount'; readonly userId: string; readonly edits: AccountEdits }
|
||||
| { readonly operation: 'edit'; readonly userId: string; readonly values: CurrencyEdits }
|
||||
| { readonly operation: 'previewOfficial'; readonly paths: readonly string[] }
|
||||
| {
|
||||
readonly operation: 'importOfficial';
|
||||
readonly paths: readonly string[];
|
||||
readonly userId: string;
|
||||
readonly options: OfficialImportOptions;
|
||||
readonly offlineClientCacheFolders?: readonly string[];
|
||||
}
|
||||
| { readonly operation: 'previewOfficial'; readonly paths: readonly string[]; readonly includeUsedVehicles: boolean }
|
||||
| { readonly operation: 'importOfficial'; readonly paths: readonly string[]; readonly userId: string; readonly options: OfficialImportOptions }
|
||||
| { readonly operation: 'readResearch'; readonly userId: string; readonly branch?: ResearchBranch }
|
||||
| { readonly operation: 'editResearch'; readonly userId: string; readonly branch: ResearchBranch; readonly action: ResearchOperation }
|
||||
| { readonly operation: 'remove'; readonly userId: string }
|
||||
| { readonly operation: 'filter'; readonly profile: Uint8Array; readonly filter: boolean }
|
||||
| { readonly operation: 'create'; readonly login: string; readonly password: string; readonly nick: string }
|
||||
);
|
||||
export type SaveResult = SaveList['saves'] | SaveDetails | OfficialPreview | SaveResearch | { userId: string } | Uint8Array | SaveAvatarChoices | string | null;
|
||||
export type SaveResult = SaveList['saves'] | SaveDetails | OfficialPreview | SaveResearch | { userId: string } | Uint8Array | null;
|
||||
export type SaveReply = { ok: true; result: SaveResult } | { ok: false; error: AppErrorCode };
|
||||
@@ -1,34 +1,22 @@
|
||||
import type { MessageEvent } from 'electron';
|
||||
import { AccountStore, editSaveAccount, editSaveCurrencies, editSaveResearch, importOfficialBackup, listSaveAvatars, listSaveSummaries, prepareTransferredProfile, previewOfficialBackup, readSaveAvatar, readSaveDetails, readSaveResearch } from '@wto/server';
|
||||
import { AccountStore, editSaveCurrencies, editSaveResearch, importOfficialBackup, listSaveSummaries, prepareTransferredProfile, previewOfficialBackup, readSaveDetails, readSaveResearch } from '@wto/server';
|
||||
import type { SaveTask, SaveReply } from './save-protocol.ts';
|
||||
|
||||
function execute(task: SaveTask): SaveReply {
|
||||
switch (task.operation) {
|
||||
case 'list':
|
||||
return { ok: true, result: listSaveSummaries(task.dataFolder, task.gameFolder) };
|
||||
return { ok: true, result: listSaveSummaries(task.dataFolder) };
|
||||
case 'details': {
|
||||
const result = readSaveDetails(task.dataFolder, task.userId, task.gameFolder);
|
||||
const result = readSaveDetails(task.dataFolder, task.userId);
|
||||
return result ? { ok: true, result } : { ok: false, error: 'save_not_found' };
|
||||
}
|
||||
case 'avatars':
|
||||
return { ok: true, result: listSaveAvatars(task) };
|
||||
case 'avatarPreview':
|
||||
return { ok: true, result: readSaveAvatar(task, task.avatar) };
|
||||
case 'editAccount':
|
||||
switch (editSaveAccount(task, task.userId, task.edits)) {
|
||||
case 'updated': return { ok: true, result: null };
|
||||
case 'invalid-nick': return { ok: false, error: 'save_nick_invalid' };
|
||||
case 'invalid-avatar': return { ok: false, error: 'save_avatar_invalid' };
|
||||
case 'invalid-level': return { ok: false, error: 'save_level_invalid' };
|
||||
case 'not-found': return { ok: false, error: 'save_not_found' };
|
||||
}
|
||||
case 'edit':
|
||||
return editSaveCurrencies(task, task.userId, task.values)
|
||||
? { ok: true, result: null } : { ok: false, error: 'save_not_found' };
|
||||
case 'previewOfficial':
|
||||
return { ok: true, result: previewOfficialBackup(task, task.paths) };
|
||||
return { ok: true, result: previewOfficialBackup(task, task.paths, task.includeUsedVehicles) };
|
||||
case 'importOfficial':
|
||||
return { ok: true, result: importOfficialBackup(task, task.userId, task.paths, task.options, task.offlineClientCacheFolders) };
|
||||
return { ok: true, result: importOfficialBackup(task, task.userId, task.paths, task.options) };
|
||||
case 'readResearch': {
|
||||
const result = readSaveResearch(task, task.userId, task.branch);
|
||||
return result ? { ok: true, result } : { ok: false, error: 'save_not_found' };
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
import { discoverMods, type DiscoveredMod } from '@wto/mods';
|
||||
import { startServer } from '@wto/server';
|
||||
|
||||
export type ServerWorkerStatus = 'listening' | 'port-busy' | 'failed';
|
||||
|
||||
function loadOrderedMods(modsDir: string | undefined, enabledJson: string | undefined): DiscoveredMod[] {
|
||||
if (!modsDir || !enabledJson) return [];
|
||||
const ids = JSON.parse(enabledJson) as unknown;
|
||||
if (!Array.isArray(ids) || ids.length === 0) return [];
|
||||
const discovered = discoverMods(modsDir);
|
||||
const byId = new Map(discovered.mods.map((mod) => [mod.manifest.id, mod]));
|
||||
const mods: DiscoveredMod[] = [];
|
||||
for (const id of ids) {
|
||||
if (typeof id !== 'string') continue;
|
||||
const mod = byId.get(id);
|
||||
if (!mod) throw new Error(`Enabled mod "${id}" not found in ${modsDir}`);
|
||||
mods.push(mod);
|
||||
}
|
||||
return mods;
|
||||
}
|
||||
|
||||
async function serve(): Promise<void> {
|
||||
const [gameFolder, dataFolder, portText, loggingFlag, modsDir, enabledModIdsJson] = process.argv.slice(2);
|
||||
const port = Number(portText);
|
||||
if (!gameFolder || !dataFolder || !Number.isInteger(port) || port < 1 || port > 65535) {
|
||||
throw new Error('Invalid local server arguments.');
|
||||
}
|
||||
const loggingEnabled = loggingFlag !== '0';
|
||||
const mods = loadOrderedMods(modsDir, enabledModIdsJson);
|
||||
const server = await startServer({
|
||||
gameFolder,
|
||||
dataFolder,
|
||||
port,
|
||||
loggingEnabled,
|
||||
...(mods.length > 0 ? { mods } : {}),
|
||||
report: console.info,
|
||||
});
|
||||
if (server.logFolder) console.info('Traffic log:', server.logFolder);
|
||||
if (server.loadedModIds.length > 0) console.info('Loaded server script mods:', server.loadedModIds.join(', '));
|
||||
process.parentPort.once('message', () => {
|
||||
void server.close().then(() => process.exit(0)).catch((error: unknown) => {
|
||||
console.error('Could not close the local server:', error);
|
||||
process.exit(1);
|
||||
});
|
||||
});
|
||||
send('listening');
|
||||
}
|
||||
|
||||
function send(status: ServerWorkerStatus): void {
|
||||
process.parentPort.postMessage(status);
|
||||
}
|
||||
|
||||
void serve().catch((error: unknown) => {
|
||||
console.error('Could not start the local server:', error);
|
||||
send((error as NodeJS.ErrnoException).code === 'EADDRINUSE' ? 'port-busy' : 'failed');
|
||||
});
|
||||
@@ -4,13 +4,11 @@ import type { IpcOutput } from '@shared/ipc/contract.ts';
|
||||
import type { Copies } from '@shared/schemas/install.ts';
|
||||
import type { LaunchState } from '@shared/schemas/launch.ts';
|
||||
import type { Settings } from '@shared/schemas/settings.ts';
|
||||
import { EllipsisTooltipHost } from './components/EllipsisTooltipHost.tsx';
|
||||
import { Sheet } from './components/Sheet.tsx';
|
||||
import { applyLanguage, resolveLanguage } from './i18n/index.ts';
|
||||
import { ipcInvoke, ipcOn } from './ipc.ts';
|
||||
import { AboutPage } from './pages/about/AboutPage.tsx';
|
||||
import { CopyMaintenance } from './pages/copies/CopyMaintenance.tsx';
|
||||
import { useCopyMaintenance } from './pages/copies/useCopyMaintenance.ts';
|
||||
import { CopyList } from './pages/copies/CopyList.tsx';
|
||||
import { CopySummary } from './pages/copies/CopySummary.tsx';
|
||||
import { FeatureStatus } from './pages/copies/FeatureStatus.tsx';
|
||||
@@ -22,7 +20,6 @@ import { useInstallWizard } from './pages/install/useInstallWizard.ts';
|
||||
import { WizardMain } from './pages/install/WizardMain.tsx';
|
||||
import { WizardSide } from './pages/install/WizardSide.tsx';
|
||||
import { wizardBar } from './pages/install/wizard-bar.ts';
|
||||
import { ModsPage } from './pages/mods/ModsPage.tsx';
|
||||
import { TuningPage } from './pages/tuning/TuningPage.tsx';
|
||||
import { SavesPage } from './pages/saves/SavesPage.tsx';
|
||||
import { DeveloperSettings } from './pages/settings/DeveloperSettings.tsx';
|
||||
@@ -33,11 +30,10 @@ import { Background } from './shell/Background.tsx';
|
||||
import { BottomBar } from './shell/BottomBar.tsx';
|
||||
import type { BarModel } from './shell/bar-model.ts';
|
||||
import { Footer } from './shell/Footer.tsx';
|
||||
import { COPY_SECTIONS, MODS_SECTIONS, navigate, SAVE_SECTIONS, SETTINGS_SECTIONS, START_ROUTE, TUNING_SECTIONS, type Destination, type Route } from './shell/navigation.ts';
|
||||
import { COPY_SECTIONS, navigate, SAVE_SECTIONS, SETTINGS_SECTIONS, START_ROUTE, TUNING_SECTIONS, type Destination, type Route } from './shell/navigation.ts';
|
||||
import { SubNav } from './shell/SubNav.tsx';
|
||||
import { TitleBar } from './shell/TitleBar.tsx';
|
||||
import { useBackgrounds } from './shell/useBackgrounds.ts';
|
||||
import { useAppUpdate } from './shell/useAppUpdate.ts';
|
||||
import { usePatchPack } from './shell/usePatchPack.ts';
|
||||
import { useErrorMessage } from './useErrorMessage.ts';
|
||||
|
||||
@@ -60,8 +56,7 @@ interface View {
|
||||
*/
|
||||
export function App({ info, initialSettings, initialCopies }: AppProps) {
|
||||
const { t } = useTranslation();
|
||||
const { error, report, clear: clearError } = useErrorMessage();
|
||||
const [errorPaused, setErrorPaused] = useState(false);
|
||||
const { message, report } = useErrorMessage();
|
||||
const [settings, setSettings] = useState(initialSettings);
|
||||
const [registry, setRegistry] = useState(initialCopies);
|
||||
const record = registry.copies.find((copy) => copy.id === registry.current) ?? null;
|
||||
@@ -69,23 +64,14 @@ export function App({ info, initialSettings, initialCopies }: AppProps) {
|
||||
const [route, setRoute] = useState<Route>(START_ROUTE);
|
||||
// The setting as the window opened: turning it on later does not check right away.
|
||||
const patchPack = usePatchPack(initialSettings.checkPatchPacksOnStart, report);
|
||||
const appUpdate = useAppUpdate(info.appUpdatesSupported, initialSettings.checkLauncherUpdatesOnStart, report);
|
||||
const maintenance = useCopyMaintenance(report);
|
||||
const supported = patchPack.active?.gameVersions ?? info.supportedGameVersions;
|
||||
|
||||
const wizard = useInstallWizard({ onInstalled: () => setRoute(START_ROUTE) });
|
||||
|
||||
const backgrounds = useBackgrounds(record && !record.folderMissing ? record.copyPath : null, settings, report);
|
||||
const backgrounds = useBackgrounds(record?.copyPath ?? null, settings, report);
|
||||
|
||||
useEffect(() => ipcOn('event:settings-changed', setSettings), []);
|
||||
useEffect(() => ipcOn('event:copies-changed', setRegistry), []);
|
||||
useEffect(() => {
|
||||
const refreshCopies = (): void => {
|
||||
ipcInvoke('copies:list').then(setRegistry).catch(() => undefined);
|
||||
};
|
||||
window.addEventListener('focus', refreshCopies);
|
||||
return () => window.removeEventListener('focus', refreshCopies);
|
||||
}, []);
|
||||
useEffect(() => applyLanguage(resolveLanguage(settings.language, info.systemLocale)), [settings.language, info.systemLocale]);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -101,37 +87,18 @@ export function App({ info, initialSettings, initialCopies }: AppProps) {
|
||||
return () => { mounted = false; dispose(); };
|
||||
}, [report]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!error || errorPaused) return;
|
||||
const timer = window.setTimeout(clearError, 6000);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [error, errorPaused, clearError]);
|
||||
|
||||
const go = (to: Destination): void => {
|
||||
clearError();
|
||||
setRoute((current) => navigate(current, to));
|
||||
};
|
||||
const go = (to: Destination): void => setRoute((current) => navigate(current, to));
|
||||
const selectCopy = (id: string, details = false): void => {
|
||||
ipcInvoke('copies:setCurrent', { id }).then(() => {
|
||||
if (details) go({ page: 'copies', section: 'summary' });
|
||||
}).catch(report);
|
||||
};
|
||||
const relocateCopy = (id: string): void => {
|
||||
clearError();
|
||||
ipcInvoke('dialog:pickFolder', { title: t('copies.relocateDialogTitle') })
|
||||
.then(({ path }) => {
|
||||
if (!path) return;
|
||||
return ipcInvoke('copies:relocate', { id, path }).then(setRegistry);
|
||||
})
|
||||
.catch(report);
|
||||
};
|
||||
const perCopyStatus = ['version-changed', 'failed', 'port-busy', 'server-exited', 'game-exited'].includes(launch.phase);
|
||||
const perCopyStatus = ['version-changed', 'failed', 'port-busy', 'server-exited'].includes(launch.phase);
|
||||
const launchStatus: LaunchState = perCopyStatus && launch.copyId && launch.copyId !== record?.id ? { phase: 'ready' } : launch;
|
||||
const home = homeBar(record, launchStatus, t, wizard.start, {
|
||||
start: () => { ipcInvoke('launch:start').catch(report); },
|
||||
stop: () => { ipcInvoke('launch:stop').catch(report); },
|
||||
checkVersion: () => go({ page: 'copies', section: 'features' }),
|
||||
relocate: () => { if (record) relocateCopy(record.id); },
|
||||
});
|
||||
|
||||
const view = ((): View => {
|
||||
@@ -152,26 +119,13 @@ export function App({ info, initialSettings, initialCopies }: AppProps) {
|
||||
bar: home,
|
||||
};
|
||||
case 'about':
|
||||
return {
|
||||
side: homeSide,
|
||||
main: (
|
||||
<AboutPage
|
||||
launcherVersion={info.version}
|
||||
supportedVersions={supported}
|
||||
patchPack={patchPack}
|
||||
appUpdate={appUpdate}
|
||||
loggingEnabled={settings.loggingEnabled}
|
||||
onError={report}
|
||||
/>
|
||||
),
|
||||
bar: home,
|
||||
};
|
||||
return { side: homeSide, main: <AboutPage launcherVersion={info.version} supportedVersions={supported} patchPack={patchPack} />, bar: home };
|
||||
case 'settings': {
|
||||
const sections = SETTINGS_SECTIONS.filter((section) => info.development || section !== 'dev');
|
||||
const content = {
|
||||
general: <GeneralSettings settings={settings} appUpdatesSupported={info.appUpdatesSupported} pictures={backgrounds.pictures} onError={report} />,
|
||||
launch: <LaunchSettings settings={settings} development={info.development} onError={report} />,
|
||||
diag: <DiagnosticsSettings settings={settings} onError={report} serverRunning={launch.phase === 'running' || launch.phase === 'server-running'} />,
|
||||
general: <GeneralSettings settings={settings} pictures={backgrounds.pictures} onError={report} />,
|
||||
launch: <LaunchSettings onError={report} />,
|
||||
diag: <DiagnosticsSettings onError={report} serverRunning={launch.phase === 'running'} />,
|
||||
dev: <DeveloperSettings settings={settings} onError={report} />,
|
||||
};
|
||||
return {
|
||||
@@ -184,7 +138,7 @@ export function App({ info, initialSettings, initialCopies }: AppProps) {
|
||||
return {
|
||||
side: <SubNav sections={SAVE_SECTIONS} active={route.saves} label={(section) => t(`saves.sections.${section}`)} onSelect={(section) => go({ page: 'saves', section })} />,
|
||||
main: record
|
||||
? <SavesPage key={record.id} copy={record} copies={registry.copies} section={route.saves} readOnly={['checking', 'building', 'starting-server', 'starting-game', 'running', 'server-running', 'stopping'].includes(launch.phase)} onError={report} />
|
||||
? <SavesPage key={record.id} copy={record} copies={registry.copies} section={route.saves} readOnly={['checking', 'building', 'starting-server', 'starting-game', 'running', 'stopping'].includes(launch.phase)} onError={report} />
|
||||
: <Sheet title={t(`saves.sections.${route.saves}`)}><p className="lead">{t('saves.noCopy')}</p></Sheet>,
|
||||
bar: home,
|
||||
};
|
||||
@@ -196,30 +150,10 @@ export function App({ info, initialSettings, initialCopies }: AppProps) {
|
||||
: <Sheet title={t(`tuning.sections.${route.tuning}`)}><p className="lead">{t('tuning.noCopy')}</p></Sheet>,
|
||||
bar: home,
|
||||
};
|
||||
case 'mods':
|
||||
return {
|
||||
side: <SubNav sections={MODS_SECTIONS} active={route.mods} label={(section) => t(`mods.sections.${section}`)} onSelect={(section) => go({ page: 'mods', section })} />,
|
||||
main: record
|
||||
? <ModsPage key={record.id} copy={record} section={route.mods} readOnly={['checking', 'building', 'starting-server', 'starting-game', 'running', 'server-running', 'stopping'].includes(launch.phase)} onError={report} />
|
||||
: <Sheet title={t(`mods.sections.${route.mods}`)}><p className="lead">{t('mods.noCopy')}</p></Sheet>,
|
||||
bar: home,
|
||||
};
|
||||
case 'copies': {
|
||||
const side = <SubNav sections={COPY_SECTIONS} active={route.copies} label={(section) => t(`copies.sections.${section}`)} onSelect={(section) => go({ page: 'copies', section })} />;
|
||||
if (route.copies === 'list') {
|
||||
return {
|
||||
side,
|
||||
main: (
|
||||
<CopyList
|
||||
registry={registry}
|
||||
supportedVersions={supported}
|
||||
onSelect={selectCopy}
|
||||
onRelocate={relocateCopy}
|
||||
onAdd={wizard.start}
|
||||
/>
|
||||
),
|
||||
bar: home,
|
||||
};
|
||||
return { side, main: <CopyList registry={registry} supportedVersions={supported} onSelect={selectCopy} onAdd={wizard.start} />, bar: home };
|
||||
}
|
||||
if (!record) {
|
||||
return {
|
||||
@@ -234,19 +168,11 @@ export function App({ info, initialSettings, initialCopies }: AppProps) {
|
||||
};
|
||||
}
|
||||
if (route.copies === 'maintain') {
|
||||
return { side, main: <CopyMaintenance key={record.id} record={record} maintenance={maintenance} onError={report} />, bar: home };
|
||||
return { side, main: <CopyMaintenance key={record.id} record={record} onError={report} />, bar: home };
|
||||
}
|
||||
const main = route.copies === 'features'
|
||||
? <FeatureStatus record={record} supportedVersions={supported} onError={report} />
|
||||
: (
|
||||
<CopySummary
|
||||
record={record}
|
||||
supportedVersions={supported}
|
||||
onShowFeatures={() => go({ page: 'copies', section: 'features' })}
|
||||
onRelocate={() => relocateCopy(record.id)}
|
||||
onError={report}
|
||||
/>
|
||||
);
|
||||
: <CopySummary record={record} supportedVersions={supported} onShowFeatures={() => go({ page: 'copies', section: 'features' })} onError={report} />;
|
||||
return { side, main, bar: home };
|
||||
}
|
||||
}
|
||||
@@ -260,26 +186,7 @@ export function App({ info, initialSettings, initialCopies }: AppProps) {
|
||||
<aside className="side">{view.side}</aside>
|
||||
<main className="main">
|
||||
{view.main}
|
||||
{error && (
|
||||
<div
|
||||
key={error.id}
|
||||
className="app-error"
|
||||
role="alert"
|
||||
onMouseEnter={() => setErrorPaused(true)}
|
||||
onMouseLeave={() => setErrorPaused(false)}
|
||||
>
|
||||
<span className="app-error-text">{error.message}</span>
|
||||
<button
|
||||
type="button"
|
||||
className="app-error-close"
|
||||
aria-label={t('window.close')}
|
||||
title={t('window.close')}
|
||||
onClick={clearError}
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{message && <p className="app-error" role="alert">{message}</p>}
|
||||
</main>
|
||||
<BottomBar model={view.bar} />
|
||||
<Footer
|
||||
@@ -287,10 +194,8 @@ export function App({ info, initialSettings, initialCopies }: AppProps) {
|
||||
gameVersion={record?.gameVersion ?? null}
|
||||
copyName={record?.name ?? null}
|
||||
packUpdate={patchPack.check?.status === 'available' ? (patchPack.check.latest?.version ?? null) : null}
|
||||
appUpdate={appUpdate.check?.status === 'available' ? appUpdate.check.release.version : null}
|
||||
onOpenUpdates={() => go({ page: 'about' })}
|
||||
onOpenPackUpdate={() => go({ page: 'about' })}
|
||||
/>
|
||||
<EllipsisTooltipHost />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,110 +0,0 @@
|
||||
import { useEffect, useLayoutEffect, useRef, useState } from 'react';
|
||||
|
||||
interface TooltipState {
|
||||
readonly text: string;
|
||||
readonly anchor: DOMRect;
|
||||
readonly element: HTMLElement;
|
||||
}
|
||||
|
||||
function isTruncated(element: HTMLElement): boolean {
|
||||
return element.scrollWidth > element.clientWidth + 1 || element.scrollHeight > element.clientHeight + 1;
|
||||
}
|
||||
|
||||
function findTooltipCandidate(start: EventTarget | null): { element: HTMLElement; text: string } | null {
|
||||
let node = start instanceof Element ? start : null;
|
||||
while (node && node instanceof HTMLElement) {
|
||||
const explicit = node.getAttribute('data-ellipsis-tip');
|
||||
if (explicit !== null) {
|
||||
const text = explicit.trim();
|
||||
if (text && (isTruncated(node) || text !== (node.textContent?.trim() ?? ''))) {
|
||||
return { element: node, text };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const style = window.getComputedStyle(node);
|
||||
if (style.textOverflow === 'ellipsis' && style.overflowX !== 'visible') {
|
||||
const text = node.textContent?.trim() ?? '';
|
||||
if (text && isTruncated(node)) {
|
||||
return { element: node, text };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
node = node.parentElement;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Window-level tooltip overlay for truncated (ellipsis) text and explicit `data-ellipsis-tip`
|
||||
* elements. Positioned fixed above the shell so overflow-hidden containers never clip it.
|
||||
*/
|
||||
export function EllipsisTooltipHost() {
|
||||
const [tip, setTip] = useState<TooltipState | null>(null);
|
||||
const [position, setPosition] = useState<{ left: number; top: number } | null>(null);
|
||||
const boxRef = useRef<HTMLDivElement | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const onPointerOver = (event: PointerEvent): void => {
|
||||
const candidate = findTooltipCandidate(event.target);
|
||||
if (!candidate) return;
|
||||
setTip({ text: candidate.text, anchor: candidate.element.getBoundingClientRect(), element: candidate.element });
|
||||
};
|
||||
|
||||
const onPointerOut = (event: PointerEvent): void => {
|
||||
setTip((current) => {
|
||||
if (!current) return null;
|
||||
const related = event.relatedTarget;
|
||||
if (related instanceof Node && current.element.contains(related)) return current;
|
||||
return null;
|
||||
});
|
||||
};
|
||||
|
||||
const clear = (): void => setTip(null);
|
||||
|
||||
document.addEventListener('pointerover', onPointerOver, true);
|
||||
document.addEventListener('pointerout', onPointerOut, true);
|
||||
document.addEventListener('pointerdown', clear, true);
|
||||
document.addEventListener('scroll', clear, true);
|
||||
window.addEventListener('blur', clear);
|
||||
window.addEventListener('resize', clear);
|
||||
return () => {
|
||||
document.removeEventListener('pointerover', onPointerOver, true);
|
||||
document.removeEventListener('pointerout', onPointerOut, true);
|
||||
document.removeEventListener('pointerdown', clear, true);
|
||||
document.removeEventListener('scroll', clear, true);
|
||||
window.removeEventListener('blur', clear);
|
||||
window.removeEventListener('resize', clear);
|
||||
};
|
||||
}, []);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (!tip || !boxRef.current) {
|
||||
setPosition(null);
|
||||
return;
|
||||
}
|
||||
const margin = 10;
|
||||
const gap = 8;
|
||||
const box = boxRef.current.getBoundingClientRect();
|
||||
const preferredLeft = tip.anchor.left + (tip.anchor.width - box.width) / 2;
|
||||
const left = Math.max(margin, Math.min(preferredLeft, window.innerWidth - box.width - margin));
|
||||
const aboveTop = tip.anchor.top - box.height - gap;
|
||||
const top = aboveTop >= margin
|
||||
? aboveTop
|
||||
: Math.min(tip.anchor.bottom + gap, window.innerHeight - box.height - margin);
|
||||
setPosition({ left, top });
|
||||
}, [tip]);
|
||||
|
||||
if (!tip) return null;
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={boxRef}
|
||||
role="tooltip"
|
||||
className="ellipsis-tooltip"
|
||||
style={position ? { left: `${position.left}px`, top: `${position.top}px`, visibility: 'visible' } : { left: 0, top: 0, visibility: 'hidden' }}
|
||||
>
|
||||
{tip.text}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
interface WordmarkProps {
|
||||
readonly className?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* The WTOffline wordmark (from assets/wordmark.svg), rendered with currentColor so it stays
|
||||
* crisp white over the launcher's dark crimson title bar regardless of OS light/dark mode.
|
||||
*/
|
||||
export function Wordmark({ className }: WordmarkProps) {
|
||||
return (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 396 206"
|
||||
className={className}
|
||||
role="img"
|
||||
aria-label="WTOffline"
|
||||
>
|
||||
<g fill="currentColor" fillRule="evenodd">
|
||||
<path d="M62 8H101L112 72L124 24H154L166 72L178 8H214L189 123H153L139 83L124 123H88ZM220 8H337V33L329 42H297V123H251V42H214V15Z" />
|
||||
<g>
|
||||
<path d="M13 60H53V68H22ZM31 74H53V82H40Z" />
|
||||
<path transform="translate(396) scale(-1 1)" d="M13 60H53V68H22ZM31 74H53V82H40Z" />
|
||||
</g>
|
||||
<g transform="translate(14 134)">
|
||||
<path transform="translate(0)" d="M9 0H48L57 9V55L48 64H9L0 55V9ZM17 12L14 15V49L17 52H40L43 49V15L40 12Z" />
|
||||
<path transform="translate(65)" d="M0 0H50V12H14V27H42V39H14V64H0Z" />
|
||||
<path transform="translate(123)" d="M0 0H50V12H14V27H42V39H14V64H0Z" />
|
||||
<path transform="translate(181)" d="M0 0H14V52H45V64H0Z" />
|
||||
<path transform="translate(234)" d="M0 0H14V64H0Z" />
|
||||
<path transform="translate(256)" d="M0 0H12L41 39V0H55V64H43L14 25V64H0Z" />
|
||||
<path transform="translate(319)" d="M0 0H49V12H14V26H43V38H14V52H49V64H0Z" />
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
@@ -7,8 +7,7 @@
|
||||
"home": "Home",
|
||||
"saves": "Saves",
|
||||
"tuning": "Tuning",
|
||||
"mods": "Mods",
|
||||
"copies": "Clients",
|
||||
"copies": "Copies",
|
||||
"settings": "Settings",
|
||||
"about": "About"
|
||||
},
|
||||
@@ -26,18 +25,17 @@
|
||||
"launcher": "Launcher {{version}}",
|
||||
"game": "{{name}} · Game {{version}}",
|
||||
"notInstalled": "Not installed",
|
||||
"packUpdate": "Adaptation pack {{version}} available · Update ›",
|
||||
"appUpdate": "Launcher {{version}} available · Update ›"
|
||||
"packUpdate": "Adaptation pack {{version}} available · Update ›"
|
||||
},
|
||||
"home": {
|
||||
"kicker": "Local server · AI battles",
|
||||
"installedKicker": "Game {{version}}",
|
||||
"body": "Select Install to set up an offline client.",
|
||||
"body": "Select Install to set up an offline copy.",
|
||||
"steps": {
|
||||
"choose": "Select game",
|
||||
"chooseBody": "Locate the game installation",
|
||||
"method": "Choose installation type",
|
||||
"methodBody": "Create a client or use an existing folder",
|
||||
"methodBody": "Create a copy or use an existing folder",
|
||||
"check": "Check patches",
|
||||
"checkBody": "Review the features available for this version"
|
||||
}
|
||||
@@ -45,12 +43,12 @@
|
||||
"side": {
|
||||
"requirements": "Installation requirements",
|
||||
"game": "Game",
|
||||
"gameValue": "War Thunder (online client)",
|
||||
"gameValue": "War Thunder (official client)",
|
||||
"versions": "Verified versions",
|
||||
"space": "Disk space",
|
||||
"spaceValue": "About 97 GB (copy installation)",
|
||||
"currentCopy": "Current client",
|
||||
"copyName": "Offline client",
|
||||
"currentCopy": "Current copy",
|
||||
"copyName": "Game copy",
|
||||
"adaptation": "Check status",
|
||||
"features": "Features",
|
||||
"allAvailable": "✓ All available",
|
||||
@@ -63,63 +61,46 @@
|
||||
},
|
||||
"bar": {
|
||||
"notInstalled": "Not installed",
|
||||
"notInstalledDetail": "Requires an installed online client of War Thunder",
|
||||
"notInstalledDetail": "Requires an installed copy of War Thunder",
|
||||
"install": "Install",
|
||||
"ready": "Ready",
|
||||
"readyMissing": "Ready · {{count}} features unavailable",
|
||||
"readyDetail": "Game {{version}}",
|
||||
"missingFolder": "Client folder not found",
|
||||
"launch": "Launch"
|
||||
},
|
||||
"launch": {
|
||||
"checking": "Checking the client",
|
||||
"checking": "Checking the game copy",
|
||||
"building": "Generating game files",
|
||||
"starting-server": "Starting local server",
|
||||
"starting-game": "Starting game",
|
||||
"starting": "Starting…",
|
||||
"running": "Game running",
|
||||
"runningDetail": "Local server · Port {{port}}",
|
||||
"server-running": "Local server running",
|
||||
"game-exited": "Game exited",
|
||||
"gameExitedServerRunning": "Game exited. The local server is still running.",
|
||||
"exitDetail": "Exit code {{code}}. Game logs: {{path}}",
|
||||
"exitCodeUnknown": "unknown",
|
||||
"stopping": "Stopping",
|
||||
"stopServer": "Close local server",
|
||||
"stopping": "Stopping game",
|
||||
"cancel": "Cancel",
|
||||
"stop": "End game",
|
||||
"retry": "Retry",
|
||||
"check": "Check",
|
||||
"version-changed": "The client version has changed",
|
||||
"version-changed": "The copy version has changed",
|
||||
"versionDetail": "Game version {{version}}",
|
||||
"port-busy": "Port {{port}} is already in use",
|
||||
"server-exited": "The local server exited unexpectedly"
|
||||
},
|
||||
"decals": {
|
||||
"source": "Decal source",
|
||||
"hint": "Import the online game's cache/content (or cache) folder for cached decals and downloadable skins. Placeholder decals are used when no cache is available.",
|
||||
"choose": "Choose decal cache…",
|
||||
"useDefault": "Use placeholder decals",
|
||||
"importing": "Importing decal cache",
|
||||
"imported": "Imported cache",
|
||||
"default": "Placeholder decals"
|
||||
},
|
||||
"folder": {
|
||||
"none": "Not selected",
|
||||
"choose": "Browse…",
|
||||
"change": "Change…"
|
||||
},
|
||||
"wizard": {
|
||||
"title": "Add a client",
|
||||
"title": "Add a copy",
|
||||
"steps": {
|
||||
"mode": "Setup mode",
|
||||
"source": "Game location",
|
||||
"method": "Installation type",
|
||||
"data": "Data folder",
|
||||
"check": "Patch check",
|
||||
"installing": "Install"
|
||||
},
|
||||
"barTitle": "Add a client · {{step}}",
|
||||
"barTitle": "Add a copy · {{step}}",
|
||||
"stepOf": "Step {{index}} of {{total}}",
|
||||
"back": "Back",
|
||||
"next": "Next",
|
||||
@@ -129,24 +110,9 @@
|
||||
"checking": "Checking patches",
|
||||
"checkingDetail": "Checking which patches apply to the selected game"
|
||||
},
|
||||
"mode": {
|
||||
"body": "Choose how to add an offline client.",
|
||||
"newTitle": "Fresh installation from online client",
|
||||
"newBody": "Create a new offline client from an installed online War Thunder folder via full copy, space-saving copy, or in-place setup.",
|
||||
"existingTitle": "Add existing offline client",
|
||||
"existingBody": "Register an already prepared offline client folder directly without copying game files."
|
||||
},
|
||||
"source": {
|
||||
"body": "Select the folder where War Thunder is installed.",
|
||||
"dialogTitle": "Select the War Thunder installation folder",
|
||||
"existingBody": "Select an existing offline client folder.",
|
||||
"existingDialogTitle": "Select an existing offline client folder",
|
||||
"offlineBackupDetected": "An existing offline original-file backup (wtoffline\\stock) was detected. This client can be added directly without copying.",
|
||||
"patchedNeedsStock": "This folder already has offline patches applied but is missing the 4 original core files (wtoffline\\stock). Select an unpatched game folder of the same version; the launcher will read-only copy only those 4 files (~150 MB) without recopying the game.",
|
||||
"stockSourceTitle": "Select an unpatched War Thunder folder of the same version",
|
||||
"stockSourcePatched": "The selected folder is also patched and missing an original backup. Choose an unpatched game folder.",
|
||||
"stockSourceVersionMismatch": "The selected original game version ({{actual}}) does not match this client ({{expected}}).",
|
||||
"stockSourceReady": "Original core file source ready (version {{version}}). Only the 4 core files will be copied into wtoffline\\stock.",
|
||||
"notAGame": "The selected folder is not a War Thunder installation. Missing: {{files}}",
|
||||
"versionVerified": "Game version {{version}} (verified)",
|
||||
"versionUnverified": "Game version {{version}} has no check record yet. Installing still tries every patch; the patch check shows which features are available.",
|
||||
@@ -157,43 +123,26 @@
|
||||
"method": {
|
||||
"copy": "Copy installation (recommended)",
|
||||
"copyBody": "Copies the game to a new folder. Requires about {{size}} of free space.",
|
||||
"spaceSaving": "Space-saving copy",
|
||||
"spaceSavingBody": "Shares read-only resource archives on the same volume. Estimated space required is {{size}}. An in-place update to the source client can change shared files in this client.",
|
||||
"spaceSavingPending": "Calculating how much space can be saved.",
|
||||
"spaceSavingUnavailable": "This installation has no read-only resource archives eligible for space-saving copying.",
|
||||
"sameVolumeRequired": "Select a destination on the same volume as the original installation.",
|
||||
"targetTitle": "Select an install location (a WTOffline subfolder will be created)",
|
||||
"targetSubfolderHint": "A dedicated WTOffline folder is automatically created under the selected location to keep game files organized.",
|
||||
"targetTitle": "Select a folder for the copy",
|
||||
"inPlace": "In-place installation",
|
||||
"inPlaceBody": "Uses the selected game folder directly as the client. Original files are backed up to wtoffline\\stock, and patches are applied on first launch.",
|
||||
"existing": "Add existing client",
|
||||
"existingBody": "Registers the selected existing game folder directly without copying files. If no original backup exists yet, one will be created in wtoffline\\stock.",
|
||||
"existingBodyWithBackup": "Registers the existing offline client directly, preserving its wtoffline\\stock original-file backup without copying game files.",
|
||||
"existingBodyWithStockSource": "Registers the existing offline client directly and copies only the 4 original core files from the selected stock folder into wtoffline\\stock.",
|
||||
"inPlaceBody": "Uses the selected game folder as the copy. Original files are backed up to wtoffline\\stock, and patches are applied on first launch.",
|
||||
"room": "Free space on target drive: {{free}}",
|
||||
"noRoom": "Not enough free space: {{needed}} required, {{free}} available on the target drive.",
|
||||
"problem": {
|
||||
"not_empty": "The selected folder is not empty. Select an empty or new folder.",
|
||||
"overlaps_stock": "The folder cannot be the online installation folder, or a folder inside or above it.",
|
||||
"overlaps_stock": "The folder cannot be the original installation folder, or a folder inside or above it.",
|
||||
"not_a_folder": "The selected path is not a folder."
|
||||
},
|
||||
"copyBodyPending": "Copies the game to a new folder. Calculating the required space."
|
||||
},
|
||||
"steam": {
|
||||
"inPlaceWarning": "Launching offline will modify the game files in this Steam installation. Steam updates or file verification may overwrite the changes. Launching the online game with modified files may result in an account ban.",
|
||||
"copyWarning": "The destination is in a Steam library. Choose a folder outside the library to keep the offline client separate.",
|
||||
"confirm": "Confirm this folder",
|
||||
"dataWarning": "Steam may remove saves, caches, and logs stored under the game folder when uninstalling the game.",
|
||||
"maintenanceWarning": "This client or its data folder is in a Steam library. Offline play can change game files in the library. Steam can replace them during an update or file verification. Using modified files online may result in an account ban. Uninstalling the game through Steam may also remove any saves stored under its folder.",
|
||||
"confirmLocations": "Confirm these locations"
|
||||
"inPlaceWarning": "Launching offline will modify the game files in this Steam installation. Steam updates or file verification may overwrite the changes. Launching the official game online with modified files may result in an account ban.",
|
||||
"copyWarning": "The destination is in a Steam library. Choose a folder outside the library to keep the offline copy separate.",
|
||||
"confirm": "Confirm this folder"
|
||||
},
|
||||
"data": {
|
||||
"body": "Select a folder for saves, caches, and logs.",
|
||||
"dialogTitle": "Select the data folder",
|
||||
"problem": {
|
||||
"overlaps_client": "The data folder cannot be the client folder, contain the client folder, or lie inside its wtoffline folder. Choose a separate folder or a dedicated subfolder inside the client (for example, data).",
|
||||
"overlaps_stock": "The data folder cannot lie inside the online installation folder."
|
||||
}
|
||||
"dialogTitle": "Select the data folder"
|
||||
},
|
||||
"check": {
|
||||
"running": "Checking patches for the selected game version.",
|
||||
@@ -207,93 +156,68 @@
|
||||
"phase": {
|
||||
"checking": "Checking game files",
|
||||
"measuring": "Counting files",
|
||||
"verifying": "Verifying resources to share",
|
||||
"copying": "Copying game files",
|
||||
"importing-decals": "Importing decal cache",
|
||||
"backing-up": "Backing up original files",
|
||||
"recording": "Finishing installation"
|
||||
},
|
||||
"copied": "Copied {{done}} / {{total}} · {{doneFiles}} / {{totalFiles}} files",
|
||||
"verified": "Verified {{done}} / {{total}} · {{doneFiles}} / {{totalFiles}} files",
|
||||
"prepared": "Prepared {{done}} / {{total}} · {{doneFiles}} / {{totalFiles}} files",
|
||||
"cancelHint": "Can be cancelled at any time; copied files will be deleted",
|
||||
"cancel": "Cancel installation",
|
||||
"cancelling": "Cancelling…"
|
||||
},
|
||||
"copies": {
|
||||
"sections": {
|
||||
"list": "All clients",
|
||||
"summary": "Client details",
|
||||
"list": "All copies",
|
||||
"summary": "Copy details",
|
||||
"features": "Feature status",
|
||||
"maintain": "Maintenance"
|
||||
},
|
||||
"add": "Add a client",
|
||||
"missingFolder": "Folder missing",
|
||||
"relocate": "Relocate…",
|
||||
"relocateDialogTitle": "Select the moved client folder",
|
||||
"list": {
|
||||
"current": "Current",
|
||||
"select": "Set as current"
|
||||
},
|
||||
"add": "Add a copy",
|
||||
"list": { "current": "Current", "select": "Set as current" },
|
||||
"none": "The offline edition is not installed yet.",
|
||||
"maintenance": {
|
||||
"update": "Update from online installation",
|
||||
"updateAction": "Update client",
|
||||
"update": "Update from official installation",
|
||||
"updateAction": "Update copy",
|
||||
"newVersion": "Version {{version}} is available from the installation source.",
|
||||
"updateKeepsSpaceSaving": "Version {{version}} is available. Updating continues sharing read-only resource archives with the source.",
|
||||
"updateDetaches": "Version {{version}} is available. Because the client and source are on different volumes, updating copies shared resources into independent files and requires additional space.",
|
||||
"currentVersion": "Installation source version {{version}}",
|
||||
"noSource": "Installation source unavailable",
|
||||
"spaceSaving": "Save space",
|
||||
"spaceSavingHint": "Share identical read-only resource archives with the source. An in-place update to the source client can change the shared files.",
|
||||
"spaceSavingUnavailable": "Requires a client and source installation of the same version on the same volume.",
|
||||
"compactAction": "Convert",
|
||||
"check": "Recheck patches",
|
||||
"checkHint": "Check the original file backup.",
|
||||
"lastCheck": "Last checked {{date}}",
|
||||
"repair": "Repair client",
|
||||
"repair": "Repair copy",
|
||||
"repairAction": "Repair",
|
||||
"repairHint": "Restore the original files from the backup. Game files will be generated again at launch.",
|
||||
"delete": "Delete client",
|
||||
"delete": "Delete copy",
|
||||
"deleteAction": "Delete…",
|
||||
"deleteHint": "The data folder is kept by default.",
|
||||
"unlink": "Remove registration",
|
||||
"unlinkAction": "Remove…",
|
||||
"unlinkHint": "The launcher keeps the Steam game files and data folder in place.",
|
||||
"unlinkLocation": "Remove the launcher's registration for {{path}}? Steam game files and data will stay in place.",
|
||||
"deleteLocation": "Delete the offline client at {{path}}?",
|
||||
"deleteLocation": "Delete the game copy at {{path}}?",
|
||||
"deleteData": "Also delete the data folder at {{path}}",
|
||||
"confirm": "Confirm deletion",
|
||||
"phase": {
|
||||
"checking": "Checking the client",
|
||||
"checking": "Checking the copy",
|
||||
"copying": "Copying changed files",
|
||||
"applying": "Applying changes"
|
||||
},
|
||||
"result": {
|
||||
"confirm-steam": "Steam locations confirmed.",
|
||||
"check": "Patch check complete.",
|
||||
"repair": "Original files restored.",
|
||||
"update": "Client updated.",
|
||||
"compact": "Space-saving conversion complete.",
|
||||
"delete": "Client deleted.",
|
||||
"cancelled": "Maintenance cancelled."
|
||||
"update": "Copy updated.",
|
||||
"delete": "Copy deleted.",
|
||||
"cancelled": "Update cancelled."
|
||||
}
|
||||
},
|
||||
"summary": {
|
||||
"name": "Client name",
|
||||
"name": "Copy name",
|
||||
"rename": "Rename",
|
||||
"source": "Installation source",
|
||||
"version": "Game version",
|
||||
"adaptation": "Check status",
|
||||
"adaptationHint": "Whether every patch was checked on this game version and verified in game",
|
||||
"location": "Location",
|
||||
"missingHint": "Game files were not found at this path. Relocate to the moved folder to keep existing saves and tuning.",
|
||||
"method": "Installation type",
|
||||
"methods": {
|
||||
"copy": "Copy installation",
|
||||
"hardlink": "Space-saving copy",
|
||||
"in-place": "In-place installation",
|
||||
"existing": "Existing client"
|
||||
"in-place": "In-place installation"
|
||||
},
|
||||
"stock": "Original file backup",
|
||||
"stockHint": "Patched files are generated from it at each launch",
|
||||
@@ -337,7 +261,7 @@
|
||||
"overview": "Overview",
|
||||
"battles": "Battle history",
|
||||
"vehicles": "Vehicles and research",
|
||||
"official": "Import online data",
|
||||
"official": "Import official backup",
|
||||
"backup": "Backup and restore"
|
||||
},
|
||||
"tree": {
|
||||
@@ -345,9 +269,10 @@
|
||||
"country": "Country",
|
||||
"type": "Vehicle type",
|
||||
"actions": "Bulk actions",
|
||||
"purchase": "Research and buy all",
|
||||
"research": "Research all",
|
||||
"purchase": "Grant regular vehicles",
|
||||
"equipment": "Unlock modifications",
|
||||
"empty": "This client has no eligible research branches.",
|
||||
"empty": "This copy has no eligible research branches.",
|
||||
"rank": "Rank {{rank}}",
|
||||
"owned": "Owned",
|
||||
"points": "{{earned}} / {{needed}} RP",
|
||||
@@ -372,35 +297,27 @@
|
||||
}
|
||||
},
|
||||
"official": {
|
||||
"auto": "Automatic import",
|
||||
"autoHint": "Locates local online data read-only, copies it into the offline folder, and imports from the copy without modifying the online files.",
|
||||
"oneClick": "Find and import",
|
||||
"discover": "Find and preview",
|
||||
"notFound": "No online data was found in the default Documents folder. Use manual file selection below.",
|
||||
"account": "Online account",
|
||||
"multipleAccounts": "{{count}} online account folders were found. Select the account to import.",
|
||||
"accountOption": "Account {{id}} ({{files}} · updated {{time}})",
|
||||
"files": "Manual selection",
|
||||
"fileHint": "Or select copied global.blk, machine.blk or storage.blk files manually.",
|
||||
"files": "Backup files",
|
||||
"fileHint": "Select copies of global.blk, machine.blk or storage.blk.",
|
||||
"choose": "Choose files…",
|
||||
"content": "Import contents",
|
||||
"settings": "Game settings and controls",
|
||||
"settings": "Game settings",
|
||||
"unlock": "Unlock vehicles from presets",
|
||||
"equipment": "Modifications",
|
||||
"equipmentHint": "All equipment unlocks regular modifications and ammunition only, without talismans.",
|
||||
"full": "All equipment",
|
||||
"basic": "Essential equipment",
|
||||
"stock": "Stock configuration",
|
||||
"includeUsed": "Include other vehicles found in the backup",
|
||||
"preview": "Preview",
|
||||
"import": "Import",
|
||||
"summary": "{{files}} file(s) · {{presets}} preset(s) · {{vehicles}} available vehicle(s)",
|
||||
"omitted": "Unavailable vehicles to skip · {{names}}",
|
||||
"done": "Online data imported. The previous save is available in Backup and restore."
|
||||
"done": "Backup imported. The previous save is available in Backup and restore."
|
||||
},
|
||||
"archive": {
|
||||
"fromCopy": "Copy from another client",
|
||||
"fromCopy": "Copy from another copy",
|
||||
"import": "Import save file…",
|
||||
"sourceCopy": "Source client",
|
||||
"sourceCopy": "Source copy",
|
||||
"transfer": "Create from save",
|
||||
"copy": "Copy",
|
||||
"export": "Export…",
|
||||
@@ -426,8 +343,8 @@
|
||||
"confirmPassword": "Confirm password",
|
||||
"passwordMismatch": "The passwords do not match.",
|
||||
"readOnly": "The local server or game is running. Saves are read-only.",
|
||||
"noCopy": "Select an offline client to manage its saves.",
|
||||
"empty": "There are no local saves for this client.",
|
||||
"noCopy": "Select a game copy to manage its saves.",
|
||||
"empty": "There are no local saves for this copy.",
|
||||
"loading": "Loading save",
|
||||
"silverLions": "Silver Lions",
|
||||
"goldenEagles": "Golden Eagles",
|
||||
@@ -437,9 +354,6 @@
|
||||
"battles": "Recorded battles",
|
||||
"lastBattle": "Last battle",
|
||||
"premiumDays": "Premium account days",
|
||||
"avatar": "Avatar",
|
||||
"avatarUnavailable": "Avatar unavailable",
|
||||
"level": "Account level",
|
||||
"apply": "Save changes",
|
||||
"saved": "Changes saved.",
|
||||
"noBattles": "The save has no recorded battles.",
|
||||
@@ -467,7 +381,6 @@
|
||||
"tankBotRespawns": "AI tank respawns",
|
||||
"airBotRespawns": "AI aircraft respawns",
|
||||
"strikeUcavSpawnScore": "Strike UCAV spawn points",
|
||||
"nuclearEscalationStrategicBombers": "Nuclear Escalation stage-3 strategic bombers (B-52H / Tu-95M)",
|
||||
"silverLions": "Starting Silver Lions",
|
||||
"goldenEagles": "Starting Golden Eagles",
|
||||
"preferLineSuccessor": "Prefer the next vehicle in the line",
|
||||
@@ -478,7 +391,7 @@
|
||||
"highestRank": "Highest rank",
|
||||
"treeOrder": "Research tree order"
|
||||
},
|
||||
"shared": "These settings apply to all saves in this client.",
|
||||
"shared": "These settings apply to all saves in this copy.",
|
||||
"nextLaunch": "Changes take effect the next time the local server starts.",
|
||||
"reset": "Restore defaults for this section",
|
||||
"default": "Default {{value}}",
|
||||
@@ -487,7 +400,7 @@
|
||||
"saved": "Tuning values saved.",
|
||||
"invalid": "Enter values within the supported range.",
|
||||
"loading": "Loading tuning values",
|
||||
"noCopy": "Select an offline client to edit its tuning values."
|
||||
"noCopy": "Select a game copy to edit its tuning values."
|
||||
},
|
||||
"settings": {
|
||||
"sections": {
|
||||
@@ -496,13 +409,8 @@
|
||||
"dev": "Developer",
|
||||
"diag": "Diagnostics"
|
||||
},
|
||||
"appUpdates": "Launcher updates",
|
||||
"appUpdatesToggle": "Check for launcher updates at start",
|
||||
"patchPacks": "Adaptation pack updates",
|
||||
"patchPacksHint": "After a game update, patches for the new version are released as an adaptation pack.",
|
||||
"updateMirror": "Update mirror repository",
|
||||
"updateMirrorHint": "Enter an HTTPS mirror with a GitHub-compatible releases list. It is used if the primary source is unreachable. Leave blank to disable it.",
|
||||
"updateMirrorInvalid": "Enter a valid HTTPS repository address or leave the field blank.",
|
||||
"patchPacksHint": "After a game update, the patches for the new version are released on GitHub as an adaptation pack.",
|
||||
"patchPacksToggle": "Check for a new adaptation pack at start",
|
||||
"windowClose": "When closing the window",
|
||||
"windowQuit": "Quit launcher",
|
||||
@@ -515,34 +423,24 @@
|
||||
"portHint": "Port set by the installed lab automation",
|
||||
"exit": "When the game exits",
|
||||
"exitHint": "Isolated launch",
|
||||
"automatic": "Close local server",
|
||||
"portMode": "Port assignment",
|
||||
"autoPort": "Assign automatically",
|
||||
"fixedPort": "Specify port",
|
||||
"arguments": "Additional arguments",
|
||||
"argumentsHint": "Command-line arguments passed to the game",
|
||||
"argumentsInvalid": "Close each double quote in the launch arguments."
|
||||
"automatic": "Close local server"
|
||||
},
|
||||
"developer": {
|
||||
"mode": "Developer mode",
|
||||
"modeHint": "Launches the lab client under the wto-lab Windows account",
|
||||
"modeHint": "Launches the lab copy under the wto-lab Windows account",
|
||||
"enabled": "Enabled",
|
||||
"stock": "Stock backup",
|
||||
"stockHint": "Defaults to the selected client’s stock backup",
|
||||
"stockHint": "Defaults to the selected copy’s stock backup",
|
||||
"data": "Lab data folder",
|
||||
"dataHint": "Defaults to the selected client’s data folder",
|
||||
"dataHint": "Defaults to the selected copy’s data folder",
|
||||
"reset": "Restore default"
|
||||
},
|
||||
"diagnostics": {
|
||||
"recordLogs": "Record runtime logs",
|
||||
"recordLogsToggle": "Write launcher, local server, and hook logs",
|
||||
"recordLogsHint": "When disabled, stops writing launcher logs, local server traffic logs, and wto_ws.log (the game engine's own .game_logs are unaffected). Re-enable before exporting logs for troubleshooting.",
|
||||
"loggingDisabledNotice": "Runtime logging is currently disabled; exported archives include only existing logs and configuration.",
|
||||
"logs": "Logs",
|
||||
"logsHint": "Logs recorded by the launcher",
|
||||
"openLogs": "Open log folder",
|
||||
"export": "Export diagnostics",
|
||||
"exportHint": "Save launcher, local server, and game logs, settings, and the installation record to a ZIP file (excludes saves)",
|
||||
"exportHint": "Save logs, settings and the installation record to a ZIP file",
|
||||
"save": "Export…",
|
||||
"saved": "Diagnostics saved to {{path}}.",
|
||||
"serverStatus": "Local server status",
|
||||
@@ -553,13 +451,13 @@
|
||||
},
|
||||
"background": {
|
||||
"title": "Background",
|
||||
"hint": "Game backgrounds come from the current client.",
|
||||
"hint": "Game backgrounds come from the current copy.",
|
||||
"official": "Website wallpapers",
|
||||
"officialHint": "Downloads wallpapers from the official website. Downloaded wallpapers are available offline.",
|
||||
"officialToggle": "Get wallpapers from the War Thunder website",
|
||||
"officialItem": "Website · {{name}}",
|
||||
"random": "Random",
|
||||
"none": "No background pictures are available. Install a client to use the game pictures, or turn on website wallpapers.",
|
||||
"none": "No background pictures are available. Install a copy to use the game pictures, or turn on website wallpapers.",
|
||||
"current": "Background: {{name}}",
|
||||
"previous": "Previous",
|
||||
"next": "Next",
|
||||
@@ -580,43 +478,35 @@
|
||||
"about": {
|
||||
"launcher": "Launcher {{version}}",
|
||||
"supported": "Supported game versions: {{versions}}",
|
||||
"feedback": {
|
||||
"title": "Feedback and logs",
|
||||
"export": "Save all logs",
|
||||
"exportHint": "Pack launcher, local server, and game logs into a ZIP file for issue reports (excludes saves).",
|
||||
"exportButton": "Save log ZIP…"
|
||||
},
|
||||
"pack": {
|
||||
"title": "Adaptation data",
|
||||
"current": "In use",
|
||||
"currentHint": "The patches used to install and update clients.",
|
||||
"currentHint": "The patches used to install and update copies.",
|
||||
"bundled": "Included with the launcher",
|
||||
"bundledVersion": "Included with the launcher ({{version}})",
|
||||
"downloaded": "Adaptation pack {{version}}",
|
||||
"useBundled": "Go back to the included patches",
|
||||
"check": "Check for updates",
|
||||
"checkHint": "Checks for a new adaptation pack.",
|
||||
"checkHint": "Looks for a new adaptation pack on GitHub. Gaijin is not contacted.",
|
||||
"checkButton": "Check",
|
||||
"checking": "Checking…",
|
||||
"applying": "Downloading and verifying the adaptation pack…",
|
||||
"upToDate": "Up to date (the newest adaptation pack is {{version}}).",
|
||||
"noneReleased": "No adaptation pack has been released yet.",
|
||||
"available": "Adaptation pack {{version}} is available. Supported game versions: {{versions}}.",
|
||||
"availableHint": "Its signature is verified before it is used. Installing and updating clients then use the new patches.",
|
||||
"availableHint": "Its signature is verified before it is used. Installing and updating copies then use the new patches.",
|
||||
"apply": "Download and use {{version}}",
|
||||
"needsAppUpdate": "Adaptation pack {{version}} needs offline version {{app}} or newer. Update the offline version first.",
|
||||
"checkFailed": {
|
||||
"no_signing_key": "This launcher has no signing key built in, so it accepts no adaptation pack.",
|
||||
"network": "The update source could not be reached. Try again later.",
|
||||
"page_limit": "Could not confirm whether a newer adaptation pack is available.",
|
||||
"network": "GitHub could not be reached. Try again later.",
|
||||
"contents": "The released adaptation pack is incomplete or malformed.",
|
||||
"signature": "The adaptation pack's signature is wrong. It was refused.",
|
||||
"size": "The adaptation pack is larger than allowed. It was refused."
|
||||
},
|
||||
"applyFailed": {
|
||||
"no_signing_key": "This launcher has no signing key built in, so it accepts no adaptation pack.",
|
||||
"network": "Could not reach the update source to download the adaptation pack. Try again later.",
|
||||
"page_limit": "Could not confirm whether a newer adaptation pack is available.",
|
||||
"network": "The download failed: GitHub could not be reached. Try again later.",
|
||||
"contents": "The adaptation pack is incomplete or malformed. It is not in use.",
|
||||
"signature": "The adaptation pack's signature is wrong. It was refused and is not in use.",
|
||||
"size": "The adaptation pack is larger than allowed. It was refused.",
|
||||
@@ -624,41 +514,12 @@
|
||||
"up_to_date": "Up to date: there is no adaptation pack to download."
|
||||
}
|
||||
},
|
||||
"update": {
|
||||
"title": "Launcher update",
|
||||
"check": "Launcher version check",
|
||||
"checking": "Checking…",
|
||||
"current": "The launcher is up to date.",
|
||||
"available": "Version {{version}} is available. Installer size {{size}}.",
|
||||
"downloading": "Downloading the installer…",
|
||||
"download": "Download update",
|
||||
"install": "Quit and install",
|
||||
"installing": "Opening the installer…",
|
||||
"errors": {
|
||||
"network": "The update source could not be reached.",
|
||||
"page_limit": "Could not confirm whether a newer version is available.",
|
||||
"contents": "The launcher release information is invalid.",
|
||||
"signature": "The launcher update signature could not be verified.",
|
||||
"no_signing_key": "The launcher update verification key is unavailable."
|
||||
}
|
||||
},
|
||||
"statement": "Project information",
|
||||
"statementBody": "WTOffline is a noncommercial hobby project independent of Gaijin. Running it requires your own War Thunder base game files.",
|
||||
"homepage": {
|
||||
"title": "Project homepage",
|
||||
"hint": "Project overview, release catalog, and community links.",
|
||||
"open": "Open homepage"
|
||||
},
|
||||
"community": {
|
||||
"discord": "Discord",
|
||||
"discordHint": "Development discussion, general chat, troubleshooting, and bug reports.",
|
||||
"openDiscord": "Open Discord"
|
||||
}
|
||||
"statementBody": "WTOffline is an independent, unofficial project with no affiliation to Gaijin Entertainment. An installed copy of the official War Thunder client is required."
|
||||
},
|
||||
"features": {
|
||||
"A-Offline startup": "Offline startup",
|
||||
"A-Local accounts": "Local accounts",
|
||||
"A-Isolation from the official game": "Isolation from the online game",
|
||||
"A-Isolation from the official game": "Isolation from the official game",
|
||||
"A-No Gaijin connections": "Gaijin connections blocked",
|
||||
"A-Tutorials": "Tutorial",
|
||||
"B-Hangar and vehicles": "Hangar and vehicles",
|
||||
@@ -676,13 +537,11 @@
|
||||
"J-Ground arcade and realistic": "Ground battles (arcade, realistic)",
|
||||
"J-Air arcade and realistic": "Air battles (arcade, realistic)",
|
||||
"J-Naval arcade and realistic": "Naval battles (arcade, realistic)",
|
||||
"E-Crew skills in battle": "Crew skills and qualifications in battle",
|
||||
"J-Sub-modes": "Additional modes (such as night battles)",
|
||||
"K-AI opponents and teammates": "AI opponents and allies",
|
||||
"K-Spawn score and respawns": "Spawn points and respawning",
|
||||
"K-Scouting": "Scouting and drones",
|
||||
"K-Kill, assist and capture scoring": "Kill, assist and capture scoring",
|
||||
"K-Player damage notices": "Player damage notices",
|
||||
"K-Additional vehicles": "Additional vehicles",
|
||||
"K-Scoreboard": "Scoreboard",
|
||||
"K-Chat and radio": "Chat and radio",
|
||||
@@ -690,108 +549,12 @@
|
||||
"L-Debriefing": "Battle results",
|
||||
"L-Battle awards": "Battle awards"
|
||||
},
|
||||
"mods": {
|
||||
"sections": {
|
||||
"list": "Mod list",
|
||||
"presets": "Presets & repository"
|
||||
},
|
||||
"loading": "Loading mods…",
|
||||
"noCopy": "Install or select an offline client first to configure its mods.",
|
||||
"enabledSummary": "{{enabled}} / {{total}} enabled",
|
||||
"experimentalChip": "Experimental",
|
||||
"experimentalTitle": "Experimental mod API notice:",
|
||||
"experimentalBody": "WTOffline is in early development (API {{api}}). Server script hooks, internal data structures, and declarative exe patch contracts may change at any time without backwards compatibility; only enable mods from trusted sources.",
|
||||
"readOnlyNotice": "Mod toggles, load order, and presets are read-only while the game, local server, or maintenance is running.",
|
||||
"searchPlaceholder": "Filter by mod name, ID, or author…",
|
||||
"autoSort": "Auto-sort by dependencies",
|
||||
"autoSorted": "Reordered mods based on dependencies and load-order hints.",
|
||||
"refresh": "Refresh",
|
||||
"openFolder": "Open mods folder",
|
||||
"openDocs": "Mod docs",
|
||||
"discoveryErrorsTitle": "{{count}} mod folder(s) could not be loaded:",
|
||||
"blockingIssuesTitle": "{{count}} blocking mod error(s) prevent launching:",
|
||||
"issuesTitle": "{{count}} mod notice(s) or overlap(s):",
|
||||
"severity": {
|
||||
"error": "Error",
|
||||
"warning": "Warning",
|
||||
"info": "Info"
|
||||
},
|
||||
"emptyTitle": "No mods found in the global mods folder yet.",
|
||||
"emptyHint": "Place mod folders containing mod.jsonc into {{path}}, then click Refresh. Standalone skins, sights, and user missions continue to work directly via the game's native UserSkins / UserSights / UserMissions folders.",
|
||||
"noSearchMatch": "No mods match the current search filter.",
|
||||
"loadOrderHint": "Load order: lower items load later and take higher priority (drag or use arrows)",
|
||||
"moveUp": "Move up",
|
||||
"moveDown": "Move down",
|
||||
"showDetails": "Details",
|
||||
"hideDetails": "Hide",
|
||||
"errorCount": "{{count}} error",
|
||||
"warnCount": "{{count}} warn",
|
||||
"badges": {
|
||||
"data": "Data / Assets",
|
||||
"gui": "GUI Patch",
|
||||
"script": "Server Script",
|
||||
"exe": "Exe Patch"
|
||||
},
|
||||
"details": {
|
||||
"folder": "Folder",
|
||||
"gameVersions": "Declared game versions",
|
||||
"requires": "Requires",
|
||||
"conflicts": "Conflicts",
|
||||
"tuning": "Server tuning overlays: {{count}}",
|
||||
"serverScript": "Executable server JS/TS script",
|
||||
"packOps": "Client pack operations: {{count}}",
|
||||
"addon": "3D model / texture addon: {{count}} file(s)",
|
||||
"guiPatches": "GUI script patches: {{count}}",
|
||||
"exePatches": "Declarative exe patches: {{count}}",
|
||||
"companionFiles": "Companion files: {{count}}",
|
||||
"configBlk": "Includes config.blk patch"
|
||||
},
|
||||
"presets": {
|
||||
"heading": "Mod presets (saved per client)",
|
||||
"description": "Save the current mod toggles and load order as named presets for quick switching or JSON export/import.",
|
||||
"quickSwitch": "Switch mod preset",
|
||||
"customOption": "Custom active selection",
|
||||
"namePlaceholder": "New preset name, e.g. Modern Vehicles",
|
||||
"saveCurrent": "Save preset",
|
||||
"import": "Import preset…",
|
||||
"empty": "No presets saved for this client yet.",
|
||||
"activeTag": "Active",
|
||||
"summary": "{{count}} enabled / {{total}} tracked",
|
||||
"apply": "Apply",
|
||||
"overwrite": "Update",
|
||||
"export": "Export",
|
||||
"delete": "Delete",
|
||||
"saved": "Saved preset \"{{name}}\".",
|
||||
"applied": "Applied preset \"{{name}}\".",
|
||||
"updated": "Updated preset \"{{name}}\" with current setup.",
|
||||
"exported": "Exported preset to: {{path}}",
|
||||
"imported": "Imported mod preset."
|
||||
},
|
||||
"repo": {
|
||||
"heading": "Global mods repository",
|
||||
"description": "All clients share one mod folder (large 3D model and texture addons mount across drives via NTFS Junctions with zero copying), while each client keeps its own toggles, load order, and presets.",
|
||||
"pathLabel": "Repository folder",
|
||||
"defaultNote": "Using launcher default mods folder",
|
||||
"customNote": "Using custom mods folder (can live on a larger drive or the same drive as your client)",
|
||||
"changeFolder": "Change folder…",
|
||||
"resetDefault": "Reset to default",
|
||||
"pickTitle": "Select global mods repository folder",
|
||||
"updated": "Updated global mods repository folder.",
|
||||
"resetDone": "Reset to default mods repository folder."
|
||||
}
|
||||
},
|
||||
"errors": {
|
||||
"app_update_unavailable": "There is no launcher update available to install.",
|
||||
"app_update_busy": "A launcher update operation is already in progress.",
|
||||
"app_update_launcher_busy": "Close the game and local server and finish any client or save operations before updating.",
|
||||
"app_update_download_failed": "The launcher installer could not be downloaded and verified. See the launcher log.",
|
||||
"app_update_installer_invalid": "The installer failed verification. Download it again.",
|
||||
"app_update_install_failed": "The launcher installer could not be opened. See the launcher log.",
|
||||
"internal_error": "An internal launcher error occurred.",
|
||||
"logs_folder_open_failed": "The launcher log folder could not be opened.",
|
||||
"diagnostics_export_failed": "The diagnostics archive could not be saved.",
|
||||
"save_official_invalid": "The selected files are not supported online data files.",
|
||||
"save_official_location": "Choose data files copied outside the online game's folders.",
|
||||
"save_official_invalid": "The selected files are not supported official backup files.",
|
||||
"save_official_location": "Choose backup files copied outside the official game's folders.",
|
||||
"save_archive_invalid": "The selected file is not a supported WTOffline save archive.",
|
||||
"save_not_found": "The selected save could not be found.",
|
||||
"save_read_only": "Saves are read-only while the game or local server is running.",
|
||||
@@ -800,61 +563,38 @@
|
||||
"save_login_exists": "An account with this login already exists.",
|
||||
"save_password_invalid": "Enter a password.",
|
||||
"save_nick_invalid": "Enter a nickname with up to 16 characters.",
|
||||
"save_avatar_invalid": "Select an avatar available in this client.",
|
||||
"save_level_invalid": "Enter a level supported by this client.",
|
||||
"tuning_invalid": "The tuning values could not be read or saved. Check the session limits and the launcher log.",
|
||||
"mods_read_only": "Mods cannot be changed while the game, local server, or maintenance is running.",
|
||||
"mods_write_failed": "The mod configuration could not be saved. See the launcher log.",
|
||||
"mods_preset_invalid": "The selected file is not a valid WTOffline mod preset.",
|
||||
"mods_blocking_issues": "Enabled mods have missing dependencies or conflicts. Resolve them on the Mods page before launching.",
|
||||
"mods_folder_invalid": "The selected global mods folder is invalid or not writable.",
|
||||
"copy_not_found": "The selected client is no longer available.",
|
||||
"copies_write_failed": "The client registry could not be saved.",
|
||||
"copy_location_in_use": "The client or data location overlaps an existing client.",
|
||||
"decal_source_invalid": "The selected folder does not contain a usable decal cache. Log into the online hangar once to populate it, then choose cache/content (or cache).",
|
||||
"decal_import_failed": "The decal cache could not be imported into the client's data folder. See the launcher log.",
|
||||
"maintenance_busy": "Maintenance requires the game, local server and other client operations to be stopped.",
|
||||
"maintenance_location": "The operation would affect files outside the registered client or data folder.",
|
||||
"copy_not_found": "The selected copy is no longer available.",
|
||||
"copies_write_failed": "The copy registry could not be saved.",
|
||||
"copy_location_in_use": "The copy or data location overlaps an existing copy.",
|
||||
"maintenance_busy": "Maintenance requires the game, local server and other copy operations to be stopped.",
|
||||
"maintenance_location": "The operation would affect files outside the registered copy or data folder.",
|
||||
"maintenance_no_update": "A newer version is unavailable at the installation source.",
|
||||
"maintenance_cancelled": "The client update was cancelled.",
|
||||
"maintenance_failed": "Client maintenance failed. See the launcher log.",
|
||||
"maintenance_cancelled": "The copy update was cancelled.",
|
||||
"maintenance_failed": "Copy maintenance failed. See the launcher log.",
|
||||
"maintenance_source_changed": "The installation source changed during the update. Retry once its update is complete.",
|
||||
"launch_no_copy": "An offline client must be installed before launching.",
|
||||
"launch_no_copy": "A game copy must be installed before launching.",
|
||||
"launch_busy": "A launch is already in progress.",
|
||||
"launch_failed": "Launch failed. See the launcher log.",
|
||||
"launch_platform_unsupported": "Game launch requires Windows.",
|
||||
"launch_lab_required": "Enable developer mode to launch through the isolated lab.",
|
||||
"launch_lab_missing": "The isolated lab automation could not be loaded.",
|
||||
"launch_lab_version": "The lab client and the stock backup must use the same game version.",
|
||||
"launch_lab_version": "The lab copy and the stock backup must use the same game version.",
|
||||
"launch_lab_failed": "The isolated launch failed. See the launcher log.",
|
||||
"launch_game_running": "Another game process is running.",
|
||||
"launch_copy_in_steam": "The development lab requires a client and data folder outside Steam.",
|
||||
"launch_steam_confirmation_required": "Confirm the Steam locations in Client Maintenance before launching.",
|
||||
"launch_location": "The client, stock backup, or data folder location is invalid.",
|
||||
"launch_stock_version": "The stock backup and client versions do not match.",
|
||||
"launch_stock_missing": "The original file backup (wtoffline\\stock) is missing or unreadable. Check your security software, or remove this client entry and add it again.",
|
||||
"launch_copy_in_steam": "The launch requires a separate copy and data folder outside Steam.",
|
||||
"launch_build_failed": "The game files could not be generated.",
|
||||
"launch_build_unavailable": "The build found unavailable patches that require review.",
|
||||
"launch_port_busy": "The local server port is already in use.",
|
||||
"launch_server_failed": "The local server could not be started. See the launcher log.",
|
||||
"launch_server_exited": "The local server is unavailable.",
|
||||
"launch_game_failed": "The game process could not start. See the launcher log.",
|
||||
"launch_game_files_missing": "Required game launch files are missing or unreadable (they may have been quarantined by antivirus software). Check your security software and the launcher log.",
|
||||
"settings_write_failed": "The settings could not be saved.",
|
||||
"folder_unreadable": "The folder cannot be read: {{path}}",
|
||||
"not_a_game_folder": "The selected folder is not a War Thunder installation: {{path}}",
|
||||
"stock_source_invalid": "This client is already patched and lacks an original backup. Select an unpatched game folder of the same version.",
|
||||
"stock_source_version_mismatch": "The selected original game version ({{actual}}) does not match the client version ({{expected}}).",
|
||||
"target_not_usable": "The selected folder cannot be used for installation.",
|
||||
"steam_library_not_confirmed": "The client or data folder is in a Steam library. Confirm the risk notice first.",
|
||||
"steam_library_not_confirmed": "The installation folder is in a Steam library. Confirm the risk notice first.",
|
||||
"not_enough_space": "Not enough disk space: {{neededGb}} GB required, {{freeGb}} GB available.",
|
||||
"essential_patches_unavailable": "Patches required by the offline edition do not apply to this game version. Installation is not possible: {{patches}}",
|
||||
"missing_features_not_accepted": "Some patches do not apply. Confirm whether to continue without the affected features.",
|
||||
"patch_check_failed": "An error occurred while checking patches.",
|
||||
"copy_failed": "Copying the game files failed. The copied files have been deleted.",
|
||||
"hardlink_unavailable": "Space-saving copying requires the destination and source to be on the same volume, and converting an existing client also requires matching versions.",
|
||||
"hardlink_no_match": "No matching read-only resource archives were found, or their contents differ from the source.",
|
||||
"hardlink_file_changed": "A resource changed during verification or copying. Finish any other file operation, then retry.",
|
||||
"install_cancelled": "Installation cancelled. The copied files have been deleted.",
|
||||
"install_busy": "An installation is already in progress.",
|
||||
"unknown": "An unknown error occurred."
|
||||
|
||||
@@ -7,8 +7,7 @@
|
||||
"home": "首页",
|
||||
"saves": "存档",
|
||||
"tuning": "数值",
|
||||
"mods": "模组",
|
||||
"copies": "客户端",
|
||||
"copies": "副本",
|
||||
"settings": "设置",
|
||||
"about": "关于"
|
||||
},
|
||||
@@ -26,18 +25,17 @@
|
||||
"launcher": "启动器 {{version}}",
|
||||
"game": "{{name}} · 游戏 {{version}}",
|
||||
"notInstalled": "未安装",
|
||||
"packUpdate": "适配包 {{version}} 可用 · 更新 ›",
|
||||
"appUpdate": "本体 {{version}} 可用 · 更新 ›"
|
||||
"packUpdate": "适配包 {{version}} 可用 · 更新 ›"
|
||||
},
|
||||
"home": {
|
||||
"kicker": "本地服务器 · AI 对局",
|
||||
"installedKicker": "游戏 {{version}}",
|
||||
"body": "选择「安装」以配置离线客户端。",
|
||||
"body": "选择「安装」以配置离线副本。",
|
||||
"steps": {
|
||||
"choose": "选择游戏",
|
||||
"chooseBody": "指定游戏的安装位置",
|
||||
"method": "选择安装方式",
|
||||
"methodBody": "创建客户端或使用已有文件夹",
|
||||
"methodBody": "创建副本或使用已有文件夹",
|
||||
"check": "检查补丁",
|
||||
"checkBody": "核对所选版本的功能状态"
|
||||
}
|
||||
@@ -45,12 +43,12 @@
|
||||
"side": {
|
||||
"requirements": "安装要求",
|
||||
"game": "游戏",
|
||||
"gameValue": "战争雷霆在线版客户端",
|
||||
"gameValue": "战争雷霆正版客户端",
|
||||
"versions": "已验证版本",
|
||||
"space": "磁盘空间",
|
||||
"spaceValue": "约 97 GB(复制安装)",
|
||||
"currentCopy": "当前客户端",
|
||||
"copyName": "离线客户端",
|
||||
"currentCopy": "当前副本",
|
||||
"copyName": "游戏副本",
|
||||
"adaptation": "核对状态",
|
||||
"features": "功能",
|
||||
"allAvailable": "✓ 全部可用",
|
||||
@@ -63,63 +61,46 @@
|
||||
},
|
||||
"bar": {
|
||||
"notInstalled": "未安装",
|
||||
"notInstalledDetail": "需要已安装的战争雷霆在线版客户端",
|
||||
"notInstalledDetail": "需要已安装的战争雷霆正版客户端",
|
||||
"install": "安装",
|
||||
"ready": "就绪",
|
||||
"readyMissing": "就绪 · {{count}} 项功能不可用",
|
||||
"readyDetail": "游戏 {{version}}",
|
||||
"missingFolder": "客户端目录不存在",
|
||||
"launch": "启动"
|
||||
},
|
||||
"launch": {
|
||||
"checking": "正在检查客户端",
|
||||
"checking": "正在检查副本",
|
||||
"building": "正在生成游戏文件",
|
||||
"starting-server": "正在启动本地服务器",
|
||||
"starting-game": "正在启动游戏",
|
||||
"starting": "启动中…",
|
||||
"running": "游戏运行中",
|
||||
"runningDetail": "本地服务器 · 端口 {{port}}",
|
||||
"server-running": "本地服务器运行中",
|
||||
"game-exited": "游戏已退出",
|
||||
"gameExitedServerRunning": "游戏已退出。本地服务器仍在运行。",
|
||||
"exitDetail": "退出码 {{code}}。游戏日志位于 {{path}}。",
|
||||
"exitCodeUnknown": "未知",
|
||||
"stopping": "正在关闭",
|
||||
"stopServer": "关闭本地服务器",
|
||||
"stopping": "正在结束游戏",
|
||||
"cancel": "取消",
|
||||
"stop": "结束游戏",
|
||||
"retry": "重试",
|
||||
"check": "检查",
|
||||
"version-changed": "客户端版本已变更",
|
||||
"version-changed": "副本版本已变更",
|
||||
"versionDetail": "游戏版本 {{version}}",
|
||||
"port-busy": "端口 {{port}} 已被占用",
|
||||
"server-exited": "本地服务器意外退出"
|
||||
},
|
||||
"decals": {
|
||||
"source": "贴花来源",
|
||||
"hint": "可导入在线版游戏的 cache/content(或 cache),同时支持已缓存的真实贴花与可下载涂装。未导入时使用占位贴花。",
|
||||
"choose": "选择贴花缓存…",
|
||||
"useDefault": "使用占位贴花",
|
||||
"importing": "正在导入贴花缓存",
|
||||
"imported": "已导入缓存",
|
||||
"default": "占位贴花"
|
||||
},
|
||||
"folder": {
|
||||
"none": "未选择",
|
||||
"choose": "浏览…",
|
||||
"change": "更改…"
|
||||
},
|
||||
"wizard": {
|
||||
"title": "添加客户端",
|
||||
"title": "添加副本",
|
||||
"steps": {
|
||||
"mode": "添加方式",
|
||||
"source": "游戏位置",
|
||||
"method": "安装方式",
|
||||
"data": "数据目录",
|
||||
"check": "补丁检查",
|
||||
"installing": "安装"
|
||||
},
|
||||
"barTitle": "添加客户端 · {{step}}",
|
||||
"barTitle": "添加副本 · {{step}}",
|
||||
"stepOf": "第 {{index}} 步,共 {{total}} 步",
|
||||
"back": "上一步",
|
||||
"next": "下一步",
|
||||
@@ -129,24 +110,9 @@
|
||||
"checking": "正在检查补丁",
|
||||
"checkingDetail": "正在核对补丁对所选游戏的适用情况"
|
||||
},
|
||||
"mode": {
|
||||
"body": "选择添加离线客户端的方式。",
|
||||
"newTitle": "从在线版全新安装",
|
||||
"newBody": "从已安装的战争雷霆在线版创建新的离线客户端,支持完整复制、省空间复制或原位安装。",
|
||||
"existingTitle": "添加已有离线客户端",
|
||||
"existingBody": "直接登记已准备好的离线客户端文件夹,不重新复制游戏文件。"
|
||||
},
|
||||
"source": {
|
||||
"body": "选择已安装的战争雷霆文件夹。",
|
||||
"dialogTitle": "选择战争雷霆安装文件夹",
|
||||
"existingBody": "选择已准备好的离线客户端文件夹。",
|
||||
"existingDialogTitle": "选择已有离线客户端文件夹",
|
||||
"offlineBackupDetected": "已检测到离线客户端的原版文件备份(wtoffline\\stock),可直接添加,无需重新复制。",
|
||||
"patchedNeedsStock": "所选文件夹已包含离线补丁,但缺少 4 个原版核心文件(wtoffline\\stock)。请选择同版本的原版游戏目录,启动器将只读复制这 4 个文件(约 150 MB),无需重新复制整包游戏。",
|
||||
"stockSourceTitle": "选择同版本的原版战争雷霆目录",
|
||||
"stockSourcePatched": "所选目录同样已打过离线补丁且缺少原版文件备份,请选择未打补丁的原版游戏目录。",
|
||||
"stockSourceVersionMismatch": "所选原版目录版本({{actual}})与当前客户端版本({{expected}})不一致。",
|
||||
"stockSourceReady": "原版核心文件来源就绪(版本 {{version}}),添加时将仅复制 4 个核心文件至 wtoffline\\stock。",
|
||||
"notAGame": "所选文件夹不是战争雷霆的安装文件夹,缺少:{{files}}",
|
||||
"versionVerified": "游戏版本 {{version}}(已核对)",
|
||||
"versionUnverified": "游戏版本 {{version}} 还没有核对记录。安装时仍会逐个尝试全部补丁,可用功能以补丁检查结果为准。",
|
||||
@@ -157,43 +123,26 @@
|
||||
"method": {
|
||||
"copy": "复制安装(推荐)",
|
||||
"copyBody": "将游戏复制到新文件夹。需要约 {{size}} 的可用空间。",
|
||||
"spaceSaving": "节省空间的复制",
|
||||
"spaceSavingBody": "与同一磁盘卷上的原版共用只读资源包,预计需要 {{size}}。原版就地更新可能改变客户端中的共享文件。",
|
||||
"spaceSavingPending": "正在估算可节省的空间。",
|
||||
"spaceSavingUnavailable": "该安装目录没有可用于省空间复制的只读资源包。",
|
||||
"sameVolumeRequired": "请选择与原版位于同一磁盘卷的目标文件夹。",
|
||||
"targetTitle": "选择安装位置(将自动创建 WTOffline 子文件夹)",
|
||||
"targetSubfolderHint": "将在所选位置下自动创建独立的 WTOffline 文件夹存放游戏文件,避免文件散落。",
|
||||
"targetTitle": "选择存放副本的文件夹",
|
||||
"inPlace": "原位安装",
|
||||
"inPlaceBody": "使用所选游戏文件夹作为客户端。原版文件备份至 wtoffline\\stock,首次启动时将应用补丁。",
|
||||
"existing": "添加已有客户端",
|
||||
"existingBody": "直接登记所选的已有游戏文件夹,不复制游戏文件;如尚未建立原版备份将自动备份至 wtoffline\\stock。",
|
||||
"existingBodyWithBackup": "直接登记已存在的离线客户端,保留现有的 wtoffline\\stock 原版文件备份,不复制游戏文件。",
|
||||
"existingBodyWithStockSource": "直接登记已存在的离线客户端,仅从所选原版目录补齐 4 个核心文件至 wtoffline\\stock,不重新复制游戏。",
|
||||
"inPlaceBody": "使用所选游戏文件夹作为副本。原版文件备份至 wtoffline\\stock,首次启动时将应用补丁。",
|
||||
"room": "目标磁盘可用空间:{{free}}",
|
||||
"noRoom": "可用空间不足:需要 {{needed}},目标磁盘仅剩 {{free}}。",
|
||||
"problem": {
|
||||
"not_empty": "所选文件夹不为空。请选择空文件夹或新建文件夹。",
|
||||
"overlaps_stock": "不能选择在线版安装文件夹本身,或其上级、下级文件夹。",
|
||||
"overlaps_stock": "不能选择正版安装文件夹本身,或其上级、下级文件夹。",
|
||||
"not_a_folder": "所选路径不是文件夹。"
|
||||
},
|
||||
"copyBodyPending": "将游戏复制到新文件夹。正在统计所需空间。"
|
||||
},
|
||||
"steam": {
|
||||
"inPlaceWarning": "离线启动会修改此 Steam 安装中的游戏文件。Steam 更新或文件校验可能覆盖改动。使用修改后的文件联网启动在线版可能导致账号封禁。",
|
||||
"copyWarning": "目标文件夹位于 Steam 游戏库。建议将客户端放在游戏库之外。",
|
||||
"confirm": "确认使用此文件夹",
|
||||
"dataWarning": "数据目录放在 Steam 游戏文件夹内时,在 Steam 中卸载游戏可能一并删除存档、缓存和日志。",
|
||||
"maintenanceWarning": "客户端或数据目录位于 Steam 游戏库中。离线启动可能修改库内的游戏文件。Steam 更新或校验可能覆盖改动,使用修改后的文件联网启动可能导致账号封禁。在 Steam 中卸载游戏还可能删除保存在该游戏文件夹内的存档。",
|
||||
"confirmLocations": "确认使用这些位置"
|
||||
"inPlaceWarning": "离线启动会修改此 Steam 安装中的游戏文件。Steam 更新或文件校验可能覆盖改动。使用修改后的文件联网启动正版可能导致账号封禁。",
|
||||
"copyWarning": "目标文件夹位于 Steam 游戏库。建议将副本放在游戏库之外。",
|
||||
"confirm": "确认使用此文件夹"
|
||||
},
|
||||
"data": {
|
||||
"body": "选择用于保存存档、缓存和日志的文件夹。",
|
||||
"dialogTitle": "选择数据目录",
|
||||
"problem": {
|
||||
"overlaps_client": "数据目录不能与客户端目录相同、包含客户端目录,或位于客户端的 wtoffline 目录内。请选择独立文件夹或客户端内的专用子文件夹(例如 data)。",
|
||||
"overlaps_stock": "数据目录不能位于在线版安装目录内。"
|
||||
}
|
||||
"dialogTitle": "选择数据目录"
|
||||
},
|
||||
"check": {
|
||||
"running": "正在检查所选游戏版本的补丁。",
|
||||
@@ -207,93 +156,68 @@
|
||||
"phase": {
|
||||
"checking": "检查游戏文件",
|
||||
"measuring": "统计文件",
|
||||
"verifying": "核对可共用的资源",
|
||||
"copying": "复制游戏文件",
|
||||
"importing-decals": "正在导入贴花缓存",
|
||||
"backing-up": "备份原版文件",
|
||||
"recording": "完成安装"
|
||||
},
|
||||
"copied": "已复制 {{done}} / {{total}} · {{doneFiles}} / {{totalFiles}} 个文件",
|
||||
"verified": "已核对 {{done}} / {{total}} · {{doneFiles}} / {{totalFiles}} 个文件",
|
||||
"prepared": "已处理 {{done}} / {{total}} · {{doneFiles}} / {{totalFiles}} 个文件",
|
||||
"cancelHint": "可随时取消,已复制的文件将被删除",
|
||||
"cancel": "取消安装",
|
||||
"cancelling": "正在取消…"
|
||||
},
|
||||
"copies": {
|
||||
"sections": {
|
||||
"list": "全部客户端",
|
||||
"summary": "客户端详情",
|
||||
"list": "全部副本",
|
||||
"summary": "副本详情",
|
||||
"features": "功能状态",
|
||||
"maintain": "维护"
|
||||
},
|
||||
"add": "添加客户端",
|
||||
"missingFolder": "目录不存在",
|
||||
"relocate": "重新定位…",
|
||||
"relocateDialogTitle": "选择挪动后的客户端文件夹",
|
||||
"list": {
|
||||
"current": "当前",
|
||||
"select": "设为当前"
|
||||
},
|
||||
"add": "添加副本",
|
||||
"list": { "current": "当前", "select": "设为当前" },
|
||||
"none": "尚未安装离线版。",
|
||||
"maintenance": {
|
||||
"update": "从在线版更新",
|
||||
"updateAction": "更新客户端",
|
||||
"update": "从正版更新",
|
||||
"updateAction": "更新副本",
|
||||
"newVersion": "安装来源已更新至 {{version}}。",
|
||||
"updateKeepsSpaceSaving": "安装来源中有新版本 {{version}}。更新时会继续与原版共用只读资源包。",
|
||||
"updateDetaches": "安装来源中有新版本 {{version}}。当前与安装来源不在同一磁盘卷,更新会把共享资源复制为独立文件,需要额外空间。",
|
||||
"currentVersion": "安装来源版本 {{version}}",
|
||||
"noSource": "安装来源不可用",
|
||||
"spaceSaving": "节省空间",
|
||||
"spaceSavingHint": "将内容一致的只读资源包与原版共用。原版就地更新可能改变这些文件。",
|
||||
"spaceSavingUnavailable": "客户端和安装来源须位于同一磁盘卷,并且版本一致。",
|
||||
"compactAction": "转换",
|
||||
"check": "重新检查补丁",
|
||||
"checkHint": "核对原版文件备份。",
|
||||
"lastCheck": "上次检查 {{date}}",
|
||||
"repair": "修复客户端",
|
||||
"repair": "修复副本",
|
||||
"repairAction": "修复",
|
||||
"repairHint": "从原版文件备份还原文件。下次启动时重新生成游戏文件。",
|
||||
"delete": "删除客户端",
|
||||
"delete": "删除副本",
|
||||
"deleteAction": "删除…",
|
||||
"deleteHint": "默认保留数据目录。",
|
||||
"unlink": "解除登记",
|
||||
"unlinkAction": "解除登记…",
|
||||
"unlinkHint": "Steam 游戏文件和数据目录将留在原处。",
|
||||
"unlinkLocation": "从启动器中解除 {{path}} 的登记?Steam 游戏文件和数据将留在原处。",
|
||||
"deleteLocation": "确认删除 {{path}} 中的离线客户端?",
|
||||
"deleteLocation": "确认删除 {{path}} 中的游戏副本?",
|
||||
"deleteData": "同时删除 {{path}} 中的数据",
|
||||
"confirm": "确认删除",
|
||||
"phase": {
|
||||
"checking": "正在检查客户端",
|
||||
"checking": "正在检查副本",
|
||||
"copying": "正在复制有变化的文件",
|
||||
"applying": "正在应用更改"
|
||||
},
|
||||
"result": {
|
||||
"confirm-steam": "已确认 Steam 目录。",
|
||||
"check": "补丁检查已完成。",
|
||||
"repair": "原版文件已还原。",
|
||||
"update": "客户端已更新。",
|
||||
"compact": "省空间转换已完成。",
|
||||
"delete": "客户端已删除。",
|
||||
"cancelled": "维护已取消。"
|
||||
"update": "副本已更新。",
|
||||
"delete": "副本已删除。",
|
||||
"cancelled": "更新已取消。"
|
||||
}
|
||||
},
|
||||
"summary": {
|
||||
"name": "客户端名称",
|
||||
"name": "副本名称",
|
||||
"rename": "重命名",
|
||||
"source": "安装来源",
|
||||
"version": "游戏版本",
|
||||
"adaptation": "核对状态",
|
||||
"adaptationHint": "这个游戏版本是否检查过全部补丁并在游戏里验证过",
|
||||
"location": "位置",
|
||||
"missingHint": "未在原位置找到游戏文件。可重新定位至挪动后的文件夹,保留现有存档和数值。",
|
||||
"method": "安装方式",
|
||||
"methods": {
|
||||
"copy": "复制安装",
|
||||
"hardlink": "节省空间的复制",
|
||||
"in-place": "原位安装",
|
||||
"existing": "已有客户端"
|
||||
"in-place": "原位安装"
|
||||
},
|
||||
"stock": "原版文件备份",
|
||||
"stockHint": "每次启动时据此生成补丁文件",
|
||||
@@ -337,7 +261,7 @@
|
||||
"overview": "概览",
|
||||
"battles": "战绩",
|
||||
"vehicles": "载具与研发",
|
||||
"official": "导入在线版数据",
|
||||
"official": "导入正版备份",
|
||||
"backup": "备份与还原"
|
||||
},
|
||||
"tree": {
|
||||
@@ -345,9 +269,10 @@
|
||||
"country": "国家",
|
||||
"type": "兵种",
|
||||
"actions": "批量操作",
|
||||
"purchase": "全部研发并购买",
|
||||
"research": "全部研发",
|
||||
"purchase": "获得常规载具",
|
||||
"equipment": "解锁改装件",
|
||||
"empty": "此客户端没有可编辑的研发分支。",
|
||||
"empty": "此副本没有可编辑的研发分支。",
|
||||
"rank": "等级 {{rank}}",
|
||||
"owned": "已拥有",
|
||||
"points": "{{earned}} / {{needed}} 研发点",
|
||||
@@ -372,35 +297,27 @@
|
||||
}
|
||||
},
|
||||
"official": {
|
||||
"auto": "自动导入",
|
||||
"autoHint": "只读查找本机在线版数据并复制到离线目录后再导入,不修改在线版原文件。",
|
||||
"oneClick": "一键查找并导入",
|
||||
"discover": "仅查找并预览",
|
||||
"notFound": "未在默认文档目录中找到在线版数据,请使用下方手动选择。",
|
||||
"account": "在线版账号",
|
||||
"multipleAccounts": "检测到 {{count}} 个在线版账号目录,请选择要导入的账号。",
|
||||
"accountOption": "账号 {{id}}({{files}} · 更新于 {{time}})",
|
||||
"files": "手动选择文件",
|
||||
"fileHint": "也可手动选择复制备份的 global.blk、machine.blk 或 storage.blk。",
|
||||
"files": "备份文件",
|
||||
"fileHint": "请选择复制备份的 global.blk、machine.blk 或 storage.blk。",
|
||||
"choose": "选择文件…",
|
||||
"content": "导入内容",
|
||||
"settings": "游戏设置与键位",
|
||||
"settings": "游戏设置",
|
||||
"unlock": "解锁预设中的载具",
|
||||
"equipment": "改装件",
|
||||
"equipmentHint": "完全体仅解锁常规改装件与弹药,不包含护身符。",
|
||||
"full": "完全体",
|
||||
"basic": "基础生存配件",
|
||||
"stock": "白板状态",
|
||||
"includeUsed": "包含备份中的其他已用载具",
|
||||
"preview": "预览",
|
||||
"import": "导入",
|
||||
"summary": "{{files}} 个文件 · {{presets}} 套预设 · {{vehicles}} 辆可用载具",
|
||||
"omitted": "将跳过的不可用载具 · {{names}}",
|
||||
"done": "在线版数据已导入。原存档可在「备份与还原」中恢复。"
|
||||
"done": "备份已导入。原存档可在「备份与还原」中恢复。"
|
||||
},
|
||||
"archive": {
|
||||
"fromCopy": "从其他客户端复制",
|
||||
"fromCopy": "从其他副本复制",
|
||||
"import": "导入存档文件…",
|
||||
"sourceCopy": "来源客户端",
|
||||
"sourceCopy": "来源副本",
|
||||
"transfer": "创建存档",
|
||||
"copy": "复制",
|
||||
"export": "导出…",
|
||||
@@ -426,8 +343,8 @@
|
||||
"confirmPassword": "确认密码",
|
||||
"passwordMismatch": "两次输入的密码不一致。",
|
||||
"readOnly": "游戏或本地服务器正在运行,存档为只读。",
|
||||
"noCopy": "选择离线客户端后即可管理该客户端的存档。",
|
||||
"empty": "此客户端没有本地存档。",
|
||||
"noCopy": "选择游戏副本后即可管理该副本的存档。",
|
||||
"empty": "此副本没有本地存档。",
|
||||
"loading": "正在读取存档",
|
||||
"silverLions": "银狮",
|
||||
"goldenEagles": "金鹰",
|
||||
@@ -437,9 +354,6 @@
|
||||
"battles": "已记录对局",
|
||||
"lastBattle": "上次对局",
|
||||
"premiumDays": "高级账户剩余天数",
|
||||
"avatar": "头像",
|
||||
"avatarUnavailable": "头像不可用",
|
||||
"level": "账号等级",
|
||||
"apply": "保存更改",
|
||||
"saved": "更改已保存。",
|
||||
"noBattles": "此存档没有对局记录。",
|
||||
@@ -467,7 +381,6 @@
|
||||
"tankBotRespawns": "AI 坦克重生次数",
|
||||
"airBotRespawns": "AI 飞机重生次数",
|
||||
"strikeUcavSpawnScore": "打击无人机所需出生点数",
|
||||
"nuclearEscalationStrategicBombers": "核战冲突启用第 3 阶段战略核轰炸机(B-52H / Tu-95M)",
|
||||
"silverLions": "初始银狮",
|
||||
"goldenEagles": "初始金鹰",
|
||||
"preferLineSuccessor": "优先研发同系载具",
|
||||
@@ -478,7 +391,7 @@
|
||||
"highestRank": "最高等级",
|
||||
"treeOrder": "研发树顺序"
|
||||
},
|
||||
"shared": "这些数值适用于此客户端的全部存档。",
|
||||
"shared": "这些数值适用于此副本的全部存档。",
|
||||
"nextLaunch": "更改将在下次启动本地服务器时生效。",
|
||||
"reset": "恢复本页默认值",
|
||||
"default": "默认 {{value}}",
|
||||
@@ -487,7 +400,7 @@
|
||||
"saved": "数值已保存。",
|
||||
"invalid": "请输入受支持范围内的数值。",
|
||||
"loading": "正在读取数值",
|
||||
"noCopy": "选择离线客户端后即可编辑数值。"
|
||||
"noCopy": "选择游戏副本后即可编辑数值。"
|
||||
},
|
||||
"settings": {
|
||||
"sections": {
|
||||
@@ -496,13 +409,8 @@
|
||||
"dev": "开发者",
|
||||
"diag": "诊断"
|
||||
},
|
||||
"appUpdates": "启动器本体更新",
|
||||
"appUpdatesToggle": "启动时检查本体更新",
|
||||
"patchPacks": "适配包更新",
|
||||
"patchPacksHint": "游戏更新后,新版本的补丁会以适配包的形式发布。",
|
||||
"updateMirror": "备用更新仓库",
|
||||
"updateMirrorHint": "填写支持 GitHub Releases 格式的 HTTPS 镜像地址。主源连接失败时使用,留空关闭。",
|
||||
"updateMirrorInvalid": "请输入有效的 HTTPS 仓库地址,或留空。",
|
||||
"patchPacksHint": "游戏更新后,新版本的补丁会以适配包的形式发布在 GitHub 上。",
|
||||
"patchPacksToggle": "启动时检查有没有新的适配包",
|
||||
"windowClose": "关闭窗口时",
|
||||
"windowQuit": "退出启动器",
|
||||
@@ -515,34 +423,24 @@
|
||||
"portHint": "使用已安装实验自动化的端口设置",
|
||||
"exit": "游戏退出后",
|
||||
"exitHint": "隔离启动",
|
||||
"automatic": "关闭本地服务器",
|
||||
"portMode": "端口分配方式",
|
||||
"autoPort": "自动分配",
|
||||
"fixedPort": "指定端口",
|
||||
"arguments": "附加启动参数",
|
||||
"argumentsHint": "传递给游戏的命令行参数",
|
||||
"argumentsInvalid": "请补全启动参数中的双引号。"
|
||||
"automatic": "关闭本地服务器"
|
||||
},
|
||||
"developer": {
|
||||
"mode": "开发模式",
|
||||
"modeHint": "以 wto-lab 用户身份启动实验客户端",
|
||||
"modeHint": "以 wto-lab 用户身份启动实验副本",
|
||||
"enabled": "启用",
|
||||
"stock": "原版文件备份",
|
||||
"stockHint": "默认使用当前客户端的原版文件备份",
|
||||
"stockHint": "默认使用当前副本的原版文件备份",
|
||||
"data": "实验数据目录",
|
||||
"dataHint": "默认使用当前客户端的数据目录",
|
||||
"dataHint": "默认使用当前副本的数据目录",
|
||||
"reset": "恢复默认"
|
||||
},
|
||||
"diagnostics": {
|
||||
"recordLogs": "生成运行日志",
|
||||
"recordLogsToggle": "记录启动器、本地服务器和钩子日志",
|
||||
"recordLogsHint": "关闭后停止写入启动器日志、本地服务器流量日志和 wto_ws.log(不影响游戏引擎原生的 .game_logs)。导出日志排查问题前建议重新开启。",
|
||||
"loggingDisabledNotice": "当前已关闭运行日志记录,导出的压缩包仅包含已有历史日志和配置。",
|
||||
"logs": "日志",
|
||||
"logsHint": "启动器运行日志",
|
||||
"openLogs": "打开日志文件夹",
|
||||
"export": "导出诊断信息",
|
||||
"exportHint": "导出包含启动器、本地服务器与游戏日志、设置和安装记录的 ZIP 文件(不含存档)",
|
||||
"exportHint": "导出包含日志、设置和安装记录的 ZIP 文件",
|
||||
"save": "导出…",
|
||||
"saved": "诊断信息已保存到 {{path}}。",
|
||||
"serverStatus": "本地服务器状态页",
|
||||
@@ -553,7 +451,7 @@
|
||||
},
|
||||
"background": {
|
||||
"title": "背景图",
|
||||
"hint": "游戏背景图来自当前客户端。",
|
||||
"hint": "游戏背景图来自当前副本。",
|
||||
"official": "官网壁纸",
|
||||
"officialHint": "联网下载官网壁纸。已下载的壁纸可离线使用。",
|
||||
"officialToggle": "从战争雷霆官网获取壁纸",
|
||||
@@ -580,43 +478,35 @@
|
||||
"about": {
|
||||
"launcher": "启动器 {{version}}",
|
||||
"supported": "支持的游戏版本:{{versions}}",
|
||||
"feedback": {
|
||||
"title": "问题反馈",
|
||||
"export": "保存全部日志",
|
||||
"exportHint": "打包启动器、本地服务器及游戏日志为 ZIP 文件以便反馈问题(不含存档)。",
|
||||
"exportButton": "保存日志 ZIP…"
|
||||
},
|
||||
"pack": {
|
||||
"title": "适配数据",
|
||||
"current": "当前使用",
|
||||
"currentHint": "安装和更新客户端时使用的补丁。",
|
||||
"currentHint": "安装和更新副本时使用的补丁。",
|
||||
"bundled": "启动器自带",
|
||||
"bundledVersion": "启动器自带({{version}})",
|
||||
"downloaded": "适配包 {{version}}",
|
||||
"useBundled": "改回启动器自带",
|
||||
"check": "检查更新",
|
||||
"checkHint": "检查是否有新的适配包。",
|
||||
"checkHint": "在 GitHub 上查找新的适配包,不会连接 Gaijin。",
|
||||
"checkButton": "检查",
|
||||
"checking": "正在检查…",
|
||||
"applying": "正在下载并校验适配包…",
|
||||
"upToDate": "已是最新(最新的适配包是 {{version}})。",
|
||||
"noneReleased": "还没有发布适配包。",
|
||||
"available": "适配包 {{version}} 可用,支持的游戏版本:{{versions}}。",
|
||||
"availableHint": "下载后会先校验签名,通过后才启用;之后安装和更新客户端都使用新的补丁。",
|
||||
"availableHint": "下载后会先校验签名,通过后才启用;之后安装和更新副本都使用新的补丁。",
|
||||
"apply": "下载并启用 {{version}}",
|
||||
"needsAppUpdate": "适配包 {{version}} 需要离线版 {{app}} 或更新的版本,请先更新离线版。",
|
||||
"checkFailed": {
|
||||
"no_signing_key": "这个启动器没有内置签名公钥,不接受适配包。",
|
||||
"network": "无法连接更新源,请稍后再试。",
|
||||
"page_limit": "无法确认是否有新的适配包。",
|
||||
"network": "连不上 GitHub,请稍后再试。",
|
||||
"contents": "发布的适配包信息不完整或格式不对。",
|
||||
"signature": "适配包的签名不对,已拒绝。",
|
||||
"size": "适配包超出大小上限,已拒绝。"
|
||||
},
|
||||
"applyFailed": {
|
||||
"no_signing_key": "这个启动器没有内置签名公钥,不接受适配包。",
|
||||
"network": "无法连接更新源来下载适配包,请稍后再试。",
|
||||
"page_limit": "无法确认是否有新的适配包。",
|
||||
"network": "下载失败:连不上 GitHub,请稍后再试。",
|
||||
"contents": "适配包内容不完整或格式不对,没有启用。",
|
||||
"signature": "适配包的签名不对,已拒绝,没有启用。",
|
||||
"size": "适配包超出大小上限,已拒绝。",
|
||||
@@ -624,41 +514,12 @@
|
||||
"up_to_date": "已是最新,没有需要下载的适配包。"
|
||||
}
|
||||
},
|
||||
"update": {
|
||||
"title": "本体更新",
|
||||
"check": "检查本体版本",
|
||||
"checking": "正在检查…",
|
||||
"current": "当前已是最新版本。",
|
||||
"available": "版本 {{version}} 可用,安装包 {{size}}。",
|
||||
"downloading": "正在下载安装包…",
|
||||
"download": "下载更新",
|
||||
"install": "退出并安装",
|
||||
"installing": "正在打开安装包…",
|
||||
"errors": {
|
||||
"network": "暂时无法访问更新源。",
|
||||
"page_limit": "无法确认是否有新版本。",
|
||||
"contents": "本体更新的发布信息无效。",
|
||||
"signature": "本体更新签名校验失败。",
|
||||
"no_signing_key": "本体更新公钥不可用。"
|
||||
}
|
||||
},
|
||||
"statement": "项目信息",
|
||||
"statementBody": "WTOffline 是一个独立于 Gaijin 的非商业兴趣项目。运行需要自备战争雷霆游戏本体文件。",
|
||||
"homepage": {
|
||||
"title": "项目主页",
|
||||
"hint": "查看项目介绍、全部版本与社区入口。",
|
||||
"open": "打开主页"
|
||||
},
|
||||
"community": {
|
||||
"discord": "Discord",
|
||||
"discordHint": "开发讨论、日常交流、使用求助与问题反馈。",
|
||||
"openDiscord": "打开 Discord"
|
||||
}
|
||||
"statementBody": "WTOffline 是独立开发的非官方项目,与 Gaijin Entertainment 无关。运行需要已安装的战争雷霆正版客户端。"
|
||||
},
|
||||
"features": {
|
||||
"A-Offline startup": "离线启动",
|
||||
"A-Local accounts": "本地账号",
|
||||
"A-Isolation from the official game": "与在线版隔离",
|
||||
"A-Isolation from the official game": "与正版隔离",
|
||||
"A-No Gaijin connections": "阻断 Gaijin 连接",
|
||||
"A-Tutorials": "新手教程",
|
||||
"B-Hangar and vehicles": "机库与载具",
|
||||
@@ -676,13 +537,11 @@
|
||||
"J-Ground arcade and realistic": "陆战(街机、历史)",
|
||||
"J-Air arcade and realistic": "空战(街机、历史)",
|
||||
"J-Naval arcade and realistic": "海战(街机、历史)",
|
||||
"E-Crew skills in battle": "战局乘员技能与资格",
|
||||
"J-Sub-modes": "附加模式(如夜战)",
|
||||
"K-AI opponents and teammates": "AI 对手与队友",
|
||||
"K-Spawn score and respawns": "出生点数与重生",
|
||||
"K-Scouting": "侦察与无人机",
|
||||
"K-Kill, assist and capture scoring": "击杀、助攻与占点计分",
|
||||
"K-Player damage notices": "玩家载具受损提示",
|
||||
"K-Additional vehicles": "补充载具",
|
||||
"K-Scoreboard": "计分板",
|
||||
"K-Chat and radio": "聊天与无线电",
|
||||
@@ -690,108 +549,12 @@
|
||||
"L-Debriefing": "战后结算",
|
||||
"L-Battle awards": "战斗嘉奖"
|
||||
},
|
||||
"mods": {
|
||||
"sections": {
|
||||
"list": "模组列表",
|
||||
"presets": "预设与仓库"
|
||||
},
|
||||
"loading": "正在读取模组信息…",
|
||||
"noCopy": "请先安装或选择一个离线客户端,再为它配置模组。",
|
||||
"enabledSummary": "已启用 {{enabled}} / {{total}}",
|
||||
"experimentalChip": "实验功能",
|
||||
"experimentalTitle": "实验期模组接口提示:",
|
||||
"experimentalBody": "离线版当前处于极初期开发阶段(API {{api}})。服务端脚本钩子、内部数据结构及声明式 exe 补丁契约随时可能随本体更新变动且不保证向下兼容;请仅启用来源可信的模组。",
|
||||
"readOnlyNotice": "游戏、本地服务器或维护任务运行期间,模组开关、排序与预设为只读。",
|
||||
"searchPlaceholder": "搜索模组名称、ID 或作者…",
|
||||
"autoSort": "按依赖自动排序",
|
||||
"autoSorted": "已按前置与排序建议重新排列模组顺序。",
|
||||
"refresh": "刷新",
|
||||
"openFolder": "打开模组目录",
|
||||
"openDocs": "开发文档",
|
||||
"discoveryErrorsTitle": "有 {{count}} 个模组目录读取失败:",
|
||||
"blockingIssuesTitle": "存在 {{count}} 项阻塞性模组错误(处理前无法启动):",
|
||||
"issuesTitle": "检测到 {{count}} 项模组提示或冲突:",
|
||||
"severity": {
|
||||
"error": "错误",
|
||||
"warning": "警告",
|
||||
"info": "提示"
|
||||
},
|
||||
"emptyTitle": "当前模组目录里还没有模组。",
|
||||
"emptyHint": "将包含 mod.jsonc 的模组文件夹放入 {{path}},点击「刷新」即可识别。独立涂装、瞄具与单人任务继续沿用游戏原生的 UserSkins / UserSights / UserMissions 目录即可。",
|
||||
"noSearchMatch": "没有匹配当前搜索条件的模组。",
|
||||
"loadOrderHint": "加载顺序:越靠后优先级越高(可拖动或使用上下按钮调整)",
|
||||
"moveUp": "上移",
|
||||
"moveDown": "下移",
|
||||
"showDetails": "详情",
|
||||
"hideDetails": "收起",
|
||||
"errorCount": "{{count}} 错误",
|
||||
"warnCount": "{{count}} 警告",
|
||||
"badges": {
|
||||
"data": "数据/资源",
|
||||
"gui": "界面补丁",
|
||||
"script": "服务端脚本",
|
||||
"exe": "二进制补丁"
|
||||
},
|
||||
"details": {
|
||||
"folder": "目录",
|
||||
"gameVersions": "声明适配版本",
|
||||
"requires": "前置依赖",
|
||||
"conflicts": "已知互斥",
|
||||
"tuning": "服务端数值叠加:{{count}} 份",
|
||||
"serverScript": "含可执行服务端 JS/TS 脚本",
|
||||
"packOps": "客户端数据包操作:{{count}} 项",
|
||||
"addon": "独立 3D 模型/贴图扩展包:{{count}} 个文件",
|
||||
"guiPatches": "界面脚本补丁:{{count}} 项",
|
||||
"exePatches": "声明式 exe 补丁:{{count}} 项",
|
||||
"companionFiles": "附带外置文件:{{count}} 个",
|
||||
"configBlk": "含 config.blk 增量补丁"
|
||||
},
|
||||
"presets": {
|
||||
"heading": "模组序列预设(当前客户端独立保存)",
|
||||
"description": "将当前的启用开关与加载顺序保存为预设,方便在不同玩法配置间一键切换,或导出 JSON 分享给其他玩家。",
|
||||
"quickSwitch": "快速切换模组预设",
|
||||
"customOption": "当前自定义配置",
|
||||
"namePlaceholder": "输入新预设名称,例如:现代载具包",
|
||||
"saveCurrent": "保存为预设",
|
||||
"import": "导入预设…",
|
||||
"empty": "当前客户端尚未保存任何模组预设。",
|
||||
"activeTag": "当前使用",
|
||||
"summary": "启用 {{count}} / 共 {{total}} 个模组",
|
||||
"apply": "应用",
|
||||
"overwrite": "覆盖更新",
|
||||
"export": "导出",
|
||||
"delete": "删除",
|
||||
"saved": "已保存预设「{{name}}」。",
|
||||
"applied": "已切换至预设「{{name}}」。",
|
||||
"updated": "已用当前配置覆盖预设「{{name}}」。",
|
||||
"exported": "预设已导出到:{{path}}",
|
||||
"imported": "已导入模组预设。"
|
||||
},
|
||||
"repo": {
|
||||
"heading": "全局模组仓库位置",
|
||||
"description": "所有客户端共享同一份模组文件仓库(大体积 3D 模型与贴图包通过跨盘目录联接点零拷贝挂载,不重复占用磁盘);每个客户端独立保存自己的开关、排序和预设。",
|
||||
"pathLabel": "当前仓库目录",
|
||||
"defaultNote": "使用启动器默认模组目录",
|
||||
"customNote": "使用自定义模组目录(可放在大容量硬盘或游戏同盘)",
|
||||
"changeFolder": "更改目录…",
|
||||
"resetDefault": "恢复默认目录",
|
||||
"pickTitle": "选择全局模组仓库目录",
|
||||
"updated": "已更新全局模组仓库目录。",
|
||||
"resetDone": "已恢复为默认模组仓库目录。"
|
||||
}
|
||||
},
|
||||
"errors": {
|
||||
"app_update_unavailable": "当前没有可安装的本体更新。",
|
||||
"app_update_busy": "本体更新操作正在进行。",
|
||||
"app_update_launcher_busy": "请在游戏退出、服务器关闭及客户端和存档操作完成后安装更新。",
|
||||
"app_update_download_failed": "无法下载并验证本体安装包。请查看启动器日志。",
|
||||
"app_update_installer_invalid": "安装包校验失败。请重新下载。",
|
||||
"app_update_install_failed": "无法打开本体安装包。请查看启动器日志。",
|
||||
"internal_error": "启动器内部错误。",
|
||||
"logs_folder_open_failed": "无法打开启动器日志文件夹。",
|
||||
"diagnostics_export_failed": "无法保存诊断信息。",
|
||||
"save_official_invalid": "所选文件不是受支持的在线版数据文件。",
|
||||
"save_official_location": "请选择复制到在线版目录以外的数据文件。",
|
||||
"save_official_invalid": "所选文件不是受支持的正版备份。",
|
||||
"save_official_location": "请选择复制到正版目录以外的备份文件。",
|
||||
"save_archive_invalid": "所选文件不是受支持的 WTOffline 存档归档。",
|
||||
"save_not_found": "找不到所选存档。",
|
||||
"save_read_only": "游戏或本地服务器运行期间存档为只读。",
|
||||
@@ -800,61 +563,38 @@
|
||||
"save_login_exists": "该登录账号已注册。",
|
||||
"save_password_invalid": "请输入密码。",
|
||||
"save_nick_invalid": "请输入最多 16 个字符的昵称。",
|
||||
"save_avatar_invalid": "请选择此客户端中可用的头像。",
|
||||
"save_level_invalid": "请输入此客户端支持的账号等级。",
|
||||
"tuning_invalid": "无法读取或保存数值。请核对对局人数限制和启动器日志。",
|
||||
"mods_read_only": "游戏、本地服务器或维护任务运行期间无法修改模组配置。",
|
||||
"mods_write_failed": "无法保存模组配置,请查看启动器日志。",
|
||||
"mods_preset_invalid": "所选文件不是有效的 WTOffline 模组预设。",
|
||||
"mods_blocking_issues": "当前启用的模组存在缺失前置或互斥冲突,请先在「模组」页面处理后再启动。",
|
||||
"mods_folder_invalid": "所选全局模组目录无效或无法写入。",
|
||||
"copy_not_found": "所选客户端已不可用。",
|
||||
"copies_write_failed": "无法保存客户端记录。",
|
||||
"copy_location_in_use": "客户端位置或数据目录与已有客户端重叠。",
|
||||
"decal_source_invalid": "选定的目录缺少有效的贴花缓存。请先登录过在线版机库生成缓存,再选择在线版目录中的 cache/content(或 cache)。",
|
||||
"decal_import_failed": "无法把贴花缓存导入客户端数据目录。请查看启动器日志。",
|
||||
"maintenance_busy": "维护前需结束游戏、本地服务器和其他客户端操作。",
|
||||
"maintenance_location": "操作会影响登记的客户端或数据目录之外的文件。",
|
||||
"copy_not_found": "所选副本已不可用。",
|
||||
"copies_write_failed": "无法保存副本记录。",
|
||||
"copy_location_in_use": "副本位置或数据目录与已有副本重叠。",
|
||||
"maintenance_busy": "维护前需结束游戏、本地服务器和其他副本操作。",
|
||||
"maintenance_location": "操作会影响登记的副本或数据目录之外的文件。",
|
||||
"maintenance_no_update": "安装来源没有可用的新版本。",
|
||||
"maintenance_cancelled": "客户端更新已取消。",
|
||||
"maintenance_failed": "客户端维护失败。请查看启动器日志。",
|
||||
"maintenance_source_changed": "安装来源在更新过程中发生变化。请在在线版更新完成后重试。",
|
||||
"launch_no_copy": "启动前需要安装离线客户端。",
|
||||
"maintenance_cancelled": "副本更新已取消。",
|
||||
"maintenance_failed": "副本维护失败。请查看启动器日志。",
|
||||
"maintenance_source_changed": "安装来源在更新过程中发生变化。请在正版更新完成后重试。",
|
||||
"launch_no_copy": "启动前需要安装游戏副本。",
|
||||
"launch_busy": "启动流程正在运行。",
|
||||
"launch_failed": "启动失败。请查看启动器日志。",
|
||||
"launch_platform_unsupported": "启动游戏需要 Windows。",
|
||||
"launch_lab_required": "请启用开发模式以通过隔离实验客户端启动。",
|
||||
"launch_lab_required": "请启用开发模式以通过隔离实验副本启动。",
|
||||
"launch_lab_missing": "无法读取隔离实验自动化配置。",
|
||||
"launch_lab_version": "实验客户端和原版文件备份必须使用同一游戏版本。",
|
||||
"launch_lab_version": "实验副本和原版文件备份必须使用同一游戏版本。",
|
||||
"launch_lab_failed": "隔离启动失败。请查看启动器日志。",
|
||||
"launch_game_running": "已有游戏进程在运行。",
|
||||
"launch_copy_in_steam": "隔离实验需使用 Steam 目录外的客户端和数据目录。",
|
||||
"launch_steam_confirmation_required": "请在客户端维护中确认 Steam 目录后再启动。",
|
||||
"launch_location": "客户端、原版文件备份或数据目录的位置无效。",
|
||||
"launch_stock_version": "原版文件备份的版本与客户端不一致。",
|
||||
"launch_stock_missing": "缺少或无法读取原版文件备份(wtoffline\\stock)。请检查安全软件拦截记录,或移除此客户端登记后重新添加。",
|
||||
"launch_copy_in_steam": "启动需使用 Steam 目录外的副本和数据目录。",
|
||||
"launch_build_failed": "无法生成游戏文件。",
|
||||
"launch_build_unavailable": "生成游戏文件时发现需要重新确认的不可用补丁。",
|
||||
"launch_port_busy": "本地服务器端口已被占用。",
|
||||
"launch_server_failed": "无法启动本地服务器。请查看启动器日志。",
|
||||
"launch_server_exited": "本地服务器不可用。",
|
||||
"launch_game_failed": "游戏进程无法启动。请查看启动器日志。",
|
||||
"launch_game_files_missing": "启动所需的核心文件缺失或无法访问(可能已被安全软件隔离)。请检查安全软件拦截记录或查看启动器日志。",
|
||||
"settings_write_failed": "无法保存设置。",
|
||||
"folder_unreadable": "无法读取文件夹:{{path}}",
|
||||
"not_a_game_folder": "所选文件夹不是战争雷霆的安装文件夹:{{path}}",
|
||||
"stock_source_invalid": "所选客户端已打过离线补丁且缺少原版文件备份,请指定一份未打补丁的同版本原版游戏目录。",
|
||||
"stock_source_version_mismatch": "所选原版游戏目录版本({{actual}})与当前客户端版本({{expected}})不一致。",
|
||||
"target_not_usable": "所选文件夹不能用于安装。",
|
||||
"steam_library_not_confirmed": "客户端或数据目录位于 Steam 游戏库中,请先确认风险提示。",
|
||||
"steam_library_not_confirmed": "安装位置位于 Steam 游戏库中,请先确认风险提示。",
|
||||
"not_enough_space": "磁盘空间不足:需要 {{neededGb}} GB,仅剩 {{freeGb}} GB。",
|
||||
"essential_patches_unavailable": "此游戏版本缺少离线版运行所必需的补丁,无法安装:{{patches}}",
|
||||
"missing_features_not_accepted": "部分补丁不适用,请先确认是否在缺少相应功能的情况下继续。",
|
||||
"patch_check_failed": "检查补丁时出错。",
|
||||
"copy_failed": "复制游戏文件失败,已复制的文件已删除。",
|
||||
"hardlink_unavailable": "省空间复制要求目标与原版位于同一磁盘卷,转换已有客户端还要求版本一致。",
|
||||
"hardlink_no_match": "未找到可共用的只读资源包,或文件内容与原版不一致。",
|
||||
"hardlink_file_changed": "核对或复制过程中有资源文件发生变化。请等待其他文件操作完成后重试。",
|
||||
"install_cancelled": "安装已取消,已复制的文件已删除。",
|
||||
"install_busy": "已有安装正在进行。",
|
||||
"unknown": "发生未知错误。"
|
||||
|
||||
@@ -1,26 +1,17 @@
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Notice } from '../../components/Notice.tsx';
|
||||
import { Row } from '../../components/Row.tsx';
|
||||
import { Sheet } from '../../components/Sheet.tsx';
|
||||
import { ipcInvoke } from '../../ipc.ts';
|
||||
import type { AppUpdateState } from '../../shell/useAppUpdate.ts';
|
||||
import { AppUpdateSection } from './AppUpdateSection.tsx';
|
||||
import type { PatchPackState } from '../../shell/usePatchPack.ts';
|
||||
|
||||
const HOMEPAGE_URL = 'https://wto-project.net';
|
||||
const DISCORD_INVITE_URL = 'https://discord.gg/P566xWNpEs';
|
||||
|
||||
interface AboutPageProps {
|
||||
readonly launcherVersion: string;
|
||||
readonly supportedVersions: readonly string[];
|
||||
readonly patchPack: PatchPackState;
|
||||
readonly appUpdate: AppUpdateState;
|
||||
readonly loggingEnabled: boolean;
|
||||
readonly onError: (error: unknown) => void;
|
||||
}
|
||||
|
||||
/** The launcher's version, the game versions it supports, updates, community links, log export, and the project statement. */
|
||||
export function AboutPage({ launcherVersion, supportedVersions, patchPack, appUpdate, loggingEnabled, onError }: AboutPageProps) {
|
||||
/** The launcher's version, the game versions it supports, adaptation pack updates, and the project statement. */
|
||||
export function AboutPage({ launcherVersion, supportedVersions, patchPack }: AboutPageProps) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<Sheet title={t('nav.about')}>
|
||||
@@ -32,97 +23,13 @@ export function AboutPage({ launcherVersion, supportedVersions, patchPack, appUp
|
||||
{t('about.supported', { versions: supportedVersions.join(', ') })}
|
||||
</div>
|
||||
</div>
|
||||
<div className="about-columns">
|
||||
<div className="about-column">
|
||||
<AppUpdateSection state={appUpdate} />
|
||||
<PatchPackSection state={patchPack} />
|
||||
</div>
|
||||
<div className="about-column">
|
||||
<HomepageSection />
|
||||
<CommunitySection />
|
||||
<FeedbackLogsSection loggingEnabled={loggingEnabled} onError={onError} />
|
||||
<section className="about-card">
|
||||
<h3 className="about-card-title">{t('about.statement')}</h3>
|
||||
<p className="about-card-meta">{t('about.statementBody')}</p>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
<PatchPackSection state={patchPack} />
|
||||
<h3 className="section-title section-title-spaced">{t('about.statement')}</h3>
|
||||
<p className="lead">{t('about.statementBody')}</p>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
|
||||
function HomepageSection() {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<section className="about-card">
|
||||
<div className="about-card-head">
|
||||
<h3 className="about-card-title">{t('about.homepage.title')}</h3>
|
||||
<div className="about-card-actions">
|
||||
<a className="button" href={HOMEPAGE_URL} target="_blank" rel="noreferrer">
|
||||
{t('about.homepage.open')}
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
<p className="about-card-meta">{t('about.homepage.hint')}</p>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function CommunitySection() {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<section className="about-card">
|
||||
<div className="about-card-head">
|
||||
<h3 className="about-card-title">{t('about.community.discord')}</h3>
|
||||
<div className="about-card-actions">
|
||||
<a className="button" href={DISCORD_INVITE_URL} target="_blank" rel="noreferrer">
|
||||
{t('about.community.openDiscord')}
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
<p className="about-card-meta">{t('about.community.discordHint')}</p>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function FeedbackLogsSection({ loggingEnabled, onError }: {
|
||||
readonly loggingEnabled: boolean;
|
||||
readonly onError: (error: unknown) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const [exporting, setExporting] = useState(false);
|
||||
const [savedPath, setSavedPath] = useState<string | null>(null);
|
||||
|
||||
async function save(): Promise<void> {
|
||||
setExporting(true);
|
||||
setSavedPath(null);
|
||||
try {
|
||||
const result = await ipcInvoke('app:exportDiagnostics');
|
||||
setSavedPath(result.path);
|
||||
} catch (error) {
|
||||
onError(error);
|
||||
} finally {
|
||||
setExporting(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="about-card">
|
||||
<div className="about-card-head">
|
||||
<h3 className="about-card-title">{t('about.feedback.title')}</h3>
|
||||
<div className="about-card-actions">
|
||||
<button type="button" className="button" disabled={exporting} onClick={() => { void save(); }}>
|
||||
{t('about.feedback.exportButton')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<p className="about-card-meta">{t('about.feedback.exportHint')}</p>
|
||||
{!loggingEnabled && <p className="small">{t('settings.diagnostics.loggingDisabledNotice')}</p>}
|
||||
{savedPath && <p className="small" role="status">{t('settings.diagnostics.saved', { path: savedPath })}</p>}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function PatchPackSection({ state }: { readonly state: PatchPackState }) {
|
||||
const { t } = useTranslation();
|
||||
const { active, check, busy } = state;
|
||||
@@ -134,30 +41,25 @@ function PatchPackSection({ state }: { readonly state: PatchPackState }) {
|
||||
? t('about.pack.bundledVersion', { version: active.version })
|
||||
: t('about.pack.bundled');
|
||||
return (
|
||||
<section className="about-card">
|
||||
<div className="about-card-head">
|
||||
<h3 className="about-card-title">{t('about.pack.title')}</h3>
|
||||
<div className="about-card-actions">
|
||||
<button type="button" className="button" disabled={busy !== null} onClick={state.checkNow}>
|
||||
{busy === 'checking' ? t('about.pack.checking') : t('about.pack.checkButton')}
|
||||
<>
|
||||
<h3 className="section-title">{t('about.pack.title')}</h3>
|
||||
<Row label={t('about.pack.current')} hint={t('about.pack.currentHint')}>
|
||||
<span>{current}</span>
|
||||
{active?.source === 'downloaded' && (
|
||||
<button type="button" className="button" disabled={busy !== null} onClick={state.useBundled}>
|
||||
{t('about.pack.useBundled')}
|
||||
</button>
|
||||
{active?.source === 'downloaded' && (
|
||||
<button type="button" className="button" disabled={busy !== null} onClick={state.useBundled}>
|
||||
{t('about.pack.useBundled')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<p className="about-card-meta">
|
||||
<span className="about-card-label">{t('about.pack.current')}</span>
|
||||
{' · '}
|
||||
{current}
|
||||
</p>
|
||||
<p className="small">{t('about.pack.currentHint')}</p>
|
||||
)}
|
||||
</Row>
|
||||
<Row label={t('about.pack.check')} hint={t('about.pack.checkHint')}>
|
||||
<button type="button" className="button" disabled={busy !== null} onClick={state.checkNow}>
|
||||
{busy === 'checking' ? t('about.pack.checking') : t('about.pack.checkButton')}
|
||||
</button>
|
||||
</Row>
|
||||
{busy === 'applying' && <p className="small">{t('about.pack.applying')}</p>}
|
||||
{state.applyFailure && <Notice tone="error"><p>{t(`about.pack.applyFailed.${state.applyFailure}`)}</p></Notice>}
|
||||
{check && busy !== 'checking' && <CheckResult state={state} />}
|
||||
</section>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,50 +0,0 @@
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Notice } from '../../components/Notice.tsx';
|
||||
import { ProgressBar } from '../../components/ProgressBar.tsx';
|
||||
import { formatBytes } from '../../format.ts';
|
||||
import type { AppUpdateState } from '../../shell/useAppUpdate.ts';
|
||||
|
||||
export function AppUpdateSection({ state }: { readonly state: AppUpdateState }) {
|
||||
const { t } = useTranslation();
|
||||
if (!state.supported) return null;
|
||||
const { check, busy, progress } = state;
|
||||
return (
|
||||
<section className="about-card">
|
||||
<div className="about-card-head">
|
||||
<h3 className="about-card-title">{t('about.update.title')}</h3>
|
||||
<div className="about-card-actions">
|
||||
<button type="button" className="button" disabled={busy !== null} onClick={state.checkNow}>
|
||||
{t(busy === 'checking' ? 'about.update.checking' : 'about.pack.checkButton')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<p className="about-card-meta">{t('about.update.check')}</p>
|
||||
{check?.status === 'current' && busy !== 'checking' && <Notice tone="info"><p>{t('about.update.current')}</p></Notice>}
|
||||
{check?.status === 'failed' && busy !== 'checking' && <Notice tone="error"><p>{t(`about.update.errors.${check.problem}`)}</p></Notice>}
|
||||
{check?.status === 'available' && busy !== 'checking' && (
|
||||
<Notice tone="info">
|
||||
<p>{t('about.update.available', { version: check.release.version, size: formatBytes(check.release.size) })}</p>
|
||||
{check.release.notes && <p className="small update-notes">{check.release.notes}</p>}
|
||||
{busy === 'downloading' ? (
|
||||
<>
|
||||
<p>{t('about.update.downloading')}</p>
|
||||
<ProgressBar value={progress?.received ?? 0} max={progress?.total ?? null} />
|
||||
</>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
className="button button-primary"
|
||||
disabled={busy !== null}
|
||||
onClick={() => {
|
||||
if (check.ready) state.install(check.release.version);
|
||||
else state.download(check.release.version);
|
||||
}}
|
||||
>
|
||||
{t(busy === 'installing' ? 'about.update.installing' : check.ready ? 'about.update.install' : 'about.update.download')}
|
||||
</button>
|
||||
)}
|
||||
</Notice>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -7,11 +7,10 @@ interface CopyListProps {
|
||||
readonly registry: Copies;
|
||||
readonly supportedVersions: readonly string[];
|
||||
readonly onSelect: (id: string, detail?: boolean) => void;
|
||||
readonly onRelocate: (id: string) => void;
|
||||
readonly onAdd: () => void;
|
||||
}
|
||||
|
||||
export function CopyList({ registry, supportedVersions, onSelect, onRelocate, onAdd }: CopyListProps) {
|
||||
export function CopyList({ registry, supportedVersions, onSelect, onAdd }: CopyListProps) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<Sheet title={t('copies.sections.list')}>
|
||||
@@ -25,7 +24,6 @@ export function CopyList({ registry, supportedVersions, onSelect, onRelocate, on
|
||||
<div className="copy-list-heading">
|
||||
<strong>{copy.name}</strong>
|
||||
{current && <span className="ok">{t('copies.list.current')}</span>}
|
||||
{copy.folderMissing && <span className="warn">{t('copies.missingFolder')}</span>}
|
||||
</div>
|
||||
<dl className="kv">
|
||||
<dt>{t('copies.summary.version')}</dt>
|
||||
@@ -37,17 +35,10 @@ export function CopyList({ registry, supportedVersions, onSelect, onRelocate, on
|
||||
: <span className="warn">{t('adaptation.unverified')}</span>}
|
||||
</dd>
|
||||
<dt>{t('copies.summary.location')}</dt>
|
||||
<dd className="folder-path" data-ellipsis-tip={copy.copyPath}>{copy.copyPath}</dd>
|
||||
<dd className="folder-path" title={copy.copyPath}>{copy.copyPath}</dd>
|
||||
</dl>
|
||||
<div className="copy-list-actions">
|
||||
{copy.folderMissing && (
|
||||
<button type="button" className="button button-primary" onClick={() => onRelocate(copy.id)}>{t('copies.relocate')}</button>
|
||||
)}
|
||||
{!current && (
|
||||
<button type="button" className={copy.folderMissing ? 'button' : 'button button-primary'} onClick={() => onSelect(copy.id)}>
|
||||
{t('copies.list.select')}
|
||||
</button>
|
||||
)}
|
||||
{!current && <button type="button" className="button button-primary" onClick={() => onSelect(copy.id)}>{t('copies.list.select')}</button>}
|
||||
<button type="button" className="button" onClick={() => onSelect(copy.id, true)}>{t('side.details')}</button>
|
||||
</div>
|
||||
</article>
|
||||
|
||||
@@ -1,24 +1,28 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import type { InstallRecord } from '@shared/schemas/install.ts';
|
||||
import type { MaintenanceInfo, MaintenanceProgress } from '@shared/schemas/maintenance.ts';
|
||||
import type { MaintenanceInfo, MaintenanceProgress, MaintenanceRequest } from '@shared/schemas/maintenance.ts';
|
||||
import { ProgressBar } from '../../components/ProgressBar.tsx';
|
||||
import { Row } from '../../components/Row.tsx';
|
||||
import { Sheet } from '../../components/Sheet.tsx';
|
||||
import { formatBytes } from '../../format.ts';
|
||||
import { ipcInvoke } from '../../ipc.ts';
|
||||
import { CopyMaintenanceActions, CopyRemoval, type CopyRemovalOptions } from './CopyMaintenanceControls.tsx';
|
||||
import type { CopyMaintenanceState, MaintenanceOperation, MaintenanceOptions } from './useCopyMaintenance.ts';
|
||||
import { AppIpcError, ipcInvoke, ipcOn } from '../../ipc.ts';
|
||||
|
||||
interface CopyMaintenanceProps {
|
||||
readonly record: InstallRecord;
|
||||
readonly maintenance: CopyMaintenanceState;
|
||||
readonly onError: (error: unknown) => void;
|
||||
}
|
||||
|
||||
export function CopyMaintenance({ record, maintenance, onError }: CopyMaintenanceProps) {
|
||||
const { t } = useTranslation();
|
||||
type Operation = MaintenanceRequest['operation'];
|
||||
|
||||
export function CopyMaintenance({ record, onError }: CopyMaintenanceProps) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const [info, setInfo] = useState<MaintenanceInfo | null>(null);
|
||||
const [removal, setRemoval] = useState<CopyRemovalOptions | null>(null);
|
||||
const [working, setWorking] = useState<Operation | null>(null);
|
||||
const [progress, setProgress] = useState<MaintenanceProgress | null>(null);
|
||||
const [confirming, setConfirming] = useState(false);
|
||||
const [deleteData, setDeleteData] = useState(false);
|
||||
const [result, setResult] = useState<Operation | 'cancelled' | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let mounted = true;
|
||||
@@ -26,57 +30,84 @@ export function CopyMaintenance({ record, maintenance, onError }: CopyMaintenanc
|
||||
if (mounted) setInfo(value);
|
||||
}).catch(onError);
|
||||
return () => { mounted = false; };
|
||||
}, [record.id, record.gameVersion, record.steamLibraryConfirmation, maintenance.revision, onError]);
|
||||
}, [record.id, record.gameVersion, onError]);
|
||||
|
||||
const run = (operation: MaintenanceOperation, options: MaintenanceOptions = {}): void => {
|
||||
if (operation === 'delete') setRemoval(null);
|
||||
maintenance.run(record.id, operation, options);
|
||||
useEffect(() => ipcOn('event:copy-maintenance', (event) => {
|
||||
if (event.id === record.id) setProgress(event);
|
||||
}), [record.id]);
|
||||
|
||||
const run = (operation: Operation): void => {
|
||||
setResult(null);
|
||||
setWorking(operation);
|
||||
setProgress(null);
|
||||
ipcInvoke('copies:maintain', { id: record.id, operation, deleteData: operation === 'delete' && deleteData })
|
||||
.then(() => {
|
||||
setResult(operation);
|
||||
setConfirming(false);
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
if (error instanceof AppIpcError && error.code === 'maintenance_cancelled') setResult('cancelled');
|
||||
else onError(error);
|
||||
})
|
||||
.finally(() => setWorking(null));
|
||||
};
|
||||
|
||||
const active = maintenance.active;
|
||||
const busy = active !== null;
|
||||
const result = maintenance.lastResult?.copyId === record.id ? maintenance.lastResult.outcome : null;
|
||||
|
||||
return (
|
||||
<Sheet title={t('copies.sections.maintain')} aside={record.name}>
|
||||
<CopyMaintenanceActions
|
||||
record={record}
|
||||
info={info}
|
||||
busy={busy}
|
||||
onRun={run}
|
||||
onConfirmSteam={(steamLocations) => run('confirm-steam', { steamLocations })}
|
||||
/>
|
||||
<CopyRemoval
|
||||
record={record}
|
||||
info={info}
|
||||
busy={busy}
|
||||
options={removal}
|
||||
onOptionsChange={setRemoval}
|
||||
onRemove={(deleteData) => run('delete', { deleteData })}
|
||||
/>
|
||||
{active && <MaintenanceStatus progress={active} onCancel={maintenance.cancel} />}
|
||||
<Row label={t('copies.maintenance.update')} hint={info?.sourceVersion
|
||||
? t(info.updateAvailable ? 'copies.maintenance.newVersion' : 'copies.maintenance.currentVersion', { version: info.sourceVersion })
|
||||
: t('copies.maintenance.noSource')}>
|
||||
<button type="button" className={info?.updateAvailable ? 'button button-primary' : 'button'}
|
||||
disabled={working !== null || !info?.updateAvailable} onClick={() => run('update')}>
|
||||
{t('copies.maintenance.updateAction')}
|
||||
</button>
|
||||
</Row>
|
||||
<Row label={t('copies.maintenance.check')} hint={record.lastCheckedAt
|
||||
? t('copies.maintenance.lastCheck', { date: new Date(record.lastCheckedAt).toLocaleString(i18n.language) })
|
||||
: t('copies.maintenance.checkHint')}>
|
||||
<button type="button" className="button" disabled={working !== null} onClick={() => run('check')}>
|
||||
{t('copies.maintenance.check')}
|
||||
</button>
|
||||
</Row>
|
||||
<Row label={t('copies.maintenance.repair')} hint={t('copies.maintenance.repairHint')}>
|
||||
<button type="button" className="button" disabled={working !== null} onClick={() => run('repair')}>
|
||||
{t('copies.maintenance.repairAction')}
|
||||
</button>
|
||||
</Row>
|
||||
<Row label={t('copies.maintenance.delete')} hint={t('copies.maintenance.deleteHint')}>
|
||||
<button type="button" className="button" disabled={working !== null} onClick={() => {
|
||||
setConfirming(true);
|
||||
setDeleteData(false);
|
||||
}}>{t('copies.maintenance.deleteAction')}</button>
|
||||
</Row>
|
||||
{confirming && (
|
||||
<section className="maintenance-confirm" role="group" aria-label={t('copies.maintenance.confirm')}>
|
||||
<p>{t('copies.maintenance.deleteLocation', { path: record.copyPath })}</p>
|
||||
<label className="check">
|
||||
<input type="checkbox" checked={deleteData} disabled={working !== null} onChange={(event) => setDeleteData(event.target.checked)} />
|
||||
{t('copies.maintenance.deleteData', { path: record.dataPath })}
|
||||
</label>
|
||||
<div className="copy-list-actions">
|
||||
<button type="button" className="button" disabled={working !== null} onClick={() => setConfirming(false)}>{t('wizard.cancel')}</button>
|
||||
<button type="button" className="button button-primary" disabled={working !== null} onClick={() => run('delete')}>
|
||||
{t('copies.maintenance.confirm')}
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
{working && (
|
||||
<div className="maintenance-progress" role="status">
|
||||
<p>{t(`copies.maintenance.phase.${progress?.phase ?? 'checking'}`)}</p>
|
||||
<ProgressBar value={progress?.doneBytes ?? 0} max={progress?.totalBytes || null} />
|
||||
{progress?.totalBytes ? <p className="small">{formatBytes(progress.doneBytes)} / {formatBytes(progress.totalBytes)}</p> : null}
|
||||
{working === 'update' && progress?.phase !== 'applying' && (
|
||||
<button type="button" className="button" onClick={() => ipcInvoke('copies:cancelMaintenance').catch(onError)}>
|
||||
{t('wizard.cancel')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{result && <p className="small" role="status">{t(`copies.maintenance.result.${result}`)}</p>}
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
|
||||
interface MaintenanceStatusProps {
|
||||
readonly progress: MaintenanceProgress;
|
||||
readonly onCancel: () => void;
|
||||
}
|
||||
|
||||
function MaintenanceStatus({ progress, onCancel }: MaintenanceStatusProps) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className="maintenance-progress" role="status">
|
||||
<p>{t(`copies.maintenance.phase.${progress.phase}`)}</p>
|
||||
<ProgressBar value={progress.doneBytes} max={progress.totalBytes || null} />
|
||||
{progress.totalBytes ? <p className="small">{formatBytes(progress.doneBytes)} / {formatBytes(progress.totalBytes)}</p> : null}
|
||||
{(progress.operation === 'update' || progress.operation === 'compact') && progress.phase !== 'applying' && (
|
||||
<button type="button" className="button" onClick={onCancel}>
|
||||
{t('wizard.cancel')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,112 +0,0 @@
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import type { InstallRecord } from '@shared/schemas/install.ts';
|
||||
import type { MaintenanceInfo, MaintenanceRequest } from '@shared/schemas/maintenance.ts';
|
||||
import { Notice } from '../../components/Notice.tsx';
|
||||
import { Row } from '../../components/Row.tsx';
|
||||
|
||||
interface CopyMaintenanceControlsProps {
|
||||
readonly record: InstallRecord;
|
||||
readonly info: MaintenanceInfo | null;
|
||||
readonly busy: boolean;
|
||||
}
|
||||
|
||||
interface CopyMaintenanceActionsProps extends CopyMaintenanceControlsProps {
|
||||
readonly onRun: (operation: 'update' | 'compact' | 'check' | 'repair') => void;
|
||||
readonly onConfirmSteam: (locations: NonNullable<MaintenanceRequest['steamLocations']>) => void;
|
||||
}
|
||||
|
||||
export function CopyMaintenanceActions({ record, info, busy, onRun, onConfirmSteam }: CopyMaintenanceActionsProps) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const steam = info?.steamLocations;
|
||||
return (
|
||||
<>
|
||||
{info?.steamConfirmationRequired && steam && (
|
||||
<Notice tone="warning">
|
||||
<p>{t('steam.maintenanceWarning')}</p>
|
||||
<p className="small">{steam.copyPath}<br />{steam.dataPath}</p>
|
||||
<button type="button" className="button" disabled={busy}
|
||||
onClick={() => onConfirmSteam({ copyPath: steam.copyPath, dataPath: steam.dataPath })}>
|
||||
{t('steam.confirmLocations')}
|
||||
</button>
|
||||
</Notice>
|
||||
)}
|
||||
<Row label={t('copies.maintenance.update')} hint={info?.sourceVersion
|
||||
? t(info.updateAvailable
|
||||
? (record.hardlinkedFiles?.length
|
||||
? (info.updatePreservesSpaceSaving ? 'copies.maintenance.updateKeepsSpaceSaving' : 'copies.maintenance.updateDetaches')
|
||||
: 'copies.maintenance.newVersion')
|
||||
: 'copies.maintenance.currentVersion', { version: info.sourceVersion })
|
||||
: t('copies.maintenance.noSource')}>
|
||||
<button type="button" className={info?.updateAvailable ? 'button button-primary' : 'button'}
|
||||
disabled={busy || !info?.updateAvailable} onClick={() => onRun('update')}>
|
||||
{t('copies.maintenance.updateAction')}
|
||||
</button>
|
||||
</Row>
|
||||
<Row label={t('copies.maintenance.spaceSaving')} hint={info?.spaceSavingAvailable
|
||||
? t('copies.maintenance.spaceSavingHint') : t('copies.maintenance.spaceSavingUnavailable')}>
|
||||
<button type="button" className="button" disabled={busy || !info?.spaceSavingAvailable}
|
||||
onClick={() => onRun('compact')}>{t('copies.maintenance.compactAction')}</button>
|
||||
</Row>
|
||||
<Row label={t('copies.maintenance.check')} hint={record.lastCheckedAt
|
||||
? t('copies.maintenance.lastCheck', { date: new Date(record.lastCheckedAt).toLocaleString(i18n.language) })
|
||||
: t('copies.maintenance.checkHint')}>
|
||||
<button type="button" className="button" disabled={busy} onClick={() => onRun('check')}>
|
||||
{t('copies.maintenance.check')}
|
||||
</button>
|
||||
</Row>
|
||||
<Row label={t('copies.maintenance.repair')} hint={t('copies.maintenance.repairHint')}>
|
||||
<button type="button" className="button" disabled={busy} onClick={() => onRun('repair')}>
|
||||
{t('copies.maintenance.repairAction')}
|
||||
</button>
|
||||
</Row>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export interface CopyRemovalOptions {
|
||||
readonly deleteData: boolean;
|
||||
}
|
||||
|
||||
interface CopyRemovalProps extends CopyMaintenanceControlsProps {
|
||||
readonly options: CopyRemovalOptions | null;
|
||||
readonly onOptionsChange: (options: CopyRemovalOptions | null) => void;
|
||||
readonly onRemove: (deleteData: boolean) => void;
|
||||
}
|
||||
|
||||
export function CopyRemoval({ record, info, busy, options, onOptionsChange, onRemove }: CopyRemovalProps) {
|
||||
const { t } = useTranslation();
|
||||
const steam = info?.steamLocations;
|
||||
const unlinkOnly = steam?.copyInSteam === true;
|
||||
const canDeleteData = !unlinkOnly && !steam?.dataInSteam;
|
||||
const action = t(unlinkOnly ? 'copies.maintenance.unlink' : 'copies.maintenance.confirm');
|
||||
|
||||
return (
|
||||
<>
|
||||
<Row label={t(unlinkOnly ? 'copies.maintenance.unlink' : 'copies.maintenance.delete')}
|
||||
hint={t(unlinkOnly ? 'copies.maintenance.unlinkHint' : 'copies.maintenance.deleteHint')}>
|
||||
<button type="button" className="button" disabled={busy || !info}
|
||||
onClick={() => onOptionsChange({ deleteData: false })}>
|
||||
{t(unlinkOnly ? 'copies.maintenance.unlinkAction' : 'copies.maintenance.deleteAction')}
|
||||
</button>
|
||||
</Row>
|
||||
{options && (
|
||||
<section className="maintenance-confirm" role="group" aria-label={action}>
|
||||
<p>{t(unlinkOnly ? 'copies.maintenance.unlinkLocation' : 'copies.maintenance.deleteLocation', { path: steam?.copyPath ?? record.copyPath })}</p>
|
||||
{canDeleteData && (
|
||||
<label className="check">
|
||||
<input type="checkbox" checked={options.deleteData} disabled={busy}
|
||||
onChange={(event) => onOptionsChange({ deleteData: event.target.checked })} />
|
||||
{t('copies.maintenance.deleteData', { path: record.dataPath })}
|
||||
</label>
|
||||
)}
|
||||
<div className="copy-list-actions">
|
||||
<button type="button" className="button" disabled={busy} onClick={() => onOptionsChange(null)}>{t('wizard.cancel')}</button>
|
||||
<button type="button" className="button button-primary" disabled={busy} onClick={() => onRemove(canDeleteData && options.deleteData)}>
|
||||
{action}
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -11,33 +11,19 @@ interface CopySummaryProps {
|
||||
readonly record: InstallRecord;
|
||||
readonly supportedVersions: readonly string[];
|
||||
readonly onShowFeatures: () => void;
|
||||
readonly onRelocate: () => void;
|
||||
readonly onError: (error: unknown) => void;
|
||||
}
|
||||
|
||||
/** What is installed where: version, adaptation, folders, installation type. */
|
||||
export function CopySummary({ record, supportedVersions, onShowFeatures, onRelocate, onError }: CopySummaryProps) {
|
||||
export function CopySummary({ record, supportedVersions, onShowFeatures, onError }: CopySummaryProps) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const [name, setName] = useState(record.name);
|
||||
const [importing, setImporting] = useState(false);
|
||||
useEffect(() => setName(record.name), [record.id, record.name]);
|
||||
const missing = missingFeatures(record).length;
|
||||
const verified = isVerified(record.gameVersion, supportedVersions);
|
||||
const applyDecals = async (chooseFolder: boolean): Promise<void> => {
|
||||
setImporting(true);
|
||||
try {
|
||||
const path = chooseFolder ? (await ipcInvoke('dialog:pickFolder', { title: t('decals.choose') })).path : null;
|
||||
if (chooseFolder && path === null) return;
|
||||
await ipcInvoke('copies:setDecalSource', { id: record.id, path });
|
||||
} catch (error) {
|
||||
onError(error);
|
||||
} finally {
|
||||
setImporting(false);
|
||||
}
|
||||
};
|
||||
const folder = (path: string) => (
|
||||
<>
|
||||
<span className="folder-path" data-ellipsis-tip={path}>{path}</span>
|
||||
<span className="folder-path" title={path}>{path}</span>
|
||||
<button type="button" className="button" onClick={() => ipcInvoke('app:openFolder', { path }).catch(onError)}>{t('copies.summary.open')}</button>
|
||||
</>
|
||||
);
|
||||
@@ -53,33 +39,11 @@ export function CopySummary({ record, supportedVersions, onShowFeatures, onReloc
|
||||
<Row label={t('copies.summary.adaptation')} hint={t('copies.summary.adaptationHint')}>
|
||||
<span className={verified ? 'ok' : 'warn'}>{verified ? t('adaptation.verified') : t('adaptation.unverified')}</span>
|
||||
</Row>
|
||||
<Row label={t('copies.summary.location')} hint={record.folderMissing ? t('copies.summary.missingHint') : undefined}>
|
||||
<span className="folder-path" data-ellipsis-tip={record.copyPath}>{record.copyPath}</span>
|
||||
{record.folderMissing && <span className="warn">{t('copies.missingFolder')}</span>}
|
||||
<button type="button" className={record.folderMissing ? 'button button-primary' : 'button'} onClick={onRelocate}>
|
||||
{t('copies.relocate')}
|
||||
</button>
|
||||
{!record.folderMissing && (
|
||||
<button type="button" className="button" onClick={() => ipcInvoke('app:openFolder', { path: record.copyPath }).catch(onError)}>
|
||||
{t('copies.summary.open')}
|
||||
</button>
|
||||
)}
|
||||
</Row>
|
||||
<Row label={t('copies.summary.method')}>{t(`copies.summary.methods.${record.hardlinkedFiles?.length ? 'hardlink' : record.method}`)}</Row>
|
||||
<Row label={t('copies.summary.location')}>{folder(record.copyPath)}</Row>
|
||||
<Row label={t('copies.summary.method')}>{t(`copies.summary.methods.${record.method}`)}</Row>
|
||||
{record.sourcePath && <Row label={t('copies.summary.source')}>{folder(record.sourcePath)}</Row>}
|
||||
<Row label={t('copies.summary.stock')} hint={t('copies.summary.stockHint')}>{folder(record.stockBackupPath)}</Row>
|
||||
<Row label={t('copies.summary.data')} hint={t('copies.summary.dataHint')}>{folder(record.dataPath)}</Row>
|
||||
<Row label={t('decals.source')} hint={t('decals.hint')}>
|
||||
<span>{t(importing ? 'decals.importing' : record.decalCacheId ? 'decals.imported' : 'decals.default')}</span>
|
||||
<button type="button" className="button" disabled={importing} onClick={() => { void applyDecals(true); }}>
|
||||
{t('decals.choose')}
|
||||
</button>
|
||||
{record.decalCacheId && (
|
||||
<button type="button" className="button" disabled={importing} onClick={() => { void applyDecals(false); }}>
|
||||
{t('decals.useDefault')}
|
||||
</button>
|
||||
)}
|
||||
</Row>
|
||||
<Row label={t('copies.summary.installedAt')}>{new Date(record.installedAt).toLocaleString(i18n.language)}</Row>
|
||||
<Row label={t('copies.summary.features')}>
|
||||
{missing === 0 ? (
|
||||
|
||||
@@ -1,60 +0,0 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import type { IpcInput } from '@shared/ipc/contract.ts';
|
||||
import type { MaintenanceProgress, MaintenanceRequest } from '@shared/schemas/maintenance.ts';
|
||||
import { AppIpcError, ipcInvoke, ipcOn } from '../../ipc.ts';
|
||||
|
||||
export type MaintenanceOperation = MaintenanceRequest['operation'];
|
||||
export type MaintenanceOptions = Pick<IpcInput<'copies:maintain'>, 'deleteData' | 'steamLocations'>;
|
||||
|
||||
export interface MaintenanceOutcome {
|
||||
readonly copyId: string;
|
||||
readonly outcome: MaintenanceOperation | 'cancelled';
|
||||
}
|
||||
|
||||
/** Tracks copy maintenance across tab switches so progress and busy state survive unmounting the maintenance page. */
|
||||
export function useCopyMaintenance(onError: (error: unknown) => void) {
|
||||
const [active, setActive] = useState<MaintenanceProgress | null>(null);
|
||||
const [lastResult, setLastResult] = useState<MaintenanceOutcome | null>(null);
|
||||
const [revision, setRevision] = useState(0);
|
||||
|
||||
useEffect(() => {
|
||||
let mounted = true;
|
||||
let receivedEvent = false;
|
||||
const dispose = ipcOn('event:copy-maintenance', (event) => {
|
||||
receivedEvent = true;
|
||||
setActive(event);
|
||||
if (event === null) setRevision((value) => value + 1);
|
||||
});
|
||||
ipcInvoke('copies:maintenanceState').then((state) => {
|
||||
if (mounted && !receivedEvent) setActive(state);
|
||||
}).catch(onError);
|
||||
return () => { mounted = false; dispose(); };
|
||||
}, [onError]);
|
||||
|
||||
const run = useCallback((id: string, operation: MaintenanceOperation, options: MaintenanceOptions = {}): void => {
|
||||
setLastResult(null);
|
||||
setActive({ id, operation, phase: 'checking', doneBytes: 0, totalBytes: 0 });
|
||||
ipcInvoke('copies:maintain', { id, operation, ...options })
|
||||
.then(() => {
|
||||
setLastResult({ copyId: id, outcome: operation });
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
if (error instanceof AppIpcError && error.code === 'maintenance_cancelled') {
|
||||
setLastResult({ copyId: id, outcome: 'cancelled' });
|
||||
} else {
|
||||
onError(error);
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
setActive((current) => (current?.id === id && current.operation === operation ? null : current));
|
||||
});
|
||||
}, [onError]);
|
||||
|
||||
const cancel = useCallback((): void => {
|
||||
ipcInvoke('copies:cancelMaintenance').catch(onError);
|
||||
}, [onError]);
|
||||
|
||||
return { active, lastResult, revision, run, cancel };
|
||||
}
|
||||
|
||||
export type CopyMaintenanceState = ReturnType<typeof useCopyMaintenance>;
|
||||
@@ -20,9 +20,7 @@ export function BackgroundSwitch({ pictures, shown, onError }: BackgroundSwitchP
|
||||
};
|
||||
return (
|
||||
<div className="background-switch">
|
||||
<span className="background-switch-label" data-ellipsis-tip={t('background.current', { name: backgroundLabel(t, shown) })}>
|
||||
{t('background.current', { name: backgroundLabel(t, shown) })}
|
||||
</span>
|
||||
<span className="background-switch-label" title={backgroundLabel(t, shown)}>{t('background.current', { name: backgroundLabel(t, shown) })}</span>
|
||||
<button type="button" title={t('background.previous')} onClick={() => step(-1)}>‹</button>
|
||||
<button type="button" title={t('background.next')} onClick={() => step(1)}>›</button>
|
||||
</div>
|
||||
|
||||
@@ -22,7 +22,7 @@ export function HomeSide({ record, copies, supportedVersions, onNavigate, onSele
|
||||
<>
|
||||
<h3 className="side-heading">{t('side.requirements')}</h3>
|
||||
<div className="side-block">
|
||||
<dl className="kv install-requirements">
|
||||
<dl className="kv">
|
||||
<dt>{t('side.game')}</dt>
|
||||
<dd>{t('side.gameValue')}</dd>
|
||||
<dt>{t('side.versions')}</dt>
|
||||
@@ -39,13 +39,8 @@ export function HomeSide({ record, copies, supportedVersions, onNavigate, onSele
|
||||
<>
|
||||
<h3 className="side-heading">{t('side.currentCopy')}</h3>
|
||||
<button type="button" className="copy-card copy-card-button" aria-expanded={choosingCopy} onClick={() => setChoosingCopy(!choosingCopy)}>
|
||||
<span className="copy-card-name">
|
||||
{record.name}
|
||||
{record.folderMissing && <> · <span className="warn">{t('copies.missingFolder')}</span></>}
|
||||
</span>
|
||||
<span className="copy-card-meta" data-ellipsis-tip={`${record.gameVersion ?? t('source.versionUnknown')} · ${record.copyPath}`}>
|
||||
{record.gameVersion ?? t('source.versionUnknown')} · {record.copyPath}
|
||||
</span>
|
||||
<span className="copy-card-name">{record.name}</span>
|
||||
<span className="copy-card-meta" title={record.copyPath}>{record.gameVersion ?? t('source.versionUnknown')} · {record.copyPath}</span>
|
||||
</button>
|
||||
{choosingCopy && (
|
||||
<div className="copy-picker">
|
||||
@@ -54,7 +49,7 @@ export function HomeSide({ record, copies, supportedVersions, onNavigate, onSele
|
||||
setChoosingCopy(false);
|
||||
onSelectCopy(copy.id);
|
||||
}}>
|
||||
{copy.name} · {copy.folderMissing ? t('copies.missingFolder') : (copy.gameVersion ?? t('source.versionUnknown'))}
|
||||
{copy.name} · {copy.gameVersion ?? t('source.versionUnknown')}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { TFunction } from 'i18next';
|
||||
import type { InstallRecord } from '@shared/schemas/install.ts';
|
||||
import { formatExitCode, type LaunchState } from '@shared/schemas/launch.ts';
|
||||
import type { LaunchState } from '@shared/schemas/launch.ts';
|
||||
import type { BarModel } from '../../shell/bar-model.ts';
|
||||
import { missingFeatures } from '../copies/missing-features.ts';
|
||||
|
||||
@@ -8,7 +8,6 @@ interface LaunchActions {
|
||||
readonly start: () => void;
|
||||
readonly stop: () => void;
|
||||
readonly checkVersion: () => void;
|
||||
readonly relocate: () => void;
|
||||
}
|
||||
|
||||
/** The installation and launch actions shown outside the wizard. */
|
||||
@@ -23,13 +22,6 @@ export function homeBar(
|
||||
const retry = { label: t('launch.retry'), onClick: actions.start };
|
||||
const starting = { label: t('launch.starting'), disabled: true };
|
||||
const progress = { value: state.filesWritten ?? 0, max: state.filesTotal || null };
|
||||
const { gameExit } = state;
|
||||
const exitCodeLabel = gameExit
|
||||
? (gameExit.code !== null ? formatExitCode(gameExit.code) : (gameExit.signal ?? t('launch.exitCodeUnknown')))
|
||||
: undefined;
|
||||
const exitDetail = gameExit && gameExit.code !== 0
|
||||
? t('launch.exitDetail', { code: exitCodeLabel, path: gameExit.logFolder })
|
||||
: undefined;
|
||||
switch (state.phase) {
|
||||
case 'checking':
|
||||
case 'building':
|
||||
@@ -49,7 +41,6 @@ export function homeBar(
|
||||
title: t(`launch.${state.phase}`),
|
||||
progress: { value: 0, max: null },
|
||||
primary: starting,
|
||||
...(state.phase === 'stopping' ? {} : { secondary: { label: t('launch.cancel'), onClick: actions.stop } }),
|
||||
};
|
||||
case 'running':
|
||||
return {
|
||||
@@ -59,16 +50,6 @@ export function homeBar(
|
||||
primary: { label: t('launch.running'), disabled: true },
|
||||
secondary: { label: t('launch.stop'), onClick: actions.stop },
|
||||
};
|
||||
case 'server-running':
|
||||
return {
|
||||
tone: exitDetail ? 'warn' : 'ok',
|
||||
title: t('launch.gameExitedServerRunning'),
|
||||
detail: exitDetail ?? t('launch.runningDetail', { port: state.port }),
|
||||
primary: launch,
|
||||
secondary: { label: t('launch.stopServer'), onClick: actions.stop },
|
||||
};
|
||||
case 'game-exited':
|
||||
return { tone: exitDetail ? 'warn' : 'ok', title: t('launch.game-exited'), detail: exitDetail, primary: launch };
|
||||
case 'port-busy':
|
||||
return { tone: 'bad', title: t('launch.port-busy', { port: state.port }), primary: retry };
|
||||
case 'server-exited':
|
||||
@@ -81,7 +62,7 @@ export function homeBar(
|
||||
primary: { label: t('launch.check'), onClick: actions.checkVersion },
|
||||
};
|
||||
case 'failed':
|
||||
return { tone: 'bad', title: t(`errors.${state.error ?? 'launch_failed'}`), primary: retry };
|
||||
return { tone: 'bad', title: t(`errors.${state.error ?? 'launch_lab_failed'}`), primary: retry };
|
||||
case 'ready':
|
||||
break;
|
||||
}
|
||||
@@ -94,14 +75,6 @@ export function homeBar(
|
||||
primary: { label: t('bar.install'), onClick: onInstall },
|
||||
};
|
||||
}
|
||||
if (record.folderMissing) {
|
||||
return {
|
||||
tone: 'bad',
|
||||
title: t('bar.missingFolder'),
|
||||
detail: record.copyPath,
|
||||
primary: { label: t('copies.relocate'), onClick: actions.relocate },
|
||||
};
|
||||
}
|
||||
const missing = missingFeatures(record).length;
|
||||
return {
|
||||
tone: missing ? 'warn' : 'ok',
|
||||
|
||||
@@ -1,43 +1,19 @@
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import type { DataFolderProblem } from '@shared/schemas/install.ts';
|
||||
import { FolderField } from '../../components/FolderField.tsx';
|
||||
import { Notice } from '../../components/Notice.tsx';
|
||||
import { Row } from '../../components/Row.tsx';
|
||||
|
||||
interface DataStepProps {
|
||||
readonly dataPath: string;
|
||||
readonly dataProblem: DataFolderProblem | null;
|
||||
readonly decalSource: string | null;
|
||||
readonly steamDataPath: string | null;
|
||||
readonly steamDataConfirmed: boolean;
|
||||
readonly onSteamDataConfirmed: (confirmed: boolean) => void;
|
||||
readonly onDecalSource: (path: string | null) => void;
|
||||
readonly onDataPath: (path: string) => void;
|
||||
readonly onError: (error: unknown) => void;
|
||||
}
|
||||
|
||||
/** Step 3: where saves, caches and logs of the offline version are kept. */
|
||||
export function DataStep({ dataPath, dataProblem, decalSource, steamDataPath, steamDataConfirmed, onSteamDataConfirmed, onDataPath, onDecalSource, onError }: DataStepProps) {
|
||||
export function DataStep({ dataPath, onDataPath, onError }: DataStepProps) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<>
|
||||
<p className="lead">{t('data.body')}</p>
|
||||
<FolderField path={dataPath} dialogTitle={t('data.dialogTitle')} onChosen={onDataPath} onError={onError} />
|
||||
{dataProblem && <Notice tone="error">{t(`data.problem.${dataProblem}`)}</Notice>}
|
||||
{!dataProblem && steamDataPath && (
|
||||
<Notice tone="warning">
|
||||
<p>{t('steam.dataWarning')}</p>
|
||||
<p className="small">{steamDataPath}</p>
|
||||
<label className="check">
|
||||
<input type="checkbox" checked={steamDataConfirmed} onChange={(event) => onSteamDataConfirmed(event.target.checked)} />
|
||||
{t('steam.confirm')}
|
||||
</label>
|
||||
</Notice>
|
||||
)}
|
||||
<Row label={t('decals.source')} hint={t('decals.hint')}>
|
||||
<FolderField path={decalSource} dialogTitle={t('decals.choose')} onChosen={onDecalSource} onError={onError} />
|
||||
{decalSource && <button type="button" className="button" onClick={() => onDecalSource(null)}>{t('decals.useDefault')}</button>}
|
||||
</Row>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { Dispatch, ReactNode, SetStateAction } from 'react';
|
||||
import type { ReactNode } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import type { FolderSize, GameFolderInspection, InstallMethod, TargetFolderInspection } from '@shared/schemas/install.ts';
|
||||
import { FolderField } from '../../components/FolderField.tsx';
|
||||
@@ -9,87 +9,45 @@ import { ipcInvoke } from '../../ipc.ts';
|
||||
/** Room the copy needs beyond the game itself; the main process checks the same margin. */
|
||||
const SPARE_BYTES = 1024 ** 3;
|
||||
|
||||
type Method = InstallMethod | 'hardlink';
|
||||
|
||||
export interface MethodChoice {
|
||||
readonly method: Method;
|
||||
readonly method: InstallMethod;
|
||||
readonly target: TargetFolderInspection | null;
|
||||
readonly steamConfirmed: boolean;
|
||||
}
|
||||
|
||||
interface MethodStepProps {
|
||||
readonly source: GameFolderInspection;
|
||||
/** Size of the installation; null while it is being measured. */
|
||||
readonly sourceSize: FolderSize | null;
|
||||
readonly choice: MethodChoice;
|
||||
readonly onChoice: Dispatch<SetStateAction<MethodChoice>>;
|
||||
readonly onChoice: (choice: MethodChoice) => void;
|
||||
readonly onError: (error: unknown) => void;
|
||||
}
|
||||
|
||||
/** Step 2: copy the game into a new folder, or install into the chosen folder itself. */
|
||||
export function MethodStep({ source, sourceSize, choice, onChoice, onError }: MethodStepProps) {
|
||||
const { t } = useTranslation();
|
||||
const choose = (method: Method): void => onChoice({ method, target: choice.target, steamConfirmed: false });
|
||||
const choose = (method: InstallMethod): void => onChoice({ method, target: choice.target, steamConfirmed: false });
|
||||
const inspectTarget = (path: string): void => {
|
||||
onChoice((current) => ({ ...current, target: null, steamConfirmed: false }));
|
||||
ipcInvoke('install:inspectTargetFolder', { path, stockPath: source.path, version: source.version })
|
||||
.then((target) => onChoice((current) => ({ ...current, target, steamConfirmed: false })))
|
||||
onChoice({ ...choice, target: null, steamConfirmed: false });
|
||||
ipcInvoke('install:inspectTargetFolder', { path, stockPath: source.path })
|
||||
.then((target) => onChoice({ method: 'copy', target, steamConfirmed: false }))
|
||||
.catch(onError);
|
||||
};
|
||||
const directFolder = choice.method === 'in-place' || choice.method === 'existing';
|
||||
const folder = directFolder ? source : choice.target;
|
||||
const steamWarning = folder?.inSteamLibrary
|
||||
? <SteamWarning method={choice.method} path={folder.resolvedPath} confirmed={choice.steamConfirmed}
|
||||
onConfirmed={(steamConfirmed) => onChoice({ ...choice, steamConfirmed })} />
|
||||
const steamWarning = steamLibraryInvolved(source, choice)
|
||||
? <SteamWarning method={choice.method} confirmed={choice.steamConfirmed} onConfirmed={(steamConfirmed) => onChoice({ ...choice, steamConfirmed })} />
|
||||
: null;
|
||||
const targetPicker = (
|
||||
<>
|
||||
<FolderField path={choice.target?.path ?? null} dialogTitle={t('method.targetTitle')} onChosen={inspectTarget} onError={onError} />
|
||||
<p className="small">{t('method.targetSubfolderHint')}</p>
|
||||
{choice.target && <TargetVerdict target={choice.target} sourceSize={sourceSize} method={choice.method} />}
|
||||
{steamWarning}
|
||||
</>
|
||||
);
|
||||
const savingAvailable = !source.needsStockSource && (sourceSize?.linkableBytes ?? 0) > 0;
|
||||
const preferExisting = source.hasOfflineBackup || source.needsStockSource;
|
||||
const existingChoice = (
|
||||
<Choice
|
||||
selected={choice.method === 'existing'}
|
||||
title={t('method.existing')}
|
||||
body={t(
|
||||
source.needsStockSource
|
||||
? 'method.existingBodyWithStockSource'
|
||||
: source.hasOfflineBackup
|
||||
? 'method.existingBodyWithBackup'
|
||||
: 'method.existingBody',
|
||||
)}
|
||||
onSelect={() => choose('existing')}
|
||||
>
|
||||
{steamWarning}
|
||||
</Choice>
|
||||
);
|
||||
return (
|
||||
<>
|
||||
{preferExisting && existingChoice}
|
||||
<Choice
|
||||
selected={choice.method === 'copy'}
|
||||
disabled={source.needsStockSource}
|
||||
title={t('method.copy')}
|
||||
body={sourceSize ? t('method.copyBody', { size: formatBytes(sourceSize.bytes) }) : t('method.copyBodyPending')}
|
||||
onSelect={() => choose('copy')}
|
||||
>
|
||||
{targetPicker}
|
||||
</Choice>
|
||||
<Choice
|
||||
selected={choice.method === 'hardlink'}
|
||||
disabled={!savingAvailable}
|
||||
title={t('method.spaceSaving')}
|
||||
body={sourceSize
|
||||
? savingAvailable
|
||||
? t('method.spaceSavingBody', { size: formatBytes(bytesToCopy(sourceSize, 'hardlink')) })
|
||||
: t('method.spaceSavingUnavailable')
|
||||
: t('method.spaceSavingPending')}
|
||||
onSelect={() => choose('hardlink')}
|
||||
>
|
||||
{targetPicker}
|
||||
<FolderField path={choice.target?.path ?? null} dialogTitle={t('method.targetTitle')} onChosen={inspectTarget} onError={onError} />
|
||||
{choice.target && <TargetVerdict target={choice.target} sourceSize={sourceSize} />}
|
||||
{steamWarning}
|
||||
</Choice>
|
||||
<Choice
|
||||
selected={choice.method === 'in-place'}
|
||||
@@ -99,25 +57,23 @@ export function MethodStep({ source, sourceSize, choice, onChoice, onError }: Me
|
||||
>
|
||||
{steamWarning}
|
||||
</Choice>
|
||||
{!preferExisting && existingChoice}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
interface ChoiceProps {
|
||||
readonly selected: boolean;
|
||||
readonly disabled?: boolean;
|
||||
readonly title: string;
|
||||
readonly body: string;
|
||||
readonly onSelect: () => void;
|
||||
/** Shown under the description while the choice is selected. */
|
||||
readonly children: ReactNode;
|
||||
}
|
||||
|
||||
function Choice({ selected, disabled, title, body, onSelect, children }: ChoiceProps) {
|
||||
function Choice({ selected, title, body, onSelect, children }: ChoiceProps) {
|
||||
return (
|
||||
<div className={selected ? 'choice choice-selected' : 'choice'} aria-disabled={disabled}
|
||||
onClick={selected || disabled ? undefined : onSelect}>
|
||||
<input type="radio" name="method" checked={selected} disabled={disabled} onChange={onSelect} aria-label={title} />
|
||||
<div className={selected ? 'choice choice-selected' : 'choice'} onClick={selected ? undefined : onSelect}>
|
||||
<input type="radio" name="method" checked={selected} onChange={onSelect} aria-label={title} />
|
||||
<span className="choice-title">{title}</span>
|
||||
<div className="choice-body">{body}</div>
|
||||
{selected && <div className="choice-detail">{children}</div>}
|
||||
@@ -125,32 +81,20 @@ function Choice({ selected, disabled, title, body, onSelect, children }: ChoiceP
|
||||
);
|
||||
}
|
||||
|
||||
function bytesToCopy(size: FolderSize, method: Method): number {
|
||||
return size.bytes - (method === 'hardlink' ? (size.linkableBytes ?? 0) : 0);
|
||||
}
|
||||
|
||||
function TargetVerdict({ target, sourceSize, method }: {
|
||||
readonly target: TargetFolderInspection;
|
||||
readonly sourceSize: FolderSize | null;
|
||||
readonly method: Method;
|
||||
}) {
|
||||
function TargetVerdict({ target, sourceSize }: { readonly target: TargetFolderInspection; readonly sourceSize: FolderSize | null }) {
|
||||
const { t } = useTranslation();
|
||||
if (target.problem) return <Notice tone="error">{t(`method.problem.${target.problem}`)}</Notice>;
|
||||
if (method === 'hardlink' && !target.sameDriveAsStock) return <Notice tone="error">{t('method.sameVolumeRequired')}</Notice>;
|
||||
if (target.freeBytes === null || !sourceSize) return null;
|
||||
const needed = bytesToCopy(sourceSize, method) + SPARE_BYTES;
|
||||
return target.freeBytes < needed
|
||||
? <Notice tone="error">{t('method.noRoom', { needed: formatBytes(needed), free: formatBytes(target.freeBytes) })}</Notice>
|
||||
: <Notice tone="info">{t('method.room', { free: formatBytes(target.freeBytes) })}</Notice>;
|
||||
if (target.freeBytes !== null && sourceSize && target.freeBytes < sourceSize.bytes + SPARE_BYTES) {
|
||||
return <Notice tone="error">{t('method.noRoom', { needed: formatBytes(sourceSize.bytes + SPARE_BYTES), free: formatBytes(target.freeBytes) })}</Notice>;
|
||||
}
|
||||
return target.freeBytes === null ? null : <Notice tone="info">{t('method.room', { free: formatBytes(target.freeBytes) })}</Notice>;
|
||||
}
|
||||
|
||||
function SteamWarning({ method, path, confirmed, onConfirmed }: { readonly method: Method; readonly path: string; readonly confirmed: boolean; readonly onConfirmed: (confirmed: boolean) => void }) {
|
||||
function SteamWarning({ method, confirmed, onConfirmed }: { readonly method: InstallMethod; readonly confirmed: boolean; readonly onConfirmed: (confirmed: boolean) => void }) {
|
||||
const { t } = useTranslation();
|
||||
const isDirect = method === 'in-place' || method === 'existing';
|
||||
return (
|
||||
<Notice tone="warning">
|
||||
<p>{t(isDirect ? 'steam.inPlaceWarning' : 'steam.copyWarning')}</p>
|
||||
<p className="small">{path}</p>
|
||||
<p>{t(method === 'in-place' ? 'steam.inPlaceWarning' : 'steam.copyWarning')}</p>
|
||||
<label className="check">
|
||||
<input type="checkbox" checked={confirmed} onChange={(event) => onConfirmed(event.target.checked)} />
|
||||
{t('steam.confirm')}
|
||||
@@ -160,15 +104,14 @@ function SteamWarning({ method, path, confirmed, onConfirmed }: { readonly metho
|
||||
}
|
||||
|
||||
function steamLibraryInvolved(source: GameFolderInspection, choice: MethodChoice): boolean {
|
||||
return choice.method === 'in-place' || choice.method === 'existing' ? source.inSteamLibrary : (choice.target?.inSteamLibrary ?? false);
|
||||
return choice.method === 'in-place' ? source.inSteamLibrary : (choice.target?.inSteamLibrary ?? false);
|
||||
}
|
||||
|
||||
/** Whether the wizard may go past step 2. */
|
||||
export function methodUsable(source: GameFolderInspection, sourceSize: FolderSize | null, choice: MethodChoice): boolean {
|
||||
if (steamLibraryInvolved(source, choice) && !choice.steamConfirmed) return false;
|
||||
if (choice.method === 'in-place' || choice.method === 'existing') return true;
|
||||
if (choice.method === 'in-place') return true;
|
||||
const target = choice.target;
|
||||
if (!target || target.problem || !sourceSize) return false;
|
||||
if (choice.method === 'hardlink' && (!target.sameDriveAsStock || !sourceSize.linkableBytes)) return false;
|
||||
return target.freeBytes === null || target.freeBytes >= bytesToCopy(sourceSize, choice.method) + SPARE_BYTES;
|
||||
return target.freeBytes === null || target.freeBytes >= sourceSize.bytes + SPARE_BYTES;
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import type { WizardMode } from './useInstallWizard.ts';
|
||||
|
||||
interface ModeStepProps {
|
||||
readonly mode: WizardMode;
|
||||
readonly onMode: (mode: WizardMode) => void;
|
||||
}
|
||||
|
||||
/** Step 1: choose whether to install a new offline client or register an existing one. */
|
||||
export function ModeStep({ mode, onMode }: ModeStepProps) {
|
||||
const { t } = useTranslation();
|
||||
const options: ReadonlyArray<{ readonly value: WizardMode; readonly title: string; readonly body: string }> = [
|
||||
{ value: 'new', title: t('mode.newTitle'), body: t('mode.newBody') },
|
||||
{ value: 'existing', title: t('mode.existingTitle'), body: t('mode.existingBody') },
|
||||
];
|
||||
return (
|
||||
<>
|
||||
<p className="lead">{t('mode.body')}</p>
|
||||
{options.map((option) => {
|
||||
const selected = mode === option.value;
|
||||
return (
|
||||
<div
|
||||
key={option.value}
|
||||
className={selected ? 'choice choice-selected' : 'choice'}
|
||||
onClick={selected ? undefined : () => onMode(option.value)}
|
||||
>
|
||||
<input
|
||||
type="radio"
|
||||
name="wizard-mode"
|
||||
checked={selected}
|
||||
onChange={() => onMode(option.value)}
|
||||
aria-label={option.title}
|
||||
/>
|
||||
<span className="choice-title">{option.title}</span>
|
||||
<div className="choice-body">{option.body}</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -4,24 +4,17 @@ import { ProgressBar } from '../../components/ProgressBar.tsx';
|
||||
import { formatBytes } from '../../format.ts';
|
||||
|
||||
/**
|
||||
* Step 5: the installation running, phase by phase. Resource verification and copying can be
|
||||
* cancelled from the bottom bar.
|
||||
* Step 5: the installation running, phase by phase. Cancelling is in the bottom bar; only the
|
||||
* copy can be stopped, the other phases take seconds.
|
||||
*/
|
||||
export function ProgressStep({ progress, useHardLinks, importDecals }: {
|
||||
readonly progress: InstallProgress | null;
|
||||
readonly useHardLinks: boolean;
|
||||
readonly importDecals: boolean;
|
||||
}) {
|
||||
export function ProgressStep({ progress }: { readonly progress: InstallProgress | null }) {
|
||||
const { t } = useTranslation();
|
||||
const phase = progress?.phase ?? 'checking';
|
||||
const phases = INSTALL_PHASES.filter((name) =>
|
||||
(useHardLinks || name !== 'verifying') && (importDecals || name !== 'importing-decals'));
|
||||
const current = phases.indexOf(phase);
|
||||
const tracking = (phase === 'copying' || phase === 'verifying') && progress !== null;
|
||||
const caption = phase === 'verifying' ? 'progress.verified' : useHardLinks ? 'progress.prepared' : 'progress.copied';
|
||||
const current = INSTALL_PHASES.indexOf(phase);
|
||||
const copying = phase === 'copying' && progress !== null;
|
||||
return (
|
||||
<>
|
||||
{phases.map((name, position) => {
|
||||
{INSTALL_PHASES.map((name, position) => {
|
||||
const state = position < current ? 'done' : position === current ? 'current' : 'pending';
|
||||
return (
|
||||
<div key={name} className={`phase phase-${state}`}>
|
||||
@@ -30,10 +23,10 @@ export function ProgressStep({ progress, useHardLinks, importDecals }: {
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
<ProgressBar value={tracking ? progress.doneBytes : 0} max={tracking ? progress.totalBytes : null} large />
|
||||
{tracking && (
|
||||
<ProgressBar value={copying ? progress.doneBytes : 0} max={copying ? progress.totalBytes : null} large />
|
||||
{copying && (
|
||||
<div className="progress-caption">
|
||||
{t(caption, {
|
||||
{t('progress.copied', {
|
||||
done: formatBytes(progress.doneBytes),
|
||||
total: formatBytes(progress.totalBytes),
|
||||
doneFiles: progress.doneFiles.toLocaleString(),
|
||||
|
||||
@@ -6,53 +6,27 @@ import { formatBytes } from '../../format.ts';
|
||||
import { ipcInvoke } from '../../ipc.ts';
|
||||
import { isVerified } from '../../versions.ts';
|
||||
|
||||
import type { WizardMode } from './useInstallWizard.ts';
|
||||
|
||||
interface SourceStepProps {
|
||||
readonly mode: WizardMode;
|
||||
readonly source: GameFolderInspection | null;
|
||||
readonly stockSource: GameFolderInspection | null;
|
||||
/** Null while the folder is measured. */
|
||||
readonly sourceSize: FolderSize | null;
|
||||
readonly supportedVersions: readonly string[];
|
||||
readonly onSource: (source: GameFolderInspection | null) => void;
|
||||
readonly onStockSource: (source: GameFolderInspection | null) => void;
|
||||
readonly onError: (error: unknown) => void;
|
||||
}
|
||||
|
||||
/** Step 1: the player's War Thunder installation, its version and the adaptation used for it. */
|
||||
export function SourceStep({ mode, source, stockSource, sourceSize, supportedVersions, onSource, onStockSource, onError }: SourceStepProps) {
|
||||
export function SourceStep({ source, sourceSize, supportedVersions, onSource, onError }: SourceStepProps) {
|
||||
const { t } = useTranslation();
|
||||
const inspect = (path: string): void => {
|
||||
onSource(null);
|
||||
ipcInvoke('install:inspectGameFolder', { path }).then(onSource).catch(onError);
|
||||
};
|
||||
const inspectStock = (path: string): void => {
|
||||
onStockSource(null);
|
||||
ipcInvoke('install:inspectGameFolder', { path }).then(onStockSource).catch(onError);
|
||||
};
|
||||
return (
|
||||
<>
|
||||
<p className="lead">{t(mode === 'existing' ? 'source.existingBody' : 'source.body')}</p>
|
||||
<FolderField
|
||||
path={source?.path ?? null}
|
||||
dialogTitle={t(mode === 'existing' ? 'source.existingDialogTitle' : 'source.dialogTitle')}
|
||||
onChosen={inspect}
|
||||
onError={onError}
|
||||
/>
|
||||
<p className="lead">{t('source.body')}</p>
|
||||
<FolderField path={source?.path ?? null} dialogTitle={t('source.dialogTitle')} onChosen={inspect} onError={onError} />
|
||||
{source && <SourceVerdict source={source} sourceSize={sourceSize} supportedVersions={supportedVersions} />}
|
||||
{source?.needsStockSource && (
|
||||
<div className="maintenance-confirm">
|
||||
<p className="lead">{t('source.patchedNeedsStock')}</p>
|
||||
<FolderField
|
||||
path={stockSource?.path ?? null}
|
||||
dialogTitle={t('source.stockSourceTitle')}
|
||||
onChosen={inspectStock}
|
||||
onError={onError}
|
||||
/>
|
||||
{stockSource && <StockSourceVerdict source={source} stockSource={stockSource} />}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -63,13 +37,11 @@ function SourceVerdict({ source, sourceSize, supportedVersions }: { readonly sou
|
||||
return <Notice tone="error">{t('source.notAGame', { files: source.missingFiles.join(', ') })}</Notice>;
|
||||
}
|
||||
const size = sourceSize ? t('source.size', { size: formatBytes(sourceSize.bytes), files: sourceSize.files.toLocaleString() }) : t('source.measuring');
|
||||
const backupNote = source.hasOfflineBackup ? <p className="small">{t('source.offlineBackupDetected')}</p> : null;
|
||||
if (isVerified(source.version, supportedVersions)) {
|
||||
return (
|
||||
<Notice tone="info">
|
||||
<p>{t('source.versionVerified', { version: source.version })}</p>
|
||||
<p className="small">{size}</p>
|
||||
{backupNote}
|
||||
</Notice>
|
||||
);
|
||||
}
|
||||
@@ -79,32 +51,11 @@ function SourceVerdict({ source, sourceSize, supportedVersions }: { readonly sou
|
||||
{t('source.versionUnverified', { version: source.version ?? t('source.versionUnknown') })}
|
||||
</p>
|
||||
<p className="small">{size}</p>
|
||||
{backupNote}
|
||||
</Notice>
|
||||
);
|
||||
}
|
||||
|
||||
function StockSourceVerdict({ source, stockSource }: { readonly source: GameFolderInspection; readonly stockSource: GameFolderInspection }) {
|
||||
const { t } = useTranslation();
|
||||
if (stockSource.missingFiles.length) {
|
||||
return <Notice tone="error">{t('source.notAGame', { files: stockSource.missingFiles.join(', ') })}</Notice>;
|
||||
}
|
||||
if (stockSource.needsStockSource) {
|
||||
return <Notice tone="error">{t('source.stockSourcePatched')}</Notice>;
|
||||
}
|
||||
if (source.version !== null && stockSource.version !== null && source.version !== stockSource.version) {
|
||||
return <Notice tone="error">{t('source.stockSourceVersionMismatch', { expected: source.version, actual: stockSource.version })}</Notice>;
|
||||
}
|
||||
return <Notice tone="info">{t('source.stockSourceReady', { version: stockSource.version ?? t('source.versionUnknown') })}</Notice>;
|
||||
}
|
||||
|
||||
/** Whether the wizard may go past step 1. */
|
||||
export function sourceUsable(
|
||||
source: GameFolderInspection | null,
|
||||
stockSource: GameFolderInspection | null = null,
|
||||
): source is GameFolderInspection {
|
||||
if (source === null || source.missingFiles.length > 0) return false;
|
||||
if (!source.needsStockSource) return true;
|
||||
if (stockSource === null || stockSource.missingFiles.length > 0 || stockSource.needsStockSource) return false;
|
||||
return source.version === null || stockSource.version === null || source.version === stockSource.version;
|
||||
export function sourceUsable(source: GameFolderInspection | null): source is GameFolderInspection {
|
||||
return source !== null && source.missingFiles.length === 0;
|
||||
}
|
||||
@@ -4,7 +4,6 @@ import { Sheet } from '../../components/Sheet.tsx';
|
||||
import { CheckStep } from './CheckStep.tsx';
|
||||
import { DataStep } from './DataStep.tsx';
|
||||
import { MethodStep } from './MethodStep.tsx';
|
||||
import { ModeStep } from './ModeStep.tsx';
|
||||
import { ProgressStep } from './ProgressStep.tsx';
|
||||
import { SourceStep, sourceUsable } from './SourceStep.tsx';
|
||||
import { WIZARD_STEPS, type InstallWizard } from './useInstallWizard.ts';
|
||||
@@ -15,20 +14,10 @@ export function WizardMain({ wizard, supportedVersions }: { readonly wizard: Ins
|
||||
const { step, source } = wizard;
|
||||
return (
|
||||
<Sheet title={t(`wizard.steps.${step}`)} aside={t('wizard.stepOf', { index: wizard.index + 1, total: WIZARD_STEPS.length })}>
|
||||
{step === 'mode' && <ModeStep mode={wizard.mode} onMode={wizard.chooseMode} />}
|
||||
{step === 'source' && (
|
||||
<SourceStep
|
||||
mode={wizard.mode}
|
||||
source={source}
|
||||
stockSource={wizard.stockSource}
|
||||
sourceSize={wizard.sourceSize}
|
||||
supportedVersions={supportedVersions}
|
||||
onSource={wizard.chooseSource}
|
||||
onStockSource={wizard.setStockSource}
|
||||
onError={wizard.report}
|
||||
/>
|
||||
<SourceStep source={source} sourceSize={wizard.sourceSize} supportedVersions={supportedVersions} onSource={wizard.chooseSource} onError={wizard.report} />
|
||||
)}
|
||||
{step === 'method' && sourceUsable(source, wizard.stockSource) && (
|
||||
{step === 'method' && sourceUsable(source) && (
|
||||
<>
|
||||
<Row label={t('copies.summary.name')}>
|
||||
<input className="input" aria-label={t('copies.summary.name')} value={wizard.name} onChange={(event) => wizard.setName(event.target.value)} />
|
||||
@@ -36,21 +25,9 @@ export function WizardMain({ wizard, supportedVersions }: { readonly wizard: Ins
|
||||
<MethodStep source={source} sourceSize={wizard.sourceSize} choice={wizard.choice} onChoice={wizard.setChoice} onError={wizard.report} />
|
||||
</>
|
||||
)}
|
||||
{step === 'data' && (
|
||||
<DataStep
|
||||
dataPath={wizard.dataPath}
|
||||
dataProblem={wizard.dataProblem}
|
||||
steamDataPath={wizard.steamDataPath}
|
||||
steamDataConfirmed={wizard.steamDataConfirmed}
|
||||
onSteamDataConfirmed={wizard.setSteamDataConfirmed}
|
||||
decalSource={wizard.decalSource}
|
||||
onDataPath={wizard.setDataPath}
|
||||
onDecalSource={wizard.setDecalSource}
|
||||
onError={wizard.report}
|
||||
/>
|
||||
)}
|
||||
{step === 'data' && <DataStep dataPath={wizard.dataPath} onDataPath={wizard.setDataPath} onError={wizard.report} />}
|
||||
{step === 'check' && <CheckStep check={wizard.check} missingAccepted={wizard.missingAccepted} onMissingAccepted={wizard.setMissingAccepted} />}
|
||||
{step === 'installing' && <ProgressStep progress={wizard.progress} useHardLinks={wizard.choice.method === 'hardlink'} importDecals={wizard.decalSource !== null} />}
|
||||
{step === 'installing' && <ProgressStep progress={wizard.progress} />}
|
||||
{wizard.message && <p className="error-text" role="alert">{wizard.message}</p>}
|
||||
</Sheet>
|
||||
);
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import type { DataFolderProblem, FolderSize, GameFolderInspection, InstallProgress, InstallRequest, PatchCheck } from '@shared/schemas/install.ts';
|
||||
import type { FolderSize, GameFolderInspection, InstallProgress, InstallRequest, PatchCheck } from '@shared/schemas/install.ts';
|
||||
import { ipcInvoke, ipcOn } from '../../ipc.ts';
|
||||
import { useErrorMessage } from '../../useErrorMessage.ts';
|
||||
import { checkUsable } from './CheckStep.tsx';
|
||||
import { methodUsable, type MethodChoice } from './MethodStep.tsx';
|
||||
import { sourceUsable } from './SourceStep.tsx';
|
||||
|
||||
export const WIZARD_STEPS = ['mode', 'source', 'method', 'data', 'check', 'installing'] as const;
|
||||
export const WIZARD_STEPS = ['source', 'method', 'data', 'check', 'installing'] as const;
|
||||
export type WizardStep = (typeof WIZARD_STEPS)[number];
|
||||
export type WizardMode = 'new' | 'existing';
|
||||
|
||||
const NO_CHOICE: MethodChoice = { method: 'copy', target: null, steamConfirmed: false };
|
||||
|
||||
@@ -24,23 +23,13 @@ interface WizardOptions {
|
||||
export function useInstallWizard({ onInstalled }: WizardOptions) {
|
||||
const { message, report, clear } = useErrorMessage();
|
||||
const [active, setActive] = useState(false);
|
||||
const [mode, setMode] = useState<WizardMode>('new');
|
||||
const [step, setStep] = useState<WizardStep>('mode');
|
||||
const [step, setStep] = useState<WizardStep>('source');
|
||||
const [source, setSource] = useState<GameFolderInspection | null>(null);
|
||||
const [stockSource, setStockSource] = useState<GameFolderInspection | null>(null);
|
||||
const [sourceSize, setSourceSize] = useState<FolderSize | null>(null);
|
||||
const [choice, setChoice] = useState<MethodChoice>(NO_CHOICE);
|
||||
const [draftId, setDraftId] = useState<string | null>(null);
|
||||
const [name, setName] = useState('');
|
||||
const [dataPath, setDataPath] = useState('');
|
||||
const [dataInspection, setDataInspection] = useState<{
|
||||
key: string;
|
||||
path: string;
|
||||
inSteam: boolean;
|
||||
problem: DataFolderProblem | null;
|
||||
confirmed: boolean;
|
||||
} | null>(null);
|
||||
const [decalSource, setDecalSource] = useState<string | null>(null);
|
||||
const [check, setCheck] = useState<PatchCheck | null>(null);
|
||||
const [missingAccepted, setMissingAccepted] = useState(false);
|
||||
const [progress, setProgress] = useState<InstallProgress | null>(null);
|
||||
@@ -49,9 +38,9 @@ export function useInstallWizard({ onInstalled }: WizardOptions) {
|
||||
// The size of the installation decides whether a target drive has room; measure it once per source.
|
||||
useEffect(() => {
|
||||
setSourceSize(null);
|
||||
if (!source || source.missingFiles.length > 0) return;
|
||||
if (!sourceUsable(source)) return;
|
||||
let current = true;
|
||||
ipcInvoke('install:measureFolder', { path: source.path, version: source.version })
|
||||
ipcInvoke('install:measureFolder', { path: source.path })
|
||||
.then((size) => current && setSourceSize(size))
|
||||
.catch((error: unknown) => current && report(error));
|
||||
return () => {
|
||||
@@ -59,53 +48,13 @@ export function useInstallWizard({ onInstalled }: WizardOptions) {
|
||||
};
|
||||
}, [source, report]);
|
||||
|
||||
const plannedCopyPath = choice.method === 'in-place' || choice.method === 'existing'
|
||||
? (source?.path ?? null)
|
||||
: (choice.target?.path ?? null);
|
||||
const plannedSourcePath = choice.method === 'copy' || choice.method === 'hardlink'
|
||||
? (source?.path ?? null)
|
||||
: null;
|
||||
const plannedStockSourcePath = source?.needsStockSource ? (stockSource?.path ?? null) : null;
|
||||
const dataInspectionKey = JSON.stringify([dataPath, plannedCopyPath, plannedSourcePath, plannedStockSourcePath]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!active || !dataPath) return;
|
||||
let current = true;
|
||||
ipcInvoke('install:inspectDataFolder', {
|
||||
path: dataPath,
|
||||
...(plannedCopyPath ? { copyPath: plannedCopyPath } : {}),
|
||||
...(plannedSourcePath ? { sourcePath: plannedSourcePath } : {}),
|
||||
...(plannedStockSourcePath ? { stockSourcePath: plannedStockSourcePath } : {}),
|
||||
})
|
||||
.then(({ path, inSteam, problem }) => {
|
||||
if (!current) return;
|
||||
setDataInspection((previous) => previous?.key === dataInspectionKey && previous.path === path &&
|
||||
previous.inSteam === inSteam && previous.problem === problem
|
||||
? previous
|
||||
: { key: dataInspectionKey, path, inSteam, problem, confirmed: false });
|
||||
})
|
||||
.catch((error: unknown) => current && report(error));
|
||||
return () => { current = false; };
|
||||
}, [active, dataPath, plannedCopyPath, plannedSourcePath, plannedStockSourcePath, dataInspectionKey, report]);
|
||||
|
||||
const dataChecked = dataInspection?.key === dataInspectionKey ? dataInspection : null;
|
||||
const dataProblem = dataChecked?.problem ?? null;
|
||||
const dataReady = dataChecked !== null && dataProblem === null && (!dataChecked.inSteam || dataChecked.confirmed);
|
||||
const setSteamDataConfirmed = (confirmed: boolean): void => {
|
||||
setDataInspection((inspection) => inspection ? { ...inspection, confirmed } : null);
|
||||
};
|
||||
|
||||
// The check runs every time the step is entered: the choices before it may have changed.
|
||||
useEffect(() => {
|
||||
if (!active || step !== 'check' || !sourceUsable(source, stockSource)) return;
|
||||
if (!active || step !== 'check' || !sourceUsable(source)) return;
|
||||
let current = true;
|
||||
setCheck(null);
|
||||
setMissingAccepted(false);
|
||||
ipcInvoke('install:checkPatches', {
|
||||
gamePath: source.path,
|
||||
dataPath,
|
||||
...(source.needsStockSource && stockSource ? { stockSourcePath: stockSource.path } : {}),
|
||||
})
|
||||
ipcInvoke('install:checkPatches', { gamePath: source.path, dataPath })
|
||||
.then((result) => current && setCheck(result))
|
||||
.catch((error: unknown) => {
|
||||
if (!current) return;
|
||||
@@ -115,22 +64,18 @@ export function useInstallWizard({ onInstalled }: WizardOptions) {
|
||||
return () => {
|
||||
current = false;
|
||||
};
|
||||
}, [active, step, source, stockSource, dataPath, report]);
|
||||
}, [active, step, source, dataPath, report]);
|
||||
|
||||
useEffect(() => ipcOn('event:install-progress', setProgress), []);
|
||||
|
||||
const start = (): void => {
|
||||
clear();
|
||||
setMode('new');
|
||||
setStep('mode');
|
||||
setStep('source');
|
||||
setSource(null);
|
||||
setStockSource(null);
|
||||
setChoice(NO_CHOICE);
|
||||
setName('');
|
||||
setDraftId(null);
|
||||
setDataPath('');
|
||||
setDataInspection(null);
|
||||
setDecalSource(null);
|
||||
setActive(true);
|
||||
ipcInvoke('install:prepareCopy').then(({ id, dataPath: folder }) => {
|
||||
setDraftId(id);
|
||||
@@ -138,51 +83,18 @@ export function useInstallWizard({ onInstalled }: WizardOptions) {
|
||||
}).catch(report);
|
||||
};
|
||||
|
||||
const chooseMode = (nextMode: WizardMode): void => {
|
||||
if (nextMode === mode) return;
|
||||
setMode(nextMode);
|
||||
setSource(null);
|
||||
setStockSource(null);
|
||||
setChoice(nextMode === 'existing' ? { method: 'existing', target: null, steamConfirmed: false } : NO_CHOICE);
|
||||
setName('');
|
||||
};
|
||||
|
||||
const chooseSource = (found: GameFolderInspection | null): void => {
|
||||
setSource(found);
|
||||
setStockSource(null);
|
||||
const isExisting = mode === 'existing' || found?.hasOfflineBackup || found?.needsStockSource;
|
||||
const defaultMethod = isExisting ? 'existing' : 'copy';
|
||||
setChoice({ method: defaultMethod, target: null, steamConfirmed: false });
|
||||
if (!found) {
|
||||
setName('');
|
||||
return;
|
||||
}
|
||||
const folderName = found.path.split(/[\\/]/).filter(Boolean).at(-1) ?? '';
|
||||
const genericName = /^(war thunder|wtoffline)$/i.test(folderName);
|
||||
if (!isExisting || genericName || !folderName) {
|
||||
setName(found.version ? `WTOffline ${found.version}` : 'WTOffline');
|
||||
} else {
|
||||
setName(folderName);
|
||||
}
|
||||
setChoice(NO_CHOICE);
|
||||
setName(found?.path.split(/[\\/]/).filter(Boolean).at(-1) ?? '');
|
||||
};
|
||||
|
||||
const install = (): void => {
|
||||
if (!sourceUsable(source, stockSource) || !draftId || !dataReady) return;
|
||||
const directFolder = choice.method === 'in-place' || choice.method === 'existing';
|
||||
const copyFolder = directFolder ? source : choice.target;
|
||||
const stockExtra = source.needsStockSource && stockSource ? { stockSourcePath: stockSource.path } : {};
|
||||
const choices = {
|
||||
id: draftId, name, dataPath,
|
||||
...(choice.steamConfirmed && copyFolder ? { confirmedSteamCopyPath: copyFolder.resolvedPath } : {}),
|
||||
...(dataChecked.confirmed ? { confirmedSteamDataPath: dataChecked.path } : {}),
|
||||
missingFeaturesAccepted: missingAccepted,
|
||||
...(decalSource ? { decalSourcePath: decalSource } : {}),
|
||||
};
|
||||
const request: InstallRequest = choice.method === 'in-place'
|
||||
? { method: 'in-place', gamePath: source.path, ...stockExtra, ...choices }
|
||||
: choice.method === 'existing'
|
||||
? { method: 'existing', gamePath: source.path, ...stockExtra, ...choices }
|
||||
: { method: 'copy', useHardLinks: choice.method === 'hardlink', sourcePath: source.path, copyPath: choice.target!.path, ...choices };
|
||||
if (!sourceUsable(source) || !draftId) return;
|
||||
const choices = { id: draftId, name, dataPath, steamLibraryConfirmed: choice.steamConfirmed, missingFeaturesAccepted: missingAccepted };
|
||||
const request: InstallRequest = choice.method === 'copy'
|
||||
? { method: 'copy', sourcePath: source.path, copyPath: choice.target!.path, ...choices }
|
||||
: { method: 'in-place', gamePath: source.path, ...choices };
|
||||
clear();
|
||||
setProgress(null);
|
||||
setCancelling(false);
|
||||
@@ -200,11 +112,10 @@ export function useInstallWizard({ onInstalled }: WizardOptions) {
|
||||
|
||||
const canGoOn = ((): boolean => {
|
||||
switch (step) {
|
||||
case 'mode': return draftId !== null;
|
||||
case 'source': return draftId !== null && sourceUsable(source, stockSource);
|
||||
case 'method': return name.trim().length > 0 && sourceUsable(source, stockSource) && methodUsable(source, sourceSize, choice);
|
||||
case 'data': return dataReady;
|
||||
case 'check': return dataReady && checkUsable(check, missingAccepted);
|
||||
case 'source': return draftId !== null && sourceUsable(source);
|
||||
case 'method': return name.trim().length > 0 && sourceUsable(source) && methodUsable(source, sourceSize, choice);
|
||||
case 'data': return dataPath.length > 0;
|
||||
case 'check': return checkUsable(check, missingAccepted);
|
||||
case 'installing': return false;
|
||||
}
|
||||
})();
|
||||
@@ -230,9 +141,8 @@ export function useInstallWizard({ onInstalled }: WizardOptions) {
|
||||
};
|
||||
|
||||
return {
|
||||
active, mode, step, index, source, stockSource, sourceSize, choice, name, dataPath, dataProblem, decalSource, check, missingAccepted, progress, cancelling, message, canGoOn,
|
||||
steamDataPath: dataChecked?.inSteam ? dataChecked.path : null, steamDataConfirmed: dataChecked?.confirmed ?? false,
|
||||
start, back, next, cancel, report, chooseMode, chooseSource, setStockSource, setChoice, setName, setDataPath, setSteamDataConfirmed, setDecalSource, setMissingAccepted,
|
||||
active, step, index, source, sourceSize, choice, name, dataPath, check, missingAccepted, progress, cancelling, message, canGoOn,
|
||||
start, back, next, cancel, report, chooseSource, setChoice, setName, setDataPath, setMissingAccepted,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -10,13 +10,12 @@ export function wizardBar(wizard: InstallWizard, t: TFunction): BarModel {
|
||||
|
||||
if (step === 'installing') {
|
||||
const phase = progress?.phase ?? 'checking';
|
||||
const tracking = (phase === 'copying' || phase === 'verifying') && progress !== null;
|
||||
const cancellable = tracking || phase === 'importing-decals';
|
||||
const copying = phase === 'copying' && progress !== null;
|
||||
return {
|
||||
tone: 'busy',
|
||||
title: t(`progress.phase.${phase}`),
|
||||
detail: cancellable ? t('progress.cancelHint') : stepOf,
|
||||
progress: tracking
|
||||
detail: copying ? t('progress.cancelHint') : stepOf,
|
||||
progress: copying
|
||||
? {
|
||||
value: progress.doneBytes,
|
||||
max: progress.totalBytes,
|
||||
@@ -25,7 +24,7 @@ export function wizardBar(wizard: InstallWizard, t: TFunction): BarModel {
|
||||
}
|
||||
: { value: 0, max: null },
|
||||
primary: { label: t('wizard.installing'), disabled: true },
|
||||
...(cancellable ? { secondary: { label: cancelling ? t('progress.cancelling') : t('progress.cancel'), disabled: cancelling, onClick: wizard.cancel } } : {}),
|
||||
...(copying ? { secondary: { label: cancelling ? t('progress.cancelling') : t('progress.cancel'), disabled: cancelling, onClick: wizard.cancel } } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,591 +0,0 @@
|
||||
import { useCallback, useEffect, useMemo, useState, type DragEvent, type FormEvent } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import type { InstallRecord } from '@shared/schemas/install.ts';
|
||||
import type { ModIssueView, ModListItem, ModsStateView } from '@shared/schemas/mods.ts';
|
||||
import { Row } from '../../components/Row.tsx';
|
||||
import { Sheet } from '../../components/Sheet.tsx';
|
||||
import { ipcInvoke } from '../../ipc.ts';
|
||||
import type { ModsSection } from '../../shell/navigation.ts';
|
||||
|
||||
const MOD_DOCS_URL = 'https://wto-project.net/mod-docs';
|
||||
|
||||
interface Props {
|
||||
readonly copy: InstallRecord;
|
||||
readonly section: ModsSection;
|
||||
readonly readOnly: boolean;
|
||||
readonly onError: (error: unknown) => void;
|
||||
}
|
||||
|
||||
function localized(value: string | Readonly<Record<string, string>> | undefined, language: string): string {
|
||||
if (!value) return '';
|
||||
if (typeof value === 'string') return value;
|
||||
const exact = value[language];
|
||||
if (exact) return exact;
|
||||
const prefix = language.split('-')[0];
|
||||
if (prefix) {
|
||||
const match = Object.entries(value).find(([key]) => key === prefix || key.startsWith(`${prefix}-`));
|
||||
if (match?.[1]) return match[1];
|
||||
}
|
||||
return value.en ?? value['en-US'] ?? Object.values(value)[0] ?? '';
|
||||
}
|
||||
|
||||
export function ModsPage({ copy, section, readOnly, onError }: Props) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const [state, setState] = useState<ModsStateView | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [query, setQuery] = useState('');
|
||||
const [expandedId, setExpandedId] = useState<string | null>(null);
|
||||
const [draggedId, setDraggedId] = useState<string | null>(null);
|
||||
const [presetName, setPresetName] = useState('');
|
||||
const [notice, setNotice] = useState<string | null>(null);
|
||||
|
||||
const load = useCallback(() => {
|
||||
setBusy(true);
|
||||
ipcInvoke('mods:getState', { copyId: copy.id })
|
||||
.then(setState)
|
||||
.catch(onError)
|
||||
.finally(() => setBusy(false));
|
||||
}, [copy.id, onError]);
|
||||
|
||||
useEffect(() => {
|
||||
let mounted = true;
|
||||
const sync = (): void => {
|
||||
ipcInvoke('mods:getState', { copyId: copy.id })
|
||||
.then((result) => { if (mounted) setState(result); })
|
||||
.catch(onError);
|
||||
};
|
||||
sync();
|
||||
window.addEventListener('focus', sync);
|
||||
return () => {
|
||||
mounted = false;
|
||||
window.removeEventListener('focus', sync);
|
||||
};
|
||||
}, [copy.id, onError]);
|
||||
|
||||
const runAction = (action: Promise<ModsStateView>, successNotice?: string): void => {
|
||||
setBusy(true);
|
||||
setNotice(null);
|
||||
action
|
||||
.then((next) => {
|
||||
setState(next);
|
||||
if (successNotice) setNotice(successNotice);
|
||||
})
|
||||
.catch(onError)
|
||||
.finally(() => setBusy(false));
|
||||
};
|
||||
|
||||
const issuesByMod = useMemo(() => {
|
||||
const map = new Map<string, ModIssueView[]>();
|
||||
for (const issue of state?.issues ?? []) {
|
||||
const list = map.get(issue.modId) ?? [];
|
||||
list.push(issue);
|
||||
map.set(issue.modId, list);
|
||||
}
|
||||
return map;
|
||||
}, [state]);
|
||||
|
||||
const title = t(`mods.sections.${section}`);
|
||||
if (!state) {
|
||||
return <Sheet title={title} aside={copy.name}><p className="lead">{t('mods.loading')}</p></Sheet>;
|
||||
}
|
||||
|
||||
const disabled = readOnly || busy;
|
||||
const enabledCount = state.mods.filter((mod) => state.enabled[mod.id] === true).length;
|
||||
|
||||
const toggleMod = (modId: string, nextEnabled: boolean): void => {
|
||||
runAction(ipcInvoke('mods:setEnabled', { copyId: copy.id, modId, enabled: nextEnabled }));
|
||||
};
|
||||
|
||||
const reorder = (nextOrder: string[]): void => {
|
||||
runAction(ipcInvoke('mods:setOrder', { copyId: copy.id, order: nextOrder }));
|
||||
};
|
||||
|
||||
const moveMod = (modId: string, delta: -1 | 1): void => {
|
||||
const idx = state.order.indexOf(modId);
|
||||
const target = idx + delta;
|
||||
if (idx < 0 || target < 0 || target >= state.order.length) return;
|
||||
const next = [...state.order];
|
||||
const [item] = next.splice(idx, 1);
|
||||
next.splice(target, 0, item!);
|
||||
reorder(next);
|
||||
};
|
||||
|
||||
const handleDrop = (targetId: string, event: DragEvent<HTMLDivElement>): void => {
|
||||
event.preventDefault();
|
||||
const sourceId = draggedId;
|
||||
setDraggedId(null);
|
||||
if (!sourceId || sourceId === targetId || disabled) return;
|
||||
const from = state.order.indexOf(sourceId);
|
||||
const to = state.order.indexOf(targetId);
|
||||
if (from < 0 || to < 0) return;
|
||||
const next = [...state.order];
|
||||
const [moved] = next.splice(from, 1);
|
||||
next.splice(to, 0, moved!);
|
||||
reorder(next);
|
||||
};
|
||||
|
||||
const savePreset = (event: FormEvent<HTMLFormElement>): void => {
|
||||
event.preventDefault();
|
||||
const trimmed = presetName.trim();
|
||||
if (!trimmed) return;
|
||||
runAction(
|
||||
ipcInvoke('mods:savePreset', { copyId: copy.id, name: trimmed }),
|
||||
t('mods.presets.saved', { name: trimmed }),
|
||||
);
|
||||
setPresetName('');
|
||||
};
|
||||
|
||||
const pickCustomFolder = (): void => {
|
||||
ipcInvoke('dialog:pickFolder', { title: t('mods.repo.pickTitle') })
|
||||
.then(({ path }) => {
|
||||
if (!path) return;
|
||||
runAction(ipcInvoke('mods:setFolder', { copyId: copy.id, path }), t('mods.repo.updated'));
|
||||
})
|
||||
.catch(onError);
|
||||
};
|
||||
|
||||
const resetFolder = (): void => {
|
||||
runAction(ipcInvoke('mods:setFolder', { copyId: copy.id, path: null }), t('mods.repo.resetDone'));
|
||||
};
|
||||
|
||||
const exportPreset = (presetId: string): void => {
|
||||
setBusy(true);
|
||||
setNotice(null);
|
||||
ipcInvoke('mods:exportPreset', { copyId: copy.id, presetId })
|
||||
.then(({ path }) => {
|
||||
if (path) setNotice(t('mods.presets.exported', { path }));
|
||||
})
|
||||
.catch(onError)
|
||||
.finally(() => setBusy(false));
|
||||
};
|
||||
|
||||
const importPreset = (): void => {
|
||||
setBusy(true);
|
||||
setNotice(null);
|
||||
ipcInvoke('mods:importPreset', { copyId: copy.id })
|
||||
.then(({ imported, state: next }) => {
|
||||
setState(next);
|
||||
if (imported) setNotice(t('mods.presets.imported'));
|
||||
})
|
||||
.catch(onError)
|
||||
.finally(() => setBusy(false));
|
||||
};
|
||||
|
||||
const normalizedQuery = query.trim().toLowerCase();
|
||||
const visibleMods = normalizedQuery
|
||||
? state.mods.filter((mod) => {
|
||||
const displayName = localized(mod.name, i18n.language).toLowerCase();
|
||||
return displayName.includes(normalizedQuery)
|
||||
|| mod.id.toLowerCase().includes(normalizedQuery)
|
||||
|| mod.author.toLowerCase().includes(normalizedQuery);
|
||||
})
|
||||
: state.mods;
|
||||
|
||||
const canDrag = !disabled && normalizedQuery.length === 0;
|
||||
|
||||
return (
|
||||
<Sheet
|
||||
title={title}
|
||||
aside={(
|
||||
<span className="mods-aside">
|
||||
<span>{copy.name} · {t('mods.enabledSummary', { enabled: enabledCount, total: state.mods.length })}</span>
|
||||
<span
|
||||
className="mods-exp-chip"
|
||||
tabIndex={0}
|
||||
aria-label={t('mods.experimentalBody', { api: state.apiVersion })}
|
||||
>
|
||||
<span>{t('mods.experimentalChip')}</span>
|
||||
<span className="mods-exp-icon" aria-hidden="true">i</span>
|
||||
<span className="mods-exp-popover" role="tooltip">
|
||||
<strong>{t('mods.experimentalTitle')}</strong>
|
||||
<span>{t('mods.experimentalBody', { api: state.apiVersion })}</span>
|
||||
</span>
|
||||
</span>
|
||||
</span>
|
||||
)}
|
||||
>
|
||||
{readOnly && (
|
||||
<div className="mods-banner mods-banner-warn" role="status">
|
||||
{t('mods.readOnlyNotice')}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{notice && (
|
||||
<div className="mods-banner mods-banner-ok" role="status">
|
||||
{notice}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{section === 'list' ? (
|
||||
<>
|
||||
<div className="mods-toolbar">
|
||||
<input
|
||||
type="search"
|
||||
className="input mods-search"
|
||||
placeholder={t('mods.searchPlaceholder')}
|
||||
value={query}
|
||||
onChange={(event) => setQuery(event.target.value)}
|
||||
/>
|
||||
{state.presets.length > 0 && (
|
||||
<select
|
||||
className="select mods-preset-select"
|
||||
aria-label={t('mods.presets.quickSwitch')}
|
||||
disabled={disabled}
|
||||
value={state.activePresetId ?? ''}
|
||||
onChange={(event) => {
|
||||
const id = event.target.value;
|
||||
if (id) runAction(ipcInvoke('mods:applyPreset', { copyId: copy.id, presetId: id }));
|
||||
}}
|
||||
>
|
||||
<option value="">{t('mods.presets.customOption')}</option>
|
||||
{state.presets.map((preset) => (
|
||||
<option key={preset.id} value={preset.id}>{preset.name}</option>
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className="button"
|
||||
disabled={disabled || state.mods.length < 2}
|
||||
onClick={() => runAction(ipcInvoke('mods:autoSort', { copyId: copy.id }), t('mods.autoSorted'))}
|
||||
>
|
||||
{t('mods.autoSort')}
|
||||
</button>
|
||||
<button type="button" className="button" disabled={busy} onClick={load}>
|
||||
{t('mods.refresh')}
|
||||
</button>
|
||||
<button type="button" className="button" onClick={() => ipcInvoke('mods:openFolder').catch(onError)}>
|
||||
{t('mods.openFolder')}
|
||||
</button>
|
||||
<a className="button" href={MOD_DOCS_URL} target="_blank" rel="noreferrer">
|
||||
{t('mods.openDocs')}
|
||||
</a>
|
||||
</div>
|
||||
|
||||
{state.discoveryErrors.length > 0 && (
|
||||
<div className="mods-issues-box mods-issues-error">
|
||||
<div className="mods-issues-title">{t('mods.discoveryErrorsTitle', { count: state.discoveryErrors.length })}</div>
|
||||
<ul>
|
||||
{state.discoveryErrors.map((err) => (
|
||||
<li key={err.folderName}>
|
||||
<code>{err.folderName}</code>: {err.reason}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{state.issues.length > 0 && (
|
||||
<div className={state.hasBlockingErrors ? 'mods-issues-box mods-issues-error' : 'mods-issues-box mods-issues-warn'}>
|
||||
<div className="mods-issues-title">
|
||||
{state.hasBlockingErrors
|
||||
? t('mods.blockingIssuesTitle', { count: state.issues.filter((i) => i.severity === 'error').length })
|
||||
: t('mods.issuesTitle', { count: state.issues.length })}
|
||||
</div>
|
||||
<ul>
|
||||
{state.issues.map((issue, idx) => (
|
||||
<li key={`${issue.modId}-${issue.kind}-${idx}`} className={`mods-issue-${issue.severity}`}>
|
||||
<span className="mods-issue-tag">{t(`mods.severity.${issue.severity}`)}</span>
|
||||
<strong>{issue.modId}</strong>: {issue.detail}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{visibleMods.length === 0 ? (
|
||||
<div className="mods-empty">
|
||||
<p className="lead">{state.mods.length === 0 ? t('mods.emptyTitle') : t('mods.noSearchMatch')}</p>
|
||||
{state.mods.length === 0 && (
|
||||
<>
|
||||
<p className="mods-hint">{t('mods.emptyHint', { path: state.modsDir })}</p>
|
||||
<button type="button" className="button button-primary" onClick={() => ipcInvoke('mods:openFolder').catch(onError)}>
|
||||
{t('mods.openFolder')}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="mods-list">
|
||||
{visibleMods.map((mod) => {
|
||||
const index = state.order.indexOf(mod.id);
|
||||
const isEnabled = state.enabled[mod.id] === true;
|
||||
const isExpanded = expandedId === mod.id;
|
||||
const modIssues = issuesByMod.get(mod.id) ?? [];
|
||||
return (
|
||||
<ModCard
|
||||
key={mod.id}
|
||||
mod={mod}
|
||||
index={index}
|
||||
total={state.order.length}
|
||||
enabled={isEnabled}
|
||||
expanded={isExpanded}
|
||||
disabled={disabled}
|
||||
canDrag={canDrag}
|
||||
language={i18n.language}
|
||||
issues={modIssues}
|
||||
onToggle={(next) => toggleMod(mod.id, next)}
|
||||
onMove={(delta) => moveMod(mod.id, delta)}
|
||||
onToggleExpand={() => setExpandedId(isExpanded ? null : mod.id)}
|
||||
onDragStart={() => setDraggedId(mod.id)}
|
||||
onDrop={(event) => handleDrop(mod.id, event)}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<section className="mods-section">
|
||||
<h3 className="mods-subheading">{t('mods.presets.heading')}</h3>
|
||||
<p className="mods-hint">{t('mods.presets.description')}</p>
|
||||
<form className="mods-preset-form" onSubmit={savePreset}>
|
||||
<input
|
||||
type="text"
|
||||
className="input"
|
||||
maxLength={80}
|
||||
disabled={disabled}
|
||||
placeholder={t('mods.presets.namePlaceholder')}
|
||||
value={presetName}
|
||||
onChange={(event) => setPresetName(event.target.value)}
|
||||
/>
|
||||
<button type="submit" className="button button-primary" disabled={disabled || !presetName.trim()}>
|
||||
{t('mods.presets.saveCurrent')}
|
||||
</button>
|
||||
<button type="button" className="button" disabled={disabled} onClick={importPreset}>
|
||||
{t('mods.presets.import')}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
{state.presets.length === 0 ? (
|
||||
<p className="mods-hint">{t('mods.presets.empty')}</p>
|
||||
) : (
|
||||
<div className="mods-preset-list">
|
||||
{state.presets.map((preset) => {
|
||||
const active = state.activePresetId === preset.id;
|
||||
const count = Object.values(preset.enabled).filter(Boolean).length;
|
||||
return (
|
||||
<div key={preset.id} className={active ? 'mods-preset-item mods-preset-active' : 'mods-preset-item'}>
|
||||
<div className="mods-preset-meta">
|
||||
<div className="mods-preset-name">
|
||||
{preset.name}
|
||||
{active && <span className="mods-badge mods-badge-data">{t('mods.presets.activeTag')}</span>}
|
||||
</div>
|
||||
<div className="mods-preset-sub">
|
||||
{t('mods.presets.summary', { count, total: preset.order.length })}
|
||||
</div>
|
||||
</div>
|
||||
<div className="copy-list-actions">
|
||||
<button
|
||||
type="button"
|
||||
className="button button-primary"
|
||||
disabled={disabled}
|
||||
onClick={() => runAction(
|
||||
ipcInvoke('mods:applyPreset', { copyId: copy.id, presetId: preset.id }),
|
||||
t('mods.presets.applied', { name: preset.name }),
|
||||
)}
|
||||
>
|
||||
{t('mods.presets.apply')}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="button"
|
||||
disabled={disabled}
|
||||
onClick={() => runAction(
|
||||
ipcInvoke('mods:savePreset', { copyId: copy.id, name: preset.name, overwriteId: preset.id }),
|
||||
t('mods.presets.updated', { name: preset.name }),
|
||||
)}
|
||||
>
|
||||
{t('mods.presets.overwrite')}
|
||||
</button>
|
||||
<button type="button" className="button" disabled={busy} onClick={() => exportPreset(preset.id)}>
|
||||
{t('mods.presets.export')}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="button"
|
||||
disabled={disabled}
|
||||
onClick={() => runAction(ipcInvoke('mods:deletePreset', { copyId: copy.id, presetId: preset.id }))}
|
||||
>
|
||||
{t('mods.presets.delete')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<section className="mods-section">
|
||||
<h3 className="mods-subheading">{t('mods.repo.heading')}</h3>
|
||||
<p className="mods-hint">{t('mods.repo.description')}</p>
|
||||
<Row
|
||||
label={t('mods.repo.pathLabel')}
|
||||
hint={state.isCustomModsDir ? t('mods.repo.customNote') : t('mods.repo.defaultNote')}
|
||||
>
|
||||
<code className="mods-path">{state.modsDir}</code>
|
||||
</Row>
|
||||
<div className="copy-list-actions" style={{ marginTop: 12 }}>
|
||||
<button type="button" className="button" onClick={() => ipcInvoke('mods:openFolder').catch(onError)}>
|
||||
{t('mods.openFolder')}
|
||||
</button>
|
||||
<button type="button" className="button" disabled={disabled} onClick={pickCustomFolder}>
|
||||
{t('mods.repo.changeFolder')}
|
||||
</button>
|
||||
{state.isCustomModsDir && (
|
||||
<button type="button" className="button" disabled={disabled} onClick={resetFolder}>
|
||||
{t('mods.repo.resetDefault')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
</>
|
||||
)}
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
|
||||
interface ModCardProps {
|
||||
readonly mod: ModListItem;
|
||||
readonly index: number;
|
||||
readonly total: number;
|
||||
readonly enabled: boolean;
|
||||
readonly expanded: boolean;
|
||||
readonly disabled: boolean;
|
||||
readonly canDrag: boolean;
|
||||
readonly language: string;
|
||||
readonly issues: readonly ModIssueView[];
|
||||
readonly onToggle: (next: boolean) => void;
|
||||
readonly onMove: (delta: -1 | 1) => void;
|
||||
readonly onToggleExpand: () => void;
|
||||
readonly onDragStart: () => void;
|
||||
readonly onDrop: (event: DragEvent<HTMLDivElement>) => void;
|
||||
}
|
||||
|
||||
function ModCard({
|
||||
mod,
|
||||
index,
|
||||
total,
|
||||
enabled,
|
||||
expanded,
|
||||
disabled,
|
||||
canDrag,
|
||||
language,
|
||||
issues,
|
||||
onToggle,
|
||||
onMove,
|
||||
onToggleExpand,
|
||||
onDragStart,
|
||||
onDrop,
|
||||
}: ModCardProps) {
|
||||
const { t } = useTranslation();
|
||||
const displayName = localized(mod.name, language) || mod.id;
|
||||
const description = localized(mod.description, language);
|
||||
const errorCount = issues.filter((i) => i.severity === 'error').length;
|
||||
const warnCount = issues.filter((i) => i.severity === 'warning').length;
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`mods-card${enabled ? ' mods-card-enabled' : ''}`}
|
||||
draggable={canDrag}
|
||||
onDragStart={onDragStart}
|
||||
onDragOver={(event) => { if (canDrag) event.preventDefault(); }}
|
||||
onDrop={onDrop}
|
||||
>
|
||||
<div className="mods-card-row">
|
||||
<span className="mods-order-num" title={t('mods.loadOrderHint')}>#{index + 1}</span>
|
||||
<input
|
||||
type="checkbox"
|
||||
className="mods-checkbox"
|
||||
checked={enabled}
|
||||
disabled={disabled}
|
||||
aria-label={displayName}
|
||||
onChange={(event) => onToggle(event.target.checked)}
|
||||
/>
|
||||
<div className="mods-card-main" onClick={onToggleExpand}>
|
||||
<div className="mods-card-title">
|
||||
<span className="mods-name">{displayName}</span>
|
||||
<span className="mods-version">v{mod.version}</span>
|
||||
<span className="mods-author">· {mod.author}</span>
|
||||
<div className="mods-badges">
|
||||
{mod.badges.map((badge) => (
|
||||
<span key={badge} className={`mods-badge mods-badge-${badge}`}>
|
||||
{t(`mods.badges.${badge}`)}
|
||||
</span>
|
||||
))}
|
||||
{errorCount > 0 && <span className="mods-badge mods-badge-error">{t('mods.errorCount', { count: errorCount })}</span>}
|
||||
{warnCount > 0 && <span className="mods-badge mods-badge-warn">{t('mods.warnCount', { count: warnCount })}</span>}
|
||||
</div>
|
||||
</div>
|
||||
{description && <div className="mods-card-desc">{description}</div>}
|
||||
</div>
|
||||
<div className="mods-card-actions">
|
||||
<button
|
||||
type="button"
|
||||
className="button mods-move-btn"
|
||||
disabled={disabled || index <= 0}
|
||||
title={t('mods.moveUp')}
|
||||
onClick={() => onMove(-1)}
|
||||
>
|
||||
↑
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="button mods-move-btn"
|
||||
disabled={disabled || index < 0 || index >= total - 1}
|
||||
title={t('mods.moveDown')}
|
||||
onClick={() => onMove(1)}
|
||||
>
|
||||
↓
|
||||
</button>
|
||||
<button type="button" className="button" onClick={onToggleExpand}>
|
||||
{expanded ? t('mods.hideDetails') : t('mods.showDetails')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{expanded && (
|
||||
<div className="mods-card-details">
|
||||
<div className="mods-detail-grid">
|
||||
<div><span>ID:</span> <code>{mod.id}</code></div>
|
||||
<div><span>API:</span> <code>{mod.apiVersion}</code></div>
|
||||
<div><span>{t('mods.details.folder')}:</span> <code>{mod.folderName}</code></div>
|
||||
{mod.gameVersions.length > 0 && (
|
||||
<div><span>{t('mods.details.gameVersions')}:</span> <code>{mod.gameVersions.join(', ')}</code></div>
|
||||
)}
|
||||
{mod.requires.length > 0 && (
|
||||
<div><span>{t('mods.details.requires')}:</span> <code>{mod.requires.join(', ')}</code></div>
|
||||
)}
|
||||
{mod.conflicts.length > 0 && (
|
||||
<div><span>{t('mods.details.conflicts')}:</span> <code>{mod.conflicts.join(', ')}</code></div>
|
||||
)}
|
||||
</div>
|
||||
<div className="mods-detail-summary">
|
||||
{mod.serverTuningFiles.length > 0 && (
|
||||
<span>{t('mods.details.tuning', { count: mod.serverTuningFiles.length })}</span>
|
||||
)}
|
||||
{mod.hasServerScript && <span>{t('mods.details.serverScript')}</span>}
|
||||
{mod.packOperations.length > 0 && (
|
||||
<span>{t('mods.details.packOps', { count: mod.packOperations.length })}</span>
|
||||
)}
|
||||
{mod.hasClientAddon && (
|
||||
<span>{t('mods.details.addon', { count: mod.addonFileCount })}</span>
|
||||
)}
|
||||
{mod.guiPatchCount > 0 && (
|
||||
<span>{t('mods.details.guiPatches', { count: mod.guiPatchCount })}</span>
|
||||
)}
|
||||
{mod.exePatchCount > 0 && (
|
||||
<span>{t('mods.details.exePatches', { count: mod.exePatchCount })}</span>
|
||||
)}
|
||||
{mod.clientFileCount > 0 && (
|
||||
<span>{t('mods.details.companionFiles', { count: mod.clientFileCount })}</span>
|
||||
)}
|
||||
{mod.hasConfigBlkPatch && <span>{t('mods.details.configBlk')}</span>}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,11 +1,11 @@
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import type { OfficialImportOptions, OfficialPreview, OnlineDataSource } from '@shared/schemas/saves.ts';
|
||||
import type { OfficialImportOptions, OfficialPreview } from '@shared/schemas/saves.ts';
|
||||
import { Row } from '../../components/Row.tsx';
|
||||
import { ipcInvoke } from '../../ipc.ts';
|
||||
|
||||
const DEFAULTS: OfficialImportOptions = {
|
||||
importSettings: true, unlockVehicles: true, equipment: 'full',
|
||||
importSettings: true, unlockVehicles: true, includeUsedVehicles: false, equipment: 'full',
|
||||
};
|
||||
|
||||
interface Props {
|
||||
@@ -13,179 +13,81 @@ interface Props {
|
||||
readonly userId: string;
|
||||
readonly readOnly: boolean;
|
||||
readonly onError: (error: unknown) => void;
|
||||
readonly onImported?: () => void;
|
||||
}
|
||||
|
||||
export function OfficialSaveImport({ copyId, userId, readOnly, onError, onImported }: Props) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const [sources, setSources] = useState<OnlineDataSource[] | null>(null);
|
||||
const [selectedAccount, setSelectedAccount] = useState<string>('');
|
||||
export function OfficialSaveImport({ copyId, userId, readOnly, onError }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const [paths, setPaths] = useState<string[]>([]);
|
||||
const [options, setOptions] = useState(DEFAULTS);
|
||||
const [preview, setPreview] = useState<OfficialPreview | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [imported, setImported] = useState(false);
|
||||
|
||||
const stageAndPreview = async (accountId: string): Promise<string[]> => {
|
||||
const copied = await ipcInvoke('saves:copyOnlineData', { copyId, userId, accountId });
|
||||
setSelectedAccount(accountId);
|
||||
setPaths(copied);
|
||||
setImported(false);
|
||||
const nextPreview = await ipcInvoke('saves:previewOfficial', { copyId, userId, paths: copied });
|
||||
setPreview(nextPreview);
|
||||
return copied;
|
||||
};
|
||||
|
||||
const discover = (importImmediately: boolean): void => {
|
||||
setBusy(true);
|
||||
setImported(false);
|
||||
ipcInvoke('saves:discoverOnlineData')
|
||||
.then(async (found) => {
|
||||
setSources(found);
|
||||
if (found.length === 0) {
|
||||
setSelectedAccount('');
|
||||
setPaths([]);
|
||||
setPreview(null);
|
||||
return;
|
||||
}
|
||||
const first = found[0]!;
|
||||
const copied = await stageAndPreview(first.accountId);
|
||||
if (importImmediately && found.length === 1 && !readOnly && (options.importSettings || options.unlockVehicles)) {
|
||||
const result = await ipcInvoke('saves:importOfficial', { copyId, userId, paths: copied, options });
|
||||
setPreview(result);
|
||||
setImported(true);
|
||||
onImported?.();
|
||||
}
|
||||
})
|
||||
.catch(onError)
|
||||
.finally(() => setBusy(false));
|
||||
};
|
||||
|
||||
const selectOnlineAccount = (accountId: string): void => {
|
||||
if (!accountId) return;
|
||||
setBusy(true);
|
||||
setImported(false);
|
||||
stageAndPreview(accountId)
|
||||
.catch(onError)
|
||||
.finally(() => setBusy(false));
|
||||
};
|
||||
const request = { copyId, userId, paths };
|
||||
|
||||
const choose = (): void => {
|
||||
ipcInvoke('saves:pickOfficialBackups').then((selection) => {
|
||||
if (selection.length === 0) return;
|
||||
setSelectedAccount('');
|
||||
setPaths(selection);
|
||||
setPreview(null);
|
||||
setImported(false);
|
||||
}).catch(onError);
|
||||
};
|
||||
|
||||
const load = (targetPaths = paths): void => {
|
||||
if (targetPaths.length === 0) return;
|
||||
const load = (): void => {
|
||||
setBusy(true);
|
||||
setImported(false);
|
||||
ipcInvoke('saves:previewOfficial', { copyId, userId, paths: targetPaths })
|
||||
.then(setPreview)
|
||||
.catch(onError)
|
||||
.finally(() => setBusy(false));
|
||||
ipcInvoke('saves:previewOfficial', { ...request, includeUsedVehicles: options.includeUsedVehicles })
|
||||
.then(setPreview).catch(onError).finally(() => setBusy(false));
|
||||
};
|
||||
|
||||
const apply = (): void => {
|
||||
if (paths.length === 0) return;
|
||||
setBusy(true);
|
||||
ipcInvoke('saves:importOfficial', { copyId, userId, paths, options })
|
||||
.then((value) => {
|
||||
setPreview(value);
|
||||
setImported(true);
|
||||
onImported?.();
|
||||
})
|
||||
.catch(onError)
|
||||
.finally(() => setBusy(false));
|
||||
ipcInvoke('saves:importOfficial', { ...request, options }).then((value) => {
|
||||
setPreview(value);
|
||||
setImported(true);
|
||||
}).catch(onError).finally(() => setBusy(false));
|
||||
};
|
||||
|
||||
const formatTime = (iso: string): string => {
|
||||
const parsed = Date.parse(iso);
|
||||
return Number.isNaN(parsed) ? iso : new Date(parsed).toLocaleString(i18n.language);
|
||||
};
|
||||
|
||||
const language = i18n.language.toLowerCase().startsWith('zh') ? 'zh' : 'en';
|
||||
const vehicleSeparator = language === 'zh' ? '、' : ', ';
|
||||
const vehicleLabel = (id: string): string => preview?.vehicleNames[id]?.[language] ?? id;
|
||||
const canImportSelection = options.importSettings || options.unlockVehicles;
|
||||
|
||||
return (
|
||||
<>
|
||||
<Row label={t('saves.official.auto')} hint={t('saves.official.autoHint')}>
|
||||
<button type="button" className="button button-primary" onClick={() => discover(true)} disabled={busy || readOnly || !canImportSelection}>
|
||||
{t('saves.official.oneClick')}
|
||||
</button>
|
||||
<button type="button" className="button" onClick={() => discover(false)} disabled={busy}>
|
||||
{t('saves.official.discover')}
|
||||
</button>
|
||||
</Row>
|
||||
{sources !== null && sources.length === 0 && (
|
||||
<p className="small">{t('saves.official.notFound')}</p>
|
||||
)}
|
||||
{sources !== null && sources.length > 0 && (
|
||||
<Row label={t('saves.official.account')} hint={sources.length > 1 ? t('saves.official.multipleAccounts', { count: sources.length }) : undefined}>
|
||||
<select
|
||||
className="select"
|
||||
aria-label={t('saves.official.account')}
|
||||
value={selectedAccount}
|
||||
disabled={busy}
|
||||
onChange={(event) => selectOnlineAccount(event.target.value)}
|
||||
>
|
||||
{sources.map((entry) => (
|
||||
<option key={entry.accountId} value={entry.accountId}>
|
||||
{t('saves.official.accountOption', {
|
||||
id: entry.accountId,
|
||||
files: entry.files.join(', '),
|
||||
time: formatTime(entry.updatedAt),
|
||||
})}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Row>
|
||||
)}
|
||||
<Row label={t('saves.official.files')} hint={t('saves.official.fileHint')}>
|
||||
<button type="button" className="button" onClick={choose} disabled={busy}>{t('saves.official.choose')}</button>
|
||||
{paths.length > 0 && (
|
||||
<span className="folder-path" data-ellipsis-tip={paths.join('\n')}>
|
||||
{paths.map((path) => path.split(/[\\/]/).at(-1)).join(', ')}
|
||||
</span>
|
||||
)}
|
||||
{paths.length > 0 && <span className="folder-path" title={paths.join('\n')}>{paths.map((path) => path.split(/[\\/]/).at(-1)).join(', ')}</span>}
|
||||
</Row>
|
||||
<Row label={t('saves.official.content')}>
|
||||
<label className="check check-inline">
|
||||
<input type="checkbox" checked={options.importSettings} disabled={busy} onChange={(event) => {
|
||||
setOptions({ ...options, importSettings: event.target.checked });
|
||||
setImported(false);
|
||||
}} />
|
||||
{t('saves.official.settings')}
|
||||
</label>
|
||||
<label className="check check-inline">
|
||||
<input type="checkbox" checked={options.unlockVehicles} disabled={busy} onChange={(event) => {
|
||||
setOptions({ ...options, unlockVehicles: event.target.checked });
|
||||
setImported(false);
|
||||
}} />
|
||||
{t('saves.official.unlock')}
|
||||
</label>
|
||||
</Row>
|
||||
<Row label={t('saves.official.equipment')} hint={t('saves.official.equipmentHint')}>
|
||||
<Row label={t('saves.official.equipment')}>
|
||||
<select className="select" aria-label={t('saves.official.equipment')} value={options.equipment} disabled={busy || !options.unlockVehicles}
|
||||
onChange={(event) => {
|
||||
setOptions({ ...options, equipment: event.target.value as OfficialImportOptions['equipment'] });
|
||||
setImported(false);
|
||||
}}>
|
||||
onChange={(event) => setOptions({ ...options, equipment: event.target.value as OfficialImportOptions['equipment'] })}>
|
||||
<option value="full">{t('saves.official.full')}</option>
|
||||
<option value="basic">{t('saves.official.basic')}</option>
|
||||
<option value="stock">{t('saves.official.stock')}</option>
|
||||
</select>
|
||||
<label className="check check-inline">
|
||||
<input type="checkbox" checked={options.includeUsedVehicles} disabled={busy || !options.unlockVehicles} onChange={(event) => {
|
||||
setOptions({ ...options, includeUsedVehicles: event.target.checked });
|
||||
setPreview(null);
|
||||
setImported(false);
|
||||
}} />
|
||||
{t('saves.official.includeUsed')}
|
||||
</label>
|
||||
</Row>
|
||||
<div className="copy-list-actions">
|
||||
<button type="button" className="button" disabled={busy || paths.length === 0} onClick={() => load()}>{t('saves.official.preview')}</button>
|
||||
<button type="button" className="button" disabled={busy || paths.length === 0} onClick={load}>{t('saves.official.preview')}</button>
|
||||
<button type="button" className="button button-primary"
|
||||
disabled={busy || readOnly || !preview || imported || !canImportSelection} onClick={apply}>
|
||||
disabled={busy || readOnly || !preview || imported || (!options.importSettings && !options.unlockVehicles)} onClick={apply}>
|
||||
{t('saves.official.import')}
|
||||
</button>
|
||||
</div>
|
||||
@@ -193,10 +95,8 @@ export function OfficialSaveImport({ copyId, userId, readOnly, onError, onImport
|
||||
{preview && (
|
||||
<div className="maintenance-confirm">
|
||||
<p>{t('saves.official.summary', { files: preview.files.length, presets: preview.presets.length, vehicles: preview.vehicles.length })}</p>
|
||||
{preview.presets.map((preset, index) => (
|
||||
<p key={index}>{preset.title} · {preset.vehicles.map(vehicleLabel).join(vehicleSeparator)}</p>
|
||||
))}
|
||||
{preview.omitted.length > 0 && <p>{t('saves.official.omitted', { names: preview.omitted.map(vehicleLabel).join(vehicleSeparator) })}</p>}
|
||||
{preview.presets.map((preset, index) => <p key={index}>{preset.title} · {preset.vehicles.join(', ')}</p>)}
|
||||
{preview.omitted.length > 0 && <p>{t('saves.official.omitted', { names: preview.omitted.join(', ') })}</p>}
|
||||
</div>
|
||||
)}
|
||||
{imported && <p className="small" role="status">{t('saves.official.done')}</p>}
|
||||
|
||||
@@ -1,69 +0,0 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import type { SaveAvatarChoices } from '@shared/schemas/saves.ts';
|
||||
import { Row } from '../../components/Row.tsx';
|
||||
import { ipcInvoke } from '../../ipc.ts';
|
||||
|
||||
interface SaveAvatarFieldProps {
|
||||
readonly copyId: string;
|
||||
readonly avatar: string;
|
||||
readonly disabled: boolean;
|
||||
readonly onError: (error: unknown) => void;
|
||||
}
|
||||
|
||||
export function SaveAvatarField({ copyId, avatar, disabled, onError }: SaveAvatarFieldProps) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const [choices, setChoices] = useState<SaveAvatarChoices | null>(null);
|
||||
const [selected, setSelected] = useState(avatar);
|
||||
const [preview, setPreview] = useState<{ id: string; data: string } | null>(null);
|
||||
const canPreview = choices?.some(({ id }) => id === selected) ?? false;
|
||||
|
||||
useEffect(() => {
|
||||
setSelected(avatar);
|
||||
}, [avatar]);
|
||||
|
||||
useEffect(() => {
|
||||
let mounted = true;
|
||||
ipcInvoke('saves:avatars', { copyId })
|
||||
.then((value) => { if (mounted) setChoices(value); })
|
||||
.catch((error: unknown) => {
|
||||
if (mounted) {
|
||||
setChoices([]);
|
||||
onError(error);
|
||||
}
|
||||
});
|
||||
return () => { mounted = false; };
|
||||
}, [copyId, onError]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!canPreview) return;
|
||||
let mounted = true;
|
||||
ipcInvoke('saves:avatarPreview', { copyId, avatar: selected })
|
||||
.then((data) => { if (mounted) setPreview(data ? { id: selected, data } : null); })
|
||||
.catch((error: unknown) => { if (mounted) onError(error); });
|
||||
return () => { mounted = false; };
|
||||
}, [canPreview, copyId, selected, onError]);
|
||||
|
||||
const label = t('saves.avatar');
|
||||
const language = i18n.language.toLowerCase().startsWith('zh') ? 'zh' : 'en';
|
||||
return (
|
||||
<Row label={label}>
|
||||
{choices === null
|
||||
? <span>{t('saves.loading')}</span>
|
||||
: choices.length === 0
|
||||
? <span>{t('saves.avatarUnavailable')}</span>
|
||||
: (
|
||||
<div className="copy-list-actions">
|
||||
{canPreview && preview?.id === selected && (
|
||||
<img src={`data:image/avif;base64,${preview.data}`} width={48} height={48} alt="" />
|
||||
)}
|
||||
<select className="select" aria-label={label} name="avatar" value={selected} disabled={disabled}
|
||||
onChange={(event) => setSelected(event.currentTarget.value)}>
|
||||
{!canPreview && <option value={selected} disabled>{t('saves.avatarUnavailable')}</option>}
|
||||
{choices.map(({ id, name }) => <option key={id} value={id}>{name[language]}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
)}
|
||||
</Row>
|
||||
);
|
||||
}
|
||||
@@ -11,7 +11,7 @@ interface Props {
|
||||
readonly onError: (error: unknown) => void;
|
||||
}
|
||||
|
||||
const ACTIONS = ['purchase', 'equipment'] as const;
|
||||
const ACTIONS = ['research', 'purchase', 'equipment'] as const;
|
||||
|
||||
export function SaveResearch({ copyId, userId, readOnly, onError }: Props) {
|
||||
const { t, i18n } = useTranslation();
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
import { useEffect, useState, type FormEvent } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import type { InstallRecord } from '@shared/schemas/install.ts';
|
||||
import type { AccountEdits, CurrencyEdits, SaveDetails, SaveList, SaveTransfer } from '@shared/schemas/saves.ts';
|
||||
import type { CurrencyEdits, SaveDetails, SaveList, SaveTransfer } from '@shared/schemas/saves.ts';
|
||||
import { Row } from '../../components/Row.tsx';
|
||||
import { Sheet } from '../../components/Sheet.tsx';
|
||||
import { ipcInvoke } from '../../ipc.ts';
|
||||
import type { SaveSection } from '../../shell/navigation.ts';
|
||||
import { OfficialSaveImport } from './OfficialSaveImport.tsx';
|
||||
import { SaveAvatarField } from './SaveAvatarField.tsx';
|
||||
import { SaveResearch } from './SaveResearch.tsx';
|
||||
import { SaveBackups } from './SaveBackups.tsx';
|
||||
|
||||
@@ -66,13 +65,6 @@ export function SavesPage({ copy, copies, section, readOnly, onError }: SavesPag
|
||||
setList((current) => current && { ...current, saves: current.saves.map((save) => save.userId === updated.save.userId ? updated.save : save) });
|
||||
};
|
||||
|
||||
const refreshSave = (): void => {
|
||||
ipcInvoke('saves:list', { copyId: copy.id }).then(setList).catch(onError);
|
||||
if (userId) {
|
||||
ipcInvoke('saves:details', { copyId: copy.id, userId }).then(updateDetails).catch(onError);
|
||||
}
|
||||
};
|
||||
|
||||
const submitNew = (event: FormEvent<HTMLFormElement>): void => {
|
||||
event.preventDefault();
|
||||
const data = new FormData(event.currentTarget);
|
||||
@@ -90,46 +82,23 @@ export function SavesPage({ copy, copies, section, readOnly, onError }: SavesPag
|
||||
.catch(onError)
|
||||
.finally(() => setSaving(false));
|
||||
};
|
||||
const submitOverview = (event: FormEvent<HTMLFormElement>): void => {
|
||||
const submitEdits = (event: FormEvent<HTMLFormElement>): void => {
|
||||
event.preventDefault();
|
||||
if (!details || !userId) return;
|
||||
if (!userId) return;
|
||||
const data = new FormData(event.currentTarget);
|
||||
|
||||
const nick = String(data.get('nick') ?? '').trim();
|
||||
const days = String(data.get('premiumDays') ?? '').trim();
|
||||
const avatar = String(data.get('avatar') ?? '');
|
||||
const level = String(data.get('level') ?? '').trim();
|
||||
const accountEdits: AccountEdits = {};
|
||||
if (nick && nick !== details.save.nick) accountEdits.nick = nick;
|
||||
if (avatar && avatar !== details.save.avatar) accountEdits.avatar = avatar;
|
||||
if (level !== '' && Number(level) !== details.save.level) accountEdits.level = Number(level);
|
||||
if (days !== '' && Number(days) !== details.save.premiumDays) accountEdits.premiumDays = Number(days);
|
||||
|
||||
const currencyValues: CurrencyEdits = {};
|
||||
const values: CurrencyEdits = {};
|
||||
for (const name of CURRENCIES) {
|
||||
const value = String(data.get(name) ?? '').trim();
|
||||
if (value) currencyValues[name] = name === 'gjnCents' ? Math.round(Number(value) * 100) : Number(value);
|
||||
if (value) values[name] = name === 'gjnCents' ? Math.round(Number(value) * 100) : Number(value);
|
||||
}
|
||||
|
||||
const hasAccount = Object.keys(accountEdits).length > 0;
|
||||
const hasCurrencies = Object.keys(currencyValues).length > 0;
|
||||
if (!hasAccount && !hasCurrencies) return;
|
||||
|
||||
if (Object.keys(values).length === 0) return;
|
||||
setSaving(true);
|
||||
setMessage('');
|
||||
(async () => {
|
||||
let updated: SaveDetails | null = null;
|
||||
if (hasAccount) {
|
||||
updated = await ipcInvoke('saves:editAccount', { copyId: copy.id, userId, edits: accountEdits });
|
||||
}
|
||||
if (hasCurrencies) {
|
||||
updated = await ipcInvoke('saves:editCurrencies', { copyId: copy.id, userId, values: currencyValues });
|
||||
}
|
||||
if (updated) {
|
||||
ipcInvoke('saves:editCurrencies', { copyId: copy.id, userId, values })
|
||||
.then((updated) => {
|
||||
updateDetails(updated);
|
||||
setMessage(t('saves.saved'));
|
||||
}
|
||||
})()
|
||||
})
|
||||
.catch(onError)
|
||||
.finally(() => setSaving(false));
|
||||
};
|
||||
@@ -193,7 +162,6 @@ export function SavesPage({ copy, copies, section, readOnly, onError }: SavesPag
|
||||
</div>
|
||||
<dl className="kv">
|
||||
<dt>{t('saves.login')}</dt><dd>{save.login}</dd>
|
||||
<dt>{t('saves.level')}</dt><dd>{save.level === null ? '—' : format.format(save.level)}</dd>
|
||||
<dt>{t('saves.silverLions')}</dt><dd>{save.currencies ? format.format(save.currencies.silverLions) : '—'}</dd>
|
||||
<dt>{t('saves.vehicles')}</dt><dd>{format.format(save.vehicleCount)}</dd>
|
||||
<dt>{t('saves.battles')}</dt><dd>{format.format(save.battleCount)}</dd>
|
||||
@@ -239,43 +207,16 @@ export function SavesPage({ copy, copies, section, readOnly, onError }: SavesPag
|
||||
|
||||
if (!details) return <Sheet title={title} aside={copy.name}><p className="lead">{t(userId ? 'saves.loading' : 'saves.empty')}</p></Sheet>;
|
||||
const { save } = details;
|
||||
const language = i18n.language.toLowerCase().startsWith('zh') ? 'zh' : 'en';
|
||||
const vehicleSeparator = language === 'zh' ? '、' : ', ';
|
||||
const overviewKey = JSON.stringify([
|
||||
copy.id,
|
||||
save.userId,
|
||||
save.nick,
|
||||
save.avatar,
|
||||
save.level,
|
||||
save.premiumDays,
|
||||
save.currencies?.silverLions,
|
||||
save.currencies?.goldenEagles,
|
||||
save.currencies?.gjnCents,
|
||||
save.currencies?.freeRp,
|
||||
]);
|
||||
return (
|
||||
<Sheet title={title} aside={save.nick}>
|
||||
{section === 'overview' && (
|
||||
<>
|
||||
{readOnly && <p className="small">{t('saves.readOnly')}</p>}
|
||||
<Row label={t('saves.login')}>{save.login}</Row>
|
||||
<Row label={t('saves.premiumDays')}>{format.format(save.premiumDays)}</Row>
|
||||
<Row label={t('saves.vehicles')}>{format.format(save.vehicleCount)}</Row>
|
||||
<Row label={t('saves.battles')}>{format.format(save.battleCount)}</Row>
|
||||
<form key={overviewKey} onSubmit={submitOverview}>
|
||||
<Row label={t('saves.nick')}>
|
||||
<input className="input" aria-label={t('saves.nick')} name="nick" defaultValue={save.nick} disabled={readOnly || saving} required />
|
||||
</Row>
|
||||
<SaveAvatarField copyId={copy.id} avatar={save.avatar} disabled={readOnly || saving} onError={onError} />
|
||||
<Row label={t('saves.level')}>
|
||||
{details.maxLevel === null ? '—' : (
|
||||
<input className="input" aria-label={t('saves.level')} type="number" min="0" max={details.maxLevel}
|
||||
step="1" name="level" defaultValue={save.level ?? ''} disabled={readOnly || saving} />
|
||||
)}
|
||||
</Row>
|
||||
<Row label={t('saves.premiumDays')}>
|
||||
<input className="input" aria-label={t('saves.premiumDays')} type="number" min="0" step="1"
|
||||
name="premiumDays" defaultValue={save.premiumDays} disabled={readOnly || saving} />
|
||||
</Row>
|
||||
<form key={save.userId} onSubmit={submitEdits}>
|
||||
{CURRENCIES.map((name) => (
|
||||
<Row key={name} label={t(`saves.${name}`)}>
|
||||
<span>{save.currencies ? format.format(name === 'gjnCents' ? save.currencies[name] / 100 : save.currencies[name]) : '—'}</span>
|
||||
@@ -283,35 +224,21 @@ export function SavesPage({ copy, copies, section, readOnly, onError }: SavesPag
|
||||
aria-label={t(`saves.${name}`)} disabled={readOnly || saving} />
|
||||
</Row>
|
||||
))}
|
||||
<div className="save-overview-actions">
|
||||
<button type="submit" className="button button-primary" disabled={readOnly || saving}>{t('saves.apply')}</button>
|
||||
{message && <p className="small" role="status">{message}</p>}
|
||||
</div>
|
||||
<button type="submit" className="button button-primary" disabled={readOnly || saving}>{t('saves.apply')}</button>
|
||||
{message && <p className="small" role="status">{message}</p>}
|
||||
</form>
|
||||
</>
|
||||
)}
|
||||
{section === 'battles' && (
|
||||
details.battles.length === 0 ? <p className="lead">{t('saves.noBattles')}</p> : details.battles.map((battle) => {
|
||||
const missionText = battle.missionName[language] || battle.mission || battle.mode;
|
||||
const vehiclesText = battle.vehicleNames.map((entry) => entry[language]).join(vehicleSeparator);
|
||||
return (
|
||||
<Row key={battle.id} label={missionText} hint={date(battle.time)}>
|
||||
<div className="battle-row">
|
||||
<div className="battle-summary">
|
||||
<span className={battle.won === true ? 'ok' : battle.won === false ? 'warn' : undefined}>
|
||||
{battle.won === null ? '—' : t(battle.won ? 'saves.win' : 'saves.loss')}
|
||||
</span>
|
||||
<span>{t('saves.battleRewards', { sl: format.format(battle.silverLions), rp: format.format(battle.researchPoints) })}</span>
|
||||
</div>
|
||||
{vehiclesText && <div className="battle-vehicles">{vehiclesText}</div>}
|
||||
</div>
|
||||
</Row>
|
||||
);
|
||||
})
|
||||
)}
|
||||
{section === 'official' && (
|
||||
<OfficialSaveImport key={save.userId} copyId={copy.id} userId={save.userId} readOnly={readOnly} onError={onError} onImported={refreshSave} />
|
||||
details.battles.length === 0 ? <p className="lead">{t('saves.noBattles')}</p> : details.battles.map((battle) => (
|
||||
<Row key={battle.id} label={battle.mission || battle.mode} hint={date(battle.time)}>
|
||||
<span>{battle.won === null ? '—' : t(battle.won ? 'saves.win' : 'saves.loss')}</span>
|
||||
<span>{t('saves.battleRewards', { sl: format.format(battle.silverLions), rp: format.format(battle.researchPoints) })}</span>
|
||||
<span>{battle.vehicles.join(', ')}</span>
|
||||
</Row>
|
||||
))
|
||||
)}
|
||||
{section === 'official' && <OfficialSaveImport key={save.userId} copyId={copy.id} userId={save.userId} readOnly={readOnly} onError={onError} />}
|
||||
{section === 'backup' && <SaveBackups key={save.userId} copyId={copy.id} userId={save.userId} readOnly={readOnly} onError={onError} onRestored={updateDetails} />}
|
||||
{section === 'vehicles' && <SaveResearch key={save.userId} copyId={copy.id} userId={save.userId} readOnly={readOnly} onError={onError} />}
|
||||
</Sheet>
|
||||
|
||||
@@ -1,25 +1,19 @@
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import type { Settings } from '@shared/schemas/settings.ts';
|
||||
import { Row } from '../../components/Row.tsx';
|
||||
import { Sheet } from '../../components/Sheet.tsx';
|
||||
import { ipcInvoke } from '../../ipc.ts';
|
||||
|
||||
interface DiagnosticsSettingsProps {
|
||||
readonly settings: Settings;
|
||||
readonly serverRunning: boolean;
|
||||
readonly onError: (error: unknown) => void;
|
||||
}
|
||||
|
||||
export function DiagnosticsSettings({ settings, onError, serverRunning }: DiagnosticsSettingsProps) {
|
||||
export function DiagnosticsSettings({ onError, serverRunning }: DiagnosticsSettingsProps) {
|
||||
const { t } = useTranslation();
|
||||
const [exporting, setExporting] = useState(false);
|
||||
const [savedPath, setSavedPath] = useState<string | null>(null);
|
||||
|
||||
const updateLogging = (loggingEnabled: boolean): void => {
|
||||
ipcInvoke('settings:update', { loggingEnabled }).catch(onError);
|
||||
};
|
||||
|
||||
async function save(): Promise<void> {
|
||||
setExporting(true);
|
||||
setSavedPath(null);
|
||||
@@ -35,16 +29,6 @@ export function DiagnosticsSettings({ settings, onError, serverRunning }: Diagno
|
||||
|
||||
return (
|
||||
<Sheet title={t('settings.sections.diag')}>
|
||||
<Row label={t('settings.diagnostics.recordLogs')} hint={t('settings.diagnostics.recordLogsHint')}>
|
||||
<label className="check check-inline">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={settings.loggingEnabled}
|
||||
onChange={(event) => updateLogging(event.target.checked)}
|
||||
/>
|
||||
{t('settings.diagnostics.recordLogsToggle')}
|
||||
</label>
|
||||
</Row>
|
||||
<Row label={t('settings.diagnostics.logs')} hint={t('settings.diagnostics.logsHint')}>
|
||||
<button type="button" className="button" onClick={() => ipcInvoke('app:openLogsFolder').catch(onError)}>
|
||||
{t('settings.diagnostics.openLogs')}
|
||||
@@ -60,7 +44,6 @@ export function DiagnosticsSettings({ settings, onError, serverRunning }: Diagno
|
||||
{t('settings.diagnostics.openStatus')}
|
||||
</button>
|
||||
</Row>
|
||||
{!settings.loggingEnabled && <p className="small">{t('settings.diagnostics.loggingDisabledNotice')}</p>}
|
||||
{savedPath && <p className="small" role="status">{t('settings.diagnostics.saved', { path: savedPath })}</p>}
|
||||
</Sheet>
|
||||
);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { BACKGROUND_RANDOM, type BackgroundPicture } from '@shared/schemas/background.ts';
|
||||
import { UpdateMirrorUrlSchema, type Settings } from '@shared/schemas/settings.ts';
|
||||
import type { Settings } from '@shared/schemas/settings.ts';
|
||||
import { Row } from '../../components/Row.tsx';
|
||||
import { Sheet } from '../../components/Sheet.tsx';
|
||||
import { ipcInvoke } from '../../ipc.ts';
|
||||
@@ -9,13 +9,12 @@ import { LanguageMenu } from '../../shell/LanguageMenu.tsx';
|
||||
|
||||
interface GeneralSettingsProps {
|
||||
readonly settings: Settings;
|
||||
readonly appUpdatesSupported: boolean;
|
||||
readonly pictures: readonly BackgroundPicture[];
|
||||
readonly onError: (error: unknown) => void;
|
||||
}
|
||||
|
||||
/** General launcher settings: language and background picture. */
|
||||
export function GeneralSettings({ settings, appUpdatesSupported, pictures, onError }: GeneralSettingsProps) {
|
||||
export function GeneralSettings({ settings, pictures, onError }: GeneralSettingsProps) {
|
||||
const { t } = useTranslation();
|
||||
const update = (patch: Partial<Settings>): void => {
|
||||
ipcInvoke('settings:update', patch).catch(onError);
|
||||
@@ -57,46 +56,12 @@ export function GeneralSettings({ settings, appUpdatesSupported, pictures, onErr
|
||||
{t('background.officialToggle')}
|
||||
</label>
|
||||
</Row>
|
||||
{appUpdatesSupported && (
|
||||
<Row label={t('settings.appUpdates')}>
|
||||
<label className="check check-inline">
|
||||
<input type="checkbox" checked={settings.checkLauncherUpdatesOnStart} onChange={(event) => update({ checkLauncherUpdatesOnStart: event.target.checked })} />
|
||||
{t('settings.appUpdatesToggle')}
|
||||
</label>
|
||||
</Row>
|
||||
)}
|
||||
<Row label={t('settings.patchPacks')} hint={t('settings.patchPacksHint')}>
|
||||
<label className="check check-inline">
|
||||
<input type="checkbox" checked={settings.checkPatchPacksOnStart} onChange={(event) => update({ checkPatchPacksOnStart: event.target.checked })} />
|
||||
{t('settings.patchPacksToggle')}
|
||||
</label>
|
||||
</Row>
|
||||
<Row label={t('settings.updateMirror')} hint={t('settings.updateMirrorHint')}>
|
||||
<input
|
||||
className="select"
|
||||
aria-label={t('settings.updateMirror')}
|
||||
type="url"
|
||||
autoComplete="off"
|
||||
spellCheck={false}
|
||||
placeholder="https://…"
|
||||
defaultValue={settings.updateMirrorUrl}
|
||||
key={settings.updateMirrorUrl}
|
||||
onChange={(event) => event.currentTarget.setCustomValidity('')}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Enter') event.currentTarget.blur();
|
||||
}}
|
||||
onBlur={(event) => {
|
||||
const input = event.currentTarget;
|
||||
const parsed = UpdateMirrorUrlSchema.safeParse(input.value);
|
||||
if (!parsed.success) {
|
||||
input.setCustomValidity(t('settings.updateMirrorInvalid'));
|
||||
input.reportValidity();
|
||||
return;
|
||||
}
|
||||
if (parsed.data !== settings.updateMirrorUrl) update({ updateMirrorUrl: parsed.data });
|
||||
}}
|
||||
/>
|
||||
</Row>
|
||||
<h3 className="section-title section-title-spaced">{t('background.title')}</h3>
|
||||
<p className="small">{t('background.hint')}</p>
|
||||
{pictures.length === 0 ? (
|
||||
|
||||
@@ -1,100 +1,28 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import type { IpcOutput } from '@shared/ipc/contract.ts';
|
||||
import { parseLaunchArguments } from '@shared/launch-arguments.ts';
|
||||
import { LAUNCH_ARGUMENTS_LIMIT, type Settings, type SettingsPatch } from '@shared/schemas/settings.ts';
|
||||
import { Row } from '../../components/Row.tsx';
|
||||
import { Sheet } from '../../components/Sheet.tsx';
|
||||
import { ipcInvoke } from '../../ipc.ts';
|
||||
|
||||
interface LaunchSettingsProps {
|
||||
readonly settings: Settings;
|
||||
readonly development: boolean;
|
||||
readonly onError: (error: unknown) => void;
|
||||
}
|
||||
|
||||
export function LaunchSettings({ settings, development, onError }: LaunchSettingsProps) {
|
||||
export function LaunchSettings({ onError }: { readonly onError: (error: unknown) => void }) {
|
||||
const { t } = useTranslation();
|
||||
const [lab, setLab] = useState<IpcOutput<'launch:getLabInfo'>>(null);
|
||||
const useLab = development && settings.developerMode;
|
||||
useEffect(() => {
|
||||
if (!useLab) return;
|
||||
let mounted = true;
|
||||
ipcInvoke('launch:getLabInfo').then((info) => {
|
||||
if (mounted) setLab(info);
|
||||
}).catch(onError);
|
||||
return () => { mounted = false; };
|
||||
}, [onError, useLab]);
|
||||
|
||||
const update = (patch: SettingsPatch): void => { ipcInvoke('settings:update', patch).catch(onError); };
|
||||
const title = t('settings.sections.launch');
|
||||
if (useLab) {
|
||||
return (
|
||||
<Sheet title={title}>
|
||||
<Row label={t('settings.launch.port')} hint={t('settings.launch.portHint')}>{lab?.port ?? '—'}</Row>
|
||||
<Row label={t('settings.launch.exit')} hint={t('settings.launch.exitHint')}>{t('settings.launch.automatic')}</Row>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
}, [onError]);
|
||||
|
||||
return (
|
||||
<Sheet title={title}>
|
||||
<Row label={t('settings.launch.port')}>
|
||||
<select
|
||||
className="select"
|
||||
aria-label={t('settings.launch.portMode')}
|
||||
value={settings.launchPortMode}
|
||||
onChange={(event) => update({ launchPortMode: event.currentTarget.value === 'fixed' ? 'fixed' : 'auto' })}
|
||||
>
|
||||
<option value="auto">{t('settings.launch.autoPort')}</option>
|
||||
<option value="fixed">{t('settings.launch.fixedPort')}</option>
|
||||
</select>
|
||||
<input
|
||||
className="select"
|
||||
aria-label={t('settings.launch.port')}
|
||||
type="number"
|
||||
min={1}
|
||||
max={65535}
|
||||
required
|
||||
disabled={settings.launchPortMode === 'auto'}
|
||||
defaultValue={settings.launchPort}
|
||||
key={settings.launchPort}
|
||||
onBlur={(event) => {
|
||||
const input = event.currentTarget;
|
||||
if (!input.reportValidity()) return;
|
||||
if (settings.launchPort !== input.valueAsNumber) update({ launchPort: input.valueAsNumber });
|
||||
}}
|
||||
/>
|
||||
<Sheet title={t('settings.sections.launch')}>
|
||||
<Row label={t('settings.launch.port')} hint={t('settings.launch.portHint')}>
|
||||
{lab?.port ?? '—'}
|
||||
</Row>
|
||||
<Row label={t('settings.launch.exit')}>
|
||||
<label className="check check-inline">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={settings.closeServerOnGameExit}
|
||||
onChange={(event) => update({ closeServerOnGameExit: event.currentTarget.checked })}
|
||||
/>
|
||||
{t('settings.launch.automatic')}
|
||||
</label>
|
||||
</Row>
|
||||
<Row label={t('settings.launch.arguments')} hint={t('settings.launch.argumentsHint')}>
|
||||
<input
|
||||
className="select"
|
||||
aria-label={t('settings.launch.arguments')}
|
||||
placeholder="-windowed"
|
||||
maxLength={LAUNCH_ARGUMENTS_LIMIT}
|
||||
defaultValue={settings.launchArguments}
|
||||
key={settings.launchArguments}
|
||||
onChange={(event) => event.currentTarget.setCustomValidity('')}
|
||||
onBlur={(event) => {
|
||||
const input = event.currentTarget;
|
||||
if (!parseLaunchArguments(input.value)) {
|
||||
input.setCustomValidity(t('settings.launch.argumentsInvalid'));
|
||||
input.reportValidity();
|
||||
return;
|
||||
}
|
||||
if (input.value !== settings.launchArguments) update({ launchArguments: input.value });
|
||||
}}
|
||||
/>
|
||||
<Row label={t('settings.launch.exit')} hint={t('settings.launch.exitHint')}>
|
||||
{t('settings.launch.automatic')}
|
||||
</Row>
|
||||
</Sheet>
|
||||
);
|
||||
|
||||
@@ -11,7 +11,7 @@ type Field = keyof TuningValues;
|
||||
type Draft = Partial<Record<Field, string | boolean>>;
|
||||
const fields = {
|
||||
rewards: ['rewardMultiplierSilverLions', 'rewardMultiplierResearchPoints', 'friendlyKillPenaltyMul'],
|
||||
battle: ['maxPlayers', 'smallTeamsMaxPlayers', 'brSpreadMrank', 'subModeChance', 'tankBotRespawns', 'airBotRespawns', 'strikeUcavSpawnScore', 'nuclearEscalationStrategicBombers'],
|
||||
battle: ['maxPlayers', 'smallTeamsMaxPlayers', 'brSpreadMrank', 'subModeChance', 'tankBotRespawns', 'airBotRespawns', 'strikeUcavSpawnScore'],
|
||||
newProfile: ['silverLions', 'goldenEagles'],
|
||||
research: ['preferLineSuccessor', 'autoTargetPick'],
|
||||
} as const satisfies Record<TuningSection, readonly Field[]>;
|
||||
@@ -70,7 +70,7 @@ export function TuningPage({ copy, section, onError }: Props) {
|
||||
const editor = (field: Field): ReactNode => {
|
||||
const active = draft[field] ?? inputValue(field, loaded.effective[field]);
|
||||
const label = t(`tuning.fields.${field}`);
|
||||
if (typeof loaded.defaults[field] === 'boolean') {
|
||||
if (field === 'preferLineSuccessor') {
|
||||
return <input type="checkbox" aria-label={label} disabled={saving} checked={active === true} onChange={(event) => set(field, event.target.checked)} />;
|
||||
}
|
||||
if (field === 'autoTargetPick') {
|
||||
|
||||
@@ -11,10 +11,8 @@ export function BottomBar({ model }: { readonly model: BarModel }) {
|
||||
<div className="status" role="status">
|
||||
<span className={`status-icon status-icon-${tone}`} aria-hidden="true">{TONE_MARKS[tone]}</span>
|
||||
<div className="status-text">
|
||||
<div className="status-title" data-ellipsis-tip={title}>{title}</div>
|
||||
{detail !== undefined && (
|
||||
<div className="status-detail" data-ellipsis-tip={typeof detail === 'string' ? detail : undefined}>{detail}</div>
|
||||
)}
|
||||
<div className="status-title">{title}</div>
|
||||
{detail !== undefined && <div className="status-detail">{detail}</div>}
|
||||
</div>
|
||||
</div>
|
||||
{secondary && (
|
||||
|
||||
@@ -7,31 +7,21 @@ interface FooterProps {
|
||||
readonly copyName: string | null;
|
||||
/** A newer adaptation pack that this launcher can use, or null. */
|
||||
readonly packUpdate: string | null;
|
||||
readonly appUpdate: string | null;
|
||||
readonly onOpenUpdates: () => void;
|
||||
readonly onOpenPackUpdate: () => void;
|
||||
}
|
||||
|
||||
/** Launcher and game versions along the bottom edge; on the right, available updates. */
|
||||
export function Footer({ launcherVersion, gameVersion, copyName, packUpdate, appUpdate, onOpenUpdates }: FooterProps) {
|
||||
/** Launcher and game versions along the bottom edge; on the right, an available adaptation pack. */
|
||||
export function Footer({ launcherVersion, gameVersion, copyName, packUpdate, onOpenPackUpdate }: FooterProps) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<footer className="footer">
|
||||
<span>{t('footer.launcher', { version: launcherVersion })}</span>
|
||||
<span className="footer-separator">|</span>
|
||||
<span className="footer-copy">{copyName ? t('footer.game', { name: copyName, version: gameVersion ?? t('source.versionUnknown') }) : t('footer.notInstalled')}</span>
|
||||
{(appUpdate || packUpdate) && (
|
||||
<div className="footer-updates">
|
||||
{appUpdate && (
|
||||
<button type="button" className="footer-update" onClick={onOpenUpdates}>
|
||||
{t('footer.appUpdate', { version: appUpdate })}
|
||||
</button>
|
||||
)}
|
||||
{packUpdate && (
|
||||
<button type="button" className="footer-update" onClick={onOpenUpdates}>
|
||||
{t('footer.packUpdate', { version: packUpdate })}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{packUpdate && (
|
||||
<button type="button" className="footer-update" onClick={onOpenPackUpdate}>
|
||||
{t('footer.packUpdate', { version: packUpdate })}
|
||||
</button>
|
||||
)}
|
||||
</footer>
|
||||
);
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import type { LanguageChoice } from '@shared/languages.ts';
|
||||
import { Wordmark } from '../components/Wordmark.tsx';
|
||||
import { ipcInvoke } from '../ipc.ts';
|
||||
import { LanguageMenu } from './LanguageMenu.tsx';
|
||||
import { PAGES, type PageId } from './navigation.ts';
|
||||
@@ -20,7 +19,7 @@ export function TitleBar({ page, navigationEnabled, language, onNavigate, onErro
|
||||
return (
|
||||
<header className="titlebar">
|
||||
<div className="logo">
|
||||
<Wordmark className="logo-mark" />
|
||||
<div className="logo-word">WT<span>OFFLINE</span></div>
|
||||
<div className="logo-sub">{t('app.subtitle')}</div>
|
||||
</div>
|
||||
<nav className="nav">
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
/**
|
||||
* The window's pages and the sections of those that have a section list in the side panel.
|
||||
* Pages for later features (saves, tuning) join this list when they are built.
|
||||
*/
|
||||
|
||||
export const PAGES = ['home', 'saves', 'tuning', 'mods', 'copies', 'settings', 'about'] as const;
|
||||
export const PAGES = ['home', 'saves', 'tuning', 'copies', 'settings', 'about'] as const;
|
||||
export type PageId = (typeof PAGES)[number];
|
||||
|
||||
export const SAVE_SECTIONS = ['list', 'overview', 'battles', 'vehicles', 'official', 'backup'] as const;
|
||||
@@ -11,9 +12,6 @@ export type SaveSection = (typeof SAVE_SECTIONS)[number];
|
||||
export const TUNING_SECTIONS = ['rewards', 'battle', 'newProfile', 'research'] as const;
|
||||
export type TuningSection = (typeof TUNING_SECTIONS)[number];
|
||||
|
||||
export const MODS_SECTIONS = ['list', 'presets'] as const;
|
||||
export type ModsSection = (typeof MODS_SECTIONS)[number];
|
||||
|
||||
export const COPY_SECTIONS = ['list', 'summary', 'features', 'maintain'] as const;
|
||||
export type CopySection = (typeof COPY_SECTIONS)[number];
|
||||
|
||||
@@ -25,25 +23,16 @@ export interface Route {
|
||||
readonly copies: CopySection;
|
||||
readonly saves: SaveSection;
|
||||
readonly tuning: TuningSection;
|
||||
readonly mods: ModsSection;
|
||||
readonly settings: SettingsSection;
|
||||
}
|
||||
|
||||
export const START_ROUTE: Route = {
|
||||
page: 'home',
|
||||
saves: 'list',
|
||||
tuning: 'rewards',
|
||||
mods: 'list',
|
||||
copies: 'list',
|
||||
settings: 'general',
|
||||
};
|
||||
export const START_ROUTE: Route = { page: 'home', saves: 'list', tuning: 'rewards', copies: 'list', settings: 'general' };
|
||||
|
||||
/** Where a link points: a page, and for pages with sections, which one. */
|
||||
export type Destination =
|
||||
| { readonly page: 'home' | 'about' }
|
||||
| { readonly page: 'saves'; readonly section?: SaveSection }
|
||||
| { readonly page: 'tuning'; readonly section?: TuningSection }
|
||||
| { readonly page: 'mods'; readonly section?: ModsSection }
|
||||
| { readonly page: 'copies'; readonly section?: CopySection }
|
||||
| { readonly page: 'settings'; readonly section?: SettingsSection };
|
||||
|
||||
@@ -53,8 +42,6 @@ export function navigate(route: Route, to: Destination): Route {
|
||||
return { ...route, page: 'saves', saves: to.section ?? route.saves };
|
||||
case 'tuning':
|
||||
return { ...route, page: 'tuning', tuning: to.section ?? route.tuning };
|
||||
case 'mods':
|
||||
return { ...route, page: 'mods', mods: to.section ?? route.mods };
|
||||
case 'copies':
|
||||
return { ...route, page: 'copies', copies: to.section ?? route.copies };
|
||||
case 'settings':
|
||||
|
||||
@@ -1,43 +0,0 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import type { AppUpdateCheck, AppUpdateProgress } from '@shared/schemas/app-update.ts';
|
||||
import { AppIpcError, ipcInvoke, ipcOn } from '../ipc.ts';
|
||||
|
||||
export function useAppUpdate(supported: boolean, checkOnStart: boolean, onError: (error: unknown) => void) {
|
||||
const [check, setCheck] = useState<AppUpdateCheck | null>(null);
|
||||
const [progress, setProgress] = useState<AppUpdateProgress | null>(null);
|
||||
const [busy, setBusy] = useState<'checking' | 'downloading' | 'installing' | null>(null);
|
||||
const started = useRef(false);
|
||||
|
||||
useEffect(() => ipcOn('event:app-update-progress', setProgress), []);
|
||||
|
||||
const checkNow = useCallback(() => {
|
||||
setBusy('checking');
|
||||
ipcInvoke('updates:check').then(setCheck).catch(onError).finally(() => setBusy(null));
|
||||
}, [onError]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!supported || !checkOnStart || started.current) return;
|
||||
started.current = true;
|
||||
checkNow();
|
||||
}, [supported, checkOnStart, checkNow]);
|
||||
|
||||
const download = (version: string): void => {
|
||||
setProgress(null);
|
||||
setBusy('downloading');
|
||||
ipcInvoke('updates:download', { version }).then(setCheck).catch(onError).finally(() => setBusy(null));
|
||||
};
|
||||
|
||||
const install = (version: string): void => {
|
||||
setBusy('installing');
|
||||
ipcInvoke('updates:install', { version }).catch((error: unknown) => {
|
||||
if (error instanceof AppIpcError && error.code === 'app_update_installer_invalid') {
|
||||
setCheck((previous) => previous?.status === 'available' ? { ...previous, ready: false } : previous);
|
||||
}
|
||||
onError(error);
|
||||
}).finally(() => setBusy(null));
|
||||
};
|
||||
|
||||
return { supported, check, progress, busy, checkNow, download, install };
|
||||
}
|
||||
|
||||
export type AppUpdateState = ReturnType<typeof useAppUpdate>;
|
||||
@@ -52,11 +52,9 @@ export function usePatchPack(checkOnStart: boolean, onError: (error: unknown) =>
|
||||
}, [checkOnStart, checkNow]);
|
||||
|
||||
const apply = useCallback((): void => {
|
||||
const version = check?.status === 'available' ? check.latest?.version : undefined;
|
||||
if (!version) return;
|
||||
setBusy('applying');
|
||||
setApplyFailure(null);
|
||||
ipcInvoke('patches:apply', { version })
|
||||
ipcInvoke('patches:apply')
|
||||
.then((result) => {
|
||||
if (!result.ok) {
|
||||
setApplyFailure(result.problem);
|
||||
@@ -67,7 +65,7 @@ export function usePatchPack(checkOnStart: boolean, onError: (error: unknown) =>
|
||||
})
|
||||
.catch(onError)
|
||||
.finally(() => setBusy(null));
|
||||
}, [check, onError]);
|
||||
}, [onError]);
|
||||
|
||||
const useBundled = useCallback((): void => {
|
||||
setBusy('reverting');
|
||||
|
||||
@@ -88,64 +88,14 @@
|
||||
left: 16px;
|
||||
right: 16px;
|
||||
bottom: 14px;
|
||||
z-index: 4;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
z-index: 2;
|
||||
margin: 0;
|
||||
padding: 8px 10px 8px 14px;
|
||||
padding: 8px 12px;
|
||||
font-size: 13px;
|
||||
color: #f6cfcc;
|
||||
background: rgba(60, 16, 14, 0.94);
|
||||
background: rgba(60, 16, 14, 0.92);
|
||||
border: 1px solid rgba(255, 110, 102, 0.45);
|
||||
border-radius: var(--radius);
|
||||
box-shadow: 0 6px 20px rgba(0, 0, 0, 0.45);
|
||||
}
|
||||
|
||||
.app-error-text {
|
||||
min-width: 0;
|
||||
line-height: 1.5;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.app-error-close {
|
||||
flex: none;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
border-radius: 2px;
|
||||
background: none;
|
||||
color: rgba(246, 207, 204, 0.8);
|
||||
font-size: 17px;
|
||||
line-height: 1;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.app-error-close:hover {
|
||||
color: var(--white);
|
||||
background: rgba(255, 255, 255, 0.12);
|
||||
}
|
||||
|
||||
/* Floating tooltip for truncated ellipsis text across the window. */
|
||||
.ellipsis-tooltip {
|
||||
position: fixed;
|
||||
z-index: 9999;
|
||||
max-width: min(480px, calc(100vw - 24px));
|
||||
padding: 6px 10px;
|
||||
font-size: 12px;
|
||||
line-height: 1.45;
|
||||
color: var(--white);
|
||||
background: rgba(14, 19, 23, 0.96);
|
||||
border: 1px solid var(--line-strong);
|
||||
border-radius: var(--radius);
|
||||
box-shadow: 0 6px 20px rgba(0, 0, 0, 0.55);
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
/* ===== Label / control rows ===== */
|
||||
@@ -162,11 +112,6 @@
|
||||
border-top: 0;
|
||||
}
|
||||
|
||||
.row-label {
|
||||
min-width: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.row-label small {
|
||||
display: block;
|
||||
margin-top: 2px;
|
||||
@@ -198,10 +143,6 @@
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.kv.install-requirements {
|
||||
grid-template-columns: max-content minmax(0, 1fr);
|
||||
}
|
||||
|
||||
.kv dt {
|
||||
color: var(--text-dim);
|
||||
}
|
||||
@@ -215,13 +156,9 @@
|
||||
|
||||
/* ===== Buttons and links ===== */
|
||||
.button {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font: 500 14px var(--font-display);
|
||||
letter-spacing: 0.04em;
|
||||
text-transform: uppercase;
|
||||
text-decoration: none;
|
||||
padding: 7px 16px;
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
@@ -412,11 +349,6 @@
|
||||
border-color: var(--line-strong);
|
||||
}
|
||||
|
||||
.choice[aria-disabled='true'] {
|
||||
cursor: default;
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
.choice-selected {
|
||||
border-color: var(--red);
|
||||
background: rgba(229, 57, 53, 0.08);
|
||||
|
||||
@@ -311,44 +311,7 @@
|
||||
margin-top: 16px;
|
||||
}
|
||||
|
||||
.save-overview-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
margin-top: 14px;
|
||||
}
|
||||
|
||||
.save-overview-actions .small {
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
.battle-row {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.battle-summary {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.battle-vehicles {
|
||||
font-size: 12.5px;
|
||||
color: var(--text-dim);
|
||||
line-height: 1.45;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
/* ===== About ===== */
|
||||
.update-notes {
|
||||
white-space: pre-line;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.about-head {
|
||||
display: flex;
|
||||
gap: 18px;
|
||||
@@ -371,461 +334,3 @@
|
||||
line-height: 1.6;
|
||||
color: var(--text-dim);
|
||||
}
|
||||
|
||||
.about-columns {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 14px;
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
.about-column {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 14px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.about-card {
|
||||
min-width: 0;
|
||||
padding: 14px 16px;
|
||||
background: rgba(0, 0, 0, 0.14);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--radius);
|
||||
}
|
||||
|
||||
.about-card-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.about-card-title {
|
||||
margin: 0;
|
||||
font: 500 14px var(--font-display);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.08em;
|
||||
color: var(--white);
|
||||
}
|
||||
|
||||
.about-card-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.about-card-meta {
|
||||
margin: 8px 0 0;
|
||||
font-size: 13px;
|
||||
line-height: 1.5;
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.about-card-label {
|
||||
color: var(--text-dim);
|
||||
}
|
||||
|
||||
.about-card .notice {
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
.about-card .notice .button {
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
/* ===== Mods ===== */
|
||||
.mods-aside {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.mods-exp-chip {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
padding: 2px 7px;
|
||||
font-size: 11.5px;
|
||||
line-height: 1.3;
|
||||
color: rgba(255, 227, 163, 0.9);
|
||||
background: rgba(214, 158, 46, 0.14);
|
||||
border: 1px solid rgba(214, 158, 46, 0.38);
|
||||
border-radius: var(--radius);
|
||||
cursor: help;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.mods-exp-chip:hover,
|
||||
.mods-exp-chip:focus-visible {
|
||||
background: rgba(214, 158, 46, 0.22);
|
||||
border-color: rgba(214, 158, 46, 0.6);
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.mods-exp-icon {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
font-size: 10px;
|
||||
font-weight: 700;
|
||||
font-style: normal;
|
||||
border-radius: 50%;
|
||||
border: 1px solid rgba(255, 227, 163, 0.55);
|
||||
}
|
||||
|
||||
.mods-exp-popover {
|
||||
position: absolute;
|
||||
top: calc(100% + 8px);
|
||||
right: 0;
|
||||
z-index: 40;
|
||||
width: 340px;
|
||||
max-width: min(340px, 70vw);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
padding: 10px 12px;
|
||||
font-size: 12px;
|
||||
line-height: 1.5;
|
||||
text-align: left;
|
||||
white-space: normal;
|
||||
color: rgba(255, 244, 218, 0.94);
|
||||
background: rgba(16, 20, 24, 0.97);
|
||||
border: 1px solid rgba(214, 158, 46, 0.5);
|
||||
border-radius: var(--radius);
|
||||
box-shadow: 0 10px 26px rgba(0, 0, 0, 0.55);
|
||||
opacity: 0;
|
||||
visibility: hidden;
|
||||
pointer-events: none;
|
||||
transform: translateY(-2px);
|
||||
transition: opacity 140ms ease, transform 140ms ease, visibility 140ms ease;
|
||||
}
|
||||
|
||||
.mods-exp-chip:hover .mods-exp-popover,
|
||||
.mods-exp-chip:focus-visible .mods-exp-popover {
|
||||
opacity: 1;
|
||||
visibility: visible;
|
||||
transform: translateY(0);
|
||||
}
|
||||
|
||||
.mods-banner {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 3px;
|
||||
padding: 10px 12px;
|
||||
margin-bottom: 12px;
|
||||
font-size: 12.5px;
|
||||
line-height: 1.5;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--radius);
|
||||
}
|
||||
|
||||
.mods-banner-warn {
|
||||
background: rgba(206, 65, 55, 0.16);
|
||||
border-color: rgba(206, 65, 55, 0.5);
|
||||
color: #ffd7d4;
|
||||
}
|
||||
|
||||
.mods-banner-ok {
|
||||
background: rgba(68, 170, 102, 0.16);
|
||||
border-color: rgba(68, 170, 102, 0.5);
|
||||
color: #d7ffe4;
|
||||
}
|
||||
|
||||
.mods-toolbar {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.mods-search {
|
||||
flex: 1 1 180px;
|
||||
min-width: 140px;
|
||||
}
|
||||
|
||||
.mods-preset-select {
|
||||
max-width: 210px;
|
||||
}
|
||||
|
||||
.mods-issues-box {
|
||||
padding: 10px 12px;
|
||||
margin-bottom: 12px;
|
||||
font-size: 12.5px;
|
||||
border-radius: var(--radius);
|
||||
border: 1px solid var(--line);
|
||||
}
|
||||
|
||||
.mods-issues-error {
|
||||
background: rgba(206, 65, 55, 0.15);
|
||||
border-color: rgba(206, 65, 55, 0.55);
|
||||
}
|
||||
|
||||
.mods-issues-warn {
|
||||
background: rgba(214, 158, 46, 0.13);
|
||||
border-color: rgba(214, 158, 46, 0.45);
|
||||
}
|
||||
|
||||
.mods-issues-title {
|
||||
font-weight: 600;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
|
||||
.mods-issues-box ul {
|
||||
margin: 0;
|
||||
padding-left: 18px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.mods-issue-tag {
|
||||
display: inline-block;
|
||||
margin-right: 6px;
|
||||
padding: 1px 5px;
|
||||
font-size: 11px;
|
||||
border-radius: 2px;
|
||||
background: rgba(255, 255, 255, 0.12);
|
||||
}
|
||||
|
||||
.mods-empty {
|
||||
padding: 20px 14px;
|
||||
text-align: center;
|
||||
border: 1px dashed var(--line);
|
||||
border-radius: var(--radius);
|
||||
}
|
||||
|
||||
.mods-hint {
|
||||
font-size: 12.5px;
|
||||
color: var(--text-dim);
|
||||
line-height: 1.5;
|
||||
margin: 6px 0 12px;
|
||||
}
|
||||
|
||||
.mods-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.mods-card {
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--radius);
|
||||
background: rgba(12, 16, 19, 0.62);
|
||||
transition: border-color 120ms ease;
|
||||
}
|
||||
|
||||
.mods-card-enabled {
|
||||
border-left: 3px solid var(--red);
|
||||
background: rgba(18, 24, 29, 0.78);
|
||||
}
|
||||
|
||||
.mods-card-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 10px 12px;
|
||||
}
|
||||
|
||||
.mods-order-num {
|
||||
min-width: 26px;
|
||||
font-size: 12px;
|
||||
color: var(--text-dim);
|
||||
text-align: right;
|
||||
cursor: grab;
|
||||
}
|
||||
|
||||
.mods-checkbox {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
flex: none;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.mods-card-main {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.mods-card-title {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.mods-name {
|
||||
font-weight: 600;
|
||||
color: var(--white);
|
||||
}
|
||||
|
||||
.mods-version,
|
||||
.mods-author {
|
||||
font-size: 12px;
|
||||
color: var(--text-dim);
|
||||
}
|
||||
|
||||
.mods-card-desc {
|
||||
margin-top: 3px;
|
||||
font-size: 12px;
|
||||
color: var(--text-dim);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.mods-badges {
|
||||
display: inline-flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.mods-badge {
|
||||
padding: 1px 6px;
|
||||
font-size: 11px;
|
||||
border-radius: 2px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.16);
|
||||
}
|
||||
|
||||
.mods-badge-data {
|
||||
background: rgba(88, 166, 255, 0.16);
|
||||
color: #b7d7ff;
|
||||
}
|
||||
|
||||
.mods-badge-gui {
|
||||
background: rgba(163, 113, 247, 0.18);
|
||||
color: #dec8ff;
|
||||
}
|
||||
|
||||
.mods-badge-script {
|
||||
background: rgba(214, 158, 46, 0.22);
|
||||
color: #ffe3a3;
|
||||
}
|
||||
|
||||
.mods-badge-exe {
|
||||
background: rgba(206, 65, 55, 0.28);
|
||||
color: #ffc2be;
|
||||
border-color: rgba(206, 65, 55, 0.55);
|
||||
}
|
||||
|
||||
.mods-badge-error {
|
||||
background: rgba(206, 65, 55, 0.35);
|
||||
color: #ffd5d2;
|
||||
}
|
||||
|
||||
.mods-badge-warn {
|
||||
background: rgba(214, 158, 46, 0.25);
|
||||
color: #ffe8b3;
|
||||
}
|
||||
|
||||
.mods-card-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
flex: none;
|
||||
}
|
||||
|
||||
.mods-move-btn {
|
||||
min-width: 28px;
|
||||
padding: 4px 6px;
|
||||
}
|
||||
|
||||
.mods-card-details {
|
||||
padding: 10px 12px 12px 48px;
|
||||
border-top: 1px solid var(--line);
|
||||
font-size: 12px;
|
||||
color: var(--text-dim);
|
||||
}
|
||||
|
||||
.mods-detail-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
|
||||
gap: 4px 12px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.mods-detail-summary {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.mods-detail-summary span {
|
||||
padding: 2px 7px;
|
||||
border-radius: 2px;
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
color: rgba(255, 255, 255, 0.85);
|
||||
}
|
||||
|
||||
.mods-section {
|
||||
margin-bottom: 22px;
|
||||
}
|
||||
|
||||
.mods-subheading {
|
||||
margin: 0 0 4px;
|
||||
font: 600 15px var(--font-display);
|
||||
color: var(--white);
|
||||
}
|
||||
|
||||
.mods-preset-form {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
margin: 10px 0 14px;
|
||||
}
|
||||
|
||||
.mods-preset-form .input {
|
||||
flex: 1 1 200px;
|
||||
}
|
||||
|
||||
.mods-preset-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.mods-preset-item {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
padding: 10px 12px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--radius);
|
||||
background: rgba(12, 16, 19, 0.62);
|
||||
}
|
||||
|
||||
.mods-preset-active {
|
||||
border-left: 3px solid var(--red);
|
||||
}
|
||||
|
||||
.mods-preset-meta {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.mods-preset-name {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-weight: 600;
|
||||
color: var(--white);
|
||||
}
|
||||
|
||||
.mods-preset-sub {
|
||||
font-size: 12px;
|
||||
color: var(--text-dim);
|
||||
margin-top: 2px;
|
||||
}
|
||||
|
||||
.mods-path {
|
||||
font-size: 12px;
|
||||
word-break: break-all;
|
||||
}
|
||||
@@ -83,30 +83,30 @@
|
||||
width: 300px;
|
||||
flex: none;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 14px;
|
||||
padding: 0 20px;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
padding: 0 22px;
|
||||
background: linear-gradient(180deg, #a00000 0%, rgba(120, 0, 0, 0.55) 55%, rgba(18, 23, 29, 0.2) 100%);
|
||||
border-right: 1px solid var(--line);
|
||||
}
|
||||
|
||||
.logo-mark {
|
||||
height: 42px;
|
||||
width: auto;
|
||||
flex: none;
|
||||
.logo-word {
|
||||
font: 700 26px/1 var(--font-display);
|
||||
color: var(--white);
|
||||
filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.55));
|
||||
letter-spacing: 0.04em;
|
||||
text-shadow: 0 1px 4px rgba(0, 0, 0, 0.6);
|
||||
}
|
||||
|
||||
.logo-word span {
|
||||
color: #ffd7d3;
|
||||
font-weight: 400;
|
||||
}
|
||||
|
||||
.logo-sub {
|
||||
font: 500 13px/1.2 var(--font-body);
|
||||
color: rgba(255, 255, 255, 0.84);
|
||||
padding-left: 12px;
|
||||
border-left: 1px solid rgba(255, 255, 255, 0.22);
|
||||
letter-spacing: 0.06em;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
font: 400 11px/1 var(--font-body);
|
||||
color: rgba(255, 255, 255, 0.72);
|
||||
margin-top: 5px;
|
||||
letter-spacing: 0.05em;
|
||||
}
|
||||
|
||||
.nav {
|
||||
@@ -550,15 +550,10 @@
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
/* Available updates at the right end. */
|
||||
.footer-updates {
|
||||
margin-left: auto;
|
||||
display: flex;
|
||||
flex: none;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
/* An available adaptation pack, at the right end. */
|
||||
.footer-update {
|
||||
margin-left: auto;
|
||||
flex: none;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: none;
|
||||
|
||||
@@ -2,30 +2,19 @@ import { useCallback, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { AppIpcError } from './ipc.ts';
|
||||
|
||||
export interface ActiveError {
|
||||
readonly id: number;
|
||||
readonly message: string;
|
||||
}
|
||||
|
||||
/** Turns a failed call into the translated message of its error code. */
|
||||
export function useErrorMessage(): {
|
||||
message: string | null;
|
||||
error: ActiveError | null;
|
||||
report: (error: unknown) => void;
|
||||
clear: () => void;
|
||||
} {
|
||||
export function useErrorMessage(): { message: string | null; report: (error: unknown) => void; clear: () => void } {
|
||||
const { t } = useTranslation();
|
||||
const [error, setError] = useState<ActiveError | null>(null);
|
||||
const [message, setMessage] = useState<string | null>(null);
|
||||
|
||||
const report = useCallback(
|
||||
(failure: unknown) => {
|
||||
console.error(failure);
|
||||
const message = failure instanceof AppIpcError ? t(`errors.${failure.code}`, failure.params) : t('errors.unknown');
|
||||
setError((previous) => ({ id: (previous?.id ?? 0) + 1, message }));
|
||||
(error: unknown) => {
|
||||
console.error(error);
|
||||
setMessage(error instanceof AppIpcError ? t(`errors.${error.code}`, error.params) : t('errors.unknown'));
|
||||
},
|
||||
[t],
|
||||
);
|
||||
const clear = useCallback(() => setError(null), []);
|
||||
const clear = useCallback(() => setMessage(null), []);
|
||||
|
||||
return { message: error?.message ?? null, error, report, clear };
|
||||
return { message, report, clear };
|
||||
}
|
||||
@@ -12,23 +12,12 @@
|
||||
export const APP_ERROR_CODES = [
|
||||
/** A bug of ours: a handler returned something its contract does not allow. */
|
||||
'internal_error',
|
||||
'app_update_unavailable',
|
||||
'app_update_busy',
|
||||
'app_update_launcher_busy',
|
||||
'app_update_download_failed',
|
||||
'app_update_installer_invalid',
|
||||
'app_update_install_failed',
|
||||
/** The launcher's own settings file could not be written. */
|
||||
'settings_write_failed',
|
||||
'logs_folder_open_failed',
|
||||
'diagnostics_export_failed',
|
||||
'copy_not_found',
|
||||
'tuning_invalid',
|
||||
'mods_read_only',
|
||||
'mods_write_failed',
|
||||
'mods_preset_invalid',
|
||||
'mods_blocking_issues',
|
||||
'mods_folder_invalid',
|
||||
'save_not_found',
|
||||
'save_archive_invalid',
|
||||
'save_official_invalid',
|
||||
@@ -39,8 +28,6 @@ export const APP_ERROR_CODES = [
|
||||
'save_login_exists',
|
||||
'save_password_invalid',
|
||||
'save_nick_invalid',
|
||||
'save_avatar_invalid',
|
||||
'save_level_invalid',
|
||||
'copies_write_failed',
|
||||
'maintenance_busy',
|
||||
'maintenance_location',
|
||||
@@ -49,42 +36,25 @@ export const APP_ERROR_CODES = [
|
||||
'maintenance_failed',
|
||||
'maintenance_source_changed',
|
||||
'copy_location_in_use',
|
||||
'decal_source_invalid',
|
||||
'decal_import_failed',
|
||||
'launch_no_copy',
|
||||
'launch_busy',
|
||||
'launch_failed',
|
||||
'launch_platform_unsupported',
|
||||
'launch_lab_required',
|
||||
'launch_lab_missing',
|
||||
'launch_lab_version',
|
||||
'launch_lab_failed',
|
||||
'launch_game_running',
|
||||
'launch_copy_in_steam',
|
||||
'launch_steam_confirmation_required',
|
||||
'launch_location',
|
||||
'launch_stock_version',
|
||||
/** The wtoffline/stock backup executable is missing or unreadable before launch. */
|
||||
'launch_stock_missing',
|
||||
'launch_build_failed',
|
||||
'launch_build_unavailable',
|
||||
'launch_port_busy',
|
||||
'launch_server_failed',
|
||||
'launch_server_exited',
|
||||
'launch_game_failed',
|
||||
/** Core files built for the launch (aces.exe, wto_ws.dll, wto_ws.cfg) are missing or unreadable. */
|
||||
'launch_game_files_missing',
|
||||
/** A folder the player chose does not exist or cannot be read (params: path). */
|
||||
'folder_unreadable',
|
||||
/** The chosen folder lacks the files of a War Thunder installation (params: path). */
|
||||
'not_a_game_folder',
|
||||
/** A patched client lacking wtoffline/stock needs an unpatched original game folder. */
|
||||
'stock_source_invalid',
|
||||
/** The chosen original game folder has a different version than the patched client. */
|
||||
'stock_source_version_mismatch',
|
||||
/** The folder chosen for the copy cannot take it (params: problem, one of TARGET_PROBLEMS). */
|
||||
'target_not_usable',
|
||||
/** A copy or data folder is inside a Steam library and the player has not confirmed the warning. */
|
||||
/** The game copy would go into a Steam library and the player has not confirmed the warning. */
|
||||
'steam_library_not_confirmed',
|
||||
/** The target drive has too little room (params: neededGb, freeGb). */
|
||||
'not_enough_space',
|
||||
@@ -96,9 +66,6 @@ export const APP_ERROR_CODES = [
|
||||
'patch_check_failed',
|
||||
/** Copying the game failed; what was copied has been removed. */
|
||||
'copy_failed',
|
||||
'hardlink_unavailable',
|
||||
'hardlink_no_match',
|
||||
'hardlink_file_changed',
|
||||
/** The player stopped the installation; what was copied has been removed. */
|
||||
'install_cancelled',
|
||||
/** An installation is already running. */
|
||||
|
||||
@@ -16,8 +16,6 @@ export const IPC_CHANNEL_PREFIXES = [
|
||||
'copies:',
|
||||
/** Settings shared by the saves of a game copy. */
|
||||
'tuning:',
|
||||
/** Additive mods repository, per-copy ordering/toggles, and presets. */
|
||||
'mods:',
|
||||
/** Local account and save management. */
|
||||
'saves:',
|
||||
/** Starting and stopping the active copy. */
|
||||
@@ -26,8 +24,6 @@ export const IPC_CHANNEL_PREFIXES = [
|
||||
'settings:',
|
||||
/** Adaptation packs: the active patch set, update checks, installing a newer pack. */
|
||||
'patches:',
|
||||
/** Checking, downloading and installing a launcher release. */
|
||||
'updates:',
|
||||
/** The launcher window itself (it draws its own title bar). */
|
||||
'window:',
|
||||
] as const;
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
import { z } from 'zod';
|
||||
import { AppReleaseVersionSchema, AppUpdateCheckSchema, AppUpdateProgressSchema } from '../schemas/app-update.ts';
|
||||
import { BackgroundPictureSchema } from '../schemas/background.ts';
|
||||
import {
|
||||
CopiesSchema,
|
||||
CopyIdSchema,
|
||||
CopyNameSchema,
|
||||
DATA_FOLDER_PROBLEMS,
|
||||
FolderSizeSchema,
|
||||
GameFolderInspectionSchema,
|
||||
InstallProgressSchema,
|
||||
@@ -17,9 +15,8 @@ import {
|
||||
} from '../schemas/install.ts';
|
||||
import { LabInfoSchema, LaunchStateSchema } from '../schemas/launch.ts';
|
||||
import { MaintenanceInfoSchema, MaintenanceProgressSchema, MaintenanceRequestSchema } from '../schemas/maintenance.ts';
|
||||
import { ModsStateViewSchema } from '../schemas/mods.ts';
|
||||
import { ActivePatchSetSchema, PackApplyResultSchema, PackCheckSchema, PackReleaseSchema } from '../schemas/patch-pack.ts';
|
||||
import { AccountEditsSchema, SaveAvatarChoicesSchema, SaveAvatarIdSchema, ResearchBranchSchema, ResearchOperationSchema, SaveResearchSchema, OfficialImportOptionsSchema, OfficialPreviewSchema, OnlineDataSourceSchema, SaveOfficialRequestSchema, CurrencyEditsSchema, SaveBackupNameSchema, SaveBackupSchema, SaveDetailsSchema, SaveKeysSchema, SaveListSchema, SaveRegistrationSchema, SaveTransferSchema } from '../schemas/saves.ts';
|
||||
import { ActivePatchSetSchema, PackApplyResultSchema, PackCheckSchema } from '../schemas/patch-pack.ts';
|
||||
import { ResearchBranchSchema, ResearchOperationSchema, SaveResearchSchema, OfficialImportOptionsSchema, OfficialPreviewSchema, SaveOfficialRequestSchema, CurrencyEditsSchema, SaveBackupNameSchema, SaveBackupSchema, SaveDetailsSchema, SaveKeysSchema, SaveListSchema, SaveRegistrationSchema, SaveTransferSchema } from '../schemas/saves.ts';
|
||||
import { TuningPatchSchema, TuningViewSchema } from '../schemas/tuning.ts';
|
||||
import { SettingsPatchSchema, SettingsSchema } from '../schemas/settings.ts';
|
||||
|
||||
@@ -37,7 +34,6 @@ export const ipcContract = {
|
||||
version: z.string(),
|
||||
electron: z.string(),
|
||||
development: z.boolean(),
|
||||
appUpdatesSupported: z.boolean(),
|
||||
/** The operating system's preferred language, as Electron reports it (e.g. "zh-CN"). */
|
||||
systemLocale: z.string(),
|
||||
userDataPath: z.string(),
|
||||
@@ -79,37 +75,16 @@ export const ipcContract = {
|
||||
output: GameFolderInspectionSchema,
|
||||
},
|
||||
'install:inspectTargetFolder': {
|
||||
input: z.object({
|
||||
path: z.string().min(1),
|
||||
stockPath: z.string().min(1),
|
||||
version: z.string().nullable().optional(),
|
||||
}),
|
||||
input: z.object({ path: z.string().min(1), stockPath: z.string().min(1) }),
|
||||
output: TargetFolderInspectionSchema,
|
||||
},
|
||||
'install:inspectDataFolder': {
|
||||
input: z.object({
|
||||
path: z.string().min(1),
|
||||
copyPath: z.string().min(1).optional(),
|
||||
sourcePath: z.string().min(1).optional(),
|
||||
stockSourcePath: z.string().min(1).optional(),
|
||||
}),
|
||||
output: z.object({
|
||||
path: z.string(),
|
||||
inSteam: z.boolean(),
|
||||
problem: z.enum(DATA_FOLDER_PROBLEMS).nullable(),
|
||||
}),
|
||||
},
|
||||
'install:measureFolder': {
|
||||
input: z.object({ path: z.string().min(1), version: z.string().nullable().optional() }),
|
||||
input: z.object({ path: z.string().min(1) }),
|
||||
output: FolderSizeSchema,
|
||||
},
|
||||
'install:checkPatches': {
|
||||
/** The game folder to install from, optional stock source folder, and the data folder whose store tuning the build uses. */
|
||||
input: z.object({
|
||||
gamePath: z.string().min(1),
|
||||
dataPath: z.string().min(1),
|
||||
stockSourcePath: z.string().min(1).optional(),
|
||||
}),
|
||||
/** The game folder to install from, and the data folder whose store tuning the build uses. */
|
||||
input: z.object({ gamePath: z.string().min(1), dataPath: z.string().min(1) }),
|
||||
output: PatchCheckSchema,
|
||||
},
|
||||
'install:start': {
|
||||
@@ -143,22 +118,10 @@ export const ipcContract = {
|
||||
input: z.object({ id: CopyIdSchema, name: CopyNameSchema }),
|
||||
output: CopiesSchema,
|
||||
},
|
||||
'copies:relocate': {
|
||||
input: z.object({ id: CopyIdSchema, path: z.string().min(1) }),
|
||||
output: CopiesSchema,
|
||||
},
|
||||
'copies:setDecalSource': {
|
||||
input: z.object({ id: CopyIdSchema, path: z.string().min(1).nullable() }),
|
||||
output: CopiesSchema,
|
||||
},
|
||||
'copies:maintenanceInfo': {
|
||||
input: z.object({ id: CopyIdSchema }),
|
||||
output: MaintenanceInfoSchema,
|
||||
},
|
||||
'copies:maintenanceState': {
|
||||
input: z.void(),
|
||||
output: MaintenanceProgressSchema.nullable(),
|
||||
},
|
||||
'copies:maintain': {
|
||||
input: MaintenanceRequestSchema,
|
||||
output: CopiesSchema,
|
||||
@@ -183,18 +146,6 @@ export const ipcContract = {
|
||||
input: SaveRegistrationSchema,
|
||||
output: SaveListSchema,
|
||||
},
|
||||
'saves:avatars': {
|
||||
input: z.object({ copyId: CopyIdSchema }),
|
||||
output: SaveAvatarChoicesSchema,
|
||||
},
|
||||
'saves:avatarPreview': {
|
||||
input: z.object({ copyId: CopyIdSchema, avatar: SaveAvatarIdSchema }),
|
||||
output: z.base64().nullable(),
|
||||
},
|
||||
'saves:editAccount': {
|
||||
input: SaveKeysSchema.extend({ edits: AccountEditsSchema }),
|
||||
output: SaveDetailsSchema,
|
||||
},
|
||||
'saves:editCurrencies': {
|
||||
input: SaveKeysSchema.extend({ values: CurrencyEditsSchema }),
|
||||
output: SaveDetailsSchema,
|
||||
@@ -227,20 +178,12 @@ export const ipcContract = {
|
||||
input: SaveKeysSchema.extend({ name: SaveBackupNameSchema }),
|
||||
output: SaveDetailsSchema,
|
||||
},
|
||||
'saves:discoverOnlineData': {
|
||||
input: z.void(),
|
||||
output: z.array(OnlineDataSourceSchema),
|
||||
},
|
||||
'saves:copyOnlineData': {
|
||||
input: SaveKeysSchema.extend({ accountId: z.string().regex(/^\d+$/) }),
|
||||
output: z.array(z.string()),
|
||||
},
|
||||
'saves:pickOfficialBackups': {
|
||||
input: z.void(),
|
||||
output: z.array(z.string()),
|
||||
},
|
||||
'saves:previewOfficial': {
|
||||
input: SaveOfficialRequestSchema,
|
||||
input: SaveOfficialRequestSchema.extend({ includeUsedVehicles: z.boolean() }),
|
||||
output: OfficialPreviewSchema,
|
||||
},
|
||||
'saves:importOfficial': {
|
||||
@@ -263,50 +206,6 @@ export const ipcContract = {
|
||||
input: z.object({ copyId: CopyIdSchema, patch: TuningPatchSchema }),
|
||||
output: TuningViewSchema,
|
||||
},
|
||||
'mods:getState': {
|
||||
input: z.object({ copyId: CopyIdSchema }),
|
||||
output: ModsStateViewSchema,
|
||||
},
|
||||
'mods:setEnabled': {
|
||||
input: z.object({ copyId: CopyIdSchema, modId: z.string().min(1), enabled: z.boolean() }),
|
||||
output: ModsStateViewSchema,
|
||||
},
|
||||
'mods:setOrder': {
|
||||
input: z.object({ copyId: CopyIdSchema, order: z.array(z.string()) }),
|
||||
output: ModsStateViewSchema,
|
||||
},
|
||||
'mods:autoSort': {
|
||||
input: z.object({ copyId: CopyIdSchema }),
|
||||
output: ModsStateViewSchema,
|
||||
},
|
||||
'mods:savePreset': {
|
||||
input: z.object({ copyId: CopyIdSchema, name: z.string().trim().min(1).max(80), overwriteId: z.string().min(1).optional() }),
|
||||
output: ModsStateViewSchema,
|
||||
},
|
||||
'mods:applyPreset': {
|
||||
input: z.object({ copyId: CopyIdSchema, presetId: z.string().min(1) }),
|
||||
output: ModsStateViewSchema,
|
||||
},
|
||||
'mods:deletePreset': {
|
||||
input: z.object({ copyId: CopyIdSchema, presetId: z.string().min(1) }),
|
||||
output: ModsStateViewSchema,
|
||||
},
|
||||
'mods:exportPreset': {
|
||||
input: z.object({ copyId: CopyIdSchema, presetId: z.string().min(1) }),
|
||||
output: z.object({ path: z.string().nullable() }),
|
||||
},
|
||||
'mods:importPreset': {
|
||||
input: z.object({ copyId: CopyIdSchema }),
|
||||
output: z.object({ imported: z.boolean(), state: ModsStateViewSchema }),
|
||||
},
|
||||
'mods:openFolder': {
|
||||
input: z.void(),
|
||||
output: z.void(),
|
||||
},
|
||||
'mods:setFolder': {
|
||||
input: z.object({ copyId: CopyIdSchema, path: z.string().min(1).nullable() }),
|
||||
output: ModsStateViewSchema,
|
||||
},
|
||||
'launch:getState': {
|
||||
input: z.void(),
|
||||
output: LaunchStateSchema,
|
||||
@@ -341,13 +240,13 @@ export const ipcContract = {
|
||||
output: ActivePatchSetSchema,
|
||||
},
|
||||
'patches:check': {
|
||||
/** Checks for a newer adaptation pack. */
|
||||
/** Asks GitHub for the newest adaptation pack. */
|
||||
input: z.void(),
|
||||
output: PackCheckSchema,
|
||||
},
|
||||
'patches:apply': {
|
||||
/** Downloads, verifies and activates the pack version selected by the player. */
|
||||
input: z.object({ version: PackReleaseSchema.shape.version }),
|
||||
/** Downloads, verifies and activates the newest pack; the window asks the player first. */
|
||||
input: z.void(),
|
||||
output: PackApplyResultSchema,
|
||||
},
|
||||
'patches:useBundled': {
|
||||
@@ -355,18 +254,6 @@ export const ipcContract = {
|
||||
input: z.void(),
|
||||
output: ActivePatchSetSchema,
|
||||
},
|
||||
'updates:check': {
|
||||
input: z.void(),
|
||||
output: AppUpdateCheckSchema,
|
||||
},
|
||||
'updates:download': {
|
||||
input: z.object({ version: AppReleaseVersionSchema }),
|
||||
output: AppUpdateCheckSchema,
|
||||
},
|
||||
'updates:install': {
|
||||
input: z.object({ version: AppReleaseVersionSchema }),
|
||||
output: z.void(),
|
||||
},
|
||||
'window:minimize': {
|
||||
input: z.void(),
|
||||
output: z.void(),
|
||||
@@ -380,10 +267,9 @@ export const ipcContract = {
|
||||
export const ipcEvents = {
|
||||
'event:settings-changed': SettingsSchema,
|
||||
'event:install-progress': InstallProgressSchema,
|
||||
'event:app-update-progress': AppUpdateProgressSchema,
|
||||
'event:launch-state': LaunchStateSchema,
|
||||
'event:copies-changed': CopiesSchema,
|
||||
'event:copy-maintenance': MaintenanceProgressSchema.nullable(),
|
||||
'event:copy-maintenance': MaintenanceProgressSchema,
|
||||
/** Another patch set became active (a pack was installed, or the bundled set restored). */
|
||||
'event:patch-set-changed': ActivePatchSetSchema,
|
||||
} as const;
|
||||
|
||||
@@ -1,39 +0,0 @@
|
||||
/** Split the launch setting into Windows arguments without going through a command shell. */
|
||||
export function parseLaunchArguments(text: string): string[] | null {
|
||||
if (/[\0\r\n]/.test(text)) return null;
|
||||
const args: string[] = [];
|
||||
let argument = '';
|
||||
let quoted = false;
|
||||
let started = false;
|
||||
let backslashes = 0;
|
||||
|
||||
for (const character of text) {
|
||||
if (character === '\\') {
|
||||
backslashes++;
|
||||
started = true;
|
||||
continue;
|
||||
}
|
||||
if (character === '"') {
|
||||
argument += '\\'.repeat(Math.floor(backslashes / 2));
|
||||
if (backslashes % 2 === 1) argument += '"';
|
||||
else quoted = !quoted;
|
||||
backslashes = 0;
|
||||
started = true;
|
||||
continue;
|
||||
}
|
||||
argument += '\\'.repeat(backslashes);
|
||||
backslashes = 0;
|
||||
if (!quoted && (character === ' ' || character === '\t')) {
|
||||
if (started) args.push(argument);
|
||||
argument = '';
|
||||
started = false;
|
||||
continue;
|
||||
}
|
||||
argument += character;
|
||||
started = true;
|
||||
}
|
||||
|
||||
if (quoted) return null;
|
||||
if (started) args.push(argument + '\\'.repeat(backslashes));
|
||||
return args;
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
[
|
||||
"-forcestart",
|
||||
"-skip_pkg_validation",
|
||||
"-nobeac",
|
||||
"-crashpad-disable-upload",
|
||||
"--nosteam"
|
||||
]
|
||||
@@ -1,55 +0,0 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
const STABLE_VERSION = /^(0|[1-9][0-9]{0,4})\.(0|[1-9][0-9]{0,4})\.(0|[1-9][0-9]{0,4})$/;
|
||||
export const AppReleaseVersionSchema = z.string().regex(STABLE_VERSION);
|
||||
export const MAX_INSTALLER_BYTES = 2 ** 31 - 1;
|
||||
|
||||
export function launcherReleaseFiles(version: string) {
|
||||
const base = `wtoffline-launcher-${AppReleaseVersionSchema.parse(version)}-win-x64`;
|
||||
return { installer: `${base}.exe`, manifest: `${base}.manifest.json`, signature: `${base}.manifest.json.sig` };
|
||||
}
|
||||
|
||||
export function portableLauncherReleaseFiles(version: string) {
|
||||
const base = `wtoffline-launcher-${AppReleaseVersionSchema.parse(version)}-win-x64-portable`;
|
||||
return { archive: `${base}.zip`, manifest: `${base}.manifest.json`, signature: `${base}.manifest.json.sig` };
|
||||
}
|
||||
|
||||
export const LauncherReleaseManifest = z.strictObject({
|
||||
kind: z.literal('wto-launcher-release'),
|
||||
format: z.literal(1),
|
||||
version: AppReleaseVersionSchema,
|
||||
platform: z.literal('win32-x64'),
|
||||
size: z.number().int().positive().max(MAX_INSTALLER_BYTES),
|
||||
sha256: z.string().regex(/^[a-f0-9]{64}$/),
|
||||
});
|
||||
export type LauncherReleaseManifest = z.output<typeof LauncherReleaseManifest>;
|
||||
|
||||
export const PortableReleaseManifest = z.strictObject({
|
||||
kind: z.literal('wto-launcher-portable-release'),
|
||||
format: z.literal(1),
|
||||
version: AppReleaseVersionSchema,
|
||||
platform: z.literal('win32-x64'),
|
||||
size: z.number().int().positive().max(MAX_INSTALLER_BYTES),
|
||||
sha256: z.string().regex(/^[a-f0-9]{64}$/),
|
||||
});
|
||||
export type PortableReleaseManifest = z.output<typeof PortableReleaseManifest>;
|
||||
|
||||
const AppUpdateReleaseSchema = z.object({
|
||||
version: AppReleaseVersionSchema,
|
||||
size: z.number().int().positive().max(MAX_INSTALLER_BYTES),
|
||||
notes: z.string(),
|
||||
});
|
||||
const AppUpdateProblemSchema = z.enum(['network', 'contents', 'signature', 'no_signing_key', 'page_limit']);
|
||||
|
||||
export const AppUpdateCheckSchema = z.discriminatedUnion('status', [
|
||||
z.object({ status: z.literal('current') }),
|
||||
z.object({ status: z.literal('available'), release: AppUpdateReleaseSchema, ready: z.boolean() }),
|
||||
z.object({ status: z.literal('failed'), problem: AppUpdateProblemSchema }),
|
||||
]);
|
||||
export type AppUpdateCheck = z.output<typeof AppUpdateCheckSchema>;
|
||||
|
||||
export const AppUpdateProgressSchema = z.object({
|
||||
received: z.number().int().nonnegative(),
|
||||
total: z.number().int().positive(),
|
||||
});
|
||||
export type AppUpdateProgress = z.output<typeof AppUpdateProgressSchema>;
|
||||
@@ -3,7 +3,6 @@ import { z } from 'zod';
|
||||
/** What the launcher found in a folder the player chose as their War Thunder installation. */
|
||||
export const GameFolderInspectionSchema = z.object({
|
||||
path: z.string(),
|
||||
resolvedPath: z.string(),
|
||||
/** Files a game folder must have that this one lacks; empty for a game folder. */
|
||||
missingFiles: z.array(z.string()),
|
||||
/** The file version of win64/aces.exe, or null when it has none or is missing. */
|
||||
@@ -12,10 +11,6 @@ export const GameFolderInspectionSchema = z.object({
|
||||
verifiedVersions: z.array(z.string()),
|
||||
/** The folder lies in a Steam library: installing into it needs the player's confirmation. */
|
||||
inSteamLibrary: z.boolean(),
|
||||
/** True when the folder already holds a complete wtoffline/stock backup from an offline setup. */
|
||||
hasOfflineBackup: z.boolean(),
|
||||
/** True when the folder is already patched for offline use but lacks a wtoffline/stock backup. */
|
||||
needsStockSource: z.boolean(),
|
||||
});
|
||||
export type GameFolderInspection = z.output<typeof GameFolderInspectionSchema>;
|
||||
|
||||
@@ -31,7 +26,6 @@ export const TARGET_PROBLEMS = [
|
||||
|
||||
export const TargetFolderInspectionSchema = z.object({
|
||||
path: z.string(),
|
||||
resolvedPath: z.string(),
|
||||
problem: z.enum(TARGET_PROBLEMS).nullable(),
|
||||
inSteamLibrary: z.boolean(),
|
||||
/** Bytes free on the drive the folder is on; null when the drive cannot be read. */
|
||||
@@ -41,19 +35,9 @@ export const TargetFolderInspectionSchema = z.object({
|
||||
});
|
||||
export type TargetFolderInspection = z.output<typeof TargetFolderInspectionSchema>;
|
||||
|
||||
/** Why a folder cannot hold the offline client's saves, caches, and logs. */
|
||||
export const DATA_FOLDER_PROBLEMS = [
|
||||
/** The data folder is the client folder itself, contains it, or lies inside its wtoffline folder. */
|
||||
'overlaps_client',
|
||||
/** The data folder lies inside the stock source folder. */
|
||||
'overlaps_stock',
|
||||
] as const;
|
||||
export type DataFolderProblem = (typeof DATA_FOLDER_PROBLEMS)[number];
|
||||
|
||||
export const FolderSizeSchema = z.object({
|
||||
bytes: z.number(),
|
||||
files: z.number(),
|
||||
linkableBytes: z.number().nonnegative().optional(),
|
||||
});
|
||||
export type FolderSize = z.output<typeof FolderSizeSchema>;
|
||||
|
||||
@@ -87,10 +71,10 @@ export type PatchCheck = z.output<typeof PatchCheckSchema>;
|
||||
|
||||
/**
|
||||
* copy: the stock installation is copied to a new folder and only read.
|
||||
* in-place: the player's own prepared folder is used directly; its stock files are backed up inside it.
|
||||
* existing: an already prepared offline client folder is registered directly without copying.
|
||||
* in-place: the player's own prepared folder is used as the copy; its stock files are kept in
|
||||
* the backup folder inside it.
|
||||
*/
|
||||
export const INSTALL_METHODS = ['copy', 'in-place', 'existing'] as const;
|
||||
export const INSTALL_METHODS = ['copy', 'in-place'] as const;
|
||||
export type InstallMethod = (typeof INSTALL_METHODS)[number];
|
||||
|
||||
export const CopyIdSchema = z.uuid();
|
||||
@@ -101,10 +85,8 @@ const InstallChoicesSchema = z.object({
|
||||
name: CopyNameSchema,
|
||||
/** Where the local server keeps saves, caches and logs. */
|
||||
dataPath: z.string().min(1),
|
||||
decalSourcePath: z.string().min(1).optional(),
|
||||
/** Resolved Steam locations shown in the risk prompts the player confirmed. */
|
||||
confirmedSteamCopyPath: z.string().min(1).optional(),
|
||||
confirmedSteamDataPath: z.string().min(1).optional(),
|
||||
/** The player confirmed installing into a Steam library after the warning. */
|
||||
steamLibraryConfirmed: z.boolean(),
|
||||
/** The player chose to go on without the features of the unavailable patches. */
|
||||
missingFeaturesAccepted: z.boolean(),
|
||||
});
|
||||
@@ -112,7 +94,6 @@ const InstallChoicesSchema = z.object({
|
||||
export const InstallRequestSchema = z.discriminatedUnion('method', [
|
||||
InstallChoicesSchema.extend({
|
||||
method: z.literal('copy'),
|
||||
useHardLinks: z.boolean().optional(),
|
||||
/** The War Thunder installation to copy; only read. */
|
||||
sourcePath: z.string().min(1),
|
||||
/** A new or empty folder for the game copy. */
|
||||
@@ -122,20 +103,11 @@ export const InstallRequestSchema = z.discriminatedUnion('method', [
|
||||
method: z.literal('in-place'),
|
||||
/** The player's prepared game folder, used as the game copy. */
|
||||
gamePath: z.string().min(1),
|
||||
/** Optional unpatched game folder to supply the 4 stock files when the folder is already patched. */
|
||||
stockSourcePath: z.string().min(1).optional(),
|
||||
}),
|
||||
InstallChoicesSchema.extend({
|
||||
method: z.literal('existing'),
|
||||
/** An already prepared offline client folder registered directly without copying. */
|
||||
gamePath: z.string().min(1),
|
||||
/** Optional unpatched game folder to supply the 4 stock files when wtoffline/stock is missing. */
|
||||
stockSourcePath: z.string().min(1).optional(),
|
||||
}),
|
||||
]);
|
||||
export type InstallRequest = z.output<typeof InstallRequestSchema>;
|
||||
|
||||
export const INSTALL_PHASES = ['checking', 'importing-decals', 'measuring', 'verifying', 'copying', 'backing-up', 'recording'] as const;
|
||||
export const INSTALL_PHASES = ['checking', 'measuring', 'copying', 'backing-up', 'recording'] as const;
|
||||
|
||||
export const InstallProgressSchema = z.object({
|
||||
phase: z.enum(INSTALL_PHASES),
|
||||
@@ -157,24 +129,14 @@ export const InstallRecordSchema = z.object({
|
||||
dataPath: z.string(),
|
||||
/** The stock files every build starts from, inside the copy. */
|
||||
stockBackupPath: z.string(),
|
||||
/** Confirmation applies only to these resolved copy and data paths. */
|
||||
steamLibraryConfirmation: z.object({
|
||||
copyPath: z.string(),
|
||||
dataPath: z.string(),
|
||||
}).optional(),
|
||||
gameVersion: z.string().nullable(),
|
||||
/** Patches that did not fit when the copy was installed; their features are missing. */
|
||||
unavailablePatches: z.array(UnavailablePatchSchema),
|
||||
installedAt: z.string(),
|
||||
lastCheckedAt: z.string().optional(),
|
||||
currentSaveId: z.string().regex(/^\d+$/).optional(),
|
||||
decalCacheId: z.uuid().optional(),
|
||||
/** Relative paths read from the installation source during the last copy or update. */
|
||||
sourceFiles: z.array(z.string().min(1)).optional(),
|
||||
/** Relative resource paths linked to the source and detached on a version update. */
|
||||
hardlinkedFiles: z.array(z.string().min(1)).optional(),
|
||||
/** Runtime check hydrated when listing copies (never persisted to copies.json): true if copyPath or core game files are missing on disk. */
|
||||
folderMissing: z.boolean().optional(),
|
||||
});
|
||||
export type InstallRecord = z.output<typeof InstallRecordSchema>;
|
||||
|
||||
|
||||
@@ -1,24 +1,10 @@
|
||||
import { z } from 'zod';
|
||||
import { APP_ERROR_CODES } from '../errors.ts';
|
||||
|
||||
const GameExitSchema = z.object({
|
||||
code: z.number().int().nullable(),
|
||||
signal: z.string().nullable(),
|
||||
logFolder: z.string(),
|
||||
});
|
||||
|
||||
export type GameExit = z.output<typeof GameExitSchema>;
|
||||
|
||||
/** Append the unsigned 32-bit hex form for Windows NTSTATUS/HRESULT exit codes. */
|
||||
export function formatExitCode(code: number): string {
|
||||
if (code >= 0 && code <= 0xffff) return String(code);
|
||||
return `${code} (0x${(code >>> 0).toString(16).toUpperCase().padStart(8, '0')})`;
|
||||
}
|
||||
|
||||
export const LaunchStateSchema = z.object({
|
||||
phase: z.enum([
|
||||
'ready', 'checking', 'building', 'starting-server', 'starting-game', 'running',
|
||||
'server-running', 'game-exited', 'stopping', 'port-busy', 'version-changed', 'server-exited', 'failed',
|
||||
'stopping', 'port-busy', 'version-changed', 'server-exited', 'failed',
|
||||
]),
|
||||
copyId: z.uuid().optional(),
|
||||
port: z.number().int().min(1).max(65535).optional(),
|
||||
@@ -26,7 +12,6 @@ export const LaunchStateSchema = z.object({
|
||||
filesTotal: z.number().int().nonnegative().optional(),
|
||||
file: z.string().optional(),
|
||||
actualVersion: z.string().nullable().optional(),
|
||||
gameExit: GameExitSchema.optional(),
|
||||
error: z.enum(APP_ERROR_CODES).optional(),
|
||||
});
|
||||
|
||||
|
||||
Loaded 100 of 417 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user