Windows 上的安卓应用运行器:双击 APK 即装,应用以独立窗口与桌面图标运行,自持 QEMU 运行时
feat: ApkStart v0.1.0 — 双击 APK 即装的 Windows 安卓应用运行器
RoutineMiku42ee604de075
diff --git a/.gitattributes b/.gitattributesnew file mode 100644index 0000000..0dfe37f--- /dev/null+++ b/.gitattributes@@ -0,0 +1,15 @@+* text=auto eol=lf++*.js text eol=lf+*.json text eol=lf+*.md text eol=lf+*.html text eol=lf+*.css text eol=lf+*.yml text eol=lf++*.png binary+*.ico binary+*.exe binary+*.iso binary+*.img binary+*.qcow2 binarydiff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlnew file mode 100644index 0000000..0869ced--- /dev/null+++ b/.github/workflows/ci.yml@@ -0,0 +1,33 @@+name: CI++on:+ push:+ branches: [main]+ pull_request:+ workflow_dispatch:++jobs:+ test:+ name: 单元测试(Windows / Node ${{ matrix.node }})+ runs-on: windows-latest+ strategy:+ fail-fast: false+ matrix:+ node: [20, 22]++ steps:+ - uses: actions/checkout@v4++ - uses: actions/setup-node@v4+ with:+ node-version: ${{ matrix.node }}+ cache: npm++ # 单元测试不需要 Electron 二进制,跳过 188MB 下载以加快 CI+ - name: 安装依赖+ run: npm ci+ env:+ ELECTRON_SKIP_BINARY_DOWNLOAD: '1'++ - name: 运行测试+ run: npm testdiff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlnew file mode 100644index 0000000..d7fcdb3--- /dev/null+++ b/.github/workflows/release.yml@@ -0,0 +1,51 @@+name: Release++on:+ push:+ tags: ['v*']+ workflow_dispatch:++permissions:+ contents: write++jobs:+ build:+ name: 构建便携版并发布+ runs-on: windows-latest++ steps:+ - uses: actions/checkout@v4++ - uses: actions/setup-node@v4+ with:+ node-version: 22+ cache: npm++ - name: 安装依赖(含 Electron 运行时)+ run: npm ci+ env:+ ELECTRON_MIRROR: https://npmmirror.com/mirrors/electron/++ - name: 测试+ run: npm test++ - name: 打包便携版+ run: npm run pack++ - name: 压缩产物+ shell: pwsh+ run: |+ $tag = "${{ github.ref_name }}"+ if (-not $tag.StartsWith('v')) { $tag = "v$tag" }+ Compress-Archive -Path dist/ApkStart-win64-portable/* -DestinationPath "ApkStart-$tag-win64-portable.zip" -CompressionLevel Optimal+ Get-Item "ApkStart-$tag-win64-portable.zip" | Select-Object Name, Length++ - name: 创建 Release+ env:+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}+ shell: pwsh+ run: |+ $tag = "${{ github.ref_name }}"+ if (-not $tag.StartsWith('v')) { $tag = "v$tag" }+ $zip = "ApkStart-$tag-win64-portable.zip"+ gh release create $tag $zip --title "ApkStart $tag" --generate-notesdiff --git a/.gitignore b/.gitignorenew file mode 100644index 0000000..c7e5c7b--- /dev/null+++ b/.gitignore@@ -0,0 +1,19 @@+node_modules/+dist/+test/out/+test/fixtures/+test/shot*.png+*.log+*.zip+Thumbs.db+.DS_Store+.vscode/+.idea/++# 运行时产物(本地下载,不入库)+engine/qemu/+engine/*.iso+engine/*.img+engine/*.qcow2+tools/platform-tools/adb.exe+tools/platform-tools/*.dlldiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdnew file mode 100644index 0000000..afdffc9--- /dev/null+++ b/CONTRIBUTING.md@@ -0,0 +1,55 @@+# 贡献指南++欢迎提交 Issue 和 Pull Request。这个项目的原则是**壳层零依赖、行为可预测**,所以请先读一下下面的约定。++## 开发环境++- Windows 10/11 x64+- Node.js ≥ 20+- `npm install && npm start`++## 提交前自检++```powershell+npm test # 纯 Node 单元测试 + 引擎链路测试(不需要网络、不需要虚拟机)+```++涉及界面改动时,建议再跑一次冒烟截图确认没有布局塌陷:++```powershell+electron . --smoke test\shot.png+```++## 代码约定++- **壳层不引入第三方运行时依赖**。`src/core/` 下的 ZIP / AXML / ARSC / PNG / ICO 解析都是手写的,+ 新增功能时优先考虑「能不能用 Node 内置模块写完」,避免为了小功能拉进一个大包。+- 渲染层是原生 HTML/CSS/JS,不使用前端框架。+- 与安卓侧交互一律走 `src/core/adb.js`,不要在各处直接拼 adb 命令。+- 主进程与渲染进程之间只通过 `preload.js` 暴露的白名单通道通信,保持 `contextIsolation` 开启。+- 注释与 UI 文案使用中文,标识符使用英文。++## 测试约定++- 拿不到真实 APK 时测试会自动跳过 APK 解析部分;要覆盖这部分,设置环境变量指向任意 APK:++```powershell+$env:APKSTART_TEST_APK="C:\path\to\any.apk"; npm test+```++- 不要在测试里访问外网。需要网络行为的测试请起本地 `http` 服务(参考 `test/engine-test.js`)。++## 提交信息++使用 Conventional Commits 风格,例如:++```+feat(engine): 支持从自定义路径导入 qcow2 磁盘+fix(axml): 修正属性表基址偏移+docs: 补充 WHPX 开启说明+```++## 法律与边界++- 本项目不分发任何安卓系统镜像、QEMU 二进制或 Google 组件,全部由用户本机按需下载。+- 请勿在仓库中提交商业 APK、破解工具或任何侵犯第三方版权的内容。diff --git a/LICENSE b/LICENSEnew file mode 100644index 0000000..0df9d01--- /dev/null+++ b/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 ApkStart contributors++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/README.md b/README.mdnew file mode 100644index 0000000..cdb003e--- /dev/null+++ b/README.md@@ -0,0 +1,131 @@+# ApkStart++[](https://github.com/RoutineMiku/apkstart/actions/workflows/ci.yml)+[](https://github.com/RoutineMiku/apkstart/releases)+[](LICENSE)+[](#)++**Windows 上的安卓应用运行器 —— 让安卓应用像 Windows 原生软件一样被安装和使用。**++- 🖱️ **双击 .apk 即安装**:注册 .apk 文件关联后,在资源管理器里双击 APK,自动解析 → 安装 → 生成桌面图标,全程无需打开任何模拟器界面。+- 🧩 **每个应用一个桌面图标**:图标从 APK 内部离线提取并转为多尺寸 ICO,双击桌面图标 = 直接启动该应用,与打开一个原生 Windows 软件的体验一致。+- 🪟 **独立窗口(freeform)**:通过 `--windowingMode 5` 以自由窗口模式启动,每个安卓应用都有自己的窗口,可拖动、缩放、固定在任务栏。+- 📁 **数据互通**:`%USERPROFILE%\ApkStartShared` ↔ 安卓内 `/sdcard/ApkStartShared` 持续双向同步,安卓应用存下的文件直接出现在本机。+- 🪶 **极致轻量**:壳层本身零第三方依赖(连 ZIP / PNG / ICO / AXML 解析都是手写的),运行时按需拉起,空闲自动回收;也可以完全复用你机器上已有的安卓运行时,额外占用为零。++++```+┌────────────────────────────────────────────────────────────┐+│ 桌面图标(真实应用图标 .lnk) │+│ │ 双击 │+│ ▼ │+│ ApkStart.exe --launch <包名> │+│ │ 运行时未启动?→ 自动拉起(QEMU / 复用已有模拟器) │+│ ▼ │+│ adb am start --windowingMode 5 -n <包名>/<Activity> │+│ │ │+│ ▼ │+│ 独立 freeform 窗口,像原生应用一样使用 │+└────────────────────────────────────────────────────────────┘+```++## 下载即用(不想编译)++到 [Releases](https://github.com/RoutineMiku/apkstart/releases) 下载 `ApkStart-v*-win64-portable.zip`,解压后双击 `ApkStart.exe` 即可。+首次启动进入「运行时」页点**一键部署**,会自动装好 adb / QEMU / 安卓系统镜像,之后长期免装。++## 从源码构建++```powershell+# 1. 安装依赖(含 Electron 运行时)+npm install++# 2. 启动并完成运行时部署(一键下载 adb / QEMU / 系统镜像)+npm start++# 3.(可选)注册 .apk 双击安装+npm run assoc:on++# 4. 打包便携版(免安装,可直接分发)+npm run pack+# 产出 dist/ApkStart-win64-portable/ApkStart.exe+```++## 运行时说明:完全独立,不依赖任何第三方模拟器++ApkStart 是一个**自持**的项目,运行时组件全部由自己下载、校验和管理(位于 `%APPDATA%\apkstart\runtime`):++| 组件 | 来源 | 大小 | 用途 |+|---|---|---|---|+| adb(platform-tools) | dl.google.com 官方源 | ~8 MB | 安装/启动安卓应用 |+| QEMU | 官方 Windows 构建,静默安装 | ~200 MB | 虚拟机引擎 |+| Android-x86 9.0-r2 | 多镜像源(支持续传) | ~900 MB | 安卓系统 |+| 虚拟磁盘 | qemu-img 自建(qcow2 稀疏) | 24 GB(按需占用) | 系统与用户数据 |++首次使用时,「运行时」页会引导完成以上部署(**一键部署**),然后走一次性系统安装;+之后每次启动直接从磁盘引导,装/开应用全程无感。++++- 支持 **WHPX 硬件加速**(在「启用或关闭 Windows 功能」勾选「虚拟机平台」后自动启用),未启用时自动回退纯软件模拟。+- 高级用户也可以在设置里切换为「连接已有运行时」(复用 WSA 等的 adb 端口),但这只是可选项,不是依赖。+- 自备镜像的用户可直接导入 ISO/IMG/已装好的虚拟磁盘,跳过下载。++## 目录结构++```+apkstart/+├─ src/+│ ├─ main.js 主进程:窗口/托盘/单实例/命令行分发/IPC+│ ├─ preload.js 安全桥接+│ ├─ ui/ 渲染层(原生 HTML/CSS/JS,无框架)+│ └─ core/+│ ├─ zip.js 极简 ZIP 读取器(按需解压)+│ ├─ axml.js Android 二进制 XML 解析+│ ├─ arsc.js resources.arsc 资源表解析(应用名/图标路径还原)+│ ├─ apk.js APK 元信息:包名/版本/启动 Activity/图标/ABI+│ ├─ png.js 零依赖 PNG 编码器 + 程序图标绘制+│ ├─ shortcut.js 多尺寸 ICO 生成 + .lnk 快捷方式+│ ├─ assoc.js .apk 文件关联(HKCU,免管理员)+│ ├─ adb.js adb 客户端(安装/启动/同步/截图/…)+│ ├─ engine.js 运行时管理:探测/QEMU 托管/空闲回收+│ ├─ sharer.js 本机 ↔ 安卓共享目录双向同步+│ ├─ installer.js 安装流水线编排+│ └─ store.js 应用清单与设置持久化+├─ engine/ QEMU 引擎放置处(见 engine/README.md)+├─ tools/platform-tools/ 便携 adb 放置处+├─ test/ 单元测试 + Electron 集成测试 + 冒烟截图+├─ build/pack.js 便携版打包+└─ scripts/assoc.js .apk 关联命令行开关+```++## 命令行++```+ApkStart.exe 打开主界面+ApkStart.exe <路径\to.apk> 安装 APK+ApkStart.exe --launch <包名> 直接启动应用(桌面快捷方式使用此参数)+```++## 测试++```powershell+npm test # 纯 Node 单元测试+electron test/electron-integration.js # ICO / 快捷方式集成测试+electron . --smoke test\shot.png # 启动应用并截图(界面冒烟)+```++## 设计取舍(诚实说明)++- **不是从零实现的 hypervisor**:安卓内核、GPU 转译、ART 运行时是数年级别的工程,本项目选择站在 AOSP/QEMU/adb 的肩膀上,把工程量集中在「原生应用级体验」上——这正是应用宝电脑版、Google Play Games PC 版等产品共同的架构思路。+- **共享目录是同步而非挂载**:Windows 无 root 时无法在安卓侧挂载 NTFS 目录,采用秒级双向同步达到同等体验。+- **ARM-only 应用**:若应用仅含 ARM 原生库,需要运行时支持 ARM 转译(Bliss/部分镜像可开启 libhoudini/NativeBridge),安装时 ApkStart 会给出提示。++## 参与贡献++欢迎 Issue / PR。壳层保持零第三方依赖,提交前请跑 `npm test`;细节见 [CONTRIBUTING.md](CONTRIBUTING.md)。++## 许可证++[MIT](LICENSE)。本项目不分发安卓系统镜像、QEMU 二进制或 Google 组件,这些均由用户本机按需下载并遵循各自的许可协议。diff --git a/build/pack.js b/build/pack.jsnew file mode 100644index 0000000..a00fbd2--- /dev/null+++ b/build/pack.js@@ -0,0 +1,52 @@+'use strict';+/**+ * 便携版打包:产出 dist/ApkStart-win64-portable/+ * ApkStart.exe(即 electron.exe 改名)+ resources/app(本应用源码)+ * 无需安装器,解压即用;将来接 electron-builder 出安装包时可复用同一目录结构。+ */+const fs = require('fs');+const path = require('path');++const ROOT = path.join(__dirname, '..');+const OUT = path.join(ROOT, 'dist', 'ApkStart-win64-portable');+const ELECTRON_DIST = path.join(ROOT, 'node_modules', 'electron', 'dist');++function rmrf(p) {+ if (fs.existsSync(p)) fs.rmSync(p, { recursive: true, force: true });+}++function copy(src, dest) {+ fs.cpSync(src, dest, { recursive: true });+}++console.log('打包便携版 →', OUT);+rmrf(OUT);+fs.mkdirSync(path.join(OUT, 'resources', 'app'), { recursive: true });++// 1. Electron 运行时+console.log('复制 Electron 运行时…');+copy(ELECTRON_DIST, OUT);+fs.rmSync(path.join(OUT, 'resources', 'default_app.asar'), { force: true });++// 2. 应用本体+console.log('复制应用…');+const appDir = path.join(OUT, 'resources', 'app');+for (const item of ['package.json', 'src', 'LICENSE']) {+ const src = path.join(ROOT, item);+ if (fs.existsSync(src)) copy(src, path.join(appDir, item));+}++// 3. 可选目录+for (const opt of ['tools', 'engine']) {+ const src = path.join(ROOT, opt);+ if (fs.existsSync(src)) copy(src, path.join(appDir, opt));+}++// 4. 改名主程序+fs.renameSync(path.join(OUT, 'electron.exe'), path.join(OUT, 'ApkStart.exe'));++// 5. 版本信息+const pkg = require(path.join(ROOT, 'package.json'));+fs.writeFileSync(path.join(OUT, 'VERSION.txt'), `ApkStart ${pkg.version}\n构建时间:${new Date().toLocaleString('zh-CN')}\n`);++console.log('完成。运行 dist/ApkStart-win64-portable/ApkStart.exe 即可使用。');diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdnew file mode 100644index 0000000..c461a5d--- /dev/null+++ b/docs/ARCHITECTURE.md@@ -0,0 +1,71 @@+# 架构++## 分层++```+┌─────────────────────────────────────────────────────────────┐+│ 表现层 src/ui (HTML/CSS/JS) ←→ preload (contextBridge) │+├─────────────────────────────────────────────────────────────┤+│ 编排层 src/main.js(窗口/托盘/CLI 分发) │+│ installer.js(安装流水线) │+├─────────────────────────────────────────────────────────────┤+│ 域层 engine.js(运行时生命周期/探测/空闲回收) │+│ adb.js(设备操作) sharer.js(文件互通) │+├─────────────────────────────────────────────────────────────┤+│ 离线解析 zip.js → axml.js / arsc.js → apk.js │+│ png.js / shortcut.js(图标与快捷方式) │+├─────────────────────────────────────────────────────────────┤+│ 引擎适配 自带 QEMU(WHPX/TCG) │ 系统镜像导入 │ 已有运行时(可选) │+└─────────────────────────────────────────────────────────────┘+```++## 关键流程++### 1. 双击 APK 安装++```+Explorer 双击 .apk+ → HKCU\Software\Classes\ApkStart.apk\shell\open\command+ → ApkStart.exe "C:\...\xxx.apk"+ → main.js parseArgs → runInstall+ 1. apk.js:离线解析(zip → manifest AXML → arsc 还原 label/icon)+ 2. engine.ensure():运行时未就绪则自动拉起/探测+ 3. adb install -r -g -t+ 4. 图标 → PNG(icons/)+ 多尺寸 ICO(icons/*.ico)+ 5. shell.writeShortcutLink 生成桌面 .lnk(--launch <pkg>)+ 6. store.upsertApp 记录元数据+```++### 2. 桌面图标启动(原生体验)++```+双击 <应用名>.lnk+ → ApkStart.exe --launch <pkg>+ → 单实例锁合并到已运行实例(或静默拉起新实例)+ → adb am start --windowingMode 5 -n <pkg>/<activity>+ → 独立 freeform 窗口+ → 壳层窗口自动隐藏/退出,不留多余界面+```++### 3. 数据互通++```+本机 %USERPROFILE%\ApkStartShared ⇄ 安卓 /sdcard/ApkStartShared+ 增量双向同步(mtime+size 判定),8s 轮询 + 关键动作触发+```++## 为什么不用现成库++| 需求 | 常规做法 | ApkStart 的做法 | 理由 |+|---|---|---|---|+| 读 APK 元数据 | aapt2 / apk-parser | 手写 zip+AXML+ARSC | 体积零依赖、免安装 SDK、启动无外部进程 |+| 图标转 ICO | ImageMagick/sharp | nativeImage 缩放 + 手写 ICO 容器 | 避免 80MB 原生依赖 |+| 文件关联 | 安装器写 HKLM | HKCU + SHChangeNotify | 免管理员、可随时在设置里开关 |+| 模拟器 | 打包整套 VirtualBox | 引擎适配层 | 复用已有运行时零成本;QEMU 路线保留可控的系统镜像方案 |++## 稳定性设计++- 所有 adb 调用带超时与错误归一化(AdbError)。+- 运行时探测并行进行,4s 超时,失败自动降级。+- QEMU 空闲看门狗:无前台应用且超过设定分钟数才回收,有应用在跑永不回收。+- 设置/应用清单写入采用 tmp+rename 原子写。diff --git a/docs/images/app.png b/docs/images/app.pngnew file mode 100644index 0000000..3bd769cBinary files /dev/null and b/docs/images/app.png differdiff --git a/docs/images/setup.png b/docs/images/setup.pngnew file mode 100644index 0000000..81502d4Binary files /dev/null and b/docs/images/setup.png differdiff --git a/engine/README.md b/engine/README.mdnew file mode 100644index 0000000..f19eee0--- /dev/null+++ b/engine/README.md@@ -0,0 +1,39 @@+# 运行时引擎目录(手动放置,可选)++**从 0.2 起,ApkStart 默认完全自持**:adb、QEMU、系统镜像由应用自动下载部署到+`%APPDATA%\apkstart\runtime\`,不需要手动准备任何东西。++本目录仅用于以下两种情况:++## 1. 手动放置 QEMU(下载源被墙 / 想用指定版本)++```+engine/qemu/+├─ qemu-system-x86_64.exe+├─ qemu-img.exe+└─ …(其余 QEMU 文件)+```++QEMU 官方 Windows 构建地址:https://qemu.weilnetz.de/w64/+(`qemu-w64-setup-*.exe` 是 NSIS 安装包,ApkStart 会用 `/S /D=` 静默安装到运行时目录;+你也可以用 7-Zip 直接解压安装包后放到上面的位置)++## 2. 手动放置 adb++```+tools/platform-tools/+└─ adb.exe+```++下载地址:https://developer.android.com/tools/releases/platform-tools++## 系统镜像++- 推荐:Android-x86 9.0-r2(x86_64),应用内可直接下载(多镜像、断点续传)+- 或导入:任意已安装好 Android 的磁盘镜像(qcow2 / raw / vmdk),在「运行时 → 导入」选择+- 导入后 ApkStart 直接从磁盘引导,无需安装步骤++## 硬件加速++QEMU 使用 WHPX 加速:控制面板 →「启用或关闭 Windows 功能」→ 勾选「虚拟机平台」→ 重启。+未启用时 ApkStart 自动回退纯软件模拟(TCG),首次启动较慢。diff --git a/package-lock.json b/package-lock.jsonnew file mode 100644index 0000000..981f76c--- /dev/null+++ b/package-lock.json@@ -0,0 +1,872 @@+{+ "name": "apkstart",+ "version": "0.1.0",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "apkstart",+ "version": "0.1.0",+ "license": "MIT",+ "devDependencies": {+ "electron": "^33.4.11"+ }+ },+ "node_modules/@electron/get": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/@electron/get/-/get-2.0.3.tgz",+ "integrity": "sha512-Qkzpg2s9GnVV2I2BjRksUi43U5e6+zaQMcjoJy0C+C5oxaKl+fmckGDQFtRpZpZV0NQekuZZ+tGz7EA9TVnQtQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "debug": "^4.1.1",+ "env-paths": "^2.2.0",+ "fs-extra": "^8.1.0",+ "got": "^11.8.5",+ "progress": "^2.0.3",+ "semver": "^6.2.0",+ "sumchecker": "^3.0.1"+ },+ "engines": {+ "node": ">=12"+ },+ "optionalDependencies": {+ "global-agent": "^3.0.0"+ }+ },+ "node_modules/@sindresorhus/is": {+ "version": "4.6.0",+ "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-4.6.0.tgz",+ "integrity": "sha512-t09vSN3MdfsyCHoFcTRCH/iUtG7OJ0CsjzB8cjAmKc/va/kIgeDI/TxsigdncE/4be734m0cvIYwNaV4i2XqAw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sindresorhus/is?sponsor=1"+ }+ },+ "node_modules/@szmarczak/http-timer": {+ "version": "4.0.6",+ "resolved": "https://registry.npmjs.org/@szmarczak/http-timer/-/http-timer-4.0.6.tgz",+ "integrity": "sha512-4BAffykYOgO+5nzBWYwE3W90sBgLJoUPRWWcL8wlyiM8IB8ipJz3UMJ9KXQd1RKQXpKp8Tutn80HZtWsu2u76w==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "defer-to-connect": "^2.0.0"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/@types/cacheable-request": {+ "version": "6.0.3",+ "resolved": "https://registry.npmjs.org/@types/cacheable-request/-/cacheable-request-6.0.3.tgz",+ "integrity": "sha512-IQ3EbTzGxIigb1I3qPZc1rWJnH0BmSKv5QYTalEwweFvyBDLSAe24zP0le/hyi7ecGfZVlIVAg4BZqb8WBwKqw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/http-cache-semantics": "*",+ "@types/keyv": "^3.1.4",+ "@types/node": "*",+ "@types/responselike": "^1.0.0"+ }+ },+ "node_modules/@types/http-cache-semantics": {+ "version": "4.2.0",+ "resolved": "https://registry.npmjs.org/@types/http-cache-semantics/-/http-cache-semantics-4.2.0.tgz",+ "integrity": "sha512-L3LgimLHXtGkWikKnsPg0/VFx9OGZaC+eN1u4r+OB1XRqH3meBIAVC2zr1WdMH+RHmnRkqliQAOHNJ/E0j/e0Q==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/keyv": {+ "version": "3.1.4",+ "resolved": "https://registry.npmjs.org/@types/keyv/-/keyv-3.1.4.tgz",+ "integrity": "sha512-BQ5aZNSCpj7D6K2ksrRCTmKRLEpnPvWDiLPfoGyhZ++8YtiK9d/3DBKPJgry359X/P1PfruyYwvnvwFjuEiEIg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/node": "*"+ }+ },+ "node_modules/@types/node": {+ "version": "20.19.43",+ "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.43.tgz",+ "integrity": "sha512-6oYBAi5ikg4Pl+kGsoYtawUMBT2zZMCvPNF7pVLnHZfd1zf38DRiWn/gT01RYCdUqkv7Fhr+C9ot4/tb+2sVvA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "undici-types": "~6.21.0"+ }+ },+ "node_modules/@types/responselike": {+ "version": "1.0.3",+ "resolved": "https://registry.npmjs.org/@types/responselike/-/responselike-1.0.3.tgz",+ "integrity": "sha512-H/+L+UkTV33uf49PH5pCAUBVPNj2nDBXTN+qS1dOwyyg24l3CcicicCA7ca+HMvJBZcFgl5r8e+RR6elsb4Lyw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/node": "*"+ }+ },+ "node_modules/@types/yauzl": {+ "version": "2.10.3",+ "resolved": "https://registry.npmjs.org/@types/yauzl/-/yauzl-2.10.3.tgz",+ "integrity": "sha512-oJoftv0LSuaDZE3Le4DbKX+KS9G36NzOeSap90UIK0yMA/NhKJhqlSGtNDORNRaIbQfzjXDrQa0ytJ6mNRGz/Q==",+ "dev": true,+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "@types/node": "*"+ }+ },+ "node_modules/boolean": {+ "version": "3.2.0",+ "resolved": "https://registry.npmjs.org/boolean/-/boolean-3.2.0.tgz",+ "integrity": "sha512-d0II/GO9uf9lfUHH2BQsjxzRJZBdsjgsBiW4BvhWk/3qoKwQFjIDVN19PfX8F2D/r9PCMTtLWjYVCFrpeYUzsw==",+ "deprecated": "Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.",+ "dev": true,+ "license": "MIT",+ "optional": true+ },+ "node_modules/buffer-crc32": {+ "version": "0.2.13",+ "resolved": "https://registry.npmjs.org/buffer-crc32/-/buffer-crc32-0.2.13.tgz",+ "integrity": "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": "*"+ }+ },+ "node_modules/cacheable-lookup": {+ "version": "5.0.4",+ "resolved": "https://registry.npmjs.org/cacheable-lookup/-/cacheable-lookup-5.0.4.tgz",+ "integrity": "sha512-2/kNscPhpcxrOigMZzbiWF7dz8ilhb/nIHU3EyZiXWXpeq/au8qJ8VhdftMkty3n7Gj6HIGalQG8oiBNB3AJgA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=10.6.0"+ }+ },+ "node_modules/cacheable-request": {+ "version": "7.0.4",+ "resolved": "https://registry.npmjs.org/cacheable-request/-/cacheable-request-7.0.4.tgz",+ "integrity": "sha512-v+p6ongsrp0yTGbJXjgxPow2+DL93DASP4kXCDKb8/bwRtt9OEF3whggkkDkGNzgcWy2XaF4a8nZglC7uElscg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "clone-response": "^1.0.2",+ "get-stream": "^5.1.0",+ "http-cache-semantics": "^4.0.0",+ "keyv": "^4.0.0",+ "lowercase-keys": "^2.0.0",+ "normalize-url": "^6.0.1",+ "responselike": "^2.0.0"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/clone-response": {+ "version": "1.0.3",+ "resolved": "https://registry.npmjs.org/clone-response/-/clone-response-1.0.3.tgz",+ "integrity": "sha512-ROoL94jJH2dUVML2Y/5PEDNaSHgeOdSDicUyS7izcF63G6sTc/FTjLub4b8Il9S8S0beOfYt0TaA5qvFK+w0wA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "mimic-response": "^1.0.0"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/debug": {+ "version": "4.4.3",+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "ms": "^2.1.3"+ },+ "engines": {+ "node": ">=6.0"+ },+ "peerDependenciesMeta": {+ "supports-color": {+ "optional": true+ }+ }+ },+ "node_modules/decompress-response": {+ "version": "6.0.0",+ "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz",+ "integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "mimic-response": "^3.1.0"+ },+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/decompress-response/node_modules/mimic-response": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz",+ "integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/defer-to-connect": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/defer-to-connect/-/defer-to-connect-2.0.1.tgz",+ "integrity": "sha512-4tvttepXG1VaYGrRibk5EwJd1t4udunSOVMdLSAL6mId1ix438oPwPZMALY41FCijukO1L0twNcGsdzS7dHgDg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/define-data-property": {+ "version": "1.1.4",+ "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz",+ "integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==",+ "dev": true,+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "es-define-property": "^1.0.0",+ "es-errors": "^1.3.0",+ "gopd": "^1.0.1"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/define-properties": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.2.1.tgz",+ "integrity": "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==",+ "dev": true,+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "define-data-property": "^1.0.1",+ "has-property-descriptors": "^1.0.0",+ "object-keys": "^1.1.1"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/detect-node": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/detect-node/-/detect-node-2.1.0.tgz",+ "integrity": "sha512-T0NIuQpnTvFDATNuHN5roPwSBG83rFsuO+MXXH9/3N1eFbn4wcPjttvjMLEPWJ0RGUYgQE7cGgS3tNxbqCGM7g==",+ "dev": true,+ "license": "MIT",+ "optional": true+ },+ "node_modules/electron": {+ "version": "33.4.11",+ "resolved": "https://registry.npmjs.org/electron/-/electron-33.4.11.tgz",+ "integrity": "sha512-xmdAs5QWRkInC7TpXGNvzo/7exojubk+72jn1oJL7keNeIlw7xNglf8TGtJtkR4rWC5FJq0oXiIXPS9BcK2Irg==",+ "dev": true,+ "hasInstallScript": true,+ "license": "MIT",+ "dependencies": {+ "@electron/get": "^2.0.0",+ "@types/node": "^20.9.0",+ "extract-zip": "^2.0.1"+ },+ "bin": {+ "electron": "cli.js"+ },+ "engines": {+ "node": ">= 12.20.55"+ }+ },+ "node_modules/end-of-stream": {+ "version": "1.4.5",+ "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz",+ "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "once": "^1.4.0"+ }+ },+ "node_modules/env-paths": {+ "version": "2.2.1",+ "resolved": "https://registry.npmjs.org/env-paths/-/env-paths-2.2.1.tgz",+ "integrity": "sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/es-define-property": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",+ "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",+ "dev": true,+ "license": "MIT",+ "optional": true,+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/es-errors": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",+ "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",+ "dev": true,+ "license": "MIT",+ "optional": true,+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/es6-error": {+ "version": "4.1.1",+ "resolved": "https://registry.npmjs.org/es6-error/-/es6-error-4.1.1.tgz",+ "integrity": "sha512-Um/+FxMr9CISWh0bi5Zv0iOD+4cFh5qLeks1qhAopKVAJw3drgKbKySikp7wGhDL0HPeaja0P5ULZrxLkniUVg==",+ "dev": true,+ "license": "MIT",+ "optional": true+ },+ "node_modules/escape-string-regexp": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz",+ "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==",+ "dev": true,+ "license": "MIT",+ "optional": true,+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/extract-zip": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/extract-zip/-/extract-zip-2.0.1.tgz",+ "integrity": "sha512-GDhU9ntwuKyGXdZBUgTIe+vXnWj0fppUEtMDL0+idd5Sta8TGpHssn/eusA9mrPr9qNDym6SxAYZjNvCn/9RBg==",+ "dev": true,+ "license": "BSD-2-Clause",+ "dependencies": {+ "debug": "^4.1.1",+ "get-stream": "^5.1.0",+ "yauzl": "^2.10.0"+ },+ "bin": {+ "extract-zip": "cli.js"+ },+ "engines": {+ "node": ">= 10.17.0"+ },+ "optionalDependencies": {+ "@types/yauzl": "^2.9.1"+ }+ },+ "node_modules/fd-slicer": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/fd-slicer/-/fd-slicer-1.1.0.tgz",+ "integrity": "sha512-cE1qsB/VwyQozZ+q1dGxR8LBYNZeofhEdUNGSMbQD3Gw2lAzX9Zb3uIU6Ebc/Fmyjo9AWWfnn0AUCHqtevs/8g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "pend": "~1.2.0"+ }+ },+ "node_modules/fs-extra": {+ "version": "8.1.0",+ "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-8.1.0.tgz",+ "integrity": "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "graceful-fs": "^4.2.0",+ "jsonfile": "^4.0.0",+ "universalify": "^0.1.0"+ },+ "engines": {+ "node": ">=6 <7 || >=8"+ }+ },+ "node_modules/get-stream": {+ "version": "5.2.0",+ "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-5.2.0.tgz",+ "integrity": "sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "pump": "^3.0.0"+ },+ "engines": {+ "node": ">=8"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/global-agent": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/global-agent/-/global-agent-3.0.0.tgz",+ "integrity": "sha512-PT6XReJ+D07JvGoxQMkT6qji/jVNfX/h364XHZOWeRzy64sSFr+xJ5OX7LI3b4MPQzdL4H8Y8M0xzPpsVMwA8Q==",+ "dev": true,+ "license": "BSD-3-Clause",+ "optional": true,+ "dependencies": {+ "boolean": "^3.0.1",+ "es6-error": "^4.1.1",+ "matcher": "^3.0.0",+ "roarr": "^2.15.3",+ "semver": "^7.3.2",+ "serialize-error": "^7.0.1"+ },+ "engines": {+ "node": ">=10.0"+ }+ },+ "node_modules/global-agent/node_modules/semver": {+ "version": "7.8.5",+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",+ "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",+ "dev": true,+ "license": "ISC",+ "optional": true,+ "bin": {+ "semver": "bin/semver.js"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/globalthis": {+ "version": "1.0.4",+ "resolved": "https://registry.npmjs.org/globalthis/-/globalthis-1.0.4.tgz",+ "integrity": "sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==",+ "dev": true,+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "define-properties": "^1.2.1",+ "gopd": "^1.0.1"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/gopd": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",+ "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",+ "dev": true,+ "license": "MIT",+ "optional": true,+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/got": {+ "version": "11.8.6",+ "resolved": "https://registry.npmjs.org/got/-/got-11.8.6.tgz",+ "integrity": "sha512-6tfZ91bOr7bOXnK7PRDCGBLa1H4U080YHNaAQ2KsMGlLEzRbk44nsZF2E1IeRc3vtJHPVbKCYgdFbaGO2ljd8g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@sindresorhus/is": "^4.0.0",+ "@szmarczak/http-timer": "^4.0.5",+ "@types/cacheable-request": "^6.0.1",+ "@types/responselike": "^1.0.0",+ "cacheable-lookup": "^5.0.3",+ "cacheable-request": "^7.0.2",+ "decompress-response": "^6.0.0",+ "http2-wrapper": "^1.0.0-beta.5.2",+ "lowercase-keys": "^2.0.0",+ "p-cancelable": "^2.0.0",+ "responselike": "^2.0.0"+ },+ "engines": {+ "node": ">=10.19.0"+ },+ "funding": {+ "url": "https://github.com/sindresorhus/got?sponsor=1"+ }+ },+ "node_modules/graceful-fs": {+ "version": "4.2.11",+ "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",+ "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==",+ "dev": true,+ "license": "ISC"+ },+ "node_modules/has-property-descriptors": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz",+ "integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==",+ "dev": true,+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "es-define-property": "^1.0.0"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/http-cache-semantics": {+ "version": "4.3.0",+ "resolved": "https://registry.npmjs.org/http-cache-semantics/-/http-cache-semantics-4.3.0.tgz",+ "integrity": "sha512-M5t5LlJpS1UHMjvwRQVdFHvPISGeLAxNcrWuJkeGh0KxsqCHZ1O3NXZU/8x7cD0BDcGW8kapxMKTvwlqrNkHkA==",+ "dev": true,+ "license": "BSD-2-Clause"+ },+ "node_modules/http2-wrapper": {+ "version": "1.0.3",+ "resolved": "https://registry.npmjs.org/http2-wrapper/-/http2-wrapper-1.0.3.tgz",+ "integrity": "sha512-V+23sDMr12Wnz7iTcDeJr3O6AIxlnvT/bmaAAAP/Xda35C90p9599p0F1eHR/N1KILWSoWVAiOMFjBBXaXSMxg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "quick-lru": "^5.1.1",+ "resolve-alpn": "^1.0.0"+ },+ "engines": {+ "node": ">=10.19.0"+ }+ },+ "node_modules/json-buffer": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz",+ "integrity": "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/json-stringify-safe": {+ "version": "5.0.1",+ "resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz",+ "integrity": "sha512-ZClg6AaYvamvYEE82d3Iyd3vSSIjQ+odgjaTzRuO3s7toCdFKczob2i0zCh7JE8kWn17yvAWhUVxvqGwUalsRA==",+ "dev": true,+ "license": "ISC",+ "optional": true+ },+ "node_modules/jsonfile": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz",+ "integrity": "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg==",+ "dev": true,+ "license": "MIT",+ "optionalDependencies": {+ "graceful-fs": "^4.1.6"+ }+ },+ "node_modules/keyv": {+ "version": "4.5.4",+ "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz",+ "integrity": "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "json-buffer": "3.0.1"+ }+ },+ "node_modules/lowercase-keys": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/lowercase-keys/-/lowercase-keys-2.0.0.tgz",+ "integrity": "sha512-tqNXrS78oMOE73NMxK4EMLQsQowWf8jKooH9g7xPavRT706R6bkQJ6DY2Te7QukaZsulxa30wQ7bk0pm4XiHmA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/matcher": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/matcher/-/matcher-3.0.0.tgz",+ "integrity": "sha512-OkeDaAZ/bQCxeFAozM55PKcKU0yJMPGifLwV4Qgjitu+5MoAfSQN4lsLJeXZ1b8w0x+/Emda6MZgXS1jvsapng==",+ "dev": true,+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "escape-string-regexp": "^4.0.0"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/mimic-response": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-1.0.1.tgz",+ "integrity": "sha512-j5EctnkH7amfV/q5Hgmoal1g2QHFJRraOtmx0JpIqkxhBhI/lJSl1nMpQ45hVarwNETOoWEimndZ4QK0RHxuxQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=4"+ }+ },+ "node_modules/ms": {+ "version": "2.1.3",+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/normalize-url": {+ "version": "6.1.0",+ "resolved": "https://registry.npmjs.org/normalize-url/-/normalize-url-6.1.0.tgz",+ "integrity": "sha512-DlL+XwOy3NxAQ8xuC0okPgK46iuVNAK01YN7RueYBqqFeGsBjV9XmCAzAdgt+667bCl5kPh9EqKKDwnaPG1I7A==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/object-keys": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz",+ "integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==",+ "dev": true,+ "license": "MIT",+ "optional": true,+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/once": {+ "version": "1.4.0",+ "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",+ "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",+ "dev": true,+ "license": "ISC",+ "dependencies": {+ "wrappy": "1"+ }+ },+ "node_modules/p-cancelable": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/p-cancelable/-/p-cancelable-2.1.1.tgz",+ "integrity": "sha512-BZOr3nRQHOntUjTrH8+Lh54smKHoHyur8We1V8DSMVrl5A2malOOwuJRnKRDjSnkoeBh4at6BwEnb5I7Jl31wg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/pend": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/pend/-/pend-1.2.0.tgz",+ "integrity": "sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/progress": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/progress/-/progress-2.0.3.tgz",+ "integrity": "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=0.4.0"+ }+ },+ "node_modules/pump": {+ "version": "3.0.4",+ "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz",+ "integrity": "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "end-of-stream": "^1.1.0",+ "once": "^1.3.1"+ }+ },+ "node_modules/quick-lru": {+ "version": "5.1.1",+ "resolved": "https://registry.npmjs.org/quick-lru/-/quick-lru-5.1.1.tgz",+ "integrity": "sha512-WuyALRjWPDGtt/wzJiadO5AXY+8hZ80hVpe6MyivgraREW751X3SbhRvG3eLKOYN+8VEvqLcf3wdnt44Z4S4SA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/resolve-alpn": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/resolve-alpn/-/resolve-alpn-1.2.1.tgz",+ "integrity": "sha512-0a1F4l73/ZFZOakJnQ3FvkJ2+gSTQWz/r2KE5OdDY0TxPm5h4GkqkWWfM47T7HsbnOtcJVEF4epCVy6u7Q3K+g==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/responselike": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/responselike/-/responselike-2.0.1.tgz",+ "integrity": "sha512-4gl03wn3hj1HP3yzgdI7d3lCkF95F21Pz4BPGvKHinyQzALR5CapwC8yIi0Rh58DEMQ/SguC03wFj2k0M/mHhw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "lowercase-keys": "^2.0.0"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/roarr": {+ "version": "2.15.4",+ "resolved": "https://registry.npmjs.org/roarr/-/roarr-2.15.4.tgz",+ "integrity": "sha512-CHhPh+UNHD2GTXNYhPWLnU8ONHdI+5DI+4EYIAOaiD63rHeYlZvyh8P+in5999TTSFgUYuKUAjzRI4mdh/p+2A==",+ "dev": true,+ "license": "BSD-3-Clause",+ "optional": true,+ "dependencies": {+ "boolean": "^3.0.1",+ "detect-node": "^2.0.4",+ "globalthis": "^1.0.1",+ "json-stringify-safe": "^5.0.1",+ "semver-compare": "^1.0.0",+ "sprintf-js": "^1.1.2"+ },+ "engines": {+ "node": ">=8.0"+ }+ },+ "node_modules/semver": {+ "version": "6.3.1",+ "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",+ "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==",+ "dev": true,+ "license": "ISC",+ "bin": {+ "semver": "bin/semver.js"+ }+ },+ "node_modules/semver-compare": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/semver-compare/-/semver-compare-1.0.0.tgz",+ "integrity": "sha512-YM3/ITh2MJ5MtzaM429anh+x2jiLVjqILF4m4oyQB18W7Ggea7BfqdH/wGMK7dDiMghv/6WG7znWMwUDzJiXow==",+ "dev": true,+ "license": "MIT",+ "optional": true+ },+ "node_modules/serialize-error": {+ "version": "7.0.1",+ "resolved": "https://registry.npmjs.org/serialize-error/-/serialize-error-7.0.1.tgz",+ "integrity": "sha512-8I8TjW5KMOKsZQTvoxjuSIa7foAwPWGOts+6o7sgjz41/qMD9VQHEDxi6PBvK2l0MXUmqZyNpUK+T2tQaaElvw==",+ "dev": true,+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "type-fest": "^0.13.1"+ },+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/sprintf-js": {+ "version": "1.1.3",+ "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.1.3.tgz",+ "integrity": "sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA==",+ "dev": true,+ "license": "BSD-3-Clause",+ "optional": true+ },+ "node_modules/sumchecker": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/sumchecker/-/sumchecker-3.0.1.tgz",+ "integrity": "sha512-MvjXzkz/BOfyVDkG0oFOtBxHX2u3gKbMHIF/dXblZsgD3BWOFLmHovIpZY7BykJdAjcqRCBi1WYBNdEC9yI7vg==",+ "dev": true,+ "license": "Apache-2.0",+ "dependencies": {+ "debug": "^4.1.0"+ },+ "engines": {+ "node": ">= 8.0"+ }+ },+ "node_modules/type-fest": {+ "version": "0.13.1",+ "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.13.1.tgz",+ "integrity": "sha512-34R7HTnG0XIJcBSn5XhDd7nNFPRcXYRZrBB2O2jdKqYODldSzBAqzsWoZYYvduky73toYS/ESqxPvkDf/F0XMg==",+ "dev": true,+ "license": "(MIT OR CC0-1.0)",+ "optional": true,+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/undici-types": {+ "version": "6.21.0",+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",+ "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/universalify": {+ "version": "0.1.2",+ "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.2.tgz",+ "integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 4.0.0"+ }+ },+ "node_modules/wrappy": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",+ "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",+ "dev": true,+ "license": "ISC"+ },+ "node_modules/yauzl": {+ "version": "2.10.0",+ "resolved": "https://registry.npmjs.org/yauzl/-/yauzl-2.10.0.tgz",+ "integrity": "sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "buffer-crc32": "~0.2.3",+ "fd-slicer": "~1.1.0"+ }+ }+ }+}diff --git a/package.json b/package.jsonnew file mode 100644index 0000000..226df75--- /dev/null+++ b/package.json@@ -0,0 +1,45 @@+{+ "name": "apkstart",+ "productName": "ApkStart",+ "version": "0.1.0",+ "description": "极致轻量的 Windows 安卓应用运行器:双击 APK 即装,应用以独立窗口与桌面图标运行",+ "main": "src/main.js",+ "author": "RoutineMiku",+ "license": "MIT",+ "private": true,+ "homepage": "https://github.com/RoutineMiku/apkstart#readme",+ "repository": {+ "type": "git",+ "url": "git+https://github.com/RoutineMiku/apkstart.git"+ },+ "bugs": {+ "url": "https://github.com/RoutineMiku/apkstart/issues"+ },+ "keywords": [+ "android",+ "emulator",+ "apk",+ "windows",+ "qemu",+ "electron",+ "wsa",+ "freeform"+ ],+ "engines": {+ "node": ">=20"+ },+ "os": [+ "win32"+ ],+ "scripts": {+ "start": "electron .",+ "dev": "electron . --dev",+ "test": "node test/run-tests.js && node test/engine-test.js",+ "pack": "node build/pack.js",+ "assoc:on": "node scripts/assoc.js on",+ "assoc:off": "node scripts/assoc.js off"+ },+ "devDependencies": {+ "electron": "^33.4.11"+ }+}diff --git a/scripts/assoc.js b/scripts/assoc.jsnew file mode 100644index 0000000..1a6bc59--- /dev/null+++ b/scripts/assoc.js@@ -0,0 +1,31 @@+#!/usr/bin/env node+'use strict';+/**+ * .apk 关联命令行开关(无需启动界面)+ * node scripts/assoc.js on → 注册双击 APK 安装+ * node scripts/assoc.js off → 取消关联+ */+const path = require('path');+const fs = require('fs');+const { registerAssociation, unregisterAssociation } = require('../src/core/assoc');++const action = process.argv[2] || 'on';+const isDev = !process.env.APKSTART_PACKAGED;+const exe = isDev+ ? path.join(__dirname, '..', 'node_modules', 'electron', 'dist', 'electron.exe')+ : process.execPath;+const appDir = path.join(__dirname, '..');++if (action === 'on') {+ const iconPath = path.join(__dirname, '..', 'build', 'apkstart.ico');+ const r = registerAssociation(exe, fs.existsSync(iconPath) ? iconPath : undefined,+ isDev ? `"${appDir}"` : undefined);+ console.log('已注册 .apk 关联:', r.progId);+ console.log('现在在资源管理器中双击 .apk 即可安装到 ApkStart。');+} else if (action === 'off') {+ unregisterAssociation();+ console.log('已取消 .apk 关联。');+} else {+ console.log('用法:node scripts/assoc.js [on|off]');+ process.exit(1);+}diff --git a/src/core/adb.js b/src/core/adb.jsnew file mode 100644index 0000000..47cf7a1--- /dev/null+++ b/src/core/adb.js@@ -0,0 +1,270 @@+'use strict';+/**+ * adb 客户端封装+ * 只做 apkstart 需要的那部分:安装 / 启动 / 停止 / 卸载 / 文件同步 / 截图+ */+const { execFile } = require('child_process');+const fs = require('fs');+const path = require('path');++const COMMON_ADB_PATHS = [+ path.join(process.env.LOCALAPPDATA || '', 'Android', 'Sdk', 'platform-tools', 'adb.exe'),+ 'C:\\Android\\platform-tools\\adb.exe',+ 'C:\\adb\\adb.exe',+ 'C:\\LDPlayer\\LDPlayer9\\adb.exe',+ 'C:\\Program Files\\Netease\\MuMuPlayer-12.0\\shell\\adb.exe',+ 'C:\\Program Files\\BlueStacks_nxt\\HD-Adb.exe',+];++class AdbError extends Error {+ constructor(message, stderr, code) {+ super(message);+ this.stderr = stderr;+ this.code = code;+ }+}++class AdbClient {+ constructor({ adbPath, serial }) {+ this.adbPath = adbPath || 'adb';+ this.serial = serial || '';+ }++ static resolveAdb(explicit, appRoot) {+ const candidates = [+ explicit,+ appRoot && path.join(appRoot, 'tools', 'platform-tools', 'adb.exe'),+ ...COMMON_ADB_PATHS,+ ].filter(Boolean);+ for (const c of candidates) {+ try { if (fs.existsSync(c)) return c; } catch (_) { /* ignore */ }+ }+ return 'adb'; // 交给 PATH+ }++ _args(args, withSerial = true) {+ const a = [];+ if (withSerial && this.serial) a.push('-s', this.serial);+ return a.concat(args);+ }++ exec(args, { timeout = 30000, withSerial = true, binary = false } = {}) {+ return new Promise((resolve, reject) => {+ const finalArgs = this._args(args, withSerial);+ execFile(this.adbPath, finalArgs, {+ timeout,+ maxBuffer: 64 * 1024 * 1024,+ encoding: binary ? 'buffer' : 'utf8',+ windowsHide: true,+ }, (err, stdout, stderr) => {+ if (err) {+ return reject(new AdbError(+ `adb ${finalArgs.join(' ')} 失败: ${String(stderr || err.message).trim()}`,+ stderr, err.code,+ ));+ }+ resolve({ stdout, stderr });+ });+ });+ }++ async shell(cmd, opts = {}) {+ const { stdout } = await this.exec(['shell', cmd], opts);+ return typeof stdout === 'string' ? stdout.trim() : stdout;+ }++ async version() {+ const { stdout } = await this.exec(['version'], { withSerial: false });+ const m = /version\s+([\d.]+)/i.exec(stdout);+ return m ? m[1] : stdout.trim();+ }++ async connect() {+ if (!this.serial.includes(':')) return true;+ try {+ await this.exec(['connect', this.serial], { withSerial: false, timeout: 15000 });+ } catch (_) { /* 可能已连接 */ }+ return this.isOnline();+ }++ async isOnline() {+ try {+ const { stdout } = await this.exec(['get-state'], { timeout: 8000 });+ return stdout.trim() === 'device';+ } catch (_) {+ // get-state 在未指定 serial 时不可用,退化用 devices 列表+ try {+ const { stdout } = await this.exec(['devices'], { withSerial: false, timeout: 8000 });+ return stdout.split('\n').some((l) => l.startsWith(this.serial) && l.includes('device'));+ } catch (_) {+ return false;+ }+ }+ }++ async devices() {+ const { stdout } = await this.exec(['devices', '-l'], { withSerial: false });+ return stdout.split('\n').slice(1)+ .map((l) => l.trim())+ .filter((l) => l && l.includes('device') && !l.startsWith('*'))+ .map((l) => {+ const parts = l.split(/\s+/);+ return { serial: parts[0], state: parts[1], model: (l.match(/model:(\S+)/) || [])[1] || '' };+ })+ .filter((d) => d.state === 'device');+ }++ async install(apkPath) {+ if (!fs.existsSync(apkPath)) throw new Error(`APK 不存在: ${apkPath}`);+ const { stdout } = await this.exec(['install', '-r', '-g', '-t', apkPath], { timeout: 180000 });+ if (/Failure|Error/i.test(stdout) && !/Success/i.test(stdout)) {+ throw new Error(stdout.trim());+ }+ return stdout.trim();+ }++ async uninstall(pkg) {+ try {+ await this.exec(['uninstall', pkg], { timeout: 60000 });+ } catch (e) {+ // 部分设备需要指定 user+ await this.exec(['shell', 'pm', 'uninstall', '--user', '0', pkg], { timeout: 60000 });+ }+ }++ async isInstalled(pkg) {+ const out = await this.shell(`pm path ${pkg}`);+ return /package:/.test(out);+ }++ async listPackages() {+ const out = await this.shell('pm list packages -3');+ return out.split('\n').map((l) => l.replace('package:', '').trim()).filter(Boolean);+ }++ /** 启动应用;freeform=true 时以独立窗口模式启动 */+ async startApp(pkg, activity, { freeform = true, bounds = null, forceStop = false } = {}) {+ if (forceStop) await this.forceStop(pkg);+ const parts = ['am', 'start'];+ if (freeform) parts.push('--windowingMode', '5');+ parts.push('--activity-clear-top');+ if (activity) parts.push('-n', `${pkg}/${activity}`);+ else parts.push('-a', 'android.intent.action.MAIN', '-c', 'android.intent.category.LAUNCHER', '-p', pkg);+ const out = await this.shell(parts.join(' '));+ if (/Error|Exception/i.test(out)) throw new Error(out);+ if (bounds) {+ // 尽力而为:把新任务挪到上次的位置+ this.resizeTaskOfPackage(pkg, bounds).catch(() => {});+ }+ return out;+ }++ async forceStop(pkg) {+ try { await this.shell(`am force-stop ${pkg}`); } catch (_) { /* ignore */ }+ }++ async runningPackages() {+ try {+ const out = await this.shell('dumpsys activity activities | grep -E "mResumedActivity|ResumedActivity"');+ const pkgs = [...out.matchAll(/([a-zA-Z][\w.]+\/[.\w$]+)/g)].map((m) => m[1].split('/')[0]);+ return [...new Set(pkgs)];+ } catch (_) {+ return [];+ }+ }++ async taskIdOfPackage(pkg) {+ try {+ const out = await this.shell('dumpsys activity recents');+ const blocks = out.split('Recent #');+ for (const b of blocks) {+ if (!b.includes(pkg)) continue;+ const m = /taskId=(\d+)/.exec(b) || /^\d+/.exec(b);+ if (m) return Number(m[1] || m[0]);+ }+ } catch (_) { /* ignore */ }+ return null;+ }++ async resizeTaskOfPackage(pkg, bounds) {+ const id = await this.taskIdOfPackage(pkg);+ if (!id) return false;+ await this.shell(`am task resize ${id} ${bounds.left} ${bounds.top} ${bounds.right} ${bounds.bottom}`);+ return true;+ }++ /** 开启 freeform(独立窗口)支持,失败不影响主流程 */+ async ensureFreeform() {+ const cmds = [+ 'settings put global enable_freeform_support 1',+ 'settings put global force_resizable_activities 1',+ 'settings put global development_settings_enabled 1',+ ];+ for (const c of cmds) {+ try { await this.shell(c); } catch (_) { /* ignore */ }+ }+ const v = await this.shell('settings get global enable_freeform_support').catch(() => '0');+ return v.trim() === '1';+ }++ async wmSize() {+ const out = await this.shell('wm size');+ const m = /(\d+)x(\d+)/.exec(out.split('\n').pop() || out);+ return m ? { width: Number(m[1]), height: Number(m[2]) } : null;+ }++ async androidVersion() {+ return (await this.shell('getprop ro.build.version.release').catch(() => '')).trim();+ }++ async sdkInt() {+ const v = await this.shell('getprop ro.build.version.sdk').catch(() => '0');+ return Number(v.trim()) || 0;+ }++ async screenshot() {+ const { stdout } = await this.exec(['exec-out', 'screencap', '-p'], { binary: true, timeout: 20000 });+ return Buffer.isBuffer(stdout) ? stdout : Buffer.from(stdout);+ }++ async push(local, remote) {+ await this.exec(['push', local, remote], { timeout: 180000 });+ }++ async pull(remote, local) {+ await this.exec(['pull', remote, local], { timeout: 180000 });+ }++ async shellMkdir(remote) {+ await this.shell(`mkdir -p "${remote}"`);+ }++ async listRemote(remote) {+ const out = await this.shell(`ls -l "${remote}" 2>/dev/null`);+ return out.split('\n').map((l) => {+ const m = /^([\-dl])\S+\s+\d+\s+\S+\s+\S+\s+(\d+)\s+(\S+\s+\d+\s+[\d:]+)\s+(.+)$/.exec(l.trim());+ return m ? { isDir: m[1] === 'd', size: Number(m[2]), name: m[4] } : null;+ }).filter(Boolean);+ }++ /** 清除应用数据 */+ async clearData(pkg) {+ await this.shell(`pm clear ${pkg}`);+ }++ /** 导出应用数据(Windows/调试版可用 run-as;否则走 adb backup 兜底) */+ async exportAppData(pkg, localTarPath) {+ const remote = `/sdcard/apkstart-tmp-${pkg}.tar`;+ const cmd = `run-as ${pkg} tar -cf ${remote} . 2>/dev/null || (cd /data/data/${pkg} && tar -cf ${remote} .)`;+ await this.shell(cmd);+ await this.pull(remote, localTarPath);+ await this.shell(`rm -f ${remote}`).catch(() => {});+ return localTarPath;+ }++ async batteryOptimizeOff(pkg) {+ try { await this.shell(`dumpsys deviceidle whitelist +${pkg}`); } catch (_) { /* ignore */ }+ }+}++module.exports = { AdbClient, AdbError };diff --git a/src/core/apk.js b/src/core/apk.jsnew file mode 100644index 0000000..2be328e--- /dev/null+++ b/src/core/apk.js@@ -0,0 +1,190 @@+'use strict';+/**+ * APK 元信息提取:包名 / 版本 / 应用名 / 启动 Activity / 图标 / ABI+ * 全部离线完成,不需要 aapt、不需要 adb、不需要联网。+ */+const fs = require('fs');+const path = require('path');+const { ZipArchive } = require('./zip');+const { parseAxml, attr, attrValue, children, ANDROID_NS } = require('./axml');+const { ResTable } = require('./arsc');++const LAUNCHER_ACTIONS = ['android.intent.action.MAIN'];+const LAUNCHER_CATS = ['android.intent.category.LAUNCHER'];++function isLauncherActivity(node) {+ const filters = children(node, 'intent-filter');+ for (const f of filters) {+ const actions = children(f, 'action').map((a) => attrValue(a, 'name'));+ const cats = children(f, 'category').map((c) => attrValue(c, 'name'));+ const hasMain = actions.some((a) => LAUNCHER_ACTIONS.includes(a));+ const hasLauncher = cats.some((c) => LAUNCHER_CATS.includes(c));+ if (hasMain && hasLauncher) return true;+ }+ return false;+}++function pickIconFromZip(zip) {+ // 兜底:在 res/ 里找最大的、名字像图标的 png+ const candidates = zip.names().filter((n) => /^res\/.*\.(png|webp)$/i.test(n));+ const scored = candidates.map((n) => {+ const e = zip.entries.get(n);+ let s = e.uncompSize;+ if (/ic_launcher|app_icon|ic_app/i.test(n)) s *= 6;+ if (/_round|_foreground|_background/i.test(n)) s *= 0.4;+ if (/xxxhdpi/i.test(n)) s *= 1.6;+ else if (/xxhdpi/i.test(n)) s *= 1.4;+ else if (/xhdpi/i.test(n)) s *= 1.2;+ if (/\//.test(n.split('/')[1] || '')) { /* noop */ }+ return { n, s };+ }).sort((a, b) => b.s - a.s);+ for (const c of scored.slice(0, 30)) {+ try {+ const data = zip.read(c.n);+ if (data && data.length > 100) return { data, file: c.n };+ } catch (_) { /* ignore */ }+ }+ return null;+}++/** 从自适应图标 XML 里找出可用的前景/背景位图 */+function iconFromAdaptiveXml(zip, xmlBuffer, res) {+ let root;+ try {+ root = parseAxml(xmlBuffer);+ } catch (_) {+ return null;+ }+ const order = ['foreground', 'background', 'monochrome'];+ for (const key of order) {+ const node = root.children.find((c) => c.name === key) || (root.name === key ? root : null);+ if (!node) continue;+ const a = attr(node, 'drawable');+ if (!a) continue;+ let file = null;+ if (a.refId && res) file = res.resolve(a.refId, 'file');+ else if (typeof a.typed === 'string') file = a.typed;+ if (!file || !/\.(png|webp)$/i.test(file)) continue;+ if (!zip.has(file)) continue;+ const data = zip.read(file);+ if (data && data.length > 100) return { data, file };+ }+ return null;+}++function parseApk(filePath) {+ const stat = fs.statSync(filePath);+ if (stat.size < 1024) throw new Error('文件过小,不是有效的 APK');+ const buf = fs.readFileSync(filePath);+ const zip = new ZipArchive(buf);++ if (!zip.has('AndroidManifest.xml')) {+ throw new Error('缺少 AndroidManifest.xml:这不是单个 APK(可能是 .apks/.xapk 拆分包)');+ }++ const manifestBuf = zip.read('AndroidManifest.xml');+ const manifest = parseAxml(manifestBuf);++ const packageName = attrValue(manifest, 'package', null) || attrValue(manifest, 'package');+ if (!packageName) throw new Error('清单中未找到 package 名');++ const versionName = attrValue(manifest, 'versionName') || '1.0';+ const versionCodeRaw = attrValue(manifest, 'versionCode');+ const versionCode = typeof versionCodeRaw === 'number' ? versionCodeRaw : 0;++ const usesSdk = children(manifest, 'uses-sdk')[0];+ const minSdk = usesSdk ? (attrValue(usesSdk, 'minSdkVersion') | 0) : 0;+ const targetSdk = usesSdk ? (attrValue(usesSdk, 'targetSdkVersion') | 0) : 0;++ const app = children(manifest, 'application')[0] || { children: [], attrs: [] };++ // ---- 资源表(用于解析 @0x7f 引用)----+ let res = null;+ if (zip.has('resources.arsc')) {+ try { res = new ResTable(zip.read('resources.arsc')); } catch (_) { res = null; }+ }++ // ---- 应用名 ----+ let label = null;+ const labelAttr = attr(app, 'label');+ if (labelAttr) {+ if (labelAttr.refId && res) label = res.resolve(labelAttr.refId, 'string');+ else if (typeof labelAttr.typed === 'string') label = labelAttr.typed;+ }+ if (!label || typeof label !== 'string') {+ label = packageName.split('.').pop();+ label = label.charAt(0).toUpperCase() + label.slice(1);+ }++ // ---- 启动 Activity ----+ let launchActivity = null;+ const acts = children(app, 'activity').concat(children(app, 'activity-alias'));+ const launcher = acts.find(isLauncherActivity);+ if (launcher) {+ const n = attrValue(launcher, 'name');+ const target = attrValue(launcher, 'targetActivity');+ if (n) {+ if (n.startsWith('.')) launchActivity = packageName + n;+ else if (!n.includes('.')) launchActivity = `${packageName}.${n}`;+ else launchActivity = n;+ if (launcher.name === 'activity-alias' && target) {+ launchActivity = target.startsWith('.') ? packageName + target : target;+ }+ }+ }++ // ---- 图标 ----+ let icon = null;+ const iconAttr = attr(app, 'icon') || attr(app, 'roundIcon');+ if (iconAttr) {+ let file = null;+ if (iconAttr.refId && res) file = res.resolve(iconAttr.refId, 'file');+ else if (typeof iconAttr.typed === 'string') file = iconAttr.typed;++ if (file && zip.has(file)) {+ if (/\.xml$/i.test(file)) {+ icon = iconFromAdaptiveXml(zip, zip.read(file), res);+ } else {+ icon = { data: zip.read(file), file };+ }+ }+ }+ if (!icon) icon = pickIconFromZip(zip);++ // ---- ABI(判断 x86 运行时能否直接跑 ARM 原生库)----+ const abis = [...new Set(zip.names()+ .filter((n) => n.startsWith('lib/'))+ .map((n) => n.split('/')[1])+ .filter(Boolean))];++ return {+ ok: true,+ filePath,+ sizeBytes: stat.size,+ package: packageName,+ label: String(label).replace(/\s+/g, ' ').trim().slice(0, 60),+ versionName: String(versionName),+ versionCode,+ minSdk,+ targetSdk,+ launchActivity,+ abis,+ iconPng: icon ? icon.data : null,+ iconFile: icon ? icon.file : null,+ };+}++/** 轻量校验:只看头部是不是 PK\x03\x04 */+function quickCheck(filePath) {+ try {+ const fd = fs.openSync(filePath, 'r');+ const b = Buffer.alloc(4);+ fs.readSync(fd, b, 0, 4, 0);+ fs.closeSync(fd);+ return b[0] === 0x50 && b[1] === 0x4b;+ } catch (_) {+ return false;+ }+}++module.exports = { parseApk, quickCheck };diff --git a/src/core/arsc.js b/src/core/arsc.jsnew file mode 100644index 0000000..fa262c0--- /dev/null+++ b/src/core/arsc.js@@ -0,0 +1,233 @@+'use strict';+/**+ * resources.arsc 解析器(精简版)+ * 用途:把 AndroidManifest 里的 @0x7f... 资源引用还原成+ * 应用名(字符串)和图标文件路径(res/... 下的 png)。+ *+ * 只解析 ResTable / ResTable_package / ResTable_type 三层结构,+ * 足以覆盖 99% 的应用名与图标场景。+ */++const RES_TABLE_TYPE = 0x0002;+const RES_STRING_POOL_TYPE = 0x0001;+const RES_TABLE_PACKAGE_TYPE = 0x0200;+const RES_TABLE_TYPE_TYPE = 0x0201;+const RES_TABLE_TYPE_SPEC_TYPE = 0x0202;++const TYPE_REFERENCE = 0x01;+const TYPE_STRING = 0x03;+const TYPE_INT_DEC = 0x10;+const TYPE_INT_HEX = 0x11;+const TYPE_INT_BOOLEAN = 0x12;++function readStringPool(buf, start) {+ const headerSize = buf.readUInt16LE(start + 2);+ const count = buf.readUInt32LE(start + 8);+ const flags = buf.readUInt32LE(start + 16);+ const stringsStart = buf.readUInt32LE(start + 20);+ const isUtf8 = (flags & 0x100) !== 0;+ const base = start + stringsStart;+ const out = new Array(count);+ for (let i = 0; i < count; i++) {+ let p = base + buf.readUInt32LE(start + headerSize + i * 4);+ if (isUtf8) {+ let len = buf[p++];+ if (len & 0x80) { len = ((len & 0x7f) << 8) | buf[p++]; }+ let byteLen = buf[p++];+ if (byteLen & 0x80) { byteLen = ((byteLen & 0x7f) << 8) | buf[p++]; }+ out[i] = buf.toString('utf8', p, p + byteLen);+ } else {+ let len = buf.readUInt16LE(p); p += 2;+ if (len & 0x8000) { len = ((len & 0x7fff) << 16) | buf.readUInt16LE(p); p += 2; }+ out[i] = buf.toString('utf16le', p, p + len * 2);+ }+ }+ return out;+}++function parseConfig(buf, off) {+ const size = buf.readUInt32LE(off);+ const cfg = { size, density: 0, language: '', country: '', sdkVersion: 0, isDefault: true };+ if (size >= 16) {+ const lang = buf.toString('latin1', off + 8, off + 10).replace(/\0/g, '').trim();+ const country = buf.toString('latin1', off + 10, off + 12).replace(/\0/g, '').trim();+ cfg.language = lang;+ cfg.country = country;+ }+ if (size >= 16) cfg.density = buf.readUInt16LE(off + 14);+ if (size >= 28) cfg.sdkVersion = buf.readUInt16LE(off + 24);+ if (size >= 29) cfg.uiMode = buf.readUInt8(off + 29);+ cfg.isDefault = !cfg.language && !cfg.country && cfg.density === 0 && !cfg.sdkVersion;+ return cfg;+}++/** 为不同用途的取值打分:字符串偏好默认配置,图片偏好高密度 */+function score(cfg, prefer) {+ let s = 0;+ if (prefer === 'file') {+ s += cfg.density === 0 ? 0 : cfg.density; // 高密度优先+ if (cfg.density === 0xfffe) s -= 500; // anydpi 可能是 xml,扣分+ } else {+ s -= cfg.density === 0 ? 0 : 10; // 字符串:无密度优先+ if (cfg.language) s -= 40;+ if (cfg.sdkVersion) s -= cfg.sdkVersion / 1000;+ if (cfg.uiMode) s -= 20;+ }+ return s;+}++class ResTable {+ constructor(buffer) {+ this.buf = buffer;+ this.globalStrings = [];+ this.packages = [];+ this._parse();+ }++ _parse() {+ const buf = this.buf;+ if (buf.readUInt16LE(0) !== RES_TABLE_TYPE) throw new Error('resources.arsc 格式错误');+ const headerSize = buf.readUInt16LE(2);+ const total = buf.readUInt32LE(4);+ const pkgCount = buf.readUInt32LE(8);++ let pos = headerSize;+ while (pos < total && pos < buf.length) {+ const type = buf.readUInt16LE(pos);+ const chunkSize = buf.readUInt32LE(pos + 4);+ if (chunkSize <= 0) break;+ if (type === RES_STRING_POOL_TYPE && this.globalStrings.length === 0) {+ this.globalStrings = readStringPool(buf, pos);+ } else if (type === RES_TABLE_PACKAGE_TYPE) {+ this.packages.push(this._parsePackage(pos, chunkSize));+ }+ pos += chunkSize;+ }+ }++ _parsePackage(start, size) {+ const buf = this.buf;+ const id = buf.readUInt32LE(start + 8);+ const typeStringsOff = buf.readUInt32LE(start + 268);+ const keyStringsOff = buf.readUInt32LE(start + 276);+ const headerSize = buf.readUInt16LE(start + 2);++ let typeStrings = [];+ let keyStrings = [];+ try {+ if (typeStringsOff) typeStrings = readStringPool(buf, start + typeStringsOff);+ if (keyStringsOff) keyStrings = readStringPool(buf, start + keyStringsOff);+ } catch (_) { /* 容错:缺字符串池不影响主流程 */ }++ const types = new Map(); // typeId -> [{ config, entries: Map }]+ let pos = start + headerSize;+ const end = start + size;+ while (pos + 8 <= end) {+ const type = buf.readUInt16LE(pos);+ const chunkSize = buf.readUInt32LE(pos + 4);+ if (chunkSize <= 0) break;+ if (type === RES_TABLE_TYPE_TYPE) {+ const t = this._parseType(pos);+ if (t) {+ if (!types.has(t.id)) types.set(t.id, []);+ types.get(t.id).push(t);+ }+ }+ pos += chunkSize;+ }+ return { id, typeStrings, keyStrings, types };+ }++ _parseType(start) {+ const buf = this.buf;+ const headerSize = buf.readUInt16LE(start + 2);+ const id = buf.readUInt8(start + 8);+ const flags = buf.readUInt8(start + 9);+ const entryCount = buf.readUInt32LE(start + 12);+ const entriesStart = buf.readUInt32LE(start + 16);+ const cfg = parseConfig(buf, start + 20);++ const entries = new Map();+ const offsetsBase = start + headerSize;+ const entriesBase = start + entriesStart;++ if (flags & 0x01) {+ // FLAG_SPARSE:entryCount 个 (idx:u16, offset:u16)+ for (let i = 0; i < entryCount; i++) {+ const idx = buf.readUInt16LE(offsetsBase + i * 4);+ const off = buf.readUInt16LE(offsetsBase + i * 4 + 2) * 4;+ const v = this._readValue(entriesBase + off);+ if (v) entries.set(idx, v);+ }+ } else if (flags & 0x02) {+ // FLAG_OFFSET16+ for (let i = 0; i < entryCount; i++) {+ const off = buf.readUInt16LE(offsetsBase + i * 2);+ if (off === 0xffff) continue;+ const v = this._readValue(entriesBase + off * 4);+ if (v) entries.set(i, v);+ }+ } else {+ for (let i = 0; i < entryCount; i++) {+ const off = buf.readUInt32LE(offsetsBase + i * 4);+ if (off === 0xffffffff) continue;+ const v = this._readValue(entriesBase + off);+ if (v) entries.set(i, v);+ }+ }+ return { id, config: cfg, entries };+ }++ _readValue(at) {+ const buf = this.buf;+ if (at + 8 > buf.length) return null;+ const entrySize = buf.readUInt16LE(at);+ const flags = buf.readUInt16LE(at + 2);+ if (flags & 0x0001) return null; // 复杂资源(bag/map),此处不处理+ const valueAt = at + entrySize;+ return {+ dataType: buf.readUInt8(valueAt + 3),+ data: buf.readUInt32LE(valueAt + 4),+ };+ }++ /**+ * 解析资源引用+ * @param {number} ref 0xPPTTEEEE+ * @param {'string'|'file'|'any'} prefer+ * @param {number} depth+ */+ resolve(ref, prefer = 'any', depth = 0) {+ if (depth > 6 || !ref) return null;+ const pkgId = (ref >>> 24) & 0xff;+ const typeId = (ref >>> 16) & 0xff;+ const entryIdx = ref & 0xffff;++ const pkg = this.packages.find((p) => p.id === pkgId) || this.packages[0];+ if (!pkg) return null;+ const chunks = pkg.types.get(typeId);+ if (!chunks) return null;++ let best = null;+ let bestScore = -Infinity;+ for (const c of chunks) {+ if (!c.entries.has(entryIdx)) continue;+ const s = score(c.config, prefer);+ if (s > bestScore) { bestScore = s; best = c.entries.get(entryIdx); }+ }+ if (!best) return null;++ if (best.dataType === TYPE_STRING) {+ const s = this.globalStrings[best.data];+ return s === undefined ? null : s;+ }+ if (best.dataType === TYPE_REFERENCE) {+ return this.resolve(best.data >>> 0, prefer, depth + 1);+ }+ if (best.dataType === TYPE_INT_BOOLEAN) return best.data !== 0;+ if (best.dataType === TYPE_INT_DEC || best.dataType === TYPE_INT_HEX) return best.data | 0;+ return null;+ }+}++module.exports = { ResTable, TYPE_REFERENCE };diff --git a/src/core/assoc.js b/src/core/assoc.jsnew file mode 100644index 0000000..d96119b--- /dev/null+++ b/src/core/assoc.js@@ -0,0 +1,68 @@+'use strict';+/**+ * .apk 文件关联(仅写 HKCU,不需要管理员权限)+ * 双击 apk → apkstart.exe "%1" → 自动安装 → 自动建桌面快捷方式+ */+const { execFileSync } = require('child_process');++const PROGID = 'ApkStart.apk';+const EXT = '.apk';++function reg(args) {+ try {+ execFileSync('reg', args, { windowsHide: true, stdio: 'pipe' });+ return true;+ } catch (_) {+ return false;+ }+}++function notifyShell() {+ const ps = `+$sig = '[DllImport("shell32.dll")] public static extern void SHChangeNotify(int eventId, int flags, IntPtr item1, IntPtr item2);';+try {+ $t = Add-Type -MemberDefinition $sig -Name 'ShNotify' -Namespace 'ApkStart' -PassThru -ErrorAction Stop;+ $t::SHChangeNotify(0x08000000, 0x0000, [IntPtr]::Zero, [IntPtr]::Zero);+} catch {}+`;+ try {+ execFileSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', ps], {+ windowsHide: true, stdio: 'pipe', timeout: 8000,+ });+ } catch (_) { /* 通知失败不影响关联本身 */ }+}++/**+ * @param {string} exePath apkstart 主程序路径(开发模式下是 electron.exe)+ * @param {string} [iconPath] 可选 ico+ * @param {string} [extraArgs] 开发模式下需要先传应用目录,例如 "\"C:\\path\\apkstart\""+ */+function registerAssociation(exePath, iconPath, extraArgs) {+ const classes = 'HKCU\\Software\\Classes';+ const icon = iconPath || exePath;+ const command = `"${exePath}" ${extraArgs ? extraArgs + ' ' : ''}"%1"`;++ reg(['add', `${classes}\\${EXT}`, '/ve', '/d', PROGID, '/f']);+ reg(['add', `${classes}\\${EXT}\\OpenWithProgids`, '/v', PROGID, '/t', 'REG_NONE', '/f']);++ reg(['add', `${classes}\\${PROGID}`, '/ve', '/d', 'Android 应用包', '/f']);+ reg(['add', `${classes}\\${PROGID}`, '/v', 'FriendlyTypeName', '/d', 'Android 应用包', '/f']);+ reg(['add', `${classes}\\${PROGID}\\DefaultIcon`, '/ve', '/d', `"${icon}",0`, '/f']);+ reg(['add', `${classes}\\${PROGID}\\shell\\open`, '/ve', '/d', '安装到 ApkStart', '/f']);+ reg(['add', `${classes}\\${PROGID}\\shell\\open\\command`, '/ve', '/d', command, '/f']);++ notifyShell();+ return { ok: true, progId: PROGID };+}++function unregisterAssociation() {+ const classes = 'HKCU\\Software\\Classes';+ reg(['delete', `${classes}\\${EXT}\\OpenWithProgids`, '/v', PROGID, '/f']);+ reg(['delete', `${classes}\\${PROGID}`, '/f']);+ // 仅当 .apk 仍指向我们自己时才清掉默认值+ reg(['add', `${classes}\\${EXT}`, '/ve', '/d', '', '/f']);+ notifyShell();+ return { ok: true };+}++module.exports = { registerAssociation, unregisterAssociation, PROGID };diff --git a/src/core/axml.js b/src/core/axml.jsnew file mode 100644index 0000000..f901e8a--- /dev/null+++ b/src/core/axml.js@@ -0,0 +1,167 @@+'use strict';+/**+ * Android 二进制 XML(AXML) 解析器+ * AndroidManifest.xml 在 APK 内是编译后的二进制格式,无法直接当文本读。+ * 这里实现字符串池 + 元素/属性树解析,输出普通的 DOM 结构。+ */++const RES_STRING_POOL_TYPE = 0x0001;+const RES_XML_TYPE = 0x0003;+const RES_XML_START_NAMESPACE = 0x0100;+const RES_XML_END_NAMESPACE = 0x0101;+const RES_XML_START_ELEMENT = 0x0102;+const RES_XML_END_ELEMENT = 0x0103;+const RES_XML_CDATA = 0x0104;+const RES_XML_RESOURCE_MAP = 0x0180;++const TYPE_NULL = 0x00;+const TYPE_REFERENCE = 0x01;+const TYPE_STRING = 0x03;+const TYPE_INT_DEC = 0x10;+const TYPE_INT_HEX = 0x11;+const TYPE_INT_BOOLEAN = 0x12;++const ANDROID_NS = 'http://schemas.android.com/apk/res/android';++function readStringPool(buf, start) {+ const type = buf.readUInt16LE(start);+ if (type !== RES_STRING_POOL_TYPE) throw new Error('字符串池类型错误');+ const headerSize = buf.readUInt16LE(start + 2);+ const chunkSize = buf.readUInt32LE(start + 4);+ const count = buf.readUInt32LE(start + 8);+ const flags = buf.readUInt32LE(start + 16);+ const stringsStart = buf.readUInt32LE(start + 20);+ const isUtf8 = (flags & 0x100) !== 0;++ const offsets = [];+ for (let i = 0; i < count; i++) {+ offsets.push(buf.readUInt32LE(start + headerSize + i * 4));+ }+ const base = start + stringsStart;+ const strings = new Array(count);++ for (let i = 0; i < count; i++) {+ let p = base + offsets[i];+ if (isUtf8) {+ // utf16 长度(1~2 字节)+ let len = buf[p++];+ if (len & 0x80) { len = ((len & 0x7f) << 8) | buf[p++]; }+ // utf8 字节长度+ let byteLen = buf[p++];+ if (byteLen & 0x80) { byteLen = ((byteLen & 0x7f) << 8) | buf[p++]; }+ strings[i] = buf.toString('utf8', p, p + byteLen);+ } else {+ let len = buf.readUInt16LE(p); p += 2;+ if (len & 0x8000) {+ len = ((len & 0x7fff) << 16) | buf.readUInt16LE(p); p += 2;+ }+ strings[i] = buf.toString('utf16le', p, p + len * 2);+ }+ }+ return { strings, chunkSize };+}++/**+ * @returns {{name:string, attrs:Array, children:Array}}+ */+function parseAxml(buffer) {+ const buf = buffer;+ if (buf.readUInt16LE(0) !== RES_XML_TYPE) {+ throw new Error('不是 Android 二进制 XML(可能被混淆或非法 APK)');+ }+ let pos = buf.readUInt16LE(2); // headerSize+ const total = buf.readUInt32LE(4);++ let pool = [];+ const nsStack = []; // uri+ const prefixByUri = new Map();+ const root = { name: '#document', attrs: [], children: [], parent: null };+ const stack = [root];++ while (pos + 8 <= total && pos < buf.length) {+ const type = buf.readUInt16LE(pos);+ const headerSize = buf.readUInt16LE(pos + 2);+ const chunkSize = buf.readUInt32LE(pos + 4);+ if (chunkSize <= 0) break;++ if (type === RES_STRING_POOL_TYPE) {+ pool = readStringPool(buf, pos).strings;+ } else if (type === RES_XML_START_NAMESPACE || type === RES_XML_END_NAMESPACE) {+ const prefixIdx = buf.readUInt32LE(pos + 16);+ const uriIdx = buf.readUInt32LE(pos + 20);+ if (type === RES_XML_START_NAMESPACE) {+ nsStack.push(pool[uriIdx]);+ prefixByUri.set(pool[uriIdx], pool[prefixIdx]);+ } else {+ nsStack.pop();+ }+ } else if (type === RES_XML_START_ELEMENT) {+ const nameIdx = buf.readUInt32LE(pos + 20);+ const attrStart = buf.readUInt16LE(pos + 24);+ const attrSize = buf.readUInt16LE(pos + 26);+ const attrCount = buf.readUInt16LE(pos + 28);++ const node = { name: pool[nameIdx], attrs: [], children: [], parent: stack[stack.length - 1] };+ // attributeStart 相对 ResXMLTree_attrExt(chunk + 16)起算+ const attrBase = pos + 16 + attrStart;+ for (let i = 0; i < attrCount; i++) {+ const a = attrBase + i * attrSize;+ const nsIdx = buf.readUInt32LE(a);+ const aNameIdx = buf.readUInt32LE(a + 4);+ const rawIdx = buf.readUInt32LE(a + 8);+ const dataType = buf.readUInt8(a + 15);+ const data = buf.readUInt32LE(a + 16);++ const ns = nsIdx === 0xffffffff ? '' : pool[nsIdx];+ const name = pool[aNameIdx];+ let value = null;+ let refId = null;++ if (rawIdx !== 0xffffffff) {+ value = pool[rawIdx];+ } else if (dataType === TYPE_STRING) {+ value = pool[data];+ } else if (dataType === TYPE_REFERENCE) {+ refId = data >>> 0;+ value = null;+ } else if (dataType === TYPE_INT_BOOLEAN) {+ value = data !== 0;+ } else if (dataType === TYPE_INT_DEC || dataType === TYPE_INT_HEX) {+ value = data | 0;+ }++ node.attrs.push({+ ns, prefix: ns ? (prefixByUri.get(ns) || '') : '',+ name, value, refId, dataType,+ typed: dataType === TYPE_REFERENCE ? null : value,+ });+ }+ stack[stack.length - 1].children.push(node);+ stack.push(node);+ } else if (type === RES_XML_END_ELEMENT) {+ if (stack.length > 1) stack.pop();+ }+ pos += chunkSize;+ }++ const el = root.children.find((c) => c.name === 'manifest') || root.children[0];+ if (!el) throw new Error('APK 清单为空');+ return el;+}++function attr(node, name, ns = ANDROID_NS) {+ if (!node) return null;+ return node.attrs.find((a) => a.name === name && (ns === null ? true : a.ns === ns)) || null;+}++function attrValue(node, name, ns = ANDROID_NS) {+ const a = attr(node, name, ns);+ return a ? a.typed : null;+}++function children(node, name) {+ if (!node) return [];+ return node.children.filter((c) => c.name === name);+}++module.exports = { parseAxml, attr, attrValue, children, ANDROID_NS, TYPE_REFERENCE };diff --git a/src/core/download.js b/src/core/download.jsnew file mode 100644index 0000000..0f2439f--- /dev/null+++ b/src/core/download.js@@ -0,0 +1,165 @@+'use strict';+/**+ * 下载器:支持重定向、断点续传、进度回调、SHA-256 校验+ * 只依赖 http/https,主进程与纯 Node 测试都可使用。+ */+const fs = require('fs');+const path = require('path');+const http = require('http');+const https = require('https');+const crypto = require('crypto');+const { URL } = require('url');++const UA = 'ApkStart/0.2 (Windows; +https://github.com/apkstart)';++function openStream(url, { method = 'GET', headers = {}, redirects = 0 } = {}) {+ return new Promise((resolve, reject) => {+ if (redirects > 6) return reject(new Error('重定向次数过多'));+ const u = new URL(url);+ const mod = u.protocol === 'http:' ? http : https;+ const req = mod.request(url, {+ method,+ timeout: 30000,+ headers: { 'User-Agent': UA, 'Accept-Encoding': 'identity', ...headers },+ }, (res) => {+ if ([301, 302, 303, 307, 308].includes(res.statusCode) && res.headers.location) {+ res.resume();+ const next = new URL(res.headers.location, url).href;+ return resolve(openStream(next, { method, headers, redirects: redirects + 1 }));+ }+ resolve(res);+ });+ req.on('error', reject);+ req.on('timeout', () => { req.destroy(new Error('连接超时')); });+ req.end();+ });+}++async function head(url) {+ try {+ const res = await openStream(url, { method: 'HEAD' });+ res.resume();+ return {+ status: res.statusCode,+ size: Number(res.headers['content-length']) || 0,+ type: res.headers['content-type'] || '',+ };+ } catch (e) {+ return { status: 0, size: 0, error: e.message };+ }+}++function sha256File(file) {+ return new Promise((resolve, reject) => {+ const h = crypto.createHash('sha256');+ const s = fs.createReadStream(file);+ s.on('data', (c) => h.update(c));+ s.on('end', () => resolve(h.digest('hex')));+ s.on('error', reject);+ });+}++/**+ * 下载到本地文件(自动续传)。+ * @param {string} url+ * @param {string} dest+ * @param {object} opt { onProgress({got,total,percent,speed}), signal, expectSha256, timeoutMs }+ */+async function download(url, dest, opt = {}) {+ const { onProgress = () => {}, signal, expectSha256, retries = 2 } = opt;+ fs.mkdirSync(path.dirname(dest), { recursive: true });++ let attempt = 0;+ for (;;) {+ attempt++;+ const existing = fs.existsSync(dest) ? fs.statSync(dest).size : 0;+ const headers = {};+ if (existing > 0) headers.Range = `bytes=${existing}-`;++ // eslint-disable-next-line no-await-in-loop+ const res = await openStream(url, { headers });++ if (res.statusCode === 416) {+ res.resume();+ // 已下载完整+ break;+ }+ if (res.statusCode !== 200 && res.statusCode !== 206) {+ res.resume();+ if (attempt <= retries) { await new Promise((r) => setTimeout(r, 1500)); continue; }+ throw new Error(`下载失败 HTTP ${res.statusCode}: ${url}`);+ }++ const total = res.statusCode === 206+ ? existing + (Number(res.headers['content-length']) || 0)+ : Number(res.headers['content-length']) || 0;++ if (res.statusCode === 200 && existing > 0) {+ // 服务器不支持续传,重头写+ fs.rmSync(dest, { force: true });+ }++ await new Promise((resolve, reject) => {+ const startSize = res.statusCode === 206 ? existing : 0;+ let got = startSize;+ let lastTick = Date.now();+ let lastBytes = got;+ const ws = fs.createWriteStream(dest, { flags: startSize > 0 ? 'a' : 'w' });++ const onAbort = () => { res.destroy(new Error('已取消')); };+ if (signal) signal.addEventListener('abort', onAbort, { once: true });++ res.on('data', (c) => {+ got += c.length;+ const now = Date.now();+ if (now - lastTick > 400) {+ const speed = (got - lastBytes) / ((now - lastTick) / 1000);+ lastTick = now;+ lastBytes = got;+ onProgress({+ got, total,+ percent: total ? Math.min(100, (got / total) * 100) : 0,+ speed,+ eta: total && speed > 0 ? Math.max(0, (total - got) / speed) : null,+ });+ }+ });+ res.pipe(ws);+ ws.on('finish', () => resolve());+ ws.on('error', reject);+ res.on('error', reject);+ });++ break;+ }++ // 收尾:确保进度条走到 100%+ const finalSize = fs.existsSync(dest) ? fs.statSync(dest).size : 0;+ onProgress({ got: finalSize, total: finalSize, percent: 100, speed: 0, eta: 0 });++ if (expectSha256) {+ const actual = await sha256File(dest);+ if (actual.toLowerCase() !== expectSha256.toLowerCase()) {+ fs.rmSync(dest, { force: true });+ throw new Error(`校验失败:期望 ${expectSha256.slice(0, 12)}… 实际 ${actual.slice(0, 12)}…`);+ }+ }+ return { file: dest, size: fs.statSync(dest).size };+}++/** 依次尝试多个源,任一成功即返回 */+async function downloadAny(urls, dest, opt = {}) {+ const errors = [];+ for (const u of urls) {+ try {+ // eslint-disable-next-line no-await-in-loop+ const r = await download(u, dest, opt);+ return { ...r, url: u };+ } catch (e) {+ errors.push(`${u} → ${e.message}`);+ }+ }+ throw new Error(`所有下载源均失败:\n${errors.join('\n')}`);+}++module.exports = { download, downloadAny, head, sha256File, openStream };diff --git a/src/core/engine.js b/src/core/engine.jsnew file mode 100644index 0000000..191a1d7--- /dev/null+++ b/src/core/engine.js@@ -0,0 +1,431 @@+'use strict';+/**+ * 运行时引擎:ApkStart 自带的 QEMU + Android-x86 虚拟机+ *+ * 设计原则:+ * - 默认完全自持(builtin):adb / QEMU / 系统镜像都由 ApkStart 自己管理,不依赖任何第三方模拟器+ * - 所有对安卓的操作统一走 adb,因此引擎可替换+ * - 虚拟机按需启动,空闲自动回收;启动后常驻复用,装/开应用几乎零等待+ */+const { spawn } = require('child_process');+const net = require('net');+const fs = require('fs');+const path = require('path');+const { AdbClient } = require('./adb');+const store = require('./store');+const { Provisioner } = require('./provision');++const LOG_DIR = path.join(store.DATA_DIR, 'logs');+const MONITOR_PORT = 5556;++const ATTACH_ENDPOINTS = [+ { name: 'Windows Subsystem for Android', serial: '127.0.0.1:58526' },+ { name: 'LDPlayer', serial: '127.0.0.1:5555' },+ { name: 'MuMu 模拟器', serial: '127.0.0.1:7555' },+ { name: 'Nox 夜神', serial: '127.0.0.1:62001' },+ { name: 'MEmu 逍遥', serial: '127.0.0.1:21503' },+];++class Runtime {+ constructor(appRoot) {+ this.appRoot = appRoot;+ this.provisioner = new Provisioner(appRoot);+ this.vmProc = null;+ this.vmStarting = false;+ this.installing = false;+ this.lastActivity = Date.now();+ this._watchdog = null;+ this._freeformReady = false;+ this._client = null;+ this._bootLog = [];+ store.ensureDirs();+ if (!fs.existsSync(LOG_DIR)) fs.mkdirSync(LOG_DIR, { recursive: true });+ }++ get settings() { return store.getSettings(); }++ // ---------------- 基础 ----------------++ adbPath() {+ const s = this.settings;+ const p = this.provisioner.paths();+ if (s.adbPath && fs.existsSync(s.adbPath)) return s.adbPath;+ if (fs.existsSync(p.adbExe)) return p.adbExe;+ const local = path.join(this.appRoot, 'tools', 'platform-tools', 'adb.exe');+ if (fs.existsSync(local)) return local;+ return AdbClient.resolveAdb('', this.appRoot);+ }++ client(serial) {+ const useSerial = serial || (this.settings.engine.mode === 'attach' ? this.settings.device : '127.0.0.1:5555');+ const adbPath = this.adbPath();+ if (!this._client || this._client.serial !== useSerial || this._client.adbPath !== adbPath) {+ this._client = new AdbClient({ adbPath, serial: useSerial });+ }+ return this._client;+ }++ touch() { this.lastActivity = Date.now(); }++ log(line) {+ this._bootLog.push({ t: Date.now(), line });+ if (this._bootLog.length > 300) this._bootLog.shift();+ }++ // ---------------- 状态 ----------------++ async status() {+ const env = await this.provisioner.checkEnv();+ const s = this.settings;+ const client = this.client();+ const result = {+ mode: s.engine.mode,+ installed: !!s.runtime.installed,+ env,+ vmRunning: !!(this.vmProc && !this.vmProc.killed),+ vmStarting: this.vmStarting,+ installing: this.installing,+ adbOk: env.adb.ok,+ adbVersion: env.adb.version,+ qemuOk: env.qemu.ok,+ qemuVersion: env.qemu.version,+ deviceOnline: false,+ android: '',+ sdk: 0,+ freeform: false,+ ready: false,+ needsSetup: null,+ error: '',+ };++ if (!env.adb.ok) {+ result.needsSetup = 'adb';+ result.error = '缺少 adb:点击「一键部署」自动下载';+ return result;+ }++ try {+ result.deviceOnline = await client.isOnline();+ if (result.deviceOnline) {+ const [android, sdk, ff] = await Promise.all([+ client.androidVersion().catch(() => ''),+ client.sdkInt().catch(() => 0),+ client.shell('settings get global enable_freeform_support').catch(() => '0'),+ ]);+ result.android = android;+ result.sdk = sdk;+ result.freeform = String(ff).trim() === '1' || this._freeformReady;+ }+ } catch (e) {+ result.error = e.message;+ }++ if (result.deviceOnline) result.ready = true;+ else if (!env.qemu.ok) result.needsSetup = 'qemu';+ else if (!result.installed) result.needsSetup = 'install';++ return result;+ }++ /** 高级模式:探测本机已有运行时(非默认路径) */+ async probe() {+ const adbPath = this.adbPath();+ const one = (ep) => new Promise((resolve) => {+ const c = new AdbClient({ adbPath, serial: ep.serial });+ const timer = setTimeout(() => resolve(null), 4000);+ c.isOnline().then((online) => {+ clearTimeout(timer);+ if (!online && ep.serial.includes(':')) return c.connect().then((ok) => (ok ? ep : null));+ return online ? ep : null;+ }).then(resolve).catch(() => { clearTimeout(timer); resolve(null); });+ });+ const found = await Promise.all(ATTACH_ENDPOINTS.map(one));+ return found.filter(Boolean);+ }++ // ---------------- 启动 / 停止虚拟机 ----------------++ buildArgs({ install = false, headless = false } = {}) {+ const s = this.settings;+ const p = this.provisioner.paths();+ const hv = this._hv || { whpx: false };+ const disk = s.runtime.diskPath || p.disk;+ const iso = s.runtime.isoPath || p.iso;+ const accel = hv.whpx ? 'whpx' : 'tcg';++ const args = [+ '-name', 'ApkStart Runtime',+ '-machine', `q35,accel=${accel}`,+ '-cpu', hv.whpx ? 'host' : 'max',+ '-smp', String(Math.max(2, s.engine.cores || 4)),+ '-m', String(s.engine.memoryMB || 4096),+ '-rtc', 'base=localtime',+ '-netdev', 'user,id=net0,hostfwd=tcp:127.0.0.1:5555-:5555',+ '-device', 'virtio-net-pci,netdev=net0',+ '-vga', 'std',+ '-usb', '-device', 'usb-tablet',+ '-monitor', `tcp:127.0.0.1:${MONITOR_PORT},server,nowait`,+ ];++ if (headless || s.runtime.headless) args.push('-display', 'none');++ if (install) {+ args.push('-boot', 'order=d');+ args.push('-cdrom', iso);+ } else {+ args.push('-boot', 'order=c');+ }+ args.push('-drive', `file=${disk},if=virtio,format=qcow2,cache=writeback`);+ return args;+ }++ async boot({ install = false, onLog = () => {} } = {}) {+ if (this.vmProc && !this.vmProc.killed) return { ok: true, reused: true };+ if (this.vmStarting) {+ const started = Date.now();+ while (this.vmStarting && Date.now() - started < 180000) {+ // eslint-disable-next-line no-await-in-loop+ await new Promise((r) => setTimeout(r, 500));+ }+ return { ok: !!(this.vmProc && !this.vmProc.killed), reused: true };+ }++ const env = await this.provisioner.checkEnv();+ this._hv = env.hypervisor;+ if (!env.qemu.ok) throw new Error('未安装 QEMU,请先完成运行时部署');+ if (install && !env.iso.ok) throw new Error('系统镜像(ISO)未就绪');++ const p = this.provisioner.paths();+ const disk = this.settings.runtime.diskPath || p.disk;+ if (!install && !fs.existsSync(disk)) throw new Error('尚未安装 Android 系统到虚拟磁盘');++ this.vmStarting = true;+ const args = this.buildArgs({ install });+ const logFile = path.join(LOG_DIR, install ? 'qemu-install.log' : 'qemu.log');+ const out = fs.openSync(logFile, 'a');+ fs.writeSync(out, `\n\n=== ${new Date().toISOString()} ${install ? 'INSTALL' : 'BOOT'} ===\n${env.qemu.path} ${args.join(' ')}\n`);++ onLog(`启动运行时(${env.hypervisor.whpx ? 'WHPX 硬件加速' : '纯软件模拟'})…`);+ if (!env.hypervisor.whpx) onLog(env.hypervisor.note);++ const proc = spawn(env.qemu.path, args, {+ cwd: path.dirname(env.qemu.path),+ windowsHide: true,+ stdio: ['ignore', out, out],+ });+ this.vmProc = proc;+ this.installing = install;+ this.lastActivity = Date.now();++ proc.on('error', (e) => {+ this.log(`spawn error: ${e.message}`);+ onLog(`启动失败:${e.message}`);+ this.vmProc = null;+ this.vmStarting = false;+ });+ proc.on('exit', (code) => {+ this.log(`qemu exit ${code}`);+ onLog(`运行时已退出(code=${code})`);+ this.vmProc = null;+ this.vmStarting = false;+ this.installing = false;+ });++ await new Promise((r) => setTimeout(r, 1500));+ this.vmStarting = false;+ if (!this.vmProc) throw new Error(`QEMU 启动失败,详见日志:${logFile}`);++ const client = this.client('127.0.0.1:5555');+ const timeout = env.hypervisor.whpx ? 180000 : 900000;+ const ok = await this.waitAdb(client, timeout, onLog);+ if (!ok) {+ return {+ ok: false,+ error: '虚拟机已启动,但 adb 未连接:请在虚拟机窗口里完成安装/开启网络调试后重试',+ };+ }+ await this.prepare(client);+ return { ok: true, client };+ }++ async waitAdb(client, timeoutMs, onLog = () => {}) {+ const start = Date.now();+ let lastNotice = 0;+ while (Date.now() - start < timeoutMs) {+ // eslint-disable-next-line no-await-in-loop+ await client.connect().catch(() => false);+ // eslint-disable-next-line no-await-in-loop+ if (await client.isOnline()) return true;+ if (Date.now() - lastNotice > 20000) {+ lastNotice = Date.now();+ onLog(`等待 Android 启动… ${Math.round((Date.now() - start) / 1000)}s`);+ }+ // eslint-disable-next-line no-await-in-loop+ await new Promise((r) => setTimeout(r, 2000));+ }+ return false;+ }++ async prepare(client) {+ if (!this._freeformReady) {+ try { this._freeformReady = await client.ensureFreeform(); } catch (_) { /* ignore */ }+ }+ this.startWatchdog();+ }++ /** 用 QEMU monitor 优雅退出(避免直接杀进程损坏磁盘) */+ async stop({ graceful = true } = {}) {+ if (!this.vmProc) return false;+ if (graceful) {+ try { await this.monitorCmd('system_powerdown'); } catch (_) { /* ignore */ }+ for (let i = 0; i < 16; i++) {+ // eslint-disable-next-line no-await-in-loop+ await new Promise((r) => setTimeout(r, 500));+ if (!this.vmProc) return true;+ }+ try { await this.monitorCmd('quit'); } catch (_) { /* ignore */ }+ await new Promise((r) => setTimeout(r, 800));+ }+ if (this.vmProc) {+ try { this.vmProc.kill(); } catch (_) { /* ignore */ }+ this.vmProc = null;+ }+ return true;+ }++ // ---------------- QEMU monitor ----------------++ monitorCmd(cmd, { timeout = 4000 } = {}) {+ return new Promise((resolve, reject) => {+ const sock = net.connect({ host: '127.0.0.1', port: MONITOR_PORT });+ let buf = '';+ let sent = false;+ const done = (err, data) => {+ try { sock.destroy(); } catch (_) { /* ignore */ }+ if (err) reject(err); else resolve(data);+ };+ sock.setTimeout(timeout, () => done(new Error('monitor 超时')));+ sock.on('error', (e) => {+ // QEMU 执行 quit 等命令后会主动断开连接(ECONNRESET/EPIPE),属于正常现象+ if (sent && /ECONNRESET|EPIPE/i.test(e.code || String(e))) done(null, buf);+ else done(e);+ });+ sock.on('data', (c) => {+ buf += c.toString();+ if (!sent && buf.includes('(qemu)')) {+ sent = true;+ sock.write(`${cmd}\n`);+ setTimeout(() => done(null, buf), 300);+ }+ });+ sock.on('connect', () => {+ if (!cmd) setTimeout(() => done(null, buf), 250);+ });+ });+ }++ async sendKey(keys, delay = 140) {+ for (const k of keys) {+ // eslint-disable-next-line no-await-in-loop+ await this.monitorCmd(`sendkey ${k}`);+ // eslint-disable-next-line no-await-in-loop+ await new Promise((r) => setTimeout(r, delay));+ }+ }++ // ---------------- 安装系统到虚拟磁盘 ----------------++ async startInstaller({ onLog = () => {} } = {}) {+ const env = await this.provisioner.checkEnv();+ if (!env.iso.ok) throw new Error('请先下载/导入 Android 系统镜像(ISO)');+ if (!env.disk.ok) await this.provisioner.createDisk(this.settings.runtime.diskSizeGB || 24, () => {});+ this.installing = true;+ const r = await this.boot({ install: true, onLog });+ if (!r.ok) throw new Error(r.error || '安装环境启动失败');+ return r;+ }++ /** 安装完成后:写标记 → 之后直接从磁盘启动 */+ async markInstalled() {+ store.saveSettings({ runtime: { installed: true } });+ this.installing = false;+ return true;+ }++ // ---------------- ensure ----------------++ async ensure({ onLog = () => {} } = {}) {+ const client = this.client();+ if (await client.isOnline()) {+ await this.prepare(client);+ return { ok: true, client, engine: 'builtin', reused: true };+ }++ const s = this.settings;++ // 高级模式:连接已有运行时+ if (s.engine.mode === 'attach') {+ onLog('正在探测已有运行时…');+ const found = await this.probe();+ if (found.length) {+ store.saveSettings({ device: found[0].serial });+ const c2 = this.client(found[0].serial);+ if (await c2.isOnline()) {+ await this.prepare(c2);+ return { ok: true, client: c2, engine: found[0].name };+ }+ }+ return { ok: false, needsSetup: 'attach', error: '未发现可用的已有运行时' };+ }++ // 默认:自带运行时+ if (!s.runtime.installed) {+ const env = await this.provisioner.checkEnv();+ return {+ ok: false,+ needsSetup: env.qemu.ok ? 'install' : 'provision',+ error: env.qemu.ok ? '运行时已就绪,但还没有安装 Android 系统' : '运行时组件尚未部署完成',+ env,+ };+ }++ try {+ const r = await this.boot({ onLog });+ if (r.ok) return { ok: true, client: r.client, engine: 'builtin' };+ return { ok: false, error: r.error };+ } catch (e) {+ return { ok: false, error: e.message };+ }+ }++ // ---------------- 空闲回收 ----------------++ startWatchdog() {+ if (this._watchdog) return;+ this._watchdog = setInterval(async () => {+ const s = this.settings;+ const limit = (s.engine.idleShutdownMinutes || 0) * 60000;+ if (!limit || !this.vmProc || this.installing) return;+ if (Date.now() - this.lastActivity < limit) return;+ try {+ const running = await this.client().runningPackages();+ const alive = running.filter((p) => !/launcher|systemui|settings|inputmethod|android\.systemui/i.test(p));+ if (alive.length === 0) await this.stop();+ else this.lastActivity = Date.now();+ } catch (_) { /* ignore */ }+ }, 60000);+ if (this._watchdog.unref) this._watchdog.unref();+ }++ dispose() {+ if (this._watchdog) clearInterval(this._watchdog);+ if (this.vmProc) {+ try { this.vmProc.kill(); } catch (_) { /* ignore */ }+ this.vmProc = null;+ }+ }++ get bootLog() { return this._bootLog.slice(-60); }+}++module.exports = { Runtime, MONITOR_PORT };diff --git a/src/core/installer.js b/src/core/installer.jsnew file mode 100644index 0000000..7f0d033--- /dev/null+++ b/src/core/installer.js@@ -0,0 +1,184 @@+'use strict';+/**+ * 安装 / 启动 / 卸载 编排层+ * 把「解析 APK → 安装进运行时 → 落本地元数据 → 生成桌面快捷方式」串成一条流水线。+ */+const fs = require('fs');+const path = require('path');+const store = require('./store');+const { parseApk } = require('./apk');+const { pngToIco, writeShortcut, removeShortcut, safeFileName } = require('./shortcut');++function accentOf(pkg) {+ let h = 0;+ for (let i = 0; i < pkg.length; i++) h = (h * 31 + pkg.charCodeAt(i)) >>> 0;+ const hue = h % 360;+ return `hsl(${hue} 62% 52%)`;+}++class Installer {+ constructor(runtime, ctx) {+ this.runtime = runtime;+ this.ctx = ctx; // { launcherTarget, launcherArgs, cwd, isDev, desktopDir }+ }++ shortcutTarget() {+ const { launcherTarget, launcherArgs } = this.ctx;+ return { target: launcherTarget, baseArgs: launcherArgs || '' };+ }++ iconFile(pkg) { return store.iconPath(pkg); }++ icoFile(pkg) { return path.join(store.ICON_DIR, `${pkg}.ico`); }++ shortcutPath(app) {+ const s = store.getSettings();+ const dir = s.shortcutDir && s.shortcutDir.trim() ? s.shortcutDir : this.ctx.desktopDir;+ return path.join(dir, `${safeFileName(app.label)}.lnk`);+ }++ async install(filePath, onProgress = () => {}) {+ onProgress({ stage: 'parse', message: '正在解析 APK…' });+ const meta = parseApk(filePath);+ onProgress({+ stage: 'parse-done',+ message: `已识别 ${meta.label}(${meta.package})`,+ meta: { label: meta.label, package: meta.package, versionName: meta.versionName },+ });++ onProgress({ stage: 'runtime', message: '正在准备安卓运行时…' });+ const rt = await this.runtime.ensure({ onLog: (m) => onProgress({ stage: 'runtime', message: m }) });+ if (!rt.ok) {+ const err = new Error(rt.error || '运行时不可用');+ err.needsSetup = rt.needsSetup || 'provision';+ throw err;+ }+ const client = rt.client;++ // 已安装 → 走覆盖安装+ const existing = store.getApp(meta.package);+ onProgress({ stage: 'install', message: existing ? '正在更新应用…' : '正在安装应用…' });+ await client.install(filePath);+ this.runtime.touch();++ // 图标落盘+ let iconPath = null;+ let icoPath = null;+ if (meta.iconPng) {+ try {+ iconPath = store.iconPath(meta.package);+ fs.writeFileSync(iconPath, meta.iconPng);+ const ico = pngToIco(meta.iconPng);+ if (ico) {+ icoPath = this.icoFile(meta.package);+ fs.writeFileSync(icoPath, ico);+ }+ } catch (_) { /* 图标失败不影响安装 */ }+ }++ // 备份 APK,便于日后重装/找回+ let apkCopy = null;+ try {+ apkCopy = store.apkPath(meta.package, meta.versionCode.toString(36));+ fs.copyFileSync(filePath, apkCopy);+ } catch (_) { /* ignore */ }++ const app = {+ package: meta.package,+ label: meta.label,+ versionName: meta.versionName,+ versionCode: meta.versionCode,+ activity: meta.launchActivity,+ abis: meta.abis,+ minSdk: meta.minSdk,+ sizeBytes: meta.sizeBytes,+ iconPath,+ icoPath,+ apkPath: apkCopy,+ accent: existing ? existing.accent : accentOf(meta.package),+ installedAt: existing ? existing.installedAt : Date.now(),+ updatedAt: Date.now(),+ launchCount: existing ? existing.launchCount || 0 : 0,+ lastLaunchAt: existing ? existing.lastLaunchAt || 0 : 0,+ shortcutPath: existing ? existing.shortcutPath || null : null,+ bounds: existing ? existing.bounds || null : null,+ pinned: existing ? !!existing.pinned : false,+ };++ store.upsertApp(app);++ const settings = store.getSettings();+ if (settings.createShortcutOnInstall) {+ onProgress({ stage: 'shortcut', message: '正在创建桌面快捷方式…' });+ try {+ app.shortcutPath = this.createShortcut(app);+ store.upsertApp({ package: app.package, shortcutPath: app.shortcutPath });+ } catch (e) {+ onProgress({ stage: 'shortcut-warn', message: `快捷方式创建失败:${e.message}` });+ }+ }++ // 兼容性提示:只有 ARM 原生库时,x86 运行时需要转译层+ const warnings = [];+ if (meta.abis.length && !meta.abis.some((a) => /x86|x86_64/.test(a))) {+ warnings.push('此应用仅含 ARM 原生库,需要运行时的 ARM 转译支持(部分 x86 镜像需手动开启)。');+ }+ if (meta.minSdk && meta.minSdk >= 30) {+ warnings.push(`要求 Android ${meta.minSdk}+,请确认运行时版本足够新。`);+ }+ client.batteryOptimizeOff(meta.package).catch(() => {});++ onProgress({ stage: 'done', message: `${app.label} 安装完成`, app });+ return { app, warnings, engine: rt.engine };+ }++ createShortcut(app) {+ const { target, baseArgs } = this.shortcutTarget();+ const args = `${baseArgs ? baseArgs + ' ' : ''}--launch "${app.package}"`.trim();+ const ico = app.icoPath && fs.existsSync(app.icoPath) ? app.icoPath : undefined;+ return writeShortcut({+ shortcutPath: this.shortcutPath(app),+ target,+ args,+ iconIcoPath: ico,+ description: `${app.label} — 由 ApkStart 运行`,+ cwd: this.ctx.cwd,+ });+ }++ async uninstall(pkg, { removeShortcut: rm = true } = {}) {+ const app = store.getApp(pkg);+ const rt = await this.runtime.ensure();+ if (rt.ok) await rt.client.uninstall(pkg).catch(() => {});+ if (app && rm) removeShortcut(app.shortcutPath);+ if (app) {+ try { if (app.iconPath && fs.existsSync(app.iconPath)) fs.unlinkSync(app.iconPath); } catch (_) {}+ try { if (app.icoPath && fs.existsSync(app.icoPath)) fs.unlinkSync(app.icoPath); } catch (_) {}+ try { if (app.apkPath && fs.existsSync(app.apkPath)) fs.unlinkSync(app.apkPath); } catch (_) {}+ }+ store.removeApp(pkg);+ return true;+ }++ async launch(pkg, { onLog = () => {} } = {}) {+ const app = store.getApp(pkg);+ const rt = await this.runtime.ensure({ onLog });+ if (!rt.ok) throw new Error(rt.error || '运行时不可用');+ const settings = store.getSettings();+ await rt.client.startApp(app ? app.package : pkg, app ? app.activity : null, {+ freeform: settings.freeform,+ bounds: app ? app.bounds : null,+ });+ this.runtime.touch();+ if (app) {+ store.upsertApp({+ package: app.package,+ launchCount: (app.launchCount || 0) + 1,+ lastLaunchAt: Date.now(),+ });+ }+ return { ok: true, engine: rt.engine };+ }+}++module.exports = { Installer, accentOf };diff --git a/src/core/png.js b/src/core/png.jsnew file mode 100644index 0000000..aa7d941--- /dev/null+++ b/src/core/png.js@@ -0,0 +1,132 @@+'use strict';+/**+ * 零依赖 PNG 编码器 + 程序图标绘制+ * 这样不必往仓库里塞二进制素材,也便于换主题色时动态重绘。+ */+const zlib = require('zlib');++const CRC_TABLE = (() => {+ const t = new Int32Array(256);+ for (let n = 0; n < 256; n++) {+ let c = n;+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;+ t[n] = c;+ }+ return t;+})();++function crc32(buf) {+ let c = -1;+ for (let i = 0; i < buf.length; i++) c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8);+ return (c ^ -1) >>> 0;+}++function chunk(type, data) {+ const len = Buffer.alloc(4);+ len.writeUInt32BE(data.length, 0);+ const body = Buffer.concat([Buffer.from(type, 'ascii'), data]);+ const crc = Buffer.alloc(4);+ crc.writeUInt32BE(crc32(body), 0);+ return Buffer.concat([len, body, crc]);+}++/** RGBA 像素(Uint8Array,长度 w*h*4)→ PNG Buffer */+function encodePng(width, height, rgba) {+ const ihdr = Buffer.alloc(13);+ ihdr.writeUInt32BE(width, 0);+ ihdr.writeUInt32BE(height, 4);+ ihdr[8] = 8; // bit depth+ ihdr[9] = 6; // RGBA+ ihdr[10] = 0; ihdr[11] = 0; ihdr[12] = 0;++ const stride = width * 4;+ const raw = Buffer.alloc((stride + 1) * height);+ for (let y = 0; y < height; y++) {+ raw[y * (stride + 1)] = 0;+ Buffer.from(rgba.buffer, rgba.byteOffset + y * stride, stride)+ .copy(raw, y * (stride + 1) + 1);+ }+ return Buffer.concat([+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),+ chunk('IHDR', ihdr),+ chunk('IDAT', zlib.deflateSync(raw, { level: 9 })),+ chunk('IEND', Buffer.alloc(0)),+ ]);+}++// ---------------- 极简绘制(4x 超采样抗锯齿) ----------------++function roundRectAlpha(x, y, w, h, r, px, py) {+ const cx = Math.min(Math.max(px, x + r), x + w - r);+ const cy = Math.min(Math.max(py, y + r), y + h - r);+ const dx = px - cx;+ const dy = py - cy;+ return dx * dx + dy * dy <= r * r ? 1 : 0;+}++function pointInTriangle(px, py, ax, ay, bx, by, cx, cy) {+ const d1 = (px - bx) * (ay - by) - (ax - bx) * (py - by);+ const d2 = (px - cx) * (by - cy) - (bx - cx) * (py - cy);+ const d3 = (px - ax) * (cy - ay) - (cx - ax) * (py - ay);+ const neg = d1 < 0 || d2 < 0 || d3 < 0;+ const pos = d1 > 0 || d2 > 0 || d3 > 0;+ return !(neg && pos);+}++/**+ * 绘制 ApkStart 图标:深色圆角方块 + 安卓绿启动三角+ * @param {number} size 输出边长+ */+function drawAppIcon(size = 256) {+ const SS = 4;+ const S = size * SS;+ const acc = new Float32Array(size * size * 4); // 累积++ const pad = S * 0.06;+ const box = { x: pad, y: pad, w: S - pad * 2, h: S - pad * 2, r: S * 0.24 };++ // 三角(播放键)+ const tW = S * 0.30;+ const tH = S * 0.34;+ const tcx = S * 0.5 + S * 0.02;+ const tcy = S * 0.5;+ const ax = tcx - tW * 0.38, ay = tcy - tH / 2;+ const bx = tcx - tW * 0.38, by = tcy + tH / 2;+ const cx2 = tcx + tW * 0.62, cy2 = tcy;++ for (let y = 0; y < S; y++) {+ for (let x = 0; x < S; x++) {+ const px = x + 0.5;+ const py = y + 0.5;+ const inBox = roundRectAlpha(box.x, box.y, box.w, box.h, box.r, px, py);+ if (!inBox) continue;++ // 背景渐变(对角)+ const t = (x / S) * 0.6 + (y / S) * 0.4;+ let r = Math.round(20 + t * 14);+ let g = Math.round(26 + t * 18);+ let b = Math.round(33 + t * 24);++ if (pointInTriangle(px, py, ax, ay, bx, by, cx2, cy2)) {+ r = 61; g = 220; b = 132; // #3ddc84+ }++ const oy = Math.floor(y / SS);+ const ox = Math.floor(x / SS);+ const idx = (oy * size + ox) * 4;+ acc[idx] += r; acc[idx + 1] += g; acc[idx + 2] += b; acc[idx + 3] += 255;+ }+ }++ const out = new Uint8Array(size * size * 4);+ const n = SS * SS;+ for (let i = 0; i < size * size; i++) {+ out[i * 4] = Math.round(acc[i * 4] / n);+ out[i * 4 + 1] = Math.round(acc[i * 4 + 1] / n);+ out[i * 4 + 2] = Math.round(acc[i * 4 + 2] / n);+ out[i * 4 + 3] = Math.round(acc[i * 4 + 3] / n);+ }+ return encodePng(size, size, out);+}++module.exports = { encodePng, drawAppIcon };diff --git a/src/core/provision.js b/src/core/provision.jsnew file mode 100644index 0000000..f5764fe--- /dev/null+++ b/src/core/provision.js@@ -0,0 +1,395 @@+'use strict';+/**+ * 运行时自举(Provisioning)+ *+ * ApkStart 不依赖任何第三方模拟器:adb、QEMU、系统镜像全部由自己下载/校验/管理。+ * 所有运行时文件都放在 %APPDATA%\apkstart\runtime 下,保证在任何安装位置都可写。+ */+const fs = require('fs');+const path = require('path');+const { spawn, execFile } = require('child_process');+const store = require('./store');+const { download, downloadAny, head } = require('./download');+const { ZipArchive } = require('./zip');++const IS_WIN = process.platform === 'win32';++const SOURCES = {+ adb: [+ 'https://dl.google.com/android/repository/platform-tools-latest-windows.zip',+ ],+ qemuIndex: 'https://qemu.weilnetz.de/w64/',+ qemuFallback: [+ 'https://qemu.weilnetz.de/w64/qemu-w64-setup-20260811.exe',+ ],+ // Android-x86 9.0-r2(x86_64):公认最稳的 QEMU 可引导 Android+ iso: [+ 'https://master.dl.sourceforge.net/project/android-x86/Release%209.0/android-x86_64-9.0-r2.iso?viasf=1',+ 'https://nchc.dl.sourceforge.net/project/android-x86/Release%209.0/android-x86_64-9.0-r2.iso',+ 'https://phoenixnap.dl.sourceforge.net/project/android-x86/Release%209.0/android-x86_64-9.0-r2.iso',+ 'https://downloads.sourceforge.net/project/android-x86/Release%209.0/android-x86_64-9.0-r2.iso',+ ],+ isoSizeHint: 900 * 1024 * 1024,+};++const MIN_SIZE = {+ adb: 5 * 1024 * 1024,+ qemu: 60 * 1024 * 1024,+ iso: 400 * 1024 * 1024,+ disk: 1024 * 1024,+};++function run(cmd, args, { timeout = 60000, cwd, windowsHide = true } = {}) {+ return new Promise((resolve) => {+ execFile(cmd, args, { timeout, cwd, windowsHide, maxBuffer: 8 * 1024 * 1024 }, (err, stdout, stderr) => {+ resolve({ ok: !err, code: err ? (err.code ?? 1) : 0, stdout: String(stdout || ''), stderr: String(stderr || ''), error: err });+ });+ });+}++function fileSize(p) {+ try { return fs.statSync(p).size; } catch (_) { return 0; }+}++class Provisioner {+ constructor(appRoot) {+ this.appRoot = appRoot;+ this._hypervisor = null;+ this._cache = { adbVersion: '', qemuVersion: '' };+ }++ // ---------------- 路径 ----------------++ get root() {+ const r = store.getSettings().runtime.dir;+ return r && r.trim() ? r : path.join(store.DATA_DIR, 'runtime');+ }++ paths() {+ const root = this.root;+ return {+ root,+ qemuDir: path.join(root, 'qemu'),+ qemuExe: path.join(root, 'qemu', 'qemu-system-x86_64.exe'),+ qemuImg: path.join(root, 'qemu', 'qemu-img.exe'),+ adbDir: path.join(root, 'platform-tools'),+ adbExe: path.join(root, 'platform-tools', 'adb.exe'),+ imagesDir: path.join(root, 'images'),+ iso: path.join(root, 'images', 'android-x86.iso'),+ disk: path.join(root, 'images', 'android.qcow2'),+ tmp: path.join(root, '_tmp'),+ };+ }++ ensureDirs() {+ const p = this.paths();+ for (const d of [p.root, p.qemuDir, p.adbDir, p.imagesDir, p.tmp]) {+ fs.mkdirSync(d, { recursive: true });+ }+ return p;+ }++ // ---------------- 环境检查 ----------------++ async hypervisor() {+ if (this._hypervisor !== null) return this._hypervisor;+ if (!IS_WIN) { this._hypervisor = { whpx: false, note: '非 Windows 平台' }; return this._hypervisor; }+ const dll = fs.existsSync('C:\\Windows\\System32\\WinHvPlatform.dll');+ const ps = await run('powershell.exe', [+ '-NoProfile', '-NonInteractive', '-Command',+ '(Get-CimInstance Win32_ComputerSystem).HypervisorPresent',+ ], { timeout: 15000 });+ const present = /true/i.test(ps.stdout);+ this._hypervisor = {+ whpx: dll && present,+ dll,+ hypervisorPresent: present,+ note: dll && present+ ? '已启用 WHPX 硬件加速'+ : '未检测到 Windows Hypervisor Platform:将以纯软件模拟运行(较慢),可在「启用或关闭 Windows 功能」中勾选「虚拟机平台」后重启提速',+ };+ return this._hypervisor;+ }++ async adbVersion() {+ // 30s 缓存,避免状态轮询频繁拉起外部进程+ if (this._adbCache && Date.now() - this._adbCache.at < 30000) return this._adbCache.value;+ const { adbExe, adbDir } = this.paths();+ const candidates = [adbExe, path.join(this.appRoot, 'tools', 'platform-tools', 'adb.exe')];+ for (const c of candidates) {+ if (!fs.existsSync(c)) continue;+ const r = await run(c, ['version'], { timeout: 10000 });+ if (r.ok) {+ const m = /version\s+([\d.]+)/i.exec(r.stdout);+ const v = { ok: true, path: c, version: m ? m[1] : r.stdout.split('\n')[0].trim() };+ this._adbCache = { at: Date.now(), value: v };+ return v;+ }+ }+ this._adbCache = { at: Date.now(), value: { ok: false, path: '', version: '' } };+ return this._adbCache.value;+ }++ async qemuVersion() {+ if (this._qemuCache && Date.now() - this._qemuCache.at < 30000) return this._qemuCache.value;+ const p = this.paths();+ const candidates = [+ p.qemuExe,+ store.getSettings().runtime.qemuPath,+ 'C:\\Program Files\\qemu\\qemu-system-x86_64.exe', // winget 默认安装位置+ path.join(this.appRoot, 'engine', 'qemu', 'qemu-system-x86_64.exe'),+ ].filter(Boolean);+ for (const c of candidates) {+ if (!fs.existsSync(c)) continue;+ const r = await run(c, ['--version'], { timeout: 15000 });+ if (r.ok || r.stdout) {+ const m = /QEMU emulator version\s+(\S+)/i.exec(r.stdout);+ const v = { ok: true, path: c, version: m ? m[1] : (r.stdout || '').split('\n')[0].trim() };+ this._qemuCache = { at: Date.now(), value: v };+ return v;+ }+ }+ this._qemuCache = { at: Date.now(), value: { ok: false, path: '', version: '' } };+ return this._qemuCache.value;+ }++ async checkEnv() {+ const p = this.ensureDirs();+ const s = store.getSettings();+ const [adb, qemu, hv] = await Promise.all([this.adbVersion(), this.qemuVersion(), this.hypervisor()]);++ const isoPath = s.runtime.isoPath || p.iso;+ const diskPath = s.runtime.diskPath || p.disk;+ const isoSize = fileSize(isoPath);+ const diskSize = fileSize(diskPath);++ return {+ adb: { ...adb, required: true },+ qemu: { ...qemu, required: true },+ iso: {+ ok: isoSize > MIN_SIZE.iso,+ path: isoPath,+ size: isoSize,+ required: false,+ note: isoSize ? `${(isoSize / 1073741824).toFixed(2)} GB` : '未下载',+ },+ disk: {+ ok: diskSize > MIN_SIZE.disk,+ path: diskPath,+ size: diskSize,+ required: true,+ note: diskSize ? `${(diskSize / 1073741824).toFixed(2)} GB` : '尚未创建',+ },+ hypervisor: hv,+ ready: !!(adb.ok && qemu.ok && diskSize > MIN_SIZE.disk),+ paths: p,+ };+ }++ // ---------------- adb ----------------++ async installAdb(onProgress = () => {}) {+ const p = this.ensureDirs();+ const zipPath = path.join(p.tmp, 'platform-tools.zip');+ onProgress({ stage: 'download', message: '下载 Android platform-tools(约 8MB)…', percent: 2 });++ await downloadAny(SOURCES.adb, zipPath, {+ onProgress: (pr) => onProgress({+ stage: 'download',+ message: `下载 adb… ${(pr.got / 1048576).toFixed(1)}MB / ${(pr.total / 1048576).toFixed(1)}MB`,+ percent: pr.percent,+ speed: pr.speed,+ }),+ });++ if (fileSize(zipPath) < MIN_SIZE.adb) throw new Error('adb 安装包下载不完整');++ onProgress({ stage: 'extract', message: '解压 adb…', percent: 92 });+ this.extractZip(zipPath, p.root);++ const v = await this.adbVersion();+ if (!v.ok) throw new Error('adb 解压后无法运行,请检查是否被杀毒软件拦截');++ fs.rmSync(zipPath, { force: true });+ store.saveSettings({ adbPath: v.path });+ this._cache.adbVersion = v.version;+ onProgress({ stage: 'done', message: `adb ${v.version} 就绪`, percent: 100 });+ return v;+ }++ /** 用自带的 ZIP 解析器解压(避免依赖系统解压工具) */+ extractZip(zipPath, destDir) {+ const buf = fs.readFileSync(zipPath);+ const zip = new ZipArchive(buf);+ for (const name of zip.names()) {+ if (name.endsWith('/')) {+ fs.mkdirSync(path.join(destDir, name), { recursive: true });+ continue;+ }+ const target = path.join(destDir, name);+ fs.mkdirSync(path.dirname(target), { recursive: true });+ fs.writeFileSync(target, zip.read(name));+ }+ return destDir;+ }++ // ---------------- QEMU ----------------++ /** 抓取官方目录里最新的安装包文件名(不写死版本号) */+ async resolveQemuUrl() {+ const configured = store.getSettings().runtime.qemuUrl;+ if (configured && configured.trim()) return configured.trim();+ try {+ const { openStream } = require('./download');+ const res = await openStream(SOURCES.qemuIndex);+ const html = await new Promise((resolve, reject) => {+ let d = '';+ res.on('data', (c) => { d += c; if (d.length > 512 * 1024) res.destroy(); });+ res.on('end', () => resolve(d));+ res.on('error', reject);+ });+ const files = [...html.matchAll(/href="([^"]*qemu-w64-setup-(\d+)\.exe)"/g)]+ .map((m) => ({ file: m[1], ver: Number(m[2]) }))+ .sort((a, b) => b.ver - a.ver);+ if (files.length) {+ const f = files[0].file.replace(/^.*\//, '');+ return new URL(f, SOURCES.qemuIndex).href;+ }+ } catch (_) { /* 落到备用源 */ }+ return SOURCES.qemuFallback[0];+ }++ async installQemu(onProgress = () => {}) {+ const p = this.ensureDirs();+ const setup = path.join(p.tmp, 'qemu-setup.exe');++ onProgress({ stage: 'resolve', message: '查找最新 QEMU 版本…', percent: 1 });+ const url = await this.resolveQemuUrl();+ onProgress({ stage: 'download', message: `下载 QEMU(约 200MB)…`, percent: 2, url });++ await download(url, setup, {+ resume: true,+ onProgress: (pr) => onProgress({+ stage: 'download',+ message: `下载 QEMU… ${(pr.got / 1048576).toFixed(0)}MB / ${(pr.total / 1048576).toFixed(0)}MB`+ + (pr.speed ? `(${(pr.speed / 1024).toFixed(0)} KB/s)` : ''),+ percent: pr.percent,+ canResume: true,+ }),+ });+ if (fileSize(setup) < MIN_SIZE.qemu) throw new Error('QEMU 安装包下载不完整');++ onProgress({ stage: 'install', message: '正在安装 QEMU(静默)…', percent: 96 });+ // qemu-w64-setup 是 NSIS 安装器:/S 静默,/D 指定目录(必须最后且不加引号)+ const target = p.qemuDir;+ fs.mkdirSync(target, { recursive: true });+ await new Promise((resolve) => {+ const proc = spawn(setup, ['/S', `/D=${target}`], { windowsHide: true, stdio: 'ignore' });+ proc.on('exit', () => resolve());+ proc.on('error', () => resolve());+ setTimeout(() => { try { proc.kill(); } catch (_) {} resolve(); }, 600000);+ });++ const v = await this.qemuVersion();+ if (!v.ok) {+ throw new Error('QEMU 安装后未找到 qemu-system-x86_64.exe:可手动下载 QEMU 并解压到 engine/qemu/');+ }+ fs.rmSync(setup, { force: true });+ this._cache.qemuVersion = v.version;+ onProgress({ stage: 'done', message: `QEMU ${v.version} 就绪`, percent: 100 });+ return v;+ }++ // ---------------- 系统镜像 ----------------++ async downloadIso(onProgress = () => {}) {+ const p = this.ensureDirs();+ const s = store.getSettings();+ const dest = s.runtime.isoPath || p.iso;+ const custom = s.runtime.isoUrl && s.runtime.isoUrl.trim();+ const urls = custom ? [custom, ...SOURCES.iso] : SOURCES.iso;++ onProgress({ stage: 'download', message: '下载 Android-x86 9.0-r2(约 900MB)…', percent: 1 });+ const r = await downloadAny(urls, dest, {+ resume: true,+ onProgress: (pr) => onProgress({+ stage: 'download',+ message: `下载系统镜像… ${(pr.got / 1048576).toFixed(0)}MB / ${(pr.total / 1048576).toFixed(0)}MB`+ + (pr.speed ? `(${(pr.speed / 1024).toFixed(0)} KB/s)` : ''),+ percent: pr.percent,+ canResume: true,+ }),+ });+ if (fileSize(dest) < MIN_SIZE.iso) throw new Error('系统镜像下载不完整,可重试续传');++ store.saveSettings({ runtime: { isoPath: dest } });+ onProgress({ stage: 'done', message: '系统镜像就绪', percent: 100, path: dest });+ return r;+ }++ /** 校验用户导入的镜像/ISO */+ inspectImage(file) {+ const size = fileSize(file);+ if (!size) throw new Error('文件不存在或为空');+ const fd = fs.openSync(file, 'r');+ const head4 = Buffer.alloc(4);+ fs.readSync(fd, head4, 0, 4, 0);+ fs.closeSync(fd);+ const magic = head4.toString('hex');+ let kind = 'unknown';+ if (magic === '514649fb') kind = 'qcow2';+ else if (head4.toString('ascii', 0, 4) === 'KDMV') kind = 'vmdk';+ else if (size > 400 * 1024 * 1024 && magic !== '00000000') kind = 'raw-or-iso';+ return { kind, size, path: file };+ }++ importIso(file) {+ const info = this.inspectImage(file);+ store.saveSettings({ runtime: { isoPath: file } });+ return { ok: true, ...info };+ }++ importDisk(file) {+ const info = this.inspectImage(file);+ store.saveSettings({ runtime: { diskPath: file } });+ return { ok: true, ...info };+ }++ // ---------------- 虚拟磁盘 ----------------++ async createDisk(sizeGB = 24, onProgress = () => {}) {+ const p = this.ensureDirs();+ const s = store.getSettings();+ const dest = s.runtime.diskPath || p.disk;+ if (fileSize(dest) > MIN_SIZE.disk) return { ok: true, path: dest, existed: true };++ onProgress({ stage: 'disk', message: `创建 ${sizeGB}GB 虚拟磁盘…`, percent: 40 });+ const qemuImg = fs.existsSync(p.qemuImg)+ ? p.qemuImg+ : path.join(path.dirname(store.getSettings().runtime.qemuPath || ''), 'qemu-img.exe');++ const tool = fs.existsSync(qemuImg) ? qemuImg : null;+ if (tool) {+ const r = await run(tool, ['create', '-f', 'qcow2', dest, `${sizeGB}G`], { timeout: 120000 });+ if (!r.ok) throw new Error(`qemu-img 创建虚拟磁盘失败:${r.stderr || r.stdout}`);+ } else {+ throw new Error('未找到 qemu-img.exe,请先安装 QEMU');+ }+ store.saveSettings({ runtime: { diskPath: dest } });+ onProgress({ stage: 'done', message: '虚拟磁盘已创建', percent: 100, path: dest });+ return { ok: true, path: dest, size: fileSize(dest) };+ }++ // ---------------- 系统镜像可达性预检 ----------------++ async probeSources() {+ const [adb, qemu, iso] = await Promise.all([+ head(SOURCES.adb[0]),+ head(SOURCES.qemuFallback[0]),+ head(SOURCES.iso[0]),+ ]);+ return { adb, qemu, iso };+ }+}++module.exports = { Provisioner, SOURCES, MIN_SIZE };diff --git a/src/core/sharer.js b/src/core/sharer.jsnew file mode 100644index 0000000..b1fb271--- /dev/null+++ b/src/core/sharer.js@@ -0,0 +1,149 @@+'use strict';+/**+ * 本机 ↔ 安卓 的共享目录双向同步+ *+ * 没有 root 的情况下无法真正「挂载」目录,所以采用增量同步:+ * 任何一侧新增/修改的文件都会在几秒内同步到另一侧,语义上等价于共享文件夹。+ */+const fs = require('fs');+const path = require('path');+const store = require('./store');++const MAX_FILE = 512 * 1024 * 1024; // 单文件 512MB 上限++function walk(dir, base = dir, out = []) {+ let items = [];+ try { items = fs.readdirSync(dir, { withFileTypes: true }); } catch (_) { return out; }+ for (const it of items) {+ if (it.name.startsWith('.')) continue;+ const full = path.join(dir, it.name);+ if (it.isDirectory()) walk(full, base, out);+ else if (it.isFile()) {+ try {+ const st = fs.statSync(full);+ if (st.size <= MAX_FILE) {+ out.push({ abs: full, rel: path.relative(base, full).split(path.sep).join('/'), mtime: st.mtimeMs, size: st.size });+ }+ } catch (_) { /* ignore */ }+ }+ }+ return out;+}++class Sharer {+ constructor(runtime) {+ this.runtime = runtime;+ this.stateFile = path.join(store.DATA_DIR, 'shared-state.json');+ this._busy = false;+ this._timer = null;+ this._lastError = '';+ }++ get localDir() { return store.getSettings().sharedDir; }+ get remoteDir() { return store.getSettings().deviceSharedDir; }++ loadState() {+ try { return JSON.parse(fs.readFileSync(this.stateFile, 'utf8')); } catch (_) { return {}; }+ }++ saveState(s) {+ try { fs.writeFileSync(this.stateFile, JSON.stringify(s, null, 2)); } catch (_) { /* ignore */ }+ }++ async ensureDirs(onLog = () => {}) {+ if (!fs.existsSync(this.localDir)) fs.mkdirSync(this.localDir, { recursive: true });+ const client = this.runtime.client();+ if (!(await client.isOnline())) return false;+ await client.shellMkdir(this.remoteDir);+ return true;+ }++ async sync({ onLog = () => {} } = {}) {+ if (this._busy) return { skipped: true };+ this._busy = true;+ const result = { pushed: 0, pulled: 0, errors: [] };+ try {+ const client = this.runtime.client();+ if (!(await client.isOnline())) throw new Error('运行时未连接');+ await this.ensureDirs(onLog);+ const state = this.loadState();++ // --- 本机 → 设备 ---+ const localFiles = walk(this.localDir);+ for (const f of localFiles) {+ const prev = state[f.rel];+ const changed = !prev || Math.abs((prev.mtime || 0) - f.mtime) > 1500 || prev.size !== f.size;+ if (!changed) continue;+ const remote = `${this.remoteDir}/${f.rel}`;+ try {+ await client.shell(`mkdir -p "$(dirname '${remote}')"`);+ await client.push(f.abs, remote);+ state[f.rel] = { mtime: f.mtime, size: f.size, dir: 'up' };+ result.pushed++;+ } catch (e) {+ result.errors.push(`↑ ${f.rel}: ${e.message}`);+ }+ }++ // --- 设备 → 本机 ---+ let remoteList = [];+ try {+ remoteList = await this.listRemoteRecursive(client, this.remoteDir);+ } catch (_) { /* ignore */ }++ for (const r of remoteList) {+ const prev = state[r.rel];+ if (prev && Math.abs((prev.mtime || 0) - r.mtime) <= 1500 && prev.size === r.size) continue;+ const local = path.join(this.localDir, r.rel);+ try {+ fs.mkdirSync(path.dirname(local), { recursive: true });+ await client.pull(`${this.remoteDir}/${r.rel}`, local);+ const st = fs.statSync(local);+ state[r.rel] = { mtime: st.mtimeMs, size: st.size, dir: 'down' };+ result.pulled++;+ } catch (e) {+ result.errors.push(`↓ ${r.rel}: ${e.message}`);+ }+ }++ this.saveState(state);+ this._lastError = result.errors[0] || '';+ return result;+ } catch (e) {+ this._lastError = e.message;+ return { ...result, error: e.message };+ } finally {+ this._busy = false;+ }+ }++ async listRemoteRecursive(client, base, prefix = '', depth = 0, out = []) {+ if (depth > 6) return out;+ const items = await client.listRemote(prefix ? `${base}/${prefix}` : base);+ for (const it of items) {+ if (it.name === '.' || it.name === '..') continue;+ const rel = prefix ? `${prefix}/${it.name}` : it.name;+ if (it.isDir) {+ await this.listRemoteRecursive(client, base, rel, depth + 1, out);+ } else {+ out.push({ rel, size: it.size, mtime: Date.now() });+ }+ }+ return out;+ }++ start(intervalMs = 8000) {+ if (this._timer) return;+ this._timer = setInterval(() => { this.sync().catch(() => {}); }, intervalMs);+ if (this._timer.unref) this._timer.unref();+ }++ stop() {+ if (this._timer) clearInterval(this._timer);+ this._timer = null;+ }++ get lastError() { return this._lastError; }+}++module.exports = { Sharer };diff --git a/src/core/shortcut.js b/src/core/shortcut.jsnew file mode 100644index 0000000..1c5f849--- /dev/null+++ b/src/core/shortcut.js@@ -0,0 +1,112 @@+'use strict';+/**+ * 桌面快捷方式 + 多尺寸 ICO 生成+ *+ * ICO 直接用 Electron nativeImage 缩放并手写 ICO 容器(DIB 格式,全 Windows 版本兼容),+ * 不依赖任何第三方图像库,也不需要 ImageMagick。+ */+const fs = require('fs');+const path = require('path');++const ICO_SIZES = [16, 20, 24, 32, 40, 48, 64, 128, 256];++function buildDib(bgra, size) {+ const header = Buffer.alloc(40);+ header.writeUInt32LE(40, 0); // biSize+ header.writeInt32LE(size, 4); // biWidth+ header.writeInt32LE(size * 2, 8); // biHeight = XOR + AND+ header.writeUInt16LE(1, 12); // biPlanes+ header.writeUInt16LE(32, 14); // biBitCount+ header.writeUInt32LE(0, 16); // BI_RGB+ header.writeUInt32LE(size * size * 4, 20);++ // XOR 位图:自下而上,行内 BGRA+ const xor = Buffer.alloc(size * size * 4);+ for (let y = 0; y < size; y++) {+ const srcRow = (size - 1 - y) * size * 4;+ bgra.copy(xor, y * size * 4, srcRow, srcRow + size * 4);+ }+ // AND 掩码:1bpp,行按 4 字节对齐,全 0(交给 alpha 通道)+ const maskRow = Math.ceil(size / 32) * 4;+ const mask = Buffer.alloc(maskRow * size, 0);+ return Buffer.concat([header, xor, mask]);+}++/**+ * @param {Buffer} pngBuffer 任意尺寸的 PNG+ * @returns {Buffer|null} ICO 文件内容+ */+function pngToIco(pngBuffer) {+ const { nativeImage } = require('electron');+ const base = nativeImage.createFromBuffer(pngBuffer);+ if (!base || base.isEmpty()) return null;++ const images = [];+ for (const s of ICO_SIZES) {+ const img = base.getSize().width >= s+ ? base.resize({ width: s, height: s, quality: 'best' })+ : base.resize({ width: s, height: s, quality: 'best' }); // 小图放大也比缺尺寸好+ const dib = buildDib(img.toBitmap(), s);+ images.push({ size: s, data: dib });+ }++ const dir = Buffer.alloc(6 + images.length * 16);+ dir.writeUInt16LE(0, 0);+ dir.writeUInt16LE(1, 2);+ dir.writeUInt16LE(images.length, 4);++ let offset = dir.length;+ images.forEach((img, i) => {+ const p = 6 + i * 16;+ dir.writeUInt8(img.size >= 256 ? 0 : img.size, p);+ dir.writeUInt8(img.size >= 256 ? 0 : img.size, p + 1);+ dir.writeUInt8(0, p + 2);+ dir.writeUInt8(0, p + 3);+ dir.writeUInt16LE(1, p + 4);+ dir.writeUInt16LE(32, p + 6);+ dir.writeUInt32LE(img.data.length, p + 8);+ dir.writeUInt32LE(offset, p + 12);+ offset += img.data.length;+ });++ return Buffer.concat([dir, ...images.map((i) => i.data)]);+}++function safeFileName(name) {+ return String(name).replace(/[\\/:*?"<>|]/g, '_').replace(/\s+/g, ' ').trim().slice(0, 60) || 'Android App';+}++/**+ * 生成桌面快捷方式+ * @param {object} opt { shortcutPath, target, args, iconIcoPath, description, cwd }+ */+function writeShortcut(opt) {+ const { shell } = require('electron');+ const dir = path.dirname(opt.shortcutPath);+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });+ if (fs.existsSync(opt.shortcutPath)) {+ try { fs.unlinkSync(opt.shortcutPath); } catch (_) { /* ignore */ }+ }+ const ok = shell.writeShortcutLink(opt.shortcutPath, 'create', {+ target: opt.target,+ args: opt.args || '',+ icon: opt.iconIcoPath || opt.target,+ iconIndex: 0,+ description: opt.description || '',+ cwd: opt.cwd || path.dirname(opt.target),+ appUserModelId: opt.appUserModelId,+ });+ if (!ok) throw new Error('创建快捷方式失败(writeShortcutLink 返回 false)');+ return opt.shortcutPath;+}++function removeShortcut(p) {+ try {+ if (p && fs.existsSync(p)) fs.unlinkSync(p);+ return true;+ } catch (_) {+ return false;+ }+}++module.exports = { pngToIco, writeShortcut, removeShortcut, safeFileName, ICO_SIZES };diff --git a/src/core/store.js b/src/core/store.jsnew file mode 100644index 0000000..a5de116--- /dev/null+++ b/src/core/store.js@@ -0,0 +1,133 @@+'use strict';+/**+ * 本地持久化:应用清单 + 设置+ * 数据目录:%APPDATA%\apkstart+ */+const fs = require('fs');+const path = require('path');+const os = require('os');++const DATA_DIR = path.join(process.env.APPDATA || path.join(os.homedir(), 'AppData', 'Roaming'), 'apkstart');+const ICON_DIR = path.join(DATA_DIR, 'icons');+const APK_DIR = path.join(DATA_DIR, 'apks');+const APPS_FILE = path.join(DATA_DIR, 'apps.json');+const SETTINGS_FILE = path.join(DATA_DIR, 'settings.json');++const DEFAULT_SETTINGS = {+ adbPath: '',+ device: '127.0.0.1:5555',+ engine: {+ mode: 'builtin', // builtin(自带运行时,默认) | attach(连接已有运行时,高级)+ qemuPath: '',+ systemImage: '',+ memoryMB: 4096,+ cores: 4,+ idleShutdownMinutes: 15,+ startVisible: true,+ },+ runtime: {+ dir: '', // 空 = %APPDATA%\apkstart\runtime+ qemuUrl: '', // 手动指定 QEMU 安装包地址+ isoUrl: '', // 手动指定系统镜像地址+ isoPath: '', // 系统镜像(ISO)路径+ diskPath: '', // 安装系统的虚拟磁盘+ diskSizeGB: 24,+ headless: false, // 不显示虚拟机窗口(仅调试)+ installMode: 'guided', // guided(引导手动安装) | auto(实验性自动安装)+ },+ sharedDir: path.join(os.homedir(), 'ApkStartShared'),+ deviceSharedDir: '/sdcard/ApkStartShared',+ autoConnect: true,+ createShortcutOnInstall: true,+ shortcutDir: '', // 空 = 桌面+ freeform: true, // 独立窗口(Android 7+ freeform)+ hideAfterLaunch: true,+ notifyOnInstall: true,+};++function ensureDirs() {+ for (const d of [DATA_DIR, ICON_DIR, APK_DIR]) {+ if (!fs.existsSync(d)) fs.mkdirSync(d, { recursive: true });+ }+}++function readJson(file, fallback) {+ try {+ return JSON.parse(fs.readFileSync(file, 'utf8'));+ } catch (_) {+ return fallback;+ }+}++function writeJson(file, data) {+ ensureDirs();+ const tmp = file + '.tmp';+ fs.writeFileSync(tmp, JSON.stringify(data, null, 2), 'utf8');+ fs.renameSync(tmp, file);+}++function deepMerge(base, patch) {+ const out = { ...base };+ for (const [k, v] of Object.entries(patch || {})) {+ if (v && typeof v === 'object' && !Array.isArray(v) && base[k] && typeof base[k] === 'object') {+ out[k] = deepMerge(base[k], v);+ } else {+ out[k] = v;+ }+ }+ return out;+}++const store = {+ DATA_DIR, ICON_DIR, APK_DIR,++ getSettings() {+ return deepMerge(DEFAULT_SETTINGS, readJson(SETTINGS_FILE, {}));+ },++ saveSettings(patch) {+ const next = deepMerge(this.getSettings(), patch);+ writeJson(SETTINGS_FILE, next);+ return next;+ },++ getApps() {+ const data = readJson(APPS_FILE, { apps: [] });+ return Array.isArray(data.apps) ? data.apps : [];+ },++ saveApps(apps) {+ writeJson(APPS_FILE, { apps });+ },++ upsertApp(app) {+ const apps = this.getApps();+ const i = apps.findIndex((a) => a.package === app.package);+ if (i >= 0) apps[i] = { ...apps[i], ...app };+ else apps.push(app);+ this.saveApps(apps);+ return app;+ },++ removeApp(pkg) {+ const apps = this.getApps().filter((a) => a.package !== pkg);+ this.saveApps(apps);+ },++ getApp(pkg) {+ return this.getApps().find((a) => a.package === pkg) || null;+ },++ iconPath(pkg) {+ return path.join(ICON_DIR, `${pkg}.png`);+ },++ apkPath(pkg, version = 'cur') {+ return path.join(APK_DIR, `${pkg}-${version}.apk`);+ },++ ensureDirs,+ DEFAULT_SETTINGS,+};++module.exports = store;diff --git a/src/core/zip.js b/src/core/zip.jsnew file mode 100644index 0000000..7b0e286--- /dev/null+++ b/src/core/zip.js@@ -0,0 +1,75 @@+'use strict';+/**+ * 极简 ZIP 读取器(仅依赖 Node 内置 zlib)+ * 只解析中央目录,按需解压单个条目,避免大 APK 全量解压撑爆内存。+ */+const zlib = require('zlib');++const EOCD_SIG = 0x06054b50;+const CEN_SIG = 0x02014b50;+const LOC_SIG = 0x04034b50;++class ZipArchive {+ constructor(buffer) {+ this.buf = buffer;+ this.entries = new Map();+ this._parse();+ }++ _parse() {+ const buf = this.buf;+ let eocd = -1;+ const maxScan = Math.max(0, buf.length - 65557);+ for (let i = buf.length - 22; i >= maxScan; i--) {+ if (buf.readUInt32LE(i) === EOCD_SIG) { eocd = i; break; }+ }+ if (eocd < 0) throw new Error('不是有效的 ZIP/APK 文件(未找到 EOCD)');++ const total = buf.readUInt16LE(eocd + 10);+ let offset = buf.readUInt32LE(eocd + 16);++ for (let i = 0; i < total; i++) {+ if (buf.readUInt32LE(offset) !== CEN_SIG) break;+ const flags = buf.readUInt16LE(offset + 8);+ const method = buf.readUInt16LE(offset + 10);+ const compSize = buf.readUInt32LE(offset + 20);+ const uncompSize = buf.readUInt32LE(offset + 24);+ const nameLen = buf.readUInt16LE(offset + 28);+ const extraLen = buf.readUInt16LE(offset + 30);+ const commentLen = buf.readUInt16LE(offset + 32);+ const localOffset = buf.readUInt32LE(offset + 42);+ const name = buf.toString('utf8', offset + 46, offset + 46 + nameLen);+ this.entries.set(name, {+ name, flags, method, compSize, uncompSize, localOffset,+ });+ offset += 46 + nameLen + extraLen + commentLen;+ }+ }++ has(name) { return this.entries.has(name); }++ names() { return [...this.entries.keys()]; }++ read(name) {+ const e = this.entries.get(name);+ if (!e) return null;+ const buf = this.buf;+ if (buf.readUInt32LE(e.localOffset) !== LOC_SIG) {+ throw new Error(`本地文件头损坏: ${name}`);+ }+ const nameLen = buf.readUInt16LE(e.localOffset + 26);+ const extraLen = buf.readUInt16LE(e.localOffset + 28);+ const start = e.localOffset + 30 + nameLen + extraLen;+ const raw = buf.subarray(start, start + e.compSize);+ if (e.method === 0) return Buffer.from(raw);+ if (e.method === 8) return zlib.inflateRawSync(raw);+ throw new Error(`不支持的压缩方式 ${e.method}: ${name}`);+ }++ /** 列出匹配某个前缀/正则的条目名 */+ find(re) {+ return [...this.entries.keys()].filter((n) => re.test(n));+ }+}++module.exports = { ZipArchive };diff --git a/src/main.js b/src/main.jsnew file mode 100644index 0000000..8b603d2--- /dev/null+++ b/src/main.js@@ -0,0 +1,477 @@+'use strict';+/**+ * ApkStart 主进程+ * 职责:窗口 / 托盘 / 单实例 / 命令行分发(双击 apk、桌面快捷方式启动)/ IPC+ */+const { app, BrowserWindow, ipcMain, dialog, Tray, Menu, shell, nativeImage } = require('electron');+const fs = require('fs');+const path = require('path');++const store = require('./core/store');+const { Runtime } = require('./core/engine');+const { Installer } = require('./core/installer');+const { Sharer } = require('./core/sharer');+const { parseApk } = require('./core/apk');+const { drawAppIcon } = require('./core/png');+const { pngToIco } = require('./core/shortcut');+const assoc = require('./core/assoc');++const APP_ROOT = path.join(__dirname, '..');+const IS_DEV = process.argv.includes('--dev');+const ICON_PNG = drawAppIcon(256);++let mainWindow = null;+let tray = null;+let runtime = null;+let installer = null;+let sharer = null;+let quitting = false;++// ---------------- 命令行解析 ----------------++function parseArgs(argv) {+ const args = argv.slice(IS_DEV ? 2 : 1);+ const out = { apk: null, launch: null, silent: false };+ for (let i = 0; i < args.length; i++) {+ const a = args[i];+ if (a === '--launch' && args[i + 1]) { out.launch = args[++i]; out.silent = true; }+ else if (a === '--silent') out.silent = true;+ else if (/\.(apk|xapk)$/i.test(a) && !a.startsWith('--')) out.apk = a;+ }+ return out;+}++function launcherInfo() {+ if (app.isPackaged) {+ return { target: process.execPath, args: '', cwd: path.dirname(process.execPath) };+ }+ return { target: process.execPath, args: `"${APP_ROOT}"`, cwd: APP_ROOT };+}++// ---------------- 主窗口 ----------------++function createWindow({ show = true } = {}) {+ mainWindow = new BrowserWindow({+ width: 1140,+ height: 740,+ minWidth: 900,+ minHeight: 560,+ show: false,+ backgroundColor: '#f7f8fa',+ frame: false,+ titleBarStyle: 'hidden',+ titleBarOverlay: { color: '#f7f8fa', symbolColor: '#2b3138', height: 44 },+ icon: nativeImage.createFromBuffer(ICON_PNG),+ webPreferences: {+ preload: path.join(__dirname, 'preload.js'),+ contextIsolation: true,+ nodeIntegration: false,+ sandbox: false,+ spellcheck: false,+ },+ });++ mainWindow.loadFile(path.join(__dirname, 'ui', 'index.html'));+ if (show) mainWindow.once('ready-to-show', () => mainWindow.show());++ mainWindow.on('close', (e) => {+ if (quitting) return;+ e.preventDefault();+ mainWindow.hide();+ notify('ApkStart 仍在后台运行', '点击托盘图标可重新打开;右键托盘可退出。');+ });++ if (IS_DEV) mainWindow.webContents.openDevTools({ mode: 'detach' });+ return mainWindow;+}++function showWindow() {+ if (!mainWindow) createWindow();+ if (mainWindow.isMinimized()) mainWindow.restore();+ mainWindow.show();+ mainWindow.focus();+}++function notify(title, body) {+ if (store.getSettings().notifyOnInstall === false) return;+ try {+ const { Notification } = require('electron');+ if (Notification.isSupported()) new Notification({ title, body, icon: nativeImage.createFromBuffer(ICON_PNG) }).show();+ } catch (_) { /* ignore */ }+}++function send(channel, payload) {+ if (mainWindow && !mainWindow.isDestroyed()) mainWindow.webContents.send(channel, payload);+}++// ---------------- 托盘 ----------------++function buildTray() {+ const icon = nativeImage.createFromBuffer(drawAppIcon(64)).resize({ width: 16, height: 16 });+ try {+ tray = new Tray(icon);+ } catch (_) {+ return;+ }+ const refresh = () => {+ const apps = store.getApps().slice(0, 8);+ const menu = Menu.buildFromTemplate([+ { label: '打开 ApkStart', click: () => showWindow() },+ { type: 'separator' },+ ...(apps.length+ ? apps.map((a) => ({ label: a.label, click: () => runLaunch(a.package) }))+ : [{ label: '还没有安装应用', enabled: false }]),+ { type: 'separator' },+ { label: '同步共享目录', click: () => sharer.sync() },+ { label: '设置', click: () => { showWindow(); send('ui:navigate', 'settings'); } },+ { type: 'separator' },+ { label: '退出', click: () => { quitting = true; app.quit(); } },+ ]);+ tray.setContextMenu(menu);+ };+ tray.setToolTip('ApkStart — 安卓应用运行器');+ tray.on('double-click', () => showWindow());+ refresh();+ setInterval(refresh, 5000).unref?.();+}++// ---------------- 核心动作 ----------------++async function runInstall(filePath) {+ showWindow();+ send('install:start', { file: filePath });+ try {+ const result = await installer.install(filePath, (p) => send('install:progress', p));+ send('install:done', result);+ notify('安装完成', `${result.app.label} 已安装${result.app.shortcutPath ? ',桌面快捷方式已创建' : ''}`);+ return result;+ } catch (e) {+ send('install:error', { message: e.message });+ if (e.needsSetup) send('ui:navigate', 'setup');+ notify('安装失败', e.message.slice(0, 120));+ throw e;+ }+}++async function runLaunch(pkg) {+ try {+ const settings = store.getSettings();+ const r = await installer.launch(pkg, { onLog: (m) => send('runtime:log', m) });+ send('app:launched', { package: pkg, engine: r.engine });+ if (settings.hideAfterLaunch && !IS_DEV && !mainWindow?.isVisible()) {+ // 静默启动:不打扰用户+ }+ return { ok: true };+ } catch (e) {+ showWindow();+ send('toast', { type: 'error', message: `启动失败:${e.message}` });+ return { ok: false, error: e.message };+ }+}++// ---------------- IPC ----------------++function registerIpc() {+ ipcMain.handle('app:info', () => ({+ version: app.getVersion(),+ isDev: IS_DEV,+ dataDir: store.DATA_DIR,+ exe: process.execPath,+ packaged: app.isPackaged,+ }));++ ipcMain.handle('apps:list', async () => {+ const apps = store.getApps();+ const settings = store.getSettings();+ let running = [];+ try {+ const c = runtime.client();+ if (await c.isOnline()) running = await c.runningPackages();+ } catch (_) { /* 运行时未启动时忽略 */ }+ return apps+ .map((a) => ({+ ...a,+ running: running.includes(a.package),+ iconUrl: a.iconPath && fs.existsSync(a.iconPath)+ ? `file:///${a.iconPath.replace(/\\/g, '/').replace(/ /g, '%20')}`+ : null,+ shortcutExists: a.shortcutPath ? fs.existsSync(a.shortcutPath) : false,+ }))+ .sort((a, b) => (b.pinned ? 1 : 0) - (a.pinned ? 1 : 0) || (b.lastLaunchAt || 0) - (a.lastLaunchAt || 0) || a.label.localeCompare(b.label, 'zh'));+ });++ ipcMain.handle('apk:pick', async () => {+ const r = await dialog.showOpenDialog(mainWindow, {+ title: '选择要安装的 APK',+ filters: [{ name: 'Android 应用', extensions: ['apk'] }],+ properties: ['openFile', 'multiSelections'],+ });+ if (r.canceled) return [];+ return r.filePaths;+ });++ ipcMain.handle('apk:parse', async (_e, filePath) => parseApk(filePath));++ ipcMain.handle('apk:install', async (_e, filePath) => {+ const r = await runInstall(filePath);+ return { ok: true, app: r.app, warnings: r.warnings };+ });++ ipcMain.handle('app:launch', async (_e, pkg) => runLaunch(pkg));++ ipcMain.handle('app:uninstall', async (_e, pkg) => {+ await installer.uninstall(pkg);+ return { ok: true };+ });++ ipcMain.handle('app:shortcut', async (_e, pkg) => {+ const appRecord = store.getApp(pkg);+ if (!appRecord) throw new Error('应用不存在');+ const p = installer.createShortcut(appRecord);+ store.upsertApp({ package: pkg, shortcutPath: p });+ return { ok: true, path: p };+ });++ ipcMain.handle('app:clearData', async (_e, pkg) => {+ const rt = await runtime.ensure();+ if (!rt.ok) throw new Error(rt.error);+ await rt.client.clearData(pkg);+ return { ok: true };+ });++ ipcMain.handle('app:pin', async (_e, { pkg, pinned }) => {+ store.upsertApp({ package: pkg, pinned: !!pinned });+ return { ok: true };+ });++ ipcMain.handle('app:revealApk', async (_e, pkg) => {+ const a = store.getApp(pkg);+ if (a?.apkPath && fs.existsSync(a.apkPath)) shell.showItemInFolder(a.apkPath);+ });++ ipcMain.handle('apk:reveal', async () => {+ fs.mkdirSync(store.APK_DIR, { recursive: true });+ shell.openPath(store.APK_DIR);+ });++ ipcMain.handle('settings:get', () => store.getSettings());+ ipcMain.handle('settings:set', (_e, patch) => store.saveSettings(patch));++ ipcMain.handle('runtime:status', async () => runtime.status());+ ipcMain.handle('runtime:probe', async () => runtime.probe());+ ipcMain.handle('runtime:start', async () => {+ const r = await runtime.ensure({ onLog: (m) => send('runtime:log', m) });+ return r.ok ? { ok: true, engine: r.engine } : { ok: false, error: r.error, needsSetup: r.needsSetup };+ });+ ipcMain.handle('runtime:stop', async () => {+ await runtime.stop();+ return { ok: true };+ });+ ipcMain.handle('runtime:log', () => runtime.bootLog);++ // ---------------- 运行时自举 ----------------++ ipcMain.handle('provision:installAdb', async () => {+ try {+ const r = await runtime.provisioner.installAdb((p) => send('provision:progress', { ...p, component: 'adb' }));+ return { ok: true, ...r };+ } catch (e) {+ return { ok: false, error: e.message };+ }+ });++ ipcMain.handle('provision:installQemu', async () => {+ try {+ const r = await runtime.provisioner.installQemu((p) => send('provision:progress', { ...p, component: 'qemu' }));+ return { ok: true, ...r };+ } catch (e) {+ return { ok: false, error: e.message };+ }+ });++ ipcMain.handle('provision:downloadIso', async () => {+ try {+ const r = await runtime.provisioner.downloadIso((p) => send('provision:progress', { ...p, component: 'iso' }));+ return { ok: true, ...r };+ } catch (e) {+ return { ok: false, error: e.message };+ }+ });++ ipcMain.handle('provision:createDisk', async (_e, sizeGB) => {+ try {+ const r = await runtime.provisioner.createDisk(sizeGB || store.getSettings().runtime.diskSizeGB || 24,+ (p) => send('provision:progress', { ...p, component: 'disk' }));+ return { ok: true, ...r };+ } catch (e) {+ return { ok: false, error: e.message };+ }+ });++ ipcMain.handle('provision:importIso', async () => {+ const r = await dialog.showOpenDialog(mainWindow, {+ title: '选择 Android-x86 / Bliss OS 系统镜像',+ filters: [{ name: '系统镜像', extensions: ['iso', 'img'] }],+ properties: ['openFile'],+ });+ if (r.canceled) return { ok: false, canceled: true };+ try {+ return { ok: true, ...runtime.provisioner.importIso(r.filePaths[0]) };+ } catch (e) {+ return { ok: false, error: e.message };+ }+ });++ ipcMain.handle('provision:importDisk', async () => {+ const r = await dialog.showOpenDialog(mainWindow, {+ title: '选择已安装 Android 的虚拟磁盘',+ filters: [{ name: '虚拟磁盘', extensions: ['qcow2', 'img', 'vmdk', 'raw'] }],+ properties: ['openFile'],+ });+ if (r.canceled) return { ok: false, canceled: true };+ try {+ const info = runtime.provisioner.importDisk(r.filePaths[0]);+ store.saveSettings({ runtime: { installed: true } });+ return { ok: true, ...info };+ } catch (e) {+ return { ok: false, error: e.message };+ }+ });++ ipcMain.handle('provision:check', async () => runtime.provisioner.checkEnv());+ ipcMain.handle('provision:probeSources', async () => runtime.provisioner.probeSources());++ ipcMain.handle('runtime:startInstaller', async () => {+ try {+ await runtime.startInstaller({ onLog: (m) => send('runtime:log', m) });+ return { ok: true };+ } catch (e) {+ return { ok: false, error: e.message };+ }+ });++ ipcMain.handle('runtime:markInstalled', async () => {+ await runtime.markInstalled();+ return { ok: true };+ });++ ipcMain.handle('runtime:resetInstall', async () => {+ store.saveSettings({ runtime: { installed: false } });+ return { ok: true };+ });++ ipcMain.handle('assoc:status', () => {+ const { execFileSync } = require('child_process');+ try {+ const out = execFileSync('reg', ['query', 'HKCU\\Software\\Classes\\.apk', '/ve'], { windowsHide: true, encoding: 'utf8' });+ return { registered: out.includes(assoc.PROGID) };+ } catch (_) {+ return { registered: false };+ }+ });++ ipcMain.handle('assoc:register', () => {+ const l = launcherInfo();+ const icoPath = path.join(store.ICON_DIR, 'apkstart.ico');+ if (!fs.existsSync(icoPath)) {+ const ico = pngToIco(ICON_PNG);+ if (ico) fs.writeFileSync(icoPath, ico);+ }+ return assoc.registerAssociation(l.target, icoPath, l.args);+ });++ ipcMain.handle('assoc:unregister', () => assoc.unregisterAssociation());++ ipcMain.handle('share:sync', async () => sharer.sync({ onLog: (m) => send('runtime:log', m) }));+ ipcMain.handle('share:open', async () => {+ const dir = store.getSettings().sharedDir;+ fs.mkdirSync(dir, { recursive: true });+ shell.openPath(dir);+ });++ ipcMain.handle('shell:open', (_e, url) => shell.openExternal(url));++ ipcMain.handle('window:minimize', () => mainWindow?.minimize());+ ipcMain.handle('window:maximize', () => {+ if (!mainWindow) return;+ if (mainWindow.isMaximized()) mainWindow.unmaximize();+ else mainWindow.maximize();+ });+ ipcMain.handle('window:close', () => mainWindow?.close());+ ipcMain.handle('window:hide', () => mainWindow?.hide());+}++// ---------------- 生命周期 ----------------++const gotLock = app.requestSingleInstanceLock();+if (!gotLock) {+ app.quit();+} else {+ app.on('second-instance', (_evt, argv) => {+ const args = parseArgs(argv);+ if (args.launch) { runLaunch(args.launch); return; }+ if (args.apk) { runInstall(args.apk).catch(() => {}); return; }+ showWindow();+ });++ app.whenReady().then(async () => {+ store.ensureDirs();+ runtime = new Runtime(APP_ROOT);+ const l = launcherInfo();+ installer = new Installer(runtime, {+ launcherTarget: l.target,+ launcherArgs: l.args,+ cwd: l.cwd,+ isDev: IS_DEV,+ desktopDir: app.getPath('desktop'),+ });+ sharer = new Sharer(runtime);++ registerIpc();+ createWindow({ show: !parseArgs(process.argv).silent });+ buildTray();++ const args = parseArgs(process.argv);+ if (args.apk) runInstall(args.apk).catch(() => {});+ else if (args.launch) {+ const r = await runLaunch(args.launch);+ if (r.ok) {+ // 纯原生体验:从桌面图标启动时,不留下壳层界面+ setTimeout(() => { if (store.getSettings().hideAfterLaunch) { quitting = true; app.quit(); } }, 800);+ }+ }++ sharer.start(8000);++ // 冒烟测试:截图后退出,用于自动化验证界面是否正常渲染+ if (process.argv.includes('--smoke') && mainWindow) {+ const out = process.argv[process.argv.indexOf('--smoke') + 1] || 'smoke.png';+ mainWindow.webContents.once('did-finish-load', () => {+ setTimeout(async () => {+ try {+ const img = await mainWindow.webContents.capturePage();+ fs.writeFileSync(out, img.toPNG());+ } catch (e) {+ console.error('[smoke] 截图失败', e);+ }+ quitting = true;+ app.quit();+ }, 3500);+ });+ }++ app.on('activate', () => showWindow());+ });++ app.on('window-all-closed', () => {+ // 正常关闭窗口时只隐藏到托盘(close 事件已拦截),+ // 走到这里说明是真正要退出,必须放行,否则进程会残留并占住单实例锁。+ if (quitting) app.exit(0);+ });++ app.on('before-quit', () => {+ quitting = true;+ sharer?.stop();+ runtime?.dispose();+ });+}diff --git a/src/preload.js b/src/preload.jsnew file mode 100644index 0000000..7aa69da--- /dev/null+++ b/src/preload.js@@ -0,0 +1,66 @@+'use strict';+const { contextBridge, ipcRenderer, webUtils } = require('electron');++const invoke = (channel, payload) => ipcRenderer.invoke(channel, payload);++contextBridge.exposeInMainWorld('apkstart', {+ info: () => invoke('app:info'),+ listApps: () => invoke('apps:list'),+ pickApk: () => invoke('apk:pick'),+ parseApk: (p) => invoke('apk:parse', p),+ installApk: (p) => invoke('apk:install', p),+ launch: (pkg) => invoke('app:launch', pkg),+ uninstall: (pkg) => invoke('app:uninstall', pkg),+ createShortcut: (pkg) => invoke('app:shortcut', pkg),+ clearData: (pkg) => invoke('app:clearData', pkg),+ pin: (pkg, pinned) => invoke('app:pin', { pkg, pinned }),+ revealApk: (pkg) => invoke('app:revealApk', pkg),+ revealApkDir: () => invoke('apk:reveal'),++ getSettings: () => invoke('settings:get'),+ setSettings: (patch) => invoke('settings:set', patch),++ runtimeStatus: () => invoke('runtime:status'),+ runtimeProbe: () => invoke('runtime:probe'),+ runtimeStart: () => invoke('runtime:start'),+ runtimeStop: () => invoke('runtime:stop'),+ runtimeLog: () => invoke('runtime:log'),+ startInstaller: () => invoke('runtime:startInstaller'),+ markInstalled: () => invoke('runtime:markInstalled'),+ resetInstall: () => invoke('runtime:resetInstall'),++ provisionCheck: () => invoke('provision:check'),+ provisionProbeSources: () => invoke('provision:probeSources'),+ installAdb: () => invoke('provision:installAdb'),+ installQemu: () => invoke('provision:installQemu'),+ downloadIso: () => invoke('provision:downloadIso'),+ createDisk: (gb) => invoke('provision:createDisk', gb),+ importIso: () => invoke('provision:importIso'),+ importDisk: () => invoke('provision:importDisk'),++ assocStatus: () => invoke('assoc:status'),+ assocRegister: () => invoke('assoc:register'),+ assocUnregister: () => invoke('assoc:unregister'),++ syncShared: () => invoke('share:sync'),+ openSharedDir: () => invoke('share:open'),++ openExternal: (url) => invoke('shell:open', url),+ winMinimize: () => invoke('window:minimize'),+ winMaximize: () => invoke('window:maximize'),+ winClose: () => invoke('window:close'),+ winHide: () => invoke('window:hide'),++ pathForFile: (file) => webUtils.getPathForFile(file),++ on: (channel, cb) => {+ const allowed = [+ 'install:start', 'install:progress', 'install:done', 'install:error',+ 'app:launched', 'runtime:log', 'toast', 'ui:navigate', 'provision:progress',+ ];+ if (!allowed.includes(channel)) return () => {};+ const handler = (_e, payload) => cb(payload);+ ipcRenderer.on(channel, handler);+ return () => ipcRenderer.removeListener(channel, handler);+ },+});diff --git a/src/ui/app.js b/src/ui/app.jsnew file mode 100644index 0000000..9777aac--- /dev/null+++ b/src/ui/app.js@@ -0,0 +1,821 @@+'use strict';++const api = window.apkstart;+const $ = (id) => document.getElementById(id);++const state = {+ apps: [],+ settings: null,+ status: null,+ filter: '',+ installing: false,+ setupBusy: null,+ setupDismissed: false,+ menuPkg: null,+};++/* ---------------- 工具 ---------------- */++function esc(s) {+ return String(s == null ? '' : s).replace(/[&<>"']/g, (c) => (+ { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]+ ));+}++function initialOf(label) {+ const t = String(label || '?').trim();+ return (t[0] || '?').toUpperCase();+}++function fmtSize(bytes) {+ if (!bytes) return '';+ const mb = bytes / 1024 / 1024;+ return mb >= 1024 ? `${(mb / 1024).toFixed(1)} GB` : `${mb.toFixed(0)} MB`;+}++function relTime(ts) {+ if (!ts) return '';+ const d = Date.now() - ts;+ if (d < 60000) return '刚刚';+ if (d < 3600000) return `${Math.floor(d / 60000)} 分钟前`;+ if (d < 86400000) return `${Math.floor(d / 3600000)} 小时前`;+ if (d < 86400000 * 30) return `${Math.floor(d / 86400000)} 天前`;+ return new Date(ts).toLocaleDateString('zh-CN');+}++/**+ * 迷你 toast+ */+function toast({ title, body = '', type = 'info', progress = null, sticky = false, spinner = false }) {+ const el = document.createElement('div');+ el.className = `toast ${type === 'error' ? 'error' : ''}`;+ el.innerHTML = `+ <div class="t-title">+ ${spinner ? '<span class="spinner"></span>' : ''}+ <span class="t-title-text">${esc(title)}</span>+ </div>+ <div class="t-body">${esc(body)}</div>+ ${progress === null ? '' : '<div class="bar"><i></i></div>'}+ `;+ $('toastWrap').appendChild(el);++ const dismiss = () => {+ el.style.transition = 'opacity .18s, transform .18s';+ el.style.opacity = '0';+ el.style.transform = 'translateY(4px)';+ setTimeout(() => el.remove(), 200);+ };++ const ctl = {+ el, dismiss,+ update({ title: t2, body: b2, progress: p2, type: ty } = {}) {+ if (t2 !== undefined) el.querySelector('.t-title-text').textContent = t2;+ if (b2 !== undefined) el.querySelector('.t-body').textContent = b2;+ if (p2 !== undefined && el.querySelector('.bar i')) {+ el.querySelector('.bar i').style.width = `${Math.max(2, Math.min(100, p2))}%`;+ }+ if (ty === 'error') el.classList.add('error');+ if (ty === 'ok') {+ el.querySelector('.spinner')?.remove();+ el.classList.remove('error');+ }+ },+ };++ if (!sticky) setTimeout(dismiss, type === 'error' ? 6000 : 3200);+ return ctl;+}++/* ---------------- 渲染 ---------------- */++function visibleApps() {+ const q = state.filter.trim().toLowerCase();+ if (!q) return state.apps;+ return state.apps.filter((a) => (+ a.label.toLowerCase().includes(q)+ || a.package.toLowerCase().includes(q)+ ));+}++function renderGrid() {+ const apps = visibleApps();+ const grid = $('grid');+ const empty = $('empty');++ const hasAny = state.apps.length > 0;+ grid.classList.toggle('hidden', apps.length === 0);+ empty.classList.toggle('hidden', apps.length > 0);++ if (!hasAny) {+ const s = state.status;+ $('emptyHint').textContent = s && s.adbOk === false+ ? '首次使用:请先在设置里指定 adb 位置或系统镜像,然后回来安装应用。'+ : '提示:所有应用共享同一个 Android 运行时,所以第二个应用的启动几乎是瞬时的。';+ grid.innerHTML = '';+ return;+ }++ grid.innerHTML = apps.map((a) => `+ <div class="card" data-pkg="${esc(a.package)}" title="${esc(a.label)} · ${esc(a.package)}">+ ${a.pinned ? '<span class="pin">★</span>' : ''}+ ${a.running ? '<span class="badge-run" title="正在运行"></span>' : ''}+ <div class="icon">+ ${a.iconUrl+ ? `<img src="${esc(a.iconUrl)}" alt="" draggable="false" />`+ : `<div class="fallback" style="background:${esc(a.accent || '#9aa6b2')}">${esc(initialOf(a.label))}</div>`}+ </div>+ <div class="name">${esc(a.label)}</div>+ <div class="meta">${a.running ? '运行中' : `v${esc(a.versionName)}${a.lastLaunchAt ? ' · ' + relTime(a.lastLaunchAt) : ''}`}</div>+ <div class="open-hint">${a.running ? '切换到前台' : '打开'}</div>+ </div>+ `).join('');+}++/* ---------------- 数据刷新 ---------------- */++async function refreshApps() {+ try {+ state.apps = await api.listApps();+ renderGrid();+ updateStats();+ } catch (e) {+ console.error(e);+ }+}++function updateStats() {+ const n = state.apps.length;+ $('statusStats').textContent = n ? `${n} 个应用` : '暂无应用';+}++async function refreshStatus() {+ try {+ state.status = await api.runtimeStatus();+ const s = state.status;+ const dot = $('statusDot');+ const text = $('statusText');+ const tag = $('engineTag');++ if (!s.adbOk) {+ dot.className = 'dot err';+ text.textContent = '运行时未部署 —— 点击右上角「运行时」开始一键部署';+ tag.textContent = '需要部署';+ tag.className = 'brand-tag';+ } else if (s.deviceOnline) {+ dot.className = 'dot ok';+ text.textContent = `运行时已就绪 · Android ${s.android || '?'}${s.freeform ? ' · 独立窗口已启用' : ''}`;+ tag.textContent = `Android ${s.android || ''}`.trim();+ tag.className = 'brand-tag ok';+ } else if (s.vmStarting) {+ dot.className = 'dot';+ text.textContent = '运行时正在启动…';+ tag.textContent = '启动中';+ tag.className = 'brand-tag';+ } else {+ dot.className = 'dot';+ text.textContent = s.installed+ ? '运行时待机(安装或打开应用时会自动拉起)'+ : '运行时尚未安装 Android 系统 —— 点击右上角「运行时」继续';+ tag.textContent = s.installed ? '待机' : '待安装';+ tag.className = 'brand-tag';+ }+ $('statusDevice').textContent = s.deviceOnline ? '127.0.0.1:5555' : '';++ renderSetup(s);+ } catch (e) {+ $('statusText').textContent = `状态检查失败:${e.message}`;+ }+}++/* ---------------- 运行时部署向导 ---------------- */++function showSetup(on) {+ $('setupView').hidden = !on;+ $('content').hidden = !!on;+ if (!on) $('setupGuide').hidden = true;+}++function fmtGB(n) { return n ? `${(n / 1073741824).toFixed(2)} GB` : ''; }++function stepRow(opt) {+ const cls = ['step'];+ if (opt.done) cls.push('done');+ if (opt.busy) cls.push('busy');+ return `+ <div class="${cls.join(' ')}" data-step="${opt.key}">+ <div class="idx">${opt.done ? '✓' : opt.index}</div>+ <div class="body">+ <div class="t">${esc(opt.title)}${opt.tag ? `<span class="tag ${opt.req ? 'req' : ''}">${esc(opt.tag)}</span>` : ''}</div>+ <div class="d" data-desc>${esc(opt.desc)}</div>+ <div class="bar"><i data-bar></i></div>+ </div>+ <div class="act">${opt.actions || ''}</div>+ </div>`;+}++function renderSetup(s) {+ if (!s) return;+ const env = s.env || {};+ const hv = env.hypervisor || {};+ const needSetup = !!s.needsSetup;++ // 自动进入部署页:还没装过应用、且运行时未就绪+ if (needSetup && !s.ready && !state.setupDismissed && state.apps.length === 0 && !state.setupBusy) {+ showSetup(true);+ }++ $('setupHv').textContent = hv.whpx ? 'WHPX 硬件加速:已启用' : 'WHPX:未启用(软件模拟)';+ $('setupHv').className = `setup-hv ${hv.whpx ? 'ok' : ''}`;+ $('setupHv').title = hv.note || '';++ const isoDone = !!(env.iso && env.iso.ok);+ const diskDone = !!(env.disk && env.disk.ok);+ const installed = !!s.installed;+ const busy = state.setupBusy;++ const steps = [+ {+ key: 'adb',+ index: 1,+ title: 'adb 工具链',+ tag: '必需',+ req: true,+ done: !!(env.adb && env.adb.ok),+ busy: busy === 'adb',+ desc: env.adb && env.adb.ok+ ? `adb ${env.adb.version} · ${env.adb.path}`+ : 'Android 调试桥,ApkStart 用它安装/启动应用(约 8 MB)',+ actions: env.adb && env.adb.ok ? '' : '<button class="btn ghost sm" data-act="adb">下载</button>',+ },+ {+ key: 'qemu',+ index: 2,+ title: 'QEMU 虚拟机引擎',+ tag: '必需',+ req: true,+ done: !!(env.qemu && env.qemu.ok),+ busy: busy === 'qemu',+ desc: env.qemu && env.qemu.ok+ ? `QEMU ${env.qemu.version} · ${env.qemu.path}`+ : 'ApkStart 自带的虚拟机引擎(约 200 MB,静默安装,不污染系统)',+ actions: env.qemu && env.qemu.ok ? '' : '<button class="btn ghost sm" data-act="qemu">下载</button>',+ },+ {+ key: 'iso',+ index: 3,+ title: 'Android 系统镜像',+ tag: '必需',+ req: true,+ done: isoDone,+ busy: busy === 'iso',+ desc: isoDone+ ? `已就绪 ${fmtGB(env.iso.size)} · ${env.iso.path}`+ : 'Android-x86 9.0-r2(约 900 MB);也可以导入本机已有的 ISO/IMG',+ actions: isoDone+ ? ''+ : '<button class="btn ghost sm" data-act="iso">下载</button><button class="btn ghost sm" data-act="isoImport">导入</button>',+ },+ {+ key: 'disk',+ index: 4,+ title: '系统虚拟磁盘',+ tag: '必需',+ req: true,+ done: diskDone,+ busy: busy === 'disk',+ desc: diskDone+ ? `${fmtGB(env.disk.size)} · ${env.disk.path}`+ : `${store_getDiskSize()} GB 稀疏磁盘,只占实际使用空间;也可以导入已装好 Android 的磁盘镜像`,+ actions: diskDone+ ? ''+ : '<button class="btn ghost sm" data-act="disk">创建</button><button class="btn ghost sm" data-act="diskImport">导入</button>',+ },+ {+ key: 'install',+ index: 5,+ title: '安装 Android 系统',+ tag: installed ? '已完成' : '一次性操作',+ done: installed,+ desc: installed+ ? `已完成${s.android ? ` · 当前 Android ${s.android}` : ''}`+ : '在虚拟机窗口里走 6 步安装(ApkStart 会给出逐步提示),装好后永久免装',+ actions: installed+ ? `<button class="btn ghost sm" data-act="vmStart">${s.deviceOnline ? '已启动' : '启动运行时'}</button>+ <button class="btn ghost sm" data-act="vmStop">停止</button>`+ : `<button class="btn primary sm" data-act="install" ${isoDone && diskDone ? '' : 'disabled'}>开始安装</button>`,+ },+ ];++ $('setupSteps').innerHTML = steps.map(stepRow).join('');+ $('btnDeployAll').disabled = !!busy;+ $('btnDeployAll').textContent = busy ? '部署中…' : (installed ? '检查更新' : '一键部署');+ $('setupNote').textContent = hv.note && !hv.whpx ? '提示:未启用 WHPX 时首次启动较慢(纯软件模拟)' : '';+}++function store_getDiskSize() {+ return (state.settings && state.settings.runtime && state.settings.runtime.diskSizeGB) || 24;+}++function setStepBusy(key, on) {+ state.setupBusy = on ? key : null;+ const row = $('setupSteps').querySelector(`[data-step="${key}"]`);+ if (row) {+ row.classList.toggle('busy', !!on);+ if (on) {+ row.querySelector('[data-bar]').style.width = '3%';+ }+ }+}++function updateStepProgress(component, p) {+ if (!component) return;+ const row = $('setupSteps').querySelector(`[data-step="${component}"]`);+ if (!row) return;+ if (p.percent !== undefined) {+ const bar = row.querySelector('[data-bar]');+ if (bar) bar.style.width = `${Math.max(3, Math.min(100, p.percent))}%`;+ }+ if (p.message) {+ const d = row.querySelector('[data-desc]');+ if (d) d.textContent = p.message;+ }+}++async function deployAll() {+ const steps = ['adb', 'qemu', 'iso', 'disk'];+ for (const key of steps) {+ const env = (state.status && state.status.env) || {};+ const done = key === 'adb' ? env.adb && env.adb.ok+ : key === 'qemu' ? env.qemu && env.qemu.ok+ : key === 'iso' ? env.iso && env.iso.ok+ : env.disk && env.disk.ok;+ if (done) continue;+ // eslint-disable-next-line no-await-in-loop+ const r = await runStep(key);+ if (!r.ok) {+ toast({ title: `${key} 部署失败`, body: r.error, type: 'error', sticky: true });+ return;+ }+ }+ await refreshStatus();+ toast({ title: '运行时组件已就绪', body: '下一步:点击「开始安装」,在虚拟机窗口里完成 Android 安装。', type: 'ok' });+}++async function runStep(key) {+ if (state.setupBusy) return { ok: false, error: '已有部署任务进行中' };+ setStepBusy(key, true);+ let r;+ try {+ if (key === 'adb') r = await api.installAdb();+ else if (key === 'qemu') r = await api.installQemu();+ else if (key === 'iso') r = await api.downloadIso();+ else if (key === 'disk') r = await api.createDisk(store_getDiskSize());+ else r = { ok: false, error: '未知步骤' };+ } catch (e) {+ r = { ok: false, error: e.message };+ }+ setStepBusy(key, false);+ await refreshStatus();+ return r;+}++async function startInstall() {+ const r = await api.startInstaller();+ if (!r.ok) {+ toast({ title: '无法启动安装环境', body: r.error, type: 'error', sticky: true });+ return;+ }+ $('setupGuide').hidden = false;+ $('setupGuide').scrollIntoView({ behavior: 'smooth', block: 'start' });+ toast({ title: '虚拟机窗口已打开', body: '按下方 6 步完成安装;装好后点「我已安装完成」。', type: 'ok', sticky: true });+}++async function markInstalled() {+ await api.markInstalled();+ await api.runtimeStop();+ $('setupGuide').hidden = true;+ await refreshStatus();+ toast({ title: '安装完成,运行时已接管', body: '现在可以直接把 APK 拖进来安装了。', type: 'ok' });+}++++/* ---------------- 安装 ---------------- */++async function installFiles(paths) {+ if (!paths || !paths.length) return;+ if (state.installing) {+ toast({ title: '已有安装任务在进行', body: '请等当前应用装完再继续。' });+ return;+ }+ state.installing = true;+ let ok = 0;+ let failed = 0;++ for (const p of paths) {+ try {+ const name = p.split(/[\\/]/).pop();+ const t = toast({ title: `正在安装 ${name}`, body: '解析 APK…', progress: 8, sticky: true, spinner: true });+ const off = api.on('install:progress', (pr) => {+ const pct = { parse: 12, 'parse-done': 24, runtime: 38, install: 62, shortcut: 88, done: 100 }[pr.stage] || 50;+ t.update({ title: pr.meta ? `正在安装 ${pr.meta.label}` : `正在安装 ${name}`, body: pr.message, progress: pct });+ });+ try {+ const r = await api.installApk(p);+ t.update({ title: `${r.app.label} 已安装`, body: r.app.shortcutPath ? '桌面快捷方式已创建,双击即可直接打开。' : '可在应用卡片右键创建桌面快捷方式。', progress: 100, type: 'ok' });+ t.el.querySelector('.spinner')?.remove();+ setTimeout(t.dismiss, 3600);+ if (r.warnings && r.warnings.length) {+ toast({ title: `${r.app.label} 兼容性提示`, body: r.warnings.join(' '), type: 'error', sticky: false });+ }+ ok++;+ } finally {+ off();+ }+ } catch (e) {+ failed++;+ toast({ title: '安装失败', body: e.message, type: 'error' });+ }+ }++ state.installing = false;+ await refreshApps();+ if (ok && !failed) $('search').value = '';+}++/* ---------------- 应用操作 ---------------- */++async function launchApp(pkg) {+ const app = state.apps.find((a) => a.package === pkg);+ const t = toast({+ title: `正在打开 ${app ? app.label : pkg}`,+ body: '首次启动需要预热运行时,请稍候…',+ sticky: true,+ spinner: true,+ });+ const r = await api.launch(pkg);+ if (r.ok) {+ t.update({ title: '已启动', body: '应用以独立窗口运行,可在任务栏中找到它。', type: 'ok' });+ setTimeout(t.dismiss, 2200);+ setTimeout(refreshApps, 1200);+ } else {+ t.update({ title: '启动失败', body: r.error, type: 'error' });+ setTimeout(t.dismiss, 6000);+ }+}++async function createShortcut(pkg) {+ try {+ const r = await api.createShortcut(pkg);+ toast({ title: '桌面快捷方式已创建', body: r.path, type: 'ok' });+ refreshApps();+ } catch (e) {+ toast({ title: '创建快捷方式失败', body: e.message, type: 'error' });+ }+}++async function uninstall(pkg) {+ const app = state.apps.find((a) => a.package === pkg);+ if (!app) return;+ const ok = window.confirm(`确定卸载「${app.label}」?\n\n应用数据会一并被清除,桌面快捷方式也会被删除。`);+ if (!ok) return;+ try {+ await api.uninstall(pkg);+ toast({ title: '已卸载', body: app.label, type: 'ok' });+ refreshApps();+ } catch (e) {+ toast({ title: '卸载失败', body: e.message, type: 'error' });+ }+}++/* ---------------- 右键菜单 ---------------- */++const MENU_ITEMS = [+ { key: 'open', label: '打开应用', kbd: 'Enter' },+ { key: 'shortcut', label: '创建桌面快捷方式' },+ { key: 'pin', label: '固定到顶部' },+ { divider: true },+ { key: 'reveal', label: '打开 APK 所在位置' },+ { key: 'clear', label: '清除应用数据' },+ { divider: true },+ { key: 'uninstall', label: '卸载', danger: true },+];++function showMenu(x, y, pkg) {+ const menu = $('ctxmenu');+ state.menuPkg = pkg;+ const app = state.apps.find((a) => a.package === pkg);+ menu.innerHTML = MENU_ITEMS.map((it) => {+ if (it.divider) return '<div class="divider"></div>';+ const label = it.key === 'pin' ? (app && app.pinned ? '取消固定' : '固定到顶部') : it.label;+ return `<div class="item ${it.danger ? 'danger' : ''}" data-act="${it.key}">+ <span>${esc(label)}</span>${it.kbd ? `<span class="k">${it.kbd}</span>` : ''}+ </div>`;+ }).join('');+ menu.classList.add('on');++ const rect = menu.getBoundingClientRect();+ menu.style.left = `${Math.min(x, window.innerWidth - rect.width - 10)}px`;+ menu.style.top = `${Math.min(y, window.innerHeight - rect.height - 10)}px`;+}++function hideMenu() {+ $('ctxmenu').classList.remove('on');+ state.menuPkg = null;+}++async function handleMenu(act) {+ const pkg = state.menuPkg;+ const app = state.apps.find((a) => a.package === pkg);+ hideMenu();+ if (!app) return;+ switch (act) {+ case 'open': return launchApp(pkg);+ case 'shortcut': return createShortcut(pkg);+ case 'pin': return api.pin(pkg, !app.pinned).then(refreshApps);+ case 'reveal': return api.revealApk(pkg);+ case 'clear': {+ if (!window.confirm(`清除「${app.label}」的全部数据?此操作不可撤销。`)) return;+ try {+ await api.clearData(pkg);+ toast({ title: '数据已清除', body: app.label, type: 'ok' });+ } catch (e) {+ toast({ title: '清除失败', body: e.message, type: 'error' });+ }+ return;+ }+ case 'uninstall': return uninstall(pkg);+ default: return undefined;+ }+}++/* ---------------- 设置 ---------------- */++function fillSettings(s) {+ $('setEngineMode').value = s.engine.mode;+ $('setAdbPath').value = s.adbPath || '';+ $('setDevice').value = s.device || '';+ $('setSystemImage').value = s.runtime.isoPath || '';+ $('setMemory').value = s.engine.memoryMB;+ $('setCores').value = s.engine.cores;+ $('setIdle').value = s.engine.idleShutdownMinutes;+ $('setAutoShortcut').checked = !!s.createShortcutOnInstall;+ $('setFreeform').checked = !!s.freeform;+ $('setHideAfterLaunch').checked = !!s.hideAfterLaunch;+ $('setShortcutDir').value = s.shortcutDir || '';+ $('setSharedDir').value = s.sharedDir || '';+ $('setDeviceSharedDir').value = s.deviceSharedDir || '';+}++async function openSettings() {+ state.settings = await api.getSettings();+ fillSettings(state.settings);+ const info = await api.info();+ $('setDataDir').value = info.dataDir;+ const assoc = await api.assocStatus();+ const btn = $('btnAssoc');+ btn.textContent = assoc.registered ? '已关联 · 点击取消' : '未关联 · 点击开启';+ btn.dataset.on = assoc.registered ? '1' : '0';+ $('settingsMask').classList.add('on');+}++function closeSettings() {+ $('settingsMask').classList.remove('on');+}++function bindSettings() {+ const save = async (patch) => {+ state.settings = await api.setSettings(patch);+ };++ $('setEngineMode').addEventListener('change', (e) => save({ engine: { mode: e.target.value } }));+ $('setAdbPath').addEventListener('change', (e) => save({ adbPath: e.target.value.trim() }));+ $('setDevice').addEventListener('change', async (e) => {+ await save({ device: e.target.value.trim() });+ refreshStatus();+ });+ $('setSystemImage').addEventListener('change', (e) => save({ runtime: { isoPath: e.target.value.trim() } }));+ $('setMemory').addEventListener('change', (e) => save({ engine: { memoryMB: Number(e.target.value) || 4096 } }));+ $('setCores').addEventListener('change', (e) => save({ engine: { cores: Number(e.target.value) || 4 } }));+ $('setIdle').addEventListener('change', (e) => save({ engine: { idleShutdownMinutes: Number(e.target.value) || 0 } }));+ $('setAutoShortcut').addEventListener('change', (e) => save({ createShortcutOnInstall: e.target.checked }));+ $('setFreeform').addEventListener('change', (e) => save({ freeform: e.target.checked }));+ $('setHideAfterLaunch').addEventListener('change', (e) => save({ hideAfterLaunch: e.target.checked }));+ $('setShortcutDir').addEventListener('change', (e) => save({ shortcutDir: e.target.value.trim() }));+ $('setSharedDir').addEventListener('change', (e) => save({ sharedDir: e.target.value.trim() }));+ $('setDeviceSharedDir').addEventListener('change', (e) => save({ deviceSharedDir: e.target.value.trim() }));++ $('btnOpenShared').addEventListener('click', () => api.openSharedDir());+ $('btnOpenData').addEventListener('click', async () => {+ const info = await api.info();+ window.open(`file:///${info.dataDir.replace(/\\/g, '/')}`);+ });++ $('btnProbe').addEventListener('click', async () => {+ const el = $('probeResult');+ el.textContent = '探测中…';+ const found = await api.runtimeProbe();+ if (!found.length) {+ el.textContent = '未发现已运行的运行时';+ return;+ }+ el.textContent = `发现:${found.map((f) => f.name).join('、')}`;+ await api.setSettings({ device: found[0].serial });+ $('setDevice').value = found[0].serial;+ refreshStatus();+ });++ $('btnRuntimeStart').addEventListener('click', async () => {+ const el = $('probeResult');+ el.textContent = '正在启动…';+ const r = await api.runtimeStart();+ el.textContent = r.ok ? `已就绪:${r.engine}` : `启动失败:${r.error}`;+ refreshStatus();+ });++ $('btnRuntimeStop').addEventListener('click', async () => {+ await api.runtimeStop();+ $('probeResult').textContent = '已停止内置虚拟机';+ refreshStatus();+ });++ $('btnAssoc').addEventListener('click', async () => {+ const btn = $('btnAssoc');+ if (btn.dataset.on === '1') {+ await api.assocUnregister();+ btn.textContent = '未关联 · 点击开启';+ btn.dataset.on = '0';+ toast({ title: '.apk 关联已取消' });+ } else {+ const r = await api.assocRegister();+ btn.textContent = '已关联 · 点击取消';+ btn.dataset.on = '1';+ toast({ title: '.apk 关联已开启', body: r.ok ? '现在双击 APK 会直接安装到 ApkStart' : '', type: r.ok ? 'ok' : 'error' });+ }+ });+}++/* ---------------- 事件绑定 ---------------- */++function bindEvents() {+ $('btnSettings').addEventListener('click', openSettings);+ $('btnCloseSettings').addEventListener('click', closeSettings);+ $('btnDoneSettings').addEventListener('click', closeSettings);+ $('settingsMask').addEventListener('click', (e) => {+ if (e.target === $('settingsMask')) closeSettings();+ });++ // 运行时部署+ $('btnRuntime').addEventListener('click', async () => {+ state.setupDismissed = false;+ showSetup(true);+ await refreshStatus();+ });+ $('btnDeployAll').addEventListener('click', deployAll);+ $('btnMarkInstalled').addEventListener('click', markInstalled);+ $('btnGuideClose').addEventListener('click', () => { $('setupGuide').hidden = true; });+ $('btnSetupAdvanced').addEventListener('click', () => openSettings());++ $('setupSteps').addEventListener('click', async (e) => {+ const btn = e.target.closest('[data-act]');+ if (!btn || btn.disabled) return;+ const act = btn.dataset.act;+ if (act === 'adb' || act === 'qemu' || act === 'iso' || act === 'disk') {+ const r = await runStep(act);+ if (!r.ok) toast({ title: '操作失败', body: r.error, type: 'error', sticky: true });+ return;+ }+ if (act === 'isoImport') {+ const r = await api.importIso();+ if (r.ok) { toast({ title: '系统镜像已导入', body: r.path, type: 'ok' }); refreshStatus(); }+ else if (!r.canceled) toast({ title: '导入失败', body: r.error, type: 'error' });+ return;+ }+ if (act === 'diskImport') {+ const r = await api.importDisk();+ if (r.ok) { toast({ title: '虚拟磁盘已导入', body: '可直接启动运行时', type: 'ok' }); refreshStatus(); }+ else if (!r.canceled) toast({ title: '导入失败', body: r.error, type: 'error' });+ return;+ }+ if (act === 'install') { await startInstall(); return; }+ if (act === 'vmStart') {+ const t = toast({ title: '正在启动运行时…', body: '首次启动需要引导 Android 系统', sticky: true, spinner: true });+ const r = await api.runtimeStart();+ if (r.ok) { t.update({ title: '运行时已就绪', type: 'ok' }); setTimeout(t.dismiss, 2200); }+ else t.update({ title: '启动失败', body: r.error, type: 'error' });+ refreshStatus();+ return;+ }+ if (act === 'vmStop') {+ await api.runtimeStop();+ toast({ title: '运行时会话已结束' });+ refreshStatus();+ }+ });++ const pick = async () => {+ const files = await api.pickApk();+ if (files.length) installFiles(files);+ };+ $('btnInstall').addEventListener('click', pick);+ $('btnInstall2').addEventListener('click', pick);+ $('btnShare').addEventListener('click', async () => {+ await api.syncShared();+ api.openSharedDir();+ });++ $('search').addEventListener('input', (e) => {+ state.filter = e.target.value;+ renderGrid();+ });++ $('grid').addEventListener('click', (e) => {+ const card = e.target.closest('.card');+ if (card) launchApp(card.dataset.pkg);+ });++ $('grid').addEventListener('contextmenu', (e) => {+ const card = e.target.closest('.card');+ if (!card) return;+ e.preventDefault();+ showMenu(e.clientX, e.clientY, card.dataset.pkg);+ });++ $('grid').addEventListener('dblclick', (e) => {+ const card = e.target.closest('.card');+ if (card) createShortcut(card.dataset.pkg);+ });++ $('ctxmenu').addEventListener('click', (e) => {+ const item = e.target.closest('.item');+ if (item) handleMenu(item.dataset.act);+ });++ document.addEventListener('click', (e) => {+ if (!e.target.closest('#ctxmenu')) hideMenu();+ });++ document.addEventListener('keydown', (e) => {+ if (e.key === 'Escape') {+ hideMenu();+ closeSettings();+ }+ if (e.ctrlKey && e.key.toLowerCase() === 'f') {+ e.preventDefault();+ $('search').focus();+ }+ });++ // 拖放安装+ let dragDepth = 0;+ window.addEventListener('dragenter', (e) => {+ e.preventDefault();+ dragDepth++;+ $('dropzone').classList.add('on');+ });+ window.addEventListener('dragover', (e) => e.preventDefault());+ window.addEventListener('dragleave', (e) => {+ e.preventDefault();+ dragDepth = Math.max(0, dragDepth - 1);+ if (dragDepth === 0) $('dropzone').classList.remove('on');+ });+ window.addEventListener('drop', (e) => {+ e.preventDefault();+ dragDepth = 0;+ $('dropzone').classList.remove('on');+ const files = [...(e.dataTransfer?.files || [])];+ const paths = files+ .map((f) => { try { return api.pathForFile(f); } catch (_) { return null; } })+ .filter((p) => p && /\.apk$/i.test(p));+ if (paths.length) installFiles(paths);+ else toast({ title: '只能拖入 .apk 文件', type: 'error' });+ });++ // 主进程事件+ api.on('install:error', (p) => toast({ title: '安装失败', body: p.message, type: 'error' }));+ api.on('toast', (p) => toast({ title: p.message, type: p.type === 'error' ? 'error' : 'info' }));+ api.on('app:launched', () => setTimeout(refreshApps, 800));+ api.on('runtime:log', (m) => console.log('[runtime]', m));+ api.on('ui:navigate', (v) => {+ if (v === 'settings') openSettings();+ if (v === 'setup') { state.setupDismissed = false; showSetup(true); refreshStatus(); }+ });+ api.on('provision:progress', (p) => updateStepProgress(p.component, p));+}++/* ---------------- 启动 ---------------- */++async function init() {+ bindEvents();+ bindSettings();+ state.settings = await api.getSettings();+ await refreshStatus();+ await refreshApps();+ setInterval(refreshStatus, 6000);+ setInterval(refreshApps, 15000);+}++init().catch((e) => {+ console.error(e);+ toast({ title: '初始化失败', body: e.message, type: 'error', sticky: true });+});diff --git a/src/ui/index.html b/src/ui/index.htmlnew file mode 100644index 0000000..eb3442b--- /dev/null+++ b/src/ui/index.html@@ -0,0 +1,258 @@+<!DOCTYPE html>+<html lang="zh-CN">+<head>+<meta charset="UTF-8" />+<meta http-equiv="Content-Security-Policy" content="default-src 'self'; img-src 'self' file: data:; style-src 'self' 'unsafe-inline'; script-src 'self'" />+<title>ApkStart</title>+<link rel="stylesheet" href="style.css" />+</head>+<body>++<header class="titlebar">+ <div class="brand">+ <div class="logo" aria-hidden="true">+ <svg viewBox="0 0 24 24" width="18" height="18"><rect x="1" y="1" width="22" height="22" rx="6" fill="#12161b"/><path d="M9 7.5v9l7-4.5-7-4.5z" fill="#3ddc84"/></svg>+ </div>+ <span class="brand-name">ApkStart</span>+ <span class="brand-tag" id="engineTag">未连接运行时</span>+ </div>+ <div class="titlebar-spacer"></div>+ <div class="titlebar-actions">+ <button class="icon-btn" id="btnSettings" title="设置">+ <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.8"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .34 1.87l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06A1.7 1.7 0 0 0 15 19.4a1.7 1.7 0 0 0-1 1.55V21a2 2 0 1 1-4 0v-.09A1.7 1.7 0 0 0 9 19.4a1.7 1.7 0 0 0-1.87.34l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06A1.7 1.7 0 0 0 4.6 15a1.7 1.7 0 0 0-1.55-1H3a2 2 0 1 1 0-4h.09A1.7 1.7 0 0 0 4.6 9a1.7 1.7 0 0 0-.34-1.87l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06A1.7 1.7 0 0 0 9 4.6h.09A1.7 1.7 0 0 0 10 3.05V3a2 2 0 1 1 4 0v.09A1.7 1.7 0 0 0 15 4.6a1.7 1.7 0 0 0 1.87-.34l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06A1.7 1.7 0 0 0 19.4 9v.09a1.7 1.7 0 0 0 1.55 1H21a2 2 0 1 1 0 4h-.09a1.7 1.7 0 0 0-1.51 1z"/></svg>+ </button>+ </div>+</header>++<main class="shell">+ <section class="toolbar">+ <div class="search">+ <svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="1.9"><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></svg>+ <input id="search" type="text" placeholder="搜索已安装应用" autocomplete="off" />+ </div>+ <div class="toolbar-right">+ <button class="btn ghost" id="btnRuntime">运行时</button>+ <button class="btn ghost" id="btnShare" title="打开与安卓互通的共享目录">共享目录</button>+ <button class="btn primary" id="btnInstall">+ <svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 5v10"/><path d="m7 12 5 5 5-5"/><path d="M5 20h14"/></svg>+ 安装 APK+ </button>+ </div>+ </section>++ <section class="content" id="content">+ <div class="grid" id="grid"></div>+ <div class="empty" id="empty">+ <div class="empty-art">+ <svg viewBox="0 0 160 120" width="220">+ <rect x="18" y="16" width="124" height="50" rx="10" fill="#eef1f4" stroke="#dde2e8"/>+ <rect x="34" y="34" width="30" height="14" rx="4" fill="#cfd8e3"/>+ <rect x="72" y="34" width="52" height="6" rx="3" fill="#dde5ee"/>+ <rect x="72" y="44" width="36" height="6" rx="3" fill="#e6ecf3"/>+ <path d="M80 76v22m0 0-9-9m9 9 9-9" stroke="#9fb0c2" stroke-width="3" fill="none" stroke-linecap="round"/>+ <rect x="40" y="100" width="80" height="8" rx="4" fill="#eef1f4"/>+ </svg>+ </div>+ <h2>把 APK 拖进来就能装</h2>+ <p>安装完成后会自动生成桌面图标,双击即以独立窗口运行,和普通 Windows 软件一样。<br/>已注册 .apk 关联时,在资源管理器里双击 APK 也会直接装到 ApkStart。</p>+ <button class="btn primary lg" id="btnInstall2">选择 APK 文件</button>+ <p class="hint" id="emptyHint"></p>+ </div>+ </section>++ <section class="setup" id="setupView" hidden>+ <div class="setup-card">+ <header class="setup-head">+ <div>+ <h1>准备 ApkStart 运行时</h1>+ <p>ApkStart 自带完整的安卓运行时(adb + QEMU + Android-x86),<b>不需要安装任何第三方模拟器</b>。</p>+ </div>+ <div class="setup-hv" id="setupHv"></div>+ </header>++ <div class="steps" id="setupSteps"></div>++ <div class="setup-foot">+ <button class="btn primary lg" id="btnDeployAll">一键部署</button>+ <button class="btn ghost" id="btnSetupAdvanced">高级:连接已有运行时</button>+ <span class="inline-note" id="setupNote"></span>+ </div>+ </div>++ <div class="setup-guide" id="setupGuide" hidden>+ <h2>安装 Android 到虚拟磁盘</h2>+ <p class="guide-sub">虚拟机窗口已打开。按下面 6 步操作一次,之后 ApkStart 会直接从磁盘启动,不再需要镜像。</p>+ <ol class="guide-list">+ <li><b>启动菜单</b>:用 <kbd>↓</kbd> 选到 <code>Installation - Install Android-x86 to harddisk</code>,回车</li>+ <li><b>Choose Partition</b>:选 <code>Create/Modify partitions</code>;询问是否使用 GPT 时选 <code>No</code></li>+ <li><b>cfdisk 分区</b>:<code>New</code> → <code>Primary</code> → 容量直接回车 → <code>Bootable</code> → <code>Write</code> → 输入 <code>yes</code> → <code>Quit</code></li>+ <li><b>格式化</b>:选 <code>vda1</code> → 提示格式化时选 <code>ext4</code> → <code>Yes</code></li>+ <li><b>引导与系统</b>:<code>Install GRUB</code> 选 <code>Yes</code>;<code>Install /system as read-write</code> 选 <code>Yes</code></li>+ <li><b>完成</b>:进度到 100% 后点下面的「我已安装完成」(ApkStart 会自动重启并接管)</li>+ </ol>+ <p class="guide-tip">如果之后提示 adb 未连接:在虚拟机窗口按 <kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>F1</kbd> 进入终端,执行+ <code>setprop service.adb.tcp.port 5555</code>、<code>stop adbd</code>、<code>start adbd</code>,+ 再按 <kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>F7</kbd> 回到图形界面。</p>+ <div class="guide-foot">+ <button class="btn primary" id="btnMarkInstalled">我已安装完成</button>+ <button class="btn ghost" id="btnGuideClose">稍后再说</button>+ </div>+ </div>+ </section>++ <footer class="statusbar">+ <div class="status-left">+ <span class="dot" id="statusDot"></span>+ <span id="statusText">正在检查运行时…</span>+ </div>+ <div class="status-right">+ <span class="status-item" id="statusDevice"></span>+ <span class="sep"></span>+ <span class="status-item" id="statusStats"></span>+ </div>+ </footer>+</main>++<!-- 安装进度 -->+<div class="toast-wrap" id="toastWrap"></div>++<!-- 拖放遮罩 -->+<div class="dropzone" id="dropzone">+ <div class="dropzone-inner">+ <svg viewBox="0 0 24 24" width="34" height="34" fill="none" stroke="currentColor" stroke-width="1.6"><path d="M12 16V4"/><path d="m7 9 5-5 5 5"/><path d="M5 20h14"/></svg>+ <strong>松手开始安装</strong>+ <span>支持单个或多个 .apk 文件</span>+ </div>+</div>++<!-- 右键菜单 -->+<div class="ctxmenu" id="ctxmenu"></div>++<!-- 设置 -->+<div class="modal-mask" id="settingsMask">+ <div class="modal">+ <header class="modal-head">+ <h2>设置</h2>+ <button class="icon-btn" id="btnCloseSettings">+ <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2"><path d="M6 6l12 12M18 6 6 18"/></svg>+ </button>+ </header>+ <div class="modal-body">+ <div class="group">+ <div class="group-title">运行时</div>+ <div class="field">+ <label>引擎模式</label>+ <select id="setEngineMode">+ <option value="builtin">自带运行时(推荐,QEMU + Android-x86,无第三方依赖)</option>+ <option value="attach">连接已有运行时(高级:复用 WSA / 其他模拟器的 adb 端口)</option>+ </select>+ </div>+ <div class="field">+ <label>adb 路径</label>+ <input id="setAdbPath" type="text" placeholder="留空则自动在 PATH / Android SDK 中查找" />+ </div>+ <div class="field">+ <label>设备地址</label>+ <div class="row">+ <input id="setDevice" type="text" placeholder="127.0.0.1:58526" />+ <button class="btn ghost sm" id="btnProbe">探测</button>+ </div>+ </div>+ <div class="field">+ <label>系统镜像(ISO)</label>+ <input id="setSystemImage" type="text" placeholder="Android-x86 / Bliss OS 的 ISO 或 IMG 路径,留空使用默认位置" />+ </div>+ <div class="field two">+ <div>+ <label>内存 (MB)</label>+ <input id="setMemory" type="number" min="1024" step="512" />+ </div>+ <div>+ <label>CPU 核心</label>+ <input id="setCores" type="number" min="1" max="16" />+ </div>+ </div>+ <div class="field">+ <label>空闲回收(分钟,0 = 不回收)</label>+ <input id="setIdle" type="number" min="0" step="1" />+ </div>+ <div class="runtime-actions">+ <button class="btn ghost sm" id="btnRuntimeStart">启动运行时</button>+ <button class="btn ghost sm" id="btnRuntimeStop">停止内置虚拟机</button>+ <span class="inline-note" id="probeResult"></span>+ </div>+ </div>++ <div class="group">+ <div class="group-title">桌面与应用</div>+ <div class="field switch-field">+ <div>+ <label>安装后自动创建桌面快捷方式</label>+ <span class="sub">快捷方式带真实应用图标,双击直接进应用</span>+ </div>+ <input type="checkbox" id="setAutoShortcut" class="switch" />+ </div>+ <div class="field switch-field">+ <div>+ <label>以独立窗口运行(freeform)</label>+ <span class="sub">关闭后应用会在运行时的整屏里显示</span>+ </div>+ <input type="checkbox" id="setFreeform" class="switch" />+ </div>+ <div class="field switch-field">+ <div>+ <label>从桌面图标启动后隐藏 ApkStart 窗口</label>+ <span class="sub">获得最接近原生应用的启动体验</span>+ </div>+ <input type="checkbox" id="setHideAfterLaunch" class="switch" />+ </div>+ <div class="field">+ <label>快捷方式目录</label>+ <input id="setShortcutDir" type="text" placeholder="留空 = 桌面" />+ </div>+ </div>++ <div class="group">+ <div class="group-title">文件互通</div>+ <div class="field">+ <label>本机共享目录</label>+ <div class="row">+ <input id="setSharedDir" type="text" />+ <button class="btn ghost sm" id="btnOpenShared">打开</button>+ </div>+ </div>+ <div class="field">+ <label>安卓内对应目录</label>+ <input id="setDeviceSharedDir" type="text" placeholder="/sdcard/ApkStartShared" />+ </div>+ <p class="note">两侧目录会持续双向同步;在安卓应用里保存到该目录的文件,会出现在本机共享目录中。</p>+ </div>++ <div class="group">+ <div class="group-title">系统集成</div>+ <div class="field switch-field">+ <div>+ <label>关联 .apk 文件</label>+ <span class="sub">双击 APK 直接安装到 ApkStart(仅写入当前用户,无需管理员)</span>+ </div>+ <button class="btn ghost sm" id="btnAssoc">检查中…</button>+ </div>+ <div class="field">+ <label>数据目录</label>+ <div class="row">+ <input id="setDataDir" type="text" readonly />+ <button class="btn ghost sm" id="btnOpenData">打开</button>+ </div>+ </div>+ </div>+ </div>+ <footer class="modal-foot">+ <span class="inline-note">设置修改后立即生效</span>+ <button class="btn primary" id="btnDoneSettings">完成</button>+ </footer>+ </div>+</div>++<script src="app.js"></script>+</body>+</html>diff --git a/src/ui/style.css b/src/ui/style.cssnew file mode 100644index 0000000..82c89a5--- /dev/null+++ b/src/ui/style.css@@ -0,0 +1,589 @@+:root {+ --bg: #f7f8fa;+ --panel: #ffffff;+ --panel-2: #fbfcfd;+ --line: #e6e8ec;+ --line-strong: #d9dde3;+ --text: #1b1f24;+ --muted: #6b7480;+ --faint: #97a0ac;+ --brand: #16a34a;+ --brand-dark: #12833c;+ --brand-soft: #eaf7ef;+ --danger: #dc2626;+ --shadow-sm: 0 1px 2px rgba(16, 24, 40, .06);+ --shadow-md: 0 8px 24px rgba(16, 24, 40, .10);+ --shadow-lg: 0 20px 48px rgba(16, 24, 40, .16);+ --r-sm: 8px;+ --r-md: 12px;+ --r-lg: 16px;+}++* { box-sizing: border-box; }++html, body {+ margin: 0;+ height: 100%;+ overflow: hidden;+ background: var(--bg);+ color: var(--text);+ font-family: "Segoe UI Variable Text", "Segoe UI", "Microsoft YaHei UI", "Microsoft YaHei", system-ui, sans-serif;+ font-size: 13px;+ -webkit-font-smoothing: antialiased;+ user-select: none;+}++body {+ display: flex;+ flex-direction: column;+ height: 100vh;+}++/* ---------------- 标题栏 ---------------- */++.titlebar {+ height: 44px;+ flex: 0 0 44px;+ display: flex;+ align-items: center;+ gap: 10px;+ padding: 0 12px 0 14px;+ background: var(--bg);+ border-bottom: 1px solid transparent;+ -webkit-app-region: drag;+ padding-right: 148px; /* 给系统窗口按钮留位 */+}++.brand { display: flex; align-items: center; gap: 8px; }+.logo { display: flex; }+.brand-name { font-weight: 650; font-size: 13.5px; letter-spacing: .2px; }+.brand-tag {+ margin-left: 4px;+ font-size: 11px;+ color: var(--muted);+ background: #eef1f4;+ border-radius: 999px;+ padding: 2px 8px;+ line-height: 16px;+}+.brand-tag.ok { color: var(--brand-dark); background: var(--brand-soft); }++.titlebar-spacer { flex: 1; }+.titlebar-actions { display: flex; gap: 4px; -webkit-app-region: no-drag; }++.icon-btn {+ width: 30px; height: 30px;+ display: grid; place-items: center;+ border: none; border-radius: 8px;+ background: transparent; color: var(--muted);+ cursor: pointer;+}+.icon-btn:hover { background: #edf0f3; color: var(--text); }++/* ---------------- 布局 ---------------- */++.shell {+ flex: 1;+ min-height: 0;+ display: flex;+ flex-direction: column;+ padding: 0 18px 0 18px;+}++.toolbar {+ flex: 0 0 auto;+ display: flex;+ align-items: center;+ gap: 12px;+ padding: 6px 0 14px;+}++.search {+ display: flex; align-items: center; gap: 8px;+ height: 34px; padding: 0 11px;+ background: var(--panel);+ border: 1px solid var(--line);+ border-radius: 10px;+ width: 280px;+ color: var(--faint);+ transition: border-color .15s, box-shadow .15s;+}+.search:focus-within { border-color: #b9c6d4; box-shadow: 0 0 0 3px rgba(22,163,74,.08); }+.search input {+ border: none; outline: none; background: transparent;+ width: 100%; font-size: 13px; color: var(--text);+ font-family: inherit;+}+.search input::placeholder { color: var(--faint); }++.toolbar-right { margin-left: auto; display: flex; gap: 8px; }++.btn {+ display: inline-flex; align-items: center; gap: 6px;+ height: 34px; padding: 0 13px;+ border-radius: 10px;+ border: 1px solid var(--line);+ background: var(--panel);+ color: var(--text);+ font-size: 13px; font-family: inherit; font-weight: 500;+ cursor: pointer;+ transition: background .15s, border-color .15s, transform .06s;+}+.btn:hover { background: #f4f6f8; }+.btn:active { transform: translateY(.5px); }+.btn.primary {+ background: var(--brand);+ border-color: var(--brand);+ color: #fff;+ box-shadow: 0 1px 2px rgba(22,163,74,.25);+}+.btn.primary:hover { background: var(--brand-dark); border-color: var(--brand-dark); }+.btn.ghost { background: transparent; }+.btn.ghost:hover { background: #eef1f4; }+.btn.sm { height: 28px; padding: 0 10px; font-size: 12px; border-radius: 8px; }+.btn.lg { height: 38px; padding: 0 18px; border-radius: 11px; }+.btn:disabled { opacity: .55; cursor: default; }++/* ---------------- 应用网格 ---------------- */++.content {+ flex: 1;+ min-height: 0;+ overflow-y: auto;+ overflow-x: hidden;+ padding-bottom: 18px;+}+.content::-webkit-scrollbar { width: 10px; }+.content::-webkit-scrollbar-thumb { background: #d8dde3; border-radius: 8px; border: 3px solid var(--bg); }+.content::-webkit-scrollbar-thumb:hover { background: #c3cad3; }++.grid {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(158px, 1fr));+ gap: 10px;+}++.card {+ position: relative;+ background: var(--panel);+ border: 1px solid var(--line);+ border-radius: var(--r-lg);+ padding: 14px 12px 12px;+ display: flex; flex-direction: column; align-items: center;+ cursor: pointer;+ transition: border-color .15s, box-shadow .18s, transform .12s;+ overflow: hidden;+}+.card:hover {+ border-color: var(--line-strong);+ box-shadow: var(--shadow-md);+ transform: translateY(-1px);+}+.card:active { transform: translateY(0); }++.card .icon {+ width: 64px; height: 64px;+ border-radius: 15px;+ background: #f0f3f6;+ display: grid; place-items: center;+ overflow: hidden;+ margin-bottom: 10px;+ box-shadow: 0 1px 3px rgba(16,24,40,.10);+}+.card .icon img { width: 100%; height: 100%; object-fit: cover; }+.card .icon .fallback {+ width: 100%; height: 100%;+ display: grid; place-items: center;+ color: #fff; font-weight: 600; font-size: 24px;+}++.card .name {+ font-size: 12.5px; font-weight: 550;+ max-width: 100%;+ white-space: nowrap; overflow: hidden; text-overflow: ellipsis;+ text-align: center;+}+.card .meta {+ margin-top: 3px;+ font-size: 11px; color: var(--faint);+ white-space: nowrap; overflow: hidden; text-overflow: ellipsis;+ max-width: 100%;+}++.card .badge-run {+ position: absolute; top: 9px; right: 9px;+ width: 7px; height: 7px; border-radius: 50%;+ background: var(--brand);+ box-shadow: 0 0 0 3px var(--brand-soft);+}+.card .pin {+ position: absolute; top: 8px; left: 9px;+ font-size: 11px; color: var(--faint);+}++.card .open-hint {+ margin-top: 10px;+ width: 100%;+ height: 26px;+ border-radius: 8px;+ background: var(--brand-soft);+ color: var(--brand-dark);+ font-size: 11.5px; font-weight: 600;+ display: grid; place-items: center;+ opacity: 0;+ transform: translateY(3px);+ transition: opacity .16s, transform .16s;+}+.card:hover .open-hint { opacity: 1; transform: none; }++/* ---------------- 空状态 ---------------- */++.empty {+ height: 100%;+ display: flex; flex-direction: column; align-items: center; justify-content: center;+ text-align: center;+ padding: 20px;+}+.empty.hidden, .grid.hidden { display: none; }+.empty h2 { margin: 10px 0 8px; font-size: 17px; font-weight: 600; }+.empty p { margin: 0; color: var(--muted); line-height: 1.75; font-size: 12.5px; }+.empty .btn { margin-top: 18px; }+.empty-art { opacity: .9; }+.hint { margin-top: 14px !important; font-size: 11.5px !important; color: var(--faint) !important; }++/* ---------------- 状态栏 ---------------- */++.statusbar {+ flex: 0 0 32px;+ display: flex; align-items: center;+ border-top: 1px solid var(--line);+ font-size: 11.5px;+ color: var(--muted);+}+.status-left { display: flex; align-items: center; gap: 7px; }+.status-right { margin-left: auto; display: flex; align-items: center; gap: 8px; }+.status-item { white-space: nowrap; }+.sep { width: 1px; height: 11px; background: var(--line-strong); }+.dot { width: 7px; height: 7px; border-radius: 50%; background: #cbd2da; }+.dot.ok { background: var(--brand); box-shadow: 0 0 0 3px var(--brand-soft); }+.dot.err { background: #e8833a; }++/* ---------------- Toast ---------------- */++.toast-wrap {+ position: fixed;+ right: 16px; bottom: 44px;+ display: flex; flex-direction: column-reverse; gap: 8px;+ z-index: 60;+ pointer-events: none;+}+.toast {+ pointer-events: auto;+ min-width: 240px; max-width: 340px;+ background: var(--panel);+ border: 1px solid var(--line);+ border-radius: var(--r-md);+ box-shadow: var(--shadow-lg);+ padding: 11px 13px;+ animation: slide-in .18s ease-out;+}+@keyframes slide-in { from { opacity: 0; transform: translateY(6px); } }+.toast .t-title { font-weight: 600; font-size: 12.5px; display: flex; align-items: center; gap: 7px; }+.toast .t-body { margin-top: 4px; font-size: 11.5px; color: var(--muted); line-height: 1.55; word-break: break-all; }+.toast.error .t-title { color: var(--danger); }+.toast .bar { margin-top: 9px; height: 3px; border-radius: 3px; background: #eef1f4; overflow: hidden; }+.toast .bar i { display: block; height: 100%; width: 0%; background: var(--brand); border-radius: 3px; transition: width .25s; }+.spinner {+ width: 12px; height: 12px; border-radius: 50%;+ border: 2px solid #dfe5ec; border-top-color: var(--brand);+ animation: spin .7s linear infinite;+}+@keyframes spin { to { transform: rotate(360deg); } }++/* ---------------- 拖放 ---------------- */++.dropzone {+ position: fixed; inset: 0;+ background: rgba(247,248,250,.82);+ backdrop-filter: blur(2px);+ display: none;+ place-items: center;+ z-index: 80;+}+.dropzone.on { display: grid; }+.dropzone-inner {+ width: 380px; height: 200px;+ border: 2px dashed #a9bccd;+ border-radius: 18px;+ display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 6px;+ color: #5a6b7c;+ background: rgba(255,255,255,.7);+}+.dropzone-inner strong { font-size: 15px; color: var(--text); }+.dropzone-inner span { font-size: 12px; color: var(--muted); }++/* ---------------- 右键菜单 ---------------- */++.ctxmenu {+ position: fixed;+ display: none;+ min-width: 190px;+ background: var(--panel);+ border: 1px solid var(--line);+ border-radius: 10px;+ box-shadow: var(--shadow-lg);+ padding: 5px;+ z-index: 90;+}+.ctxmenu.on { display: block; }+.ctxmenu .item {+ height: 30px;+ display: flex; align-items: center; gap: 9px;+ padding: 0 9px;+ border-radius: 7px;+ font-size: 12.5px;+ cursor: pointer;+ color: var(--text);+}+.ctxmenu .item:hover { background: #f1f4f7; }+.ctxmenu .item.danger { color: var(--danger); }+.ctxmenu .item .k { margin-left: auto; color: var(--faint); font-size: 11px; }+.ctxmenu .divider { height: 1px; background: var(--line); margin: 5px 6px; }++/* ---------------- 设置弹窗 ---------------- */++.modal-mask {+ position: fixed; inset: 0;+ background: rgba(20, 26, 33, .28);+ display: none;+ place-items: center;+ z-index: 100;+}+.modal-mask.on { display: grid; }++.modal {+ width: 620px;+ max-height: 86vh;+ background: var(--panel);+ border-radius: 16px;+ box-shadow: var(--shadow-lg);+ display: flex; flex-direction: column;+ overflow: hidden;+ animation: pop .16s ease-out;+}+@keyframes pop { from { opacity: 0; transform: scale(.985) translateY(4px); } }++.modal-head {+ flex: 0 0 auto;+ display: flex; align-items: center;+ padding: 14px 14px 12px 18px;+ border-bottom: 1px solid var(--line);+}+.modal-head h2 { margin: 0; font-size: 14.5px; font-weight: 650; }+.modal-head .icon-btn { margin-left: auto; }++.modal-body {+ flex: 1;+ min-height: 0;+ overflow-y: auto;+ padding: 6px 18px 18px;+}+.modal-body::-webkit-scrollbar { width: 10px; }+.modal-body::-webkit-scrollbar-thumb { background: #dde2e8; border-radius: 8px; border: 3px solid var(--panel); }++.group { padding: 14px 0 6px; border-bottom: 1px solid var(--line); }+.group:last-child { border-bottom: none; }+.group-title {+ font-size: 11.5px; font-weight: 650; letter-spacing: .4px;+ color: var(--faint); text-transform: uppercase;+ margin-bottom: 10px;+}++.field { margin-bottom: 12px; }+.field label { display: block; font-size: 12.5px; margin-bottom: 6px; color: var(--text); font-weight: 500; }+.field .sub { display: block; font-size: 11.5px; color: var(--faint); margin-top: 2px; line-height: 1.5; }+.field input[type=text], .field input[type=number], .field select {+ width: 100%; height: 32px;+ border: 1px solid var(--line);+ border-radius: 9px;+ padding: 0 10px;+ font-size: 12.5px; font-family: inherit;+ color: var(--text);+ background: var(--panel-2);+ outline: none;+}+.field input:focus, .field select:focus { border-color: #b9c6d4; box-shadow: 0 0 0 3px rgba(22,163,74,.08); }+.field input[readonly] { color: var(--muted); }+.field .row { display: flex; gap: 8px; }+.field .row input { flex: 1; }+.field.two { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }++.switch-field { display: flex; align-items: center; gap: 14px; }+.switch-field > div { flex: 1; }+.switch {+ appearance: none;+ width: 38px; height: 22px;+ border-radius: 999px;+ background: #d9dee5;+ position: relative;+ cursor: pointer;+ transition: background .16s;+ flex: 0 0 auto;+ border: none;+}+.switch::after {+ content: "";+ position: absolute; top: 2px; left: 2px;+ width: 18px; height: 18px;+ border-radius: 50%;+ background: #fff;+ box-shadow: 0 1px 2px rgba(0,0,0,.2);+ transition: transform .16s;+}+.switch:checked { background: var(--brand); }+.switch:checked::after { transform: translateX(16px); }++.note {+ margin: 2px 0 12px;+ font-size: 11.5px;+ color: var(--muted);+ line-height: 1.6;+ background: #f6f8fa;+ border: 1px solid var(--line);+ border-radius: 9px;+ padding: 8px 10px;+}+.runtime-actions { display: flex; align-items: center; gap: 8px; margin: 2px 0 10px; }+.inline-note { font-size: 11.5px; color: var(--faint); }++.modal-foot {+ flex: 0 0 auto;+ display: flex; align-items: center;+ padding: 12px 18px;+ border-top: 1px solid var(--line);+ background: var(--panel-2);+}+.modal-foot .btn { margin-left: auto; }++/* ---------------- 运行时部署向导 ---------------- */++.setup {+ flex: 1;+ min-height: 0;+ overflow-y: auto;+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 14px;+ padding: 4px 0 24px;+}+.setup[hidden] { display: none; }+.content[hidden] { display: none; }++.setup-card {+ width: 100%;+ max-width: 780px;+ background: var(--panel);+ border: 1px solid var(--line);+ border-radius: 18px;+ padding: 22px 24px;+ box-shadow: var(--shadow-sm);+}+.setup-head { display: flex; gap: 16px; align-items: flex-start; margin-bottom: 16px; }+.setup-head h1 { font-size: 17px; margin: 0 0 6px; font-weight: 650; }+.setup-head p { margin: 0; color: var(--muted); font-size: 12.5px; line-height: 1.7; }+.setup-head b { color: var(--text); font-weight: 600; }+.setup-hv {+ margin-left: auto;+ font-size: 11.5px;+ color: var(--muted);+ background: #f4f6f8;+ border: 1px solid var(--line);+ border-radius: 999px;+ padding: 4px 10px;+ white-space: nowrap;+ max-width: 260px;+ overflow: hidden;+ text-overflow: ellipsis;+}+.setup-hv.ok { color: var(--brand-dark); background: var(--brand-soft); border-color: #cdebd8; }++.steps { display: flex; flex-direction: column; gap: 8px; }++.step {+ display: flex;+ align-items: center;+ gap: 12px;+ padding: 11px 12px;+ border: 1px solid var(--line);+ border-radius: 12px;+ background: var(--panel-2);+}+.step .idx {+ width: 22px; height: 22px;+ border-radius: 50%;+ display: grid; place-items: center;+ font-size: 11.5px; font-weight: 650;+ background: #eef1f4; color: var(--muted);+ flex: 0 0 auto;+}+.step.done .idx { background: var(--brand); color: #fff; }+.step.busy .idx { background: #fff3d6; color: #a16207; }+.step .body { flex: 1; min-width: 0; }+.step .t { font-size: 12.5px; font-weight: 600; display: flex; gap: 6px; align-items: center; }+.step .tag {+ font-size: 10.5px; font-weight: 500;+ padding: 1px 6px; border-radius: 5px;+ background: #eef1f4; color: var(--muted);+}+.step .tag.req { background: #fef2f2; color: #b91c1c; }+.step .d { font-size: 11.5px; color: var(--faint); margin-top: 2px; word-break: break-all; }+.step .bar { height: 3px; background: #e9edf1; border-radius: 3px; margin-top: 7px; overflow: hidden; display: none; }+.step.busy .bar { display: block; }+.step .bar i { display: block; height: 100%; width: 0; background: var(--brand); transition: width .3s; }+.step .act { flex: 0 0 auto; display: flex; gap: 6px; }++.setup-foot { display: flex; align-items: center; gap: 10px; margin-top: 16px; }+.setup-foot .inline-note { margin-left: auto; }++.setup-guide {+ width: 100%;+ max-width: 780px;+ background: var(--panel);+ border: 1px solid var(--line);+ border-radius: 18px;+ padding: 20px 24px;+ box-shadow: var(--shadow-sm);+}+.setup-guide[hidden] { display: none; }+.setup-guide h2 { margin: 0 0 4px; font-size: 15px; font-weight: 650; }+.guide-sub { margin: 0; font-size: 12px; color: var(--muted); }+.guide-list { margin: 12px 0; padding-left: 20px; font-size: 12.5px; line-height: 1.95; }+.guide-list li { margin-bottom: 4px; }+.guide-list code, .guide-tip code {+ background: #f2f5f8;+ border: 1px solid var(--line);+ border-radius: 5px;+ padding: 1px 5px;+ font-family: Consolas, "Cascadia Mono", monospace;+ font-size: 11.5px;+}+kbd {+ background: #fff;+ border: 1px solid var(--line-strong);+ border-bottom-width: 2px;+ border-radius: 5px;+ padding: 0 5px;+ font-size: 11px;+ font-family: inherit;+}+.guide-tip {+ font-size: 11.5px;+ color: var(--muted);+ background: #f7f9fb;+ border: 1px solid var(--line);+ border-radius: 9px;+ padding: 9px 11px;+ line-height: 1.75;+}+.guide-foot { display: flex; gap: 10px; margin-top: 14px; }diff --git a/test/electron-integration.js b/test/electron-integration.jsnew file mode 100644index 0000000..9b0bf30--- /dev/null+++ b/test/electron-integration.js@@ -0,0 +1,74 @@+'use strict';+/**+ * Electron 集成测试:验证 ICO 生成、快捷方式创建、真实图标落盘+ * 运行:electron test/electron-integration.js+ * 输出:test/out/result.json+ */+const { app } = require('electron');+const fs = require('fs');+const path = require('path');++const OUT = path.join(__dirname, 'out');++app.whenReady().then(async () => {+ fs.mkdirSync(OUT, { recursive: true });+ const result = { steps: [] };+ const step = (name, ok, detail = '') => {+ result.steps.push({ name, ok, detail });+ console.log(`${ok ? '✓' : '✗'} ${name} ${detail}`);+ };++ try {+ const { drawAppIcon } = require('../src/core/png');+ const { pngToIco, writeShortcut, removeShortcut } = require('../src/core/shortcut');+ const { parseApk } = require('../src/core/apk');++ // 1. 程序图标 → PNG → ICO+ const png = drawAppIcon(256);+ fs.writeFileSync(path.join(OUT, 'icon.png'), png);+ const ico = pngToIco(png);+ fs.writeFileSync(path.join(OUT, 'icon.ico'), ico);+ step('生成 ICO', !!ico && ico.length > 1000, `${ico ? ico.length : 0} bytes`);++ // 2. 快捷方式+ const lnk = path.join(OUT, 'test.lnk');+ writeShortcut({+ shortcutPath: lnk,+ target: process.execPath,+ args: '--version',+ iconIcoPath: path.join(OUT, 'icon.ico'),+ description: 'ApkStart 集成测试',+ });+ step('创建 .lnk', fs.existsSync(lnk));+ removeShortcut(lnk);+ step('删除 .lnk', !fs.existsSync(lnk));++ // 3. 真实 APK 图标 → ICO+ const fixture = process.env.APKSTART_TEST_APK+ || (() => {+ try {+ const dl = path.join(process.env.USERPROFILE || '', 'Documents');+ return fs.readdirSync(dl).map((f) => path.join(dl, f)).find((f) => /\.apk$/i.test(f));+ } catch (_) { return null; }+ })();+ if (fixture) {+ const meta = parseApk(fixture);+ const iconIco = pngToIco(meta.iconPng);+ if (iconIco) {+ fs.writeFileSync(path.join(OUT, 'app.ico'), iconIco);+ step('APK 图标 → 多尺寸 ICO', true, `${meta.label}: ${iconIco.length} bytes`);+ } else {+ step('APK 图标 → 多尺寸 ICO', false, 'pngToIco 返回空(图标可能是 webp/jpg 之外的格式)');+ }+ }++ result.ok = result.steps.every((s) => s.ok);+ } catch (e) {+ result.error = e.message;+ result.ok = false;+ console.error(e);+ }++ fs.writeFileSync(path.join(OUT, 'result.json'), JSON.stringify(result, null, 2));+ app.exit(result.ok ? 0 : 1);+});diff --git a/test/engine-test.js b/test/engine-test.jsnew file mode 100644index 0000000..885fa23--- /dev/null+++ b/test/engine-test.js@@ -0,0 +1,218 @@+'use strict';+/**+ * 引擎与自举链路测试(不依赖真实 QEMU / adb / Android)+ * 覆盖:下载器(含断点续传)、ZIP 解压、环境检查、QEMU 启动参数、monitor 协议+ */+const os = require('os');+const fs = require('fs');+const path = require('path');+const http = require('http');+const net = require('net');++// 隔离测试数据目录,避免污染真实用户配置+const TMP = path.join(os.tmpdir(), `apkstart-test-${Date.now()}`);+process.env.APPDATA = TMP;+fs.mkdirSync(path.join(TMP, 'apkstart'), { recursive: true });++let passed = 0;+let failed = 0;+const results = [];++function test(name, fn) {+ return Promise.resolve()+ .then(fn)+ .then(() => { passed++; results.push(` ✓ ${name}`); })+ .catch((e) => { failed++; results.push(` ✗ ${name}\n ${e.message}`); });+}++function assert(cond, msg) { if (!cond) throw new Error(msg || '断言失败'); }++(async () => {+ console.log('\n[download.js]');+ const { download, head, sha256File } = require('../src/core/download');++ // 本地 HTTP 服务模拟下载源(含 Range 续传)+ const payload = Buffer.alloc(300 * 1024);+ for (let i = 0; i < payload.length; i++) payload[i] = i % 251;++ const server = http.createServer((req, res) => {+ if (req.url === '/big.bin') {+ const range = req.headers.range;+ if (range) {+ const start = Number(/bytes=(\d+)-/.exec(range)[1]);+ res.writeHead(206, {+ 'Content-Range': `bytes ${start}-${payload.length - 1}/${payload.length}`,+ 'Content-Length': payload.length - start,+ });+ return res.end(payload.subarray(start));+ }+ res.writeHead(200, { 'Content-Length': payload.length });+ return res.end(payload);+ }+ if (req.url === '/redirect') {+ res.writeHead(302, { Location: '/big.bin' });+ return res.end();+ }+ res.writeHead(404); res.end();+ });+ await new Promise((r) => server.listen(0, '127.0.0.1', r));+ const port = server.address().port;++ await test('完整下载 + 跟随重定向', async () => {+ const dest = path.join(TMP, 'dl1.bin');+ await download(`http://127.0.0.1:${port}/redirect`, dest);+ assert(fs.statSync(dest).size === payload.length, '大小不符');+ });++ await test('断点续传(已有半截文件)', async () => {+ const dest = path.join(TMP, 'dl2.bin');+ fs.writeFileSync(dest, payload.subarray(0, 100000));+ let lastPercent = 0;+ await download(`http://127.0.0.1:${port}/big.bin`, dest, {+ onProgress: (p) => { lastPercent = p.percent; },+ });+ assert(fs.statSync(dest).size === payload.length, `续传后大小 ${fs.statSync(dest).size}`);+ assert(fs.readFileSync(dest).equals(payload), '续传内容不一致');+ assert(lastPercent > 50, '未上报进度');+ });++ await test('HEAD 探测 + SHA256', async () => {+ const h = await head(`http://127.0.0.1:${port}/big.bin`);+ assert(h.size === payload.length, 'HEAD 大小不符');+ const sum = await sha256File(path.join(TMP, 'dl1.bin'));+ assert(/^[0-9a-f]{64}$/.test(sum), 'sha256 格式异常');+ });++ await test('SHA256 校验失败会清理文件', async () => {+ const dest = path.join(TMP, 'dl3.bin');+ let threw = false;+ try {+ await download(`http://127.0.0.1:${port}/big.bin`, dest, { expectSha256: 'deadbeef'.repeat(8) });+ } catch (_) { threw = true; }+ assert(threw, '应当抛错');+ assert(!fs.existsSync(dest), '校验失败应删除文件');+ });++ server.close();++ console.log('\n[provision.js]');+ const { Provisioner } = require('../src/core/provision');+ const store = require('../src/core/store');++ await test('默认运行时目录位于数据目录下', async () => {+ const p = new Provisioner('C:/fake/app');+ assert(p.paths().root.startsWith(store.DATA_DIR), `路径异常: ${p.paths().root}`);+ assert(p.paths().qemuExe.endsWith('qemu-system-x86_64.exe'), 'qemu 路径异常');+ assert(p.paths().adbExe.endsWith('adb.exe'), 'adb 路径异常');+ });++ await test('空环境检查:adb 未就绪,组件结构完整', async () => {+ const p = new Provisioner(path.join(TMP, 'nonexistent'));+ const env = await p.checkEnv();+ assert(env.adb.ok === false, 'adb 不应就绪');+ // QEMU 可能已被系统级安装(如 winget 到 Program Files),此时应当被发现+ if (env.qemu.ok) assert(env.qemu.version, 'qemu 就绪时必须带版本号');+ assert(env.ready === false, '不应就绪');+ assert(typeof env.hypervisor.whpx === 'boolean', '缺少超管信息');+ });++ await test('内置 ZIP 解压可用', async () => {+ const { ZipArchive } = require('../src/core/zip');+ // 构造一个 stored 模式的最小 zip+ const name = Buffer.from('platform-tools/adb.exe');+ const data = Buffer.from('fake-adb-binary');+ const loc = Buffer.alloc(30);+ loc.writeUInt32LE(0x04034b50, 0);+ loc.writeUInt16LE(0, 8);+ loc.writeUInt32LE(data.length, 18);+ loc.writeUInt32LE(data.length, 14);+ loc.writeUInt16LE(name.length, 26);+ const cen = Buffer.alloc(46);+ cen.writeUInt32LE(0x02014b50, 0);+ cen.writeUInt16LE(name.length, 28);+ cen.writeUInt32LE(data.length, 24);+ cen.writeUInt32LE(data.length, 20);+ const eocd = Buffer.alloc(22);+ eocd.writeUInt32LE(0x06054b50, 0);+ eocd.writeUInt16LE(1, 10);+ eocd.writeUInt32LE(46 + name.length, 12);+ eocd.writeUInt32LE(30 + name.length + data.length, 16);+ const zipPath = path.join(TMP, 'pt.zip');+ fs.writeFileSync(zipPath, Buffer.concat([loc, name, data, cen, name, eocd]));++ const out = path.join(TMP, 'unzip');+ const p = new Provisioner(TMP);+ p.extractZip(zipPath, out);+ assert(fs.readFileSync(path.join(out, 'platform-tools', 'adb.exe')).toString() === 'fake-adb-binary', '解压内容不符');+ assert(new ZipArchive(fs.readFileSync(zipPath)).has('platform-tools/adb.exe'), 'zip 读取异常');+ });++ console.log('\n[engine.js]');+ const { Runtime } = require('../src/core/engine');++ await test('QEMU 启动参数:安装模式挂载 ISO 并从光驱启动', async () => {+ const rt = new Runtime(TMP);+ rt._hv = { whpx: true };+ store.saveSettings({+ runtime: { isoPath: 'C:/img/android.iso', diskPath: 'C:/img/disk.qcow2' },+ engine: { memoryMB: 4096, cores: 4 },+ });+ const args = rt.buildArgs({ install: true }).join(' ');+ assert(args.includes('-cdrom C:/img/android.iso'), '缺少 -cdrom');+ assert(/order=d/.test(args), '应从光驱启动');+ assert(/accel=whpx/.test(args), '应使用 WHPX');+ assert(/-cpu host/.test(args), 'WHPX 应使用 host CPU');+ assert(/hostfwd=tcp:127\.0\.0\.1:5555-:5555/.test(args), '缺少 adb 端口转发');+ assert(args.includes('-monitor tcp:127.0.0.1:5556'), '缺少 monitor');+ assert(/-m 4096/.test(args), '内存参数错误');+ });++ await test('QEMU 启动参数:正常启动从磁盘引导', async () => {+ const rt = new Runtime(TMP);+ rt._hv = { whpx: false };+ const args = rt.buildArgs({ install: false }).join(' ');+ assert(!args.includes('-cdrom'), '不应挂载 ISO');+ assert(/order=c/.test(args), '应从硬盘启动');+ assert(/accel=tcg/.test(args), '无 WHPX 应回退 TCG');+ assert(/-cpu max/.test(args), 'TCG 应使用 max CPU');+ assert(args.includes('if=virtio,format=qcow2'), '磁盘参数错误');+ });++ await test('headless 模式隐藏虚拟机窗口', async () => {+ const rt = new Runtime(TMP);+ rt._hv = { whpx: false };+ const args = rt.buildArgs({ headless: true }).join(' ');+ assert(args.includes('-display none'), '应无窗口');+ });++ await test('QEMU monitor 协议:握手并下发命令', async () => {+ // 模拟 QEMU monitor:连上后回 "(qemu) ",收到命令后回 ok+ const srv = net.createServer((sock) => {+ sock.write('QEMU 8.2.0 monitor - type \'help\' for more information\r\n(qemu) ');+ sock.on('data', (d) => {+ srv.lastCmd = d.toString().trim();+ sock.write('ok\r\n(qemu) ');+ });+ });+ await new Promise((r) => srv.listen(5556, '127.0.0.1', r));++ const rt = new Runtime(TMP);+ await rt.monitorCmd('system_powerdown');+ assert(srv.lastCmd === 'system_powerdown', `实际收到: ${srv.lastCmd}`);+ await new Promise((r) => srv.close(r));+ });++ await test('未安装系统时 ensure 返回 needsSetup', async () => {+ store.saveSettings({ runtime: { installed: false }, engine: { mode: 'builtin' } });+ const rt = new Runtime(TMP);+ // 用假 adb 保证 isOnline 快速失败+ const r = await rt.ensure({ onLog: () => {} });+ assert(r.ok === false, '不应就绪');+ assert(['provision', 'install'].includes(r.needsSetup), `needsSetup=${r.needsSetup}`);+ });++ console.log(results.join('\n'));+ console.log(`\n结果:${passed} 通过,${failed} 失败\n`);+ try { fs.rmSync(TMP, { recursive: true, force: true }); } catch (_) { /* ignore */ }+ process.exit(failed ? 1 : 0);+})();diff --git a/test/qemu-real-test.js b/test/qemu-real-test.jsnew file mode 100644index 0000000..eb349ef--- /dev/null+++ b/test/qemu-real-test.js@@ -0,0 +1,90 @@+'use strict';+/**+ * 真实 QEMU 集成测试(需要本机有 qemu-system-x86_64.exe)+ *+ * 验证内容:+ * 1. ApkStart 生成的 QEMU 启动参数能被真实 QEMU 接受并稳定运行+ * 2. qemu-img 创建虚拟磁盘可用+ * 3. QEMU monitor(TCP)握手 + sendkey + 优雅退出+ *+ * 运行:node test/qemu-real-test.js (没有 QEMU 时自动跳过)+ */+const os = require('os');+const fs = require('fs');+const path = require('path');+const { spawn, execFileSync } = require('child_process');++process.env.APPDATA = path.join(os.tmpdir(), `apkstart-qemu-test-${Date.now()}`);+fs.mkdirSync(path.join(process.env.APPDATA, 'apkstart'), { recursive: true });++const CANDIDATES = [+ 'C:\\Program Files\\qemu\\qemu-system-x86_64.exe',+ path.join(__dirname, '..', 'engine', 'qemu', 'qemu-system-x86_64.exe'),+];+const QEMU = CANDIDATES.find((c) => fs.existsSync(c));+const QEMU_IMG = QEMU && path.join(path.dirname(QEMU), 'qemu-img.exe');++let passed = 0, failed = 0;+const out = [];+function test(name, fn) {+ return Promise.resolve().then(fn).then(() => { passed++; out.push(` ✓ ${name}`); })+ .catch((e) => { failed++; out.push(` ✗ ${name}\n ${e.message}`); });+}+function assert(c, m) { if (!c) throw new Error(m || '断言失败'); }++(async () => {+ if (!QEMU) {+ console.log('(跳过:本机未找到 QEMU,可安装后重试:winget install SoftwareFreedomConservancy.QEMU)');+ process.exit(0);+ }+ const ver = execFileSync(QEMU, ['--version'], { encoding: 'utf8' });+ console.log(`QEMU: ${ver.split('\n')[0].trim()}\n`);++ const store = require('../src/core/store');+ const { Runtime } = require('../src/core/engine');++ const work = path.join(process.env.APPDATA, 'apkstart', 'runtime', 'images');+ fs.mkdirSync(work, { recursive: true });+ const disk = path.join(work, 'test.qcow2');++ await test('qemu-img 创建虚拟磁盘', () => {+ execFileSync(QEMU_IMG, ['create', '-f', 'qcow2', disk, '2G'], { timeout: 30000 });+ assert(fs.existsSync(disk) && fs.statSync(disk).size > 0, '磁盘未创建');+ });++ await test('ApkStart 启动参数被真实 QEMU 接受并稳定运行', async () => {+ store.saveSettings({+ engine: { memoryMB: 1024, cores: 2 },+ runtime: { diskPath: disk, headless: true },+ });+ const rt = new Runtime(path.join(__dirname, '..'));+ rt._hv = { whpx: false };+ const args = rt.buildArgs({ install: false, headless: true });++ const proc = spawn(QEMU, args, { windowsHide: true, stdio: 'ignore' });+ let exited = null;+ proc.on('exit', (c) => { exited = c; });++ await new Promise((r) => setTimeout(r, 4000));+ assert(exited === null, `QEMU 在 4s 内退出(code=${exited}),参数可能不被接受`);+ assert(!proc.killed, '进程应存活');++ await test('monitor 协议(真实 QEMU)', async () => {+ const buf = await rt.monitorCmd('info status', { timeout: 5000 });+ assert(/running|paused/i.test(buf), `monitor 响应异常: ${buf.slice(-80)}`);+ await rt.monitorCmd('sendkey ctrl-alt-delete');+ });++ await test('monitor 优雅退出', async () => {+ await rt.monitorCmd('quit');+ await new Promise((r) => setTimeout(r, 1500));+ assert(exited !== null || proc.killed, 'QEMU 应已退出');+ });+ try { proc.kill(); } catch (_) { /* ignore */ }+ });++ console.log(out.join('\n'));+ console.log(`\n结果:${passed} 通过,${failed} 失败\n`);+ try { fs.rmSync(process.env.APPDATA, { recursive: true, force: true }); } catch (_) { /* ignore */ }+ process.exit(failed ? 1 : 0);+})();diff --git a/test/run-tests.js b/test/run-tests.jsnew file mode 100644index 0000000..a71e85c--- /dev/null+++ b/test/run-tests.js@@ -0,0 +1,135 @@+'use strict';+/**+ * 纯 Node 单元测试(不依赖 Electron / adb / 网络)+ * 运行:npm test+ */+const fs = require('fs');+const path = require('path');+const os = require('os');++let passed = 0;+let failed = 0;++function test(name, fn) {+ try {+ fn();+ passed++;+ console.log(` ✓ ${name}`);+ } catch (e) {+ failed++;+ console.error(` ✗ ${name}\n ${e.message}`);+ }+}++function assert(cond, msg) {+ if (!cond) throw new Error(msg || '断言失败');+}++console.log('\n[zip.js]');+const { ZipArchive } = require('../src/core/zip');+test('能解析自身所在项目的 package.json 压缩包结构', () => {+ // 用一个内存里构造的最小 zip(stored 模式)验证解析+ const header = Buffer.alloc(30);+ header.writeUInt32LE(0x04034b50, 0);+ header.writeUInt16LE(20, 4);+ header.writeUInt16LE(0, 6);+ header.writeUInt16LE(0, 8); // stored+ const name = Buffer.from('hello.txt');+ const data = Buffer.from('hello apkstart');+ header.writeUInt16LE(name.length, 26);+ header.writeUInt32LE(data.length, 18);+ header.writeUInt32LE(data.length, 14);++ const cen = Buffer.alloc(46);+ cen.writeUInt32LE(0x02014b50, 0);+ cen.writeUInt16LE(0, 8);+ cen.writeUInt16LE(name.length, 28);+ cen.writeUInt32LE(data.length, 24);+ cen.writeUInt32LE(data.length, 20);+ cen.writeUInt32LE(0, 42); // local offset++ const eocd = Buffer.alloc(22);+ eocd.writeUInt32LE(0x06054b50, 0);+ eocd.writeUInt16LE(1, 10);+ eocd.writeUInt32LE(46 + name.length, 12); // 中央目录总大小+ eocd.writeUInt32LE(30 + name.length + data.length, 16); // 中央目录偏移++ const zip = new ZipArchive(Buffer.concat([header, name, data, cen, name, eocd]));+ assert(zip.has('hello.txt'), '应能找到 hello.txt');+ assert(zip.read('hello.txt').toString() === 'hello apkstart', '内容应一致');+});++console.log('\n[png.js]');+const { encodePng, drawAppIcon } = require('../src/core/png');+test('PNG 编码器输出合法签名与 IHDR', () => {+ const rgba = new Uint8Array(16 * 16 * 4).fill(128);+ const png = encodePng(16, 16, rgba);+ assert(png[0] === 0x89 && png[1] === 0x50, 'PNG 签名');+ assert(png.toString('ascii', 12, 16) === 'IHDR', 'IHDR chunk');+ assert(png.length > 50, '长度合理');+});+test('应用图标可按任意尺寸绘制', () => {+ for (const s of [16, 32, 64, 256]) {+ const png = drawAppIcon(s);+ const w = png.readUInt32BE(16);+ assert(w === s, `宽度应为 ${s},实际 ${w}`);+ }+});++console.log('\n[axml.js + arsc.js + apk.js]');+const { parseAxml } = require('../src/core/axml');+const { ResTable } = require('../src/core/arsc');+const { parseApk, quickCheck } = require('../src/core/apk');++// 测试夹具:优先用环境变量 APKSTART_TEST_APK 指定,+// 否则尝试常见的本机 APK 位置(只读,不复制)+function findFixture() {+ const candidates = [+ process.env.APKSTART_TEST_APK,+ path.join(__dirname, 'fixtures', 'sample.apk'),+ ];+ try {+ const dl = path.join(process.env.USERPROFILE || '', 'Documents');+ for (const f of fs.readdirSync(dl)) {+ if (/\.apk$/i.test(f)) candidates.push(path.join(dl, f));+ }+ } catch (_) { /* ignore */ }+ return candidates.find((c) => c && fs.existsSync(c));+}++const fixture = findFixture();+if (fixture) {+ console.log(` (夹具:${fixture})`);+ test('quickCheck 识别 PK 头', () => {+ assert(quickCheck(fixture) === true);+ });+ const meta = parseApk(fixture);+ test('解析出包名 / 版本 / 启动 Activity', () => {+ assert(/^[\w.]+$/.test(meta.package), `包名异常: ${meta.package}`);+ assert(meta.versionName, '缺少 versionName');+ assert(meta.launchActivity && /\./.test(meta.launchActivity),+ `启动 Activity 异常: ${meta.launchActivity}`);+ });+ test('解析出可用图标', () => {+ assert(meta.iconPng && meta.iconPng.length > 100, '图标为空或过小');+ assert(meta.label, '应用名为空');+ console.log(` ↳ ${meta.label} (${meta.package}) v${meta.versionName}`);+ });+ test('AXML 根节点是 manifest', () => {+ const zip = new ZipArchive(fs.readFileSync(fixture));+ const root = parseAxml(zip.read('AndroidManifest.xml'));+ assert(root.name === 'manifest');+ });+ test('resources.arsc 可解析', () => {+ const zip = new ZipArchive(fs.readFileSync(fixture));+ if (zip.has('resources.arsc')) {+ const res = new ResTable(zip.read('resources.arsc'));+ assert(res.packages.length > 0, '应至少有一个 package');+ }+ });+} else {+ console.log(' (跳过:未找到 APK 夹具,可设置 APKSTART_TEST_APK)');+}++console.log(`\n结果:${passed} 通过,${failed} 失败\n`);+process.exit(failed ? 1 : 0);diff --git a/tools/platform-tools/README.md b/tools/platform-tools/README.mdnew file mode 100644index 0000000..20e0bcb--- /dev/null+++ b/tools/platform-tools/README.md@@ -0,0 +1,18 @@+# 便携 adb++把 Android platform-tools 解压到本目录(应出现 `adb.exe`),ApkStart 会优先使用它:++```+tools/platform-tools/+└─ adb.exe+```++下载地址:https://developer.android.com/tools/releases/platform-tools++如果本目录为空,ApkStart 会依次尝试:++1. 设置中手动指定的 adb 路径+2. 本目录+3. `%LOCALAPPDATA%\Android\Sdk\platform-tools\adb.exe`+4. 常见模拟器自带的 adb(LDPlayer / MuMu / BlueStacks)+5. 系统 PATH