Windows 上的安卓应用运行器:双击 APK 即装,应用以独立窗口与桌面图标运行,自持 QEMU 运行时
feat(engine): 切换到 Google 官方 Android Emulator 运行时,下载提速 2400 倍
RoutineMikud6be113ce67f
diff --git a/.gitignore b/.gitignoreindex c7e5c7b..2d14749 100644--- a/.gitignore+++ b/.gitignore@@ -10,8 +10,14 @@ Thumbs.db.vscode/.idea/-# 运行时产物(本地下载,不入库)+# 运行时产物(本地下载,不入库):二进制、镜像、AVD 数据一律排除engine/qemu/+engine/emulator/+engine/system-images/+engine/platform-tools/+engine/avd/+engine/aehd/+engine/_dl/engine/*.isoengine/*.imgengine/*.qcow2diff --git a/README.md b/README.mdindex d8272c6..61351dc 100644--- a/README.md+++ b/README.md@@ -59,19 +59,21 @@ ApkStart 是一个**自持**的项目,运行时组件全部由自己下载、| 组件 | 来源 | 大小 | 用途 ||---|---|---|---|| adb(platform-tools) | dl.google.com 官方源 | ~8 MB | 安装/启动安卓应用 |-| QEMU | 官方 Windows 构建,静默安装 | ~200 MB | 虚拟机引擎 |-| Android-x86 9.0-r2 | 多镜像源(支持续传) | ~900 MB | 安卓系统 |-| 虚拟磁盘 | qemu-img 自建(qcow2 稀疏) | 24 GB(按需占用) | 系统与用户数据 |+| Android Emulator | dl.google.com 官方源(8 线程并行下载) | ~440 MB | 运行时引擎(自带设备模型与 GPU 转译) |+| AOSP Android 11 系统镜像 | dl.google.com 官方源 | ~645 MB | 安卓系统(镜像即系统,无需安装) |+| AEHD 驱动(可选) | dl.google.com 官方源 | ~0.2 MB | 硬件加速(或用 Windows「虚拟机平台」WHPX) |-首次使用时,「运行时」页会引导完成以上部署(**一键部署**),然后走一次性系统安装;-之后每次启动直接从磁盘引导,装/开应用全程无感。+首次使用时,「运行时」页会引导完成以上部署(**一键部署**):+1. adb 与运行时引擎、系统镜像自动下载(官方源实测 10+ MB/s,一般 2 分钟内完成);+2. 点「启用」安装硬件加速驱动(弹一次管理员确认),或在「Windows 功能」勾选「虚拟机平台」后重启;+3. 点「启动运行时」开机,之后每次双击桌面图标自动拉起,全程无感。-- 支持 **WHPX 硬件加速**(在「启用或关闭 Windows 功能」勾选「虚拟机平台」后自动启用),未启用时自动回退纯软件模拟。-- 大文件下载默认 **8 线程分块 + 断点续传**;部分网络环境下 SourceForge 各镜像会被限速到几十 KB/s,此时建议直接「导入」本机已有的 ISO(官网 android-x86.org 或任意镜像站下载均可),ApkStart 会做 ISO9660 完整性校验。+- **硬件加速是必需的**:Windows 上 Android x86_64 虚拟化没有加速无法开机(AEHD 驱动装完即用无需重启;WHPX 需要重启一次)。+- 大文件下载默认 **8 线程分块 + 断点续传**,不支持 Range 的源自动回退单流。- 高级用户也可以在设置里切换为「连接已有运行时」(复用 WSA 等的 adb 端口),但这只是可选项,不是依赖。-- 自备镜像的用户可直接导入 ISO/IMG/已装好的虚拟磁盘,跳过下载。+- 高级路径:自备 Android-x86 ISO 的用户仍可用 QEMU 引擎引导(设置中启用),ApkStart 会做 ISO9660 完整性校验。## 目录结构diff --git a/build/pack.js b/build/pack.jsindex a00fbd2..ee65598 100644--- a/build/pack.js+++ b/build/pack.js@@ -37,9 +37,18 @@ for (const item of ['package.json', 'src', 'LICENSE']) {}// 3. 可选目录+// engine/ 下只有文档类内容随包分发;大体积运行时组件(emulator、system-images、+// platform-tools、avd)由应用首次启动时自动从官方源下载,不进安装包。+const ENGINE_SKIP = new Set(['emulator', 'system-images', 'platform-tools', 'avd', 'aehd', '_dl', 'qemu']);for (const opt of ['tools', 'engine']) {const src = path.join(ROOT, opt);- if (fs.existsSync(src)) copy(src, path.join(appDir, opt));+ if (!fs.existsSync(src)) continue;+ const dest = path.join(appDir, opt);+ fs.mkdirSync(dest, { recursive: true });+ for (const entry of fs.readdirSync(src, { withFileTypes: true })) {+ if (opt === 'engine' && ENGINE_SKIP.has(entry.name)) continue;+ fs.cpSync(path.join(src, entry.name), path.join(dest, entry.name), { recursive: true });+ }}// 4. 改名主程序diff --git a/docs/images/setup.png b/docs/images/setup.pngindex 81502d4..35a36f8 100644Binary files a/docs/images/setup.png and b/docs/images/setup.png differdiff --git a/src/core/emulator.js b/src/core/emulator.jsnew file mode 100644index 0000000..046c0e5--- /dev/null+++ b/src/core/emulator.js@@ -0,0 +1,236 @@+'use strict';+/**+ * Emulator 引擎:驱动 Google 官方 Android Emulator 作为 ApkStart 的运行时。+ *+ * 为什么用官方 emulator 而不是裸 QEMU:+ * - 它自带 Android 专用设备模型(ranchu)、GPU 转译(swiftshader/host)与快照机制,+ * 冷启动与交互体验远超"QEMU + 通用 ISO";+ * - 支持 -no-window 无头运行,便于把画面渲染进 ApkStart 自己的窗口;+ * - 官方源(dl.google.com)下载速度远高于 SourceForge 上的社区镜像。+ *+ * 本模块只负责"把模拟器正确拉起来/停下去",不关心装了哪些应用。+ */+const { spawn } = require('child_process');+const fs = require('fs');+const path = require('path');+const store = require('./store');+const { Provisioner } = require('./provision');++const AVD_NAME = 'apkstart';++class EmulatorEngine {+ constructor(appRoot) {+ this.appRoot = appRoot;+ this.provisioner = new Provisioner(appRoot);+ this.proc = null;+ this._log = [];+ }++ log(line) {+ this._log.push({ t: Date.now(), line });+ if (this._log.length > 400) this._log.shift();+ }++ get settings() { return store.getSettings(); }++ /** emulator.exe 与系统镜像目录(优先用户运行时目录,回退到仓库内 engine/) */+ locate() {+ const p = this.provisioner.paths();+ const emuCandidates = [p.emulatorExe, path.join(this.appRoot, 'engine', 'emulator', 'emulator.exe')];+ const emulatorExe = emuCandidates.find((c) => fs.existsSync(c)) || '';+ const img = this.provisioner.systemImageInfo();+ return { emulatorExe, sysImgDir: img.dir, sysImgOk: img.ok, root: emulatorExe ? path.dirname(path.dirname(emulatorExe)) : p.root };+ }++ /**+ * 准备 AVD:写 config.ini。放在运行时目录下,不污染用户 ~/.android。+ * 每次启动都重写,保证设置项(内存/核数/分辨率)改了立即生效。+ */+ ensureAvd({ memoryMB = 4096, cores = 4, width = 1080, height = 1920, density = 420, gpu = 'swiftshader_indirect' } = {}) {+ const p = this.provisioner.ensureDirs();+ const home = p.avdHome;+ const avdDir = path.join(home, `${AVD_NAME}.avd`);+ fs.mkdirSync(avdDir, { recursive: true });++ fs.writeFileSync(+ path.join(home, `${AVD_NAME}.ini`),+ `avd.ini.encoding=UTF-8\npath=${avdDir.replace(/\\/g, '/')}\ntarget=android-${p.sysApi}\n`,+ );++ const cfg = [+ `AvdId=${AVD_NAME}`,+ 'avd.ini.displayname=ApkStart',+ 'avd.ini.encoding=UTF-8',+ `abi.type=${p.sysAbi}`,+ `hw.cpu.arch=${p.sysAbi.split('_')[0]}`,+ `hw.cpu.ncore=${cores}`,+ `hw.ramSize=${memoryMB}`,+ 'vm.heapSize=512',+ `image.sysdir.1=system-images/android-${p.sysApi}/${p.sysTag}/${p.sysAbi}/`,+ `tag.id=${p.sysTag}`,+ 'tag.display=AOSP',+ 'disk.dataPartition.size=16G',+ 'hw.gpu.enabled=yes',+ `hw.gpu.mode=${gpu}`,+ 'hw.keyboard=yes',+ `hw.lcd.width=${width}`,+ `hw.lcd.height=${height}`,+ `hw.lcd.density=${density}`,+ 'hw.mainKeys=no',+ 'ShowDeviceFrame=no',+ 'PlayStore.enabled=false',+ 'fastboot.forceColdBoot=yes',+ 'hw.sdCard=no',+ 'hw.audioInput=none',+ 'hw.camera.back=none',+ 'hw.camera.front=none',+ 'hw.gps=no',+ 'hw.sensors.orientation=no',+ ].join('\n') + '\n';+ fs.writeFileSync(path.join(avdDir, 'config.ini'), cfg);++ return { home, avdDir, ini: path.join(home, `${AVD_NAME}.ini`) };+ }++ /** emulator 依赖这三个环境变量定位 SDK / AVD */+ env(root) {+ return {+ ...process.env,+ ANDROID_SDK_ROOT: root,+ ANDROID_HOME: root,+ ANDROID_AVD_HOME: path.join(root, 'avd'),+ ANDROID_EMULATOR_HOME: path.join(root, 'avd'),+ // 不弹 metrics 询问、不写用户级配置+ ANDROID_EMULATOR_USE_SYSTEM_LIBS: '',+ };+ }++ buildArgs({ headless = true, accel = 'auto', port = 5554, snapshot = false, wipe = false } = {}) {+ const s = this.settings;+ const args = [+ '-avd', AVD_NAME,+ '-port', String(port),+ '-no-audio',+ '-no-boot-anim',+ '-no-metrics',+ '-gpu', s.engine.gpuMode || 'swiftshader_indirect',+ ];+ if (headless) args.push('-no-window');+ if (snapshot) args.push('-snapshot', 'default');+ else args.push('-no-snapshot');+ if (wipe) args.push('-wipe-data');+ if (accel === 'off') args.push('-accel', 'off');+ return args;+ }++ /**+ * 启动模拟器。返回 { ok, port, serial, accel, proc }。+ * 只负责把进程拉起来;"Android 是否可用"由上层等 adb 判断。+ */+ async start({ headless = true, onLog = () => {}, port = 5554, wipe = false } = {}) {+ if (this.proc && !this.proc.killed) return { ok: true, reused: true, serial: `emulator-${port}`, port };++ const loc = this.locate();+ if (!loc.emulatorExe) throw new Error('未安装运行时引擎,请先在「运行时」页完成部署');+ if (!loc.sysImgOk) throw new Error('系统镜像未就绪,请先在「运行时」页下载 Android 系统镜像');++ const s = this.settings;+ this.ensureAvd({+ memoryMB: s.engine.memoryMB || 4096,+ cores: s.engine.cores || 4,+ });++ const accelInfo = await this.provisioner.emulatorAccel();+ const accel = accelInfo.ok ? 'auto' : 'off';+ const args = this.buildArgs({ headless, accel, port, wipe });++ const env = this.env(loc.root);+ // 没有硬件加速时必须显式授权 TCG,否则 emulator 直接拒绝启动+ if (accel === 'off') env.ANDROID_I_WANT_MY_TCG = 'yes';++ onLog(accelInfo.ok+ ? `启动运行时(${accelInfo.note})…`+ : `启动运行时(${accelInfo.note})…`);++ const logFile = path.join(store.DATA_DIR, 'logs', 'emulator.log');+ fs.mkdirSync(path.dirname(logFile), { recursive: true });+ fs.appendFileSync(logFile, `\n\n=== ${new Date().toISOString()} START ===\n${loc.emulatorExe} ${args.join(' ')}\n`);++ const proc = spawn(loc.emulatorExe, args, {+ cwd: path.dirname(loc.emulatorExe),+ env,+ windowsHide: true,+ stdio: ['ignore', 'pipe', 'pipe'],+ });+ this.proc = proc;++ const pipe = (stream) => {+ stream.setEncoding('utf8');+ let buf = '';+ stream.on('data', (chunk) => {+ buf += chunk;+ const lines = buf.split('\n');+ buf = lines.pop() || '';+ for (const l of lines) {+ if (l.trim()) this.log(l.trim());+ }+ });+ };+ pipe(proc.stdout);+ pipe(proc.stderr);++ proc.on('exit', (code) => {+ this.log(`emulator exit ${code}`);+ this.proc = null;+ onLog(`运行时已退出(code=${code})`);+ });+ proc.on('error', (e) => {+ this.log(`spawn error: ${e.message}`);+ this.proc = null;+ });++ // 等进程稳定;emulator 参数错误会立刻退出+ await new Promise((r) => setTimeout(r, 2500));+ if (!this.proc) throw new Error(`运行时启动失败,详见日志:${logFile}`);++ return { ok: true, serial: `emulator-${port}`, port, accel: accelInfo, logFile };+ }++ running() {+ return !!(this.proc && !this.proc.killed);+ }++ /** 优雅停止:优先走模拟器控制台,失败再杀进程树 */+ async stop({ adbPath } = {}) {+ if (!this.proc) return true;+ const port = 5554;+ try {+ if (adbPath) {+ const { execFile } = require('child_process');+ await new Promise((resolve) => {+ execFile(adbPath, ['-s', `emulator-${port}`, 'emu', 'kill'], { timeout: 8000 }, () => resolve());+ });+ }+ } catch (_) { /* 落到强杀 */ }++ for (let i = 0; i < 20 && this.proc; i += 1) {+ // eslint-disable-next-line no-await-in-loop+ await new Promise((r) => setTimeout(r, 300));+ }+ if (this.proc) {+ try { this.proc.kill(); } catch (_) { /* ignore */ }+ // emulator 会拉起子进程(qemu-system),必须整棵树杀+ try {+ spawn('taskkill', ['/PID', String(this.proc.pid), '/T', '/F'], { windowsHide: true });+ } catch (_) { /* ignore */ }+ }+ this.proc = null;+ return true;+ }++ recentLog(n = 40) {+ return this._log.slice(-n).map((x) => x.line);+ }+}++module.exports = { EmulatorEngine, AVD_NAME };diff --git a/src/core/engine.js b/src/core/engine.jsindex 7b15c5d..bd1450d 100644--- a/src/core/engine.js+++ b/src/core/engine.js@@ -14,9 +14,12 @@ const path = require('path');const { AdbClient } = require('./adb');const store = require('./store');const { Provisioner } = require('./provision');+const { EmulatorEngine } = require('./emulator');const LOG_DIR = path.join(store.DATA_DIR, 'logs');const MONITOR_PORT = 5556;+const EMU_PORT = 5554;+const EMU_SERIAL = `emulator-${EMU_PORT}`;const ATTACH_ENDPOINTS = [{ name: 'Windows Subsystem for Android', serial: '127.0.0.1:58526' },@@ -30,6 +33,7 @@ class Runtime {constructor(appRoot) {this.appRoot = appRoot;this.provisioner = new Provisioner(appRoot);+ this.emulator = new EmulatorEngine(appRoot);this.vmProc = null;this.vmStarting = false;this.installing = false;@@ -44,6 +48,9 @@ class Runtime {get settings() { return store.getSettings(); }+ /** emulator 引擎是否在运行 */+ get emuRunning() { return this.emulator.running(); }+// ---------------- 基础 ----------------adbPath() {@@ -57,7 +64,8 @@ class Runtime {}client(serial) {- const useSerial = serial || (this.settings.engine.mode === 'attach' ? this.settings.device : '127.0.0.1:5555');+ const useSerial = serial+ || (this.settings.engine.mode === 'attach' ? this.settings.device : EMU_SERIAL);const adbPath = this.adbPath();if (!this._client || this._client.serial !== useSerial || this._client.adbPath !== adbPath) {this._client = new AdbClient({ adbPath, serial: useSerial });@@ -82,7 +90,13 @@ class Runtime {mode: s.engine.mode,installed: !!s.runtime.installed,env,- vmRunning: !!(this.vmProc && !this.vmProc.killed),+ engineKind: env.engine,+ emulatorOk: env.emulator.ok,+ emulatorVersion: env.emulator.version,+ sysimgOk: env.sysimg.ok,+ sysimgNote: env.sysimg.note,+ accel: env.accel,+ vmRunning: this.emulator.running() || !!(this.vmProc && !this.vmProc.killed),vmStarting: this.vmStarting,installing: this.installing,adbOk: env.adb.ok,@@ -121,14 +135,16 @@ class Runtime {}if (result.deviceOnline) result.ready = true;- else if (!env.qemu.ok) result.needsSetup = 'qemu';- else if (!result.installed) result.needsSetup = 'install';+ else if (!env.emulator.ok) result.needsSetup = 'emulator';+ else if (!env.sysimg.ok) result.needsSetup = 'sysimg';+ else if (!env.accel.ok && !s.engine.forceTcg) result.needsSetup = 'accel';+ else result.needsSetup = 'boot';result.phase = result.deviceOnline? 'ready': this.installing? 'installing'- : (this.vmProc && !this.vmProc.killed)+ : result.vmRunning? 'booting': 'idle';@@ -188,18 +204,91 @@ class Runtime {}async boot({ install = false, onLog = () => {} } = {}) {- if (this.vmProc && !this.vmProc.killed) return { ok: true, reused: true };+ const env = await this.provisioner.checkEnv();+ this._hv = env.hypervisor;++ // 首选:官方 emulator(自带设备模型与 GPU 转译,体验最好)+ if (env.emulator.ok && env.sysimg.ok) {+ return this.bootEmulator({ env, onLog });+ }++ return this.bootQemu({ install, env, onLog });+ }++ /**+ * 用官方 emulator 启动 Android。+ * 与 QEMU+ISO 不同,这里没有"安装系统"这一步:镜像本身就是系统,首次启动即开机。+ */+ async bootEmulator({ env, onLog = () => {} } = {}) {+ if (this.emulator.running()) {+ const client = this.client(EMU_SERIAL);+ if (!(await client.isOnline())) {+ // 进程还在但还没就绪,等它+ } else {+ await this.prepare(client);+ return { ok: true, client, reused: true };+ }+ }+if (this.vmStarting) {const started = Date.now();- while (this.vmStarting && Date.now() - started < 180000) {+ while (this.vmStarting && Date.now() - started < 300000) {// eslint-disable-next-line no-await-in-loopawait new Promise((r) => setTimeout(r, 500));}- return { ok: !!(this.vmProc && !this.vmProc.killed), reused: true };+ const client = this.client(EMU_SERIAL);+ if (await client.isOnline()) {+ await this.prepare(client);+ return { ok: true, client, reused: true };+ }}- const env = await this.provisioner.checkEnv();- this._hv = env.hypervisor;+ const s = this.settings;+ const accel = env.accel || await this.provisioner.emulatorAccel();++ // Windows 上纯软件模拟(TCG)不可用:qemu 会挂在 boot 阶段且不消耗 CPU。+ // 与其让用户干等十几分钟,不如直接给出可执行的解决办法。+ if (!accel.ok && !s.engine.forceTcg) {+ throw new Error(+ '需要启用硬件加速才能启动 Android。'+ + '请点上方「启用硬件加速」按钮(一键安装 AEHD 驱动,需管理员确认),'+ + '或在「启用或关闭 Windows 功能」里勾选「虚拟机平台」后重启电脑。',+ );+ }+ if (!accel.ok) onLog('已强制软件模拟:Windows 下 TCG 可能卡在内核引导阶段');++ this.vmStarting = true;+ try {+ const st = await this.emulator.start({+ headless: s.engine.headless !== false,+ onLog,+ });+ this.lastActivity = Date.now();++ const client = this.client(EMU_SERIAL);+ const timeout = accel.ok ? 240000 : 900000;+ onLog(`等待 Android 开机…(${accel.ok ? '硬件加速' : '软件模拟,可能很慢'})`);+ const linked = await this.waitAdb(client, timeout, onLog);+ if (!linked) {+ return { ok: false, error: '运行时已启动,但 adb 未能连上。请查看运行时日志(%APPDATA%\\apkstart\\logs\\emulator.log)' };+ }+ const ready = await this.waitAndroidReady(client, timeout, onLog);+ if (!ready.ok) {+ return {+ ok: false,+ error: ready.stage === 'kernel'+ ? 'Android 内核未完成引导:可能是硬件加速未真正生效,或镜像文件损坏'+ : 'Android 已引导但系统服务未就绪(可能停在首次开机向导)',+ };+ }+ await this.prepare(client);+ return { ok: true, client, engine: 'emulator', serial: st.serial };+ } finally {+ this.vmStarting = false;+ }+ }++ async bootQemu({ install = false, env, onLog = () => {} } = {}) {if (!env.qemu.ok) throw new Error('未安装 QEMU,请先完成运行时部署');if (install && !env.iso.ok) throw new Error('系统镜像(ISO)未就绪');@@ -315,9 +404,14 @@ class Runtime {async waitAdb(client, timeoutMs, onLog = () => {}) {const start = Date.now();let lastNotice = 0;+ const needConnect = String(client.serial || '').includes(':')+ && !/^emulator-/.test(client.serial);while (Date.now() - start < timeoutMs) {- // eslint-disable-next-line no-await-in-loop- await client.connect().catch(() => false);+ // emulator-5554 这类由 emulator 自己注册,不需要 adb connect+ if (needConnect) {+ // eslint-disable-next-line no-await-in-loop+ await client.connect().catch(() => false);+ }// eslint-disable-next-line no-await-in-loopif (await client.isOnline()) return true;if (Date.now() - lastNotice > 20000) {@@ -337,8 +431,12 @@ class Runtime {this.startWatchdog();}- /** 用 QEMU monitor 优雅退出(避免直接杀进程损坏磁盘) */+ /** 优雅停止:emulator 走控制台关机,QEMU 走 monitor */async stop({ graceful = true } = {}) {+ if (this.emulator.running()) {+ await this.emulator.stop({ adbPath: this.adbPath() });+ return true;+ }if (!this.vmProc) return false;if (graceful) {try { await this.monitorCmd('system_powerdown'); } catch (_) { /* ignore */ }@@ -448,12 +546,35 @@ class Runtime {}// 默认:自带运行时+ const env = await this.provisioner.checkEnv();++ // emulator 路径:镜像即系统,没有"安装到磁盘"这一步+ if (env.emulator.ok && env.sysimg.ok) {+ if (!env.accel.ok && !s.engine.forceTcg) {+ return {+ ok: false,+ needsSetup: 'accel',+ error: '需要启用硬件加速才能启动 Android(点「启用硬件加速」一键安装驱动)',+ env,+ };+ }+ try {+ const r = await this.boot({ onLog });+ if (r.ok) return { ok: true, client: r.client, engine: 'emulator' };+ return { ok: false, error: r.error, env };+ } catch (e) {+ return { ok: false, error: e.message, env };+ }+ }++ // QEMU 路径(用户自备 ISO 并已装到虚拟磁盘)if (!s.runtime.installed) {- const env = await this.provisioner.checkEnv();return {ok: false,- needsSetup: env.qemu.ok ? 'install' : 'provision',- error: env.qemu.ok ? '运行时已就绪,但还没有安装 Android 系统' : '运行时组件尚未部署完成',+ needsSetup: env.emulator.ok ? 'sysimg' : 'provision',+ error: env.emulator.ok+ ? '还差系统镜像:点「下载系统镜像」即可'+ : '运行时组件尚未部署完成',env,};}@@ -474,7 +595,7 @@ class Runtime {this._watchdog = setInterval(async () => {const s = this.settings;const limit = (s.engine.idleShutdownMinutes || 0) * 60000;- if (!limit || !this.vmProc || this.installing) return;+ if (!limit || !this.vmRunning) return;if (Date.now() - this.lastActivity < limit) return;try {const running = await this.client().runningPackages();@@ -486,8 +607,13 @@ class Runtime {if (this._watchdog.unref) this._watchdog.unref();}+ get vmRunning() { return this.emulator.running() || !!(this.vmProc && !this.vmProc.killed); }+dispose() {if (this._watchdog) clearInterval(this._watchdog);+ if (this.emulator.running()) {+ try { this.emulator.proc.kill(); } catch (_) { /* ignore */ }+ }if (this.vmProc) {try { this.vmProc.kill(); } catch (_) { /* ignore */ }this.vmProc = null;diff --git a/src/core/provision.js b/src/core/provision.jsindex 7e14e62..51514c8 100644--- a/src/core/provision.js+++ b/src/core/provision.js@@ -22,7 +22,17 @@ const SOURCES = {qemuFallback: ['https://qemu.weilnetz.de/w64/qemu-w64-setup-20260811.exe',],- // Android-x86 9.0-r2(x86_64):公认最稳的 QEMU 可引导 Android+ // Google 官方 SDK 索引:emulator 与系统镜像的真实地址从这里动态解析,不写死版本号+ sdkIndex: 'https://dl.google.com/android/repository/repository2-3.xml',+ sysImgIndexes: [+ 'https://dl.google.com/android/repository/sys-img/android/sys-img2-3.xml',+ 'https://dl.google.com/android/repository/sys-img/google_apis/sys-img2-3.xml',+ ],+ aehdFallback: 'https://dl.google.com/android/repository/aehd-windows_v2.2.zip',+ // 兜底:索引不可用时直接用的已知版本+ emulatorFallback: 'https://dl.google.com/android/repository/emulator-windows_x64-16847572.zip',+ sysimgFallback: 'https://dl.google.com/android/repository/sys-img/android/x86_64-30_r11.zip',+ // Android-x86 9.0-r2(x86_64):仅在用户已自备 ISO 时使用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',@@ -32,11 +42,17 @@ const SOURCES = {isoSizeHint: 900 * 1024 * 1024,};+/** 想默认使用的系统镜像(API 级别 + 渠道)。AOSP 版体积小、无 GMS 授权问题。 */+const DEFAULT_SYSIMG = { api: '30', tag: 'default', abi: 'x86_64' };+const MIN_SIZE = {adb: 5 * 1024 * 1024,qemu: 60 * 1024 * 1024,iso: 400 * 1024 * 1024,disk: 1024 * 1024,+ emulator: 200 * 1024 * 1024,+ sysimg: 300 * 1024 * 1024,+ aeHD: 64 * 1024,};function run(cmd, args, { timeout = 60000, cwd, windowsHide = true } = {}) {@@ -67,6 +83,9 @@ class Provisioner {paths() {const root = this.root;+ const sysTag = DEFAULT_SYSIMG.tag;+ const sysApi = DEFAULT_SYSIMG.api;+ const sysAbi = DEFAULT_SYSIMG.abi;return {root,qemuDir: path.join(root, 'qemu'),@@ -74,16 +93,24 @@ class Provisioner {qemuImg: path.join(root, 'qemu', 'qemu-img.exe'),adbDir: path.join(root, 'platform-tools'),adbExe: path.join(root, 'platform-tools', 'adb.exe'),+ // emulator 运行时(Google 官方):root 同时充当 ANDROID_SDK_ROOT+ emulatorDir: path.join(root, 'emulator'),+ emulatorExe: path.join(root, 'emulator', 'emulator.exe'),+ sysImgRoot: path.join(root, 'system-images'),+ sysImgDir: path.join(root, 'system-images', `android-${sysApi}`, sysTag, sysAbi),+ avdHome: path.join(root, 'avd'),+ aehdDir: path.join(root, 'aehd'),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'),+ sysTag, sysApi, sysAbi,};}ensureDirs() {const p = this.paths();- for (const d of [p.root, p.qemuDir, p.adbDir, p.imagesDir, p.tmp]) {+ for (const d of [p.root, p.qemuDir, p.adbDir, p.imagesDir, p.tmp, p.avdHome]) {fs.mkdirSync(d, { recursive: true });}return p;@@ -94,19 +121,16 @@ class Provisioner {async hypervisor() {if (this._hypervisor !== null) return this._hypervisor;if (!IS_WIN) { this._hypervisor = { whpx: false, note: '非 Windows 平台' }; return this._hypervisor; }+ // 只做毫秒级的文件检查。真正"WHPX 是否可用"由 emulator -accel-check 给出权威答案,+ // 避免在这里拉起 PowerShell(冷启动 1-2 秒)拖慢每次状态轮询。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,+ whpx: false, // 由 emulatorAccel() 覆盖为真实值dll,- hypervisorPresent: present,- note: dll && present- ? '已启用 WHPX 硬件加速'- : '未检测到 Windows Hypervisor Platform:将以纯软件模拟运行(较慢),可在「启用或关闭 Windows 功能」中勾选「虚拟机平台」后重启提速',+ hypervisorPresent: false,+ note: dll+ ? '虚拟机平台组件存在(可用性由运行时引擎检测)'+ : '未检测到 Windows Hypervisor Platform 组件:可在「启用或关闭 Windows 功能」中勾选「虚拟机平台」后重启',};return this._hypervisor;}@@ -183,16 +207,34 @@ class Provisioner {async checkEnv() {const p = this.ensureDirs();const s = store.getSettings();- const [adb, qemu, hv] = await Promise.all([this.adbVersion(), this.qemuVersion(), this.hypervisor()]);+ const [adb, qemu, hv, emulator, accel] = await Promise.all([+ this.adbVersion(), this.qemuVersion(), this.hypervisor(),+ this.emulatorVersion(), this.emulatorAccel(),+ ]);const isoPath = s.runtime.isoPath || p.iso;const diskPath = s.runtime.diskPath || p.disk;const iso = this.inspectIso(isoPath);const diskSize = fileSize(diskPath);+ const sysimg = this.systemImageInfo();++ // 两条路径:emulator(推荐,Google 官方)或 QEMU+ISO(用户自备镜像时)+ const emulatorReady = emulator.ok && sysimg.ok;+ const qemuReady = qemu.ok && diskSize > MIN_SIZE.disk;return {adb: { ...adb, required: true },- qemu: { ...qemu, required: true },+ emulator: { ...emulator, required: true, note: emulator.ok ? emulator.version : '未安装' },+ sysimg: {+ ok: sysimg.ok,+ dir: sysimg.dir,+ size: sysimg.size,+ api: sysimg.api,+ required: false,+ note: sysimg.ok ? `Android ${sysimg.api}(${(sysimg.size / 1073741824).toFixed(2)} GB)` : (sysimg.note || '未下载'),+ },+ accel,+ qemu: { ...qemu, required: false },iso: {ok: iso.ok,path: isoPath,@@ -206,11 +248,12 @@ class Provisioner {ok: diskSize > MIN_SIZE.disk,path: diskPath,size: diskSize,- required: true,+ required: false,note: diskSize ? `${(diskSize / 1073741824).toFixed(2)} GB` : '尚未创建',},hypervisor: hv,- ready: !!(adb.ok && qemu.ok && diskSize > MIN_SIZE.disk),+ ready: !!(adb.ok && (emulatorReady || qemuReady)),+ engine: emulatorReady ? 'emulator' : (qemuReady ? 'qemu' : 'none'),paths: p,};}@@ -234,7 +277,7 @@ class Provisioner {if (fileSize(zipPath) < MIN_SIZE.adb) throw new Error('adb 安装包下载不完整');onProgress({ stage: 'extract', message: '解压 adb…', percent: 92 });- this.extractZip(zipPath, p.root);+ await this.extractZip(zipPath, p.root);const v = await this.adbVersion();if (!v.ok) throw new Error('adb 解压后无法运行,请检查是否被杀毒软件拦截');@@ -246,10 +289,17 @@ class Provisioner {return v;}- /** 用自带的 ZIP 解析器解压(避免依赖系统解压工具) */- extractZip(zipPath, destDir) {+ /**+ * 用自带的 ZIP 解析器解压(避免依赖系统解压工具)+ * 大条目(GB 级 system.img)走流式,小条目整块读,避免撞 Node 的单 Buffer 上限。+ */+ async extractZip(zipPath, destDir, opts = {}) {const buf = fs.readFileSync(zipPath);const zip = new ZipArchive(buf);+ const STREAM_THRESHOLD = 64 * 1024 * 1024;+ const total = zip.names().length;+ let done = 0;+for (const name of zip.names()) {if (name.endsWith('/')) {fs.mkdirSync(path.join(destDir, name), { recursive: true });@@ -257,11 +307,279 @@ class Provisioner {}const target = path.join(destDir, name);fs.mkdirSync(path.dirname(target), { recursive: true });- fs.writeFileSync(target, zip.read(name));+ const e = zip.entries.get(name);+ if (e.uncompSize > STREAM_THRESHOLD) {+ await zip.pipeTo(name, fs.createWriteStream(target));+ } else {+ fs.writeFileSync(target, zip.read(name));+ }+ done += 1;+ if (opts.onEntry) opts.onEntry(name, done, total);}return destDir;}+ // ---------------- Emulator(Google 官方运行时) ----------------++ /** 抓取一段 XML 文本(带大小上限,索引文件约 400KB) */+ async _fetchText(url, limit = 2 * 1024 * 1024) {+ const { openStream } = require('./download');+ const res = await openStream(url);+ return new Promise((resolve, reject) => {+ let d = '';+ res.on('data', (c) => { d += c; if (d.length > limit) res.destroy(); });+ res.on('end', () => resolve(d));+ res.on('error', () => resolve(d));+ });+ }++ /** 从 SDK 索引里动态解析最新的 Windows emulator 包地址 */+ async resolveEmulatorUrl() {+ const cached = store.getSettings().runtime.emulatorUrl;+ if (cached && cached.trim()) return cached.trim();+ if (this._cache.emulatorUrl) return this._cache.emulatorUrl;+ try {+ const xml = await this._fetchText(SOURCES.sdkIndex);+ const block = /<remotePackage path="emulator"[\s\S]*?<\/remotePackage>/.exec(xml);+ if (block) {+ const urls = [...block[0].matchAll(/<url>([^<]+)<\/url>/g)].map((m) => m[1]);+ const win = urls.find((u) => /windows_x64.*\.zip$/i.test(u));+ if (win) {+ this._cache.emulatorUrl = win;+ return win;+ }+ }+ } catch (_) { /* 落兜底 */ }+ this._cache.emulatorUrl = SOURCES.emulatorFallback;+ return SOURCES.emulatorFallback;+ }++ /** 从 sys-img 索引里解析默认 AOSP 系统镜像地址 */+ async resolveSysimgUrl() {+ const cached = store.getSettings().runtime.sysimgUrl;+ if (cached && cached.trim()) return cached.trim();+ if (this._cache.sysimgUrl) return this._cache.sysimgUrl;+ const want = `system-images;android-${DEFAULT_SYSIMG.api};${DEFAULT_SYSIMG.tag};${DEFAULT_SYSIMG.abi}`;+ for (const idx of SOURCES.sysImgIndexes) {+ try {+ // eslint-disable-next-line no-await-in-loop+ const xml = await this._fetchText(idx);+ const re = new RegExp(`<remotePackage path="${want.replace(/[;]/g, ';')}"[\\s\\S]*?</remotePackage>`);+ const block = re.exec(xml);+ if (block) {+ const urls = [...block[0].matchAll(/<url>([^<]+)<\/url>/g)].map((m) => m[1])+ .filter((u) => /x86_64.*\.zip$/i.test(u));+ if (urls.length) {+ this._cache.sysimgUrl = urls[urls.length - 1];+ return this._cache.sysimgUrl;+ }+ }+ } catch (_) { /* 换下一个索引 */ }+ }+ this._cache.sysimgUrl = SOURCES.sysimgFallback;+ return SOURCES.sysimgFallback;+ }++ async emulatorVersion() {+ if (this._cache.emulatorVersion && this._cache.emulatorVerAt && Date.now() - this._cache.emulatorVerAt < 30000) {+ return this._cache.emulatorVersion;+ }+ const p = this.paths();+ const candidates = [p.emulatorExe, path.join(this.appRoot, 'engine', 'emulator', 'emulator.exe')];+ for (const c of candidates) {+ if (!fs.existsSync(c)) continue;+ // eslint-disable-next-line no-await-in-loop+ const r = await run(c, ['-version'], { timeout: 20000 });+ const text = `${r.stdout}${r.stderr}`;+ const m = /Android emulator version\s+([\d.]+)/i.exec(text);+ if (m) {+ this._cache.emulatorVersion = { ok: true, path: c, version: m[1] };+ this._cache.emulatorVerAt = Date.now();+ return this._cache.emulatorVersion;+ }+ }+ return { ok: false, path: '', version: '' };+ }++ /** 系统镜像是否完整(system.img 是硬指标,缺失或过小都视为没下完) */+ systemImageInfo() {+ const p = this.paths();+ const dirs = [p.sysImgDir, path.join(this.appRoot, 'engine', 'system-images',+ `android-${DEFAULT_SYSIMG.api}`, DEFAULT_SYSIMG.tag, DEFAULT_SYSIMG.abi)];+ for (const dir of dirs) {+ const system = path.join(dir, 'system.img');+ const kernel = path.join(dir, 'kernel-ranchu');+ const size = fileSize(system);+ if (size > MIN_SIZE.sysimg && fs.existsSync(kernel)) {+ return { ok: true, dir, size, api: DEFAULT_SYSIMG.api, tag: DEFAULT_SYSIMG.tag };+ }+ if (fs.existsSync(dir)) {+ return { ok: false, dir, size, api: DEFAULT_SYSIMG.api, tag: DEFAULT_SYSIMG.tag, note: size ? '镜像不完整' : '缺少 system.img' };+ }+ }+ return { ok: false, dir: p.sysImgDir, size: 0, api: DEFAULT_SYSIMG.api, tag: DEFAULT_SYSIMG.tag, note: '未下载' };+ }++ /**+ * 硬件加速状态。+ * emulator 在 Windows 上支持两种加速:WHPX(系统功能,需重启)与 AEHD(Google 自家驱动,装完即用)。+ */+ async emulatorAccel() {+ // 状态轮询每几秒一次,而 -accel-check 要拉起一个 emulator 进程,必须缓存+ if (this._cache.accel && this._cache.accelAt && Date.now() - this._cache.accelAt < 30000) {+ return this._cache.accel;+ }+ const p = this.paths();+ const exe = fs.existsSync(p.emulatorExe) ? p.emulatorExe+ : path.join(this.appRoot, 'engine', 'emulator', 'emulator.exe');+ if (!fs.existsSync(exe)) return { ok: false, kind: 'none', note: '未安装 emulator' };++ const aehdSys = path.join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'drivers', 'aehd.sys');+ const hasAehdFile = fs.existsSync(aehdSys) || fs.existsSync(path.join(p.aehdDir, 'aehd.sys'));+ const hv = await this.hypervisor();++ const r = await run(exe, ['-accel-check'], { timeout: 30000 });+ const text = `${r.stdout}${r.stderr}`;+ const usable = /accel:\s*\n?0\b/.test(text) && !/ERROR_ACCESS_DENIED|not installed/i.test(text);++ let result;+ if (usable) {+ const kind = hasAehdFile && /aehd/i.test(text) ? 'aehd' : 'whpx';+ result = { ok: true, kind, note: kind === 'whpx' ? 'WHPX 硬件加速已启用' : 'AEHD 硬件加速已启用' };+ } else if (hasAehdFile && /aehd/i.test(text) && !/ERROR_ACCESS_DENIED/i.test(text)) {+ result = { ok: true, kind: 'aehd', note: 'AEHD 硬件加速已启用' };+ } else if (hv.dll && /whpx/i.test(text) && !/error|denied/i.test(text)) {+ result = { ok: true, kind: 'whpx', note: 'WHPX 硬件加速已启用' };+ } else {+ result = {+ ok: false,+ kind: 'none',+ whpx: hv.whpx,+ aehdInstalled: hasAehdFile,+ viaTcg: true,+ note: '未启用硬件加速:将回退软件模拟(能跑但很慢)。建议安装 AEHD 驱动或开启「虚拟机平台」',+ };+ }+ this._cache.accel = result;+ this._cache.accelAt = Date.now();+ return result;+ }++ /** 下载并安装 emulator(zip 顶层就是 emulator/,直接解到 SDK root) */+ async installEmulator(onProgress = () => {}) {+ const p = this.ensureDirs();+ const url = await this.resolveEmulatorUrl();+ const zip = path.join(p.tmp, 'emulator.zip');+ onProgress({ stage: 'download', message: '下载运行时引擎(约 440MB,走 Google 官方源)…', percent: 1 });++ await downloadAnyParallel([url], zip, {+ connections: 8,+ minChunk: 4 * 1024 * 1024,+ onProgress: (pr) => onProgress({+ stage: 'download',+ message: `下载运行时引擎 ${(pr.got / 1048576).toFixed(0)}MB / ${(pr.total / 1048576).toFixed(0)}MB`+ + (pr.speed ? `(${(pr.speed / 1048576).toFixed(1)} MB/s)` : ''),+ percent: Math.round(pr.percent * 0.85),+ canResume: true,+ }),+ });+ if (fileSize(zip) < MIN_SIZE.emulator) throw new Error('运行时引擎下载不完整,可重试续传');++ onProgress({ stage: 'extract', message: '解压运行时引擎…', percent: 88 });+ await this.extractZip(zip, p.root);+ fs.rmSync(zip, { force: true });++ // SDK root 必须同时具备 platform-tools,否则 emulator 拒绝启动+ this.ensurePlatformTools();++ const v = await this.emulatorVersion();+ if (!v.ok) throw new Error('emulator 解压后无法运行,请检查是否被杀毒软件拦截');+ this._cache.emulatorVersion = v.version;+ onProgress({ stage: 'done', message: `运行时引擎 ${v.version} 就绪`, percent: 100 });+ return v;+ }++ /** emulator 要求 SDK root 下有 platform-tools 目录,否则直接 FATAL */+ ensurePlatformTools() {+ const p = this.paths();+ fs.mkdirSync(p.adbDir, { recursive: true });+ if (fs.existsSync(p.adbExe)) return true;+ const src = [+ path.join(this.appRoot, 'engine', 'platform-tools'),+ path.join(this.appRoot, 'tools', 'platform-tools'),+ path.dirname(this.adbVersionPath() || ''),+ ].find((d) => d && fs.existsSync(path.join(d, 'adb.exe')));+ if (!src) return false;+ for (const f of ['adb.exe', 'AdbWinApi.dll', 'AdbWinUsbApi.dll']) {+ const from = path.join(src, f);+ if (fs.existsSync(from)) fs.copyFileSync(from, path.join(p.adbDir, f));+ }+ return fs.existsSync(p.adbExe);+ }++ adbVersionPath() {+ try {+ const s = store.getSettings();+ if (s.adbPath && fs.existsSync(s.adbPath)) return s.adbPath;+ } catch (_) { /* ignore */ }+ return '';+ }++ /** 下载并安装系统镜像(zip 顶层是 x86_64/,解到 android-30/<tag>/ 下) */+ async installSystemImage(onProgress = () => {}) {+ const p = this.ensureDirs();+ const url = await this.resolveSysimgUrl();+ const zip = path.join(p.tmp, 'sysimg.zip');+ onProgress({ stage: 'download', message: '下载 Android 系统镜像(约 645MB)…', percent: 1 });++ await downloadAnyParallel([url], zip, {+ connections: 8,+ minChunk: 4 * 1024 * 1024,+ onProgress: (pr) => onProgress({+ stage: 'download',+ message: `下载系统镜像 ${(pr.got / 1048576).toFixed(0)}MB / ${(pr.total / 1048576).toFixed(0)}MB`+ + (pr.speed ? `(${(pr.speed / 1048576).toFixed(1)} MB/s)` : ''),+ percent: Math.round(pr.percent * 0.8),+ canResume: true,+ }),+ });+ if (fileSize(zip) < MIN_SIZE.sysimg) throw new Error('系统镜像下载不完整,可重试续传');++ const dest = path.join(p.sysImgRoot, `android-${DEFAULT_SYSIMG.api}`, DEFAULT_SYSIMG.tag);+ fs.mkdirSync(dest, { recursive: true });+ onProgress({ stage: 'extract', message: '解压系统镜像(3GB,需十余秒)…', percent: 82 });+ await this.extractZip(zip, dest, {+ onEntry: (_n, i, total) => onProgress({+ stage: 'extract',+ message: `解压系统镜像 ${i}/${total}`,+ percent: 82 + Math.round((i / Math.max(1, total)) * 15),+ }),+ });+ fs.rmSync(zip, { force: true });++ const info = this.systemImageInfo();+ if (!info.ok) throw new Error('系统镜像解压后校验失败(system.img 缺失或不完整)');+ onProgress({ stage: 'done', message: `Android ${DEFAULT_SYSIMG.api} 系统镜像就绪`, percent: 100 });+ return info;+ }++ /** 下载 AEHD 驱动(小文件);安装需要管理员权限,交给引导流程 */+ async installAehd(onProgress = () => {}) {+ const p = this.ensureDirs();+ const zip = path.join(p.tmp, 'aehd.zip');+ onProgress({ stage: 'download', message: '下载 AEHD 驱动…', percent: 10 });+ await downloadAnyParallel([SOURCES.aehdFallback], zip, { connections: 2 });+ fs.mkdirSync(p.aehdDir, { recursive: true });+ await this.extractZip(zip, p.aehdDir);+ fs.rmSync(zip, { force: true });+ const has = fs.existsSync(path.join(p.aehdDir, 'aehd.Sys')) || fs.existsSync(path.join(p.aehdDir, 'aehd.sys'));+ if (!has) throw new Error('AEHD 驱动包解压异常');+ this._cache.accel = null;+ this._cache.accelAt = 0;+ onProgress({ stage: 'done', message: 'AEHD 驱动已就绪,需管理员权限安装', percent: 100 });+ return { ok: true, dir: p.aehdDir, installer: path.join(p.aehdDir, 'silent_install.bat') };+ }+// ---------------- QEMU ----------------/** 抓取官方目录里最新的安装包文件名(不写死版本号) */diff --git a/src/core/store.js b/src/core/store.jsindex a5de116..f9ec28d 100644--- a/src/core/store.js+++ b/src/core/store.js@@ -24,6 +24,9 @@ const DEFAULT_SETTINGS = {cores: 4,idleShutdownMinutes: 15,startVisible: true,+ headless: true, // 无头运行:画面由 ApkStart 自己的窗口承载+ gpuMode: 'swiftshader_indirect', // swiftshader_indirect(兼容) | host(用独显) | off+ forceTcg: false, // 允许无硬件加速的纯软件模拟(Windows 上极慢,仅排障用)},runtime: {dir: '', // 空 = %APPDATA%\apkstart\runtime@@ -34,6 +37,8 @@ const DEFAULT_SETTINGS = {diskSizeGB: 24,headless: false, // 不显示虚拟机窗口(仅调试)installMode: 'guided', // guided(引导手动安装) | auto(实验性自动安装)+ emulatorUrl: '', // 手动指定 emulator 包地址(空 = 自动从 SDK 索引解析最新版)+ sysimgUrl: '', // 手动指定系统镜像包地址},sharedDir: path.join(os.homedir(), 'ApkStartShared'),deviceSharedDir: '/sdcard/ApkStartShared',diff --git a/src/core/zip.js b/src/core/zip.jsindex 7b0e286..517b4d7 100644--- a/src/core/zip.js+++ b/src/core/zip.js@@ -70,6 +70,56 @@ class ZipArchive {find(re) {return [...this.entries.keys()].filter((n) => re.test(n));}++ /**+ * 流式解压单个条目到可写流。+ * system.img 这类 GB 级条目无法整块 inflate 进内存(会撞上 Node 的 2GB 单 Buffer 上限),+ * 必须边解压边落盘。+ */+ pipeTo(name, dest) {+ const e = this.entries.get(name);+ if (!e) return Promise.reject(new Error(`条目不存在: ${name}`));+ const buf = this.buf;+ if (buf.readUInt32LE(e.localOffset) !== LOC_SIG) {+ return Promise.reject(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);++ return new Promise((resolve, reject) => {+ const done = (err) => { if (err) reject(err); else resolve(e.uncompSize); };+ dest.on('error', done);+ dest.on('finish', () => done(null));++ if (e.method === 0) {+ dest.end(raw);+ return;+ }+ if (e.method !== 8) return done(new Error(`不支持的压缩方式 ${e.method}: ${name}`));++ const inflater = zlib.createInflateRaw();+ // 分片喂入,避免一次性把 GB 数据塞进 zlib 缓冲区+ const SLICE = 1 << 20;+ let pos = 0;+ const pump = () => {+ while (pos < raw.length) {+ const end = Math.min(pos + SLICE, raw.length);+ const chunk = raw.subarray(pos, end);+ pos = end;+ if (!inflater.write(chunk)) {+ inflater.once('drain', pump);+ return;+ }+ }+ inflater.end();+ };+ inflater.on('error', done);+ inflater.pipe(dest);+ pump();+ });+ }}module.exports = { ZipArchive };diff --git a/src/main.js b/src/main.jsindex 8b603d2..af1fe1c 100644--- a/src/main.js+++ b/src/main.js@@ -271,6 +271,71 @@ function registerIpc() {// ---------------- 运行时自举 ----------------+ ipcMain.handle('provision:installEmulator', async () => {+ try {+ const r = await runtime.provisioner.installEmulator(+ (p) => send('provision:progress', { ...p, component: 'emulator' }),+ );+ return { ok: true, ...r };+ } catch (e) {+ return { ok: false, error: e.message };+ }+ });++ ipcMain.handle('provision:installSysimg', async () => {+ try {+ const r = await runtime.provisioner.installSystemImage(+ (p) => send('provision:progress', { ...p, component: 'sysimg' }),+ );+ return { ok: true, ...r };+ } catch (e) {+ return { ok: false, error: e.message };+ }+ });++ ipcMain.handle('provision:installAehd', async () => {+ try {+ const r = await runtime.provisioner.installAehd(+ (p) => send('provision:progress', { ...p, component: 'aehd' }),+ );+ return { ok: true, ...r };+ } catch (e) {+ return { ok: false, error: e.message };+ }+ });++ /** 提权安装 AEHD 驱动:弹出 UAC,用户确认后静默安装 */+ ipcMain.handle('provision:enableAccel', async () => {+ try {+ const p = runtime.provisioner.paths();+ const bat = path.join(p.aehdDir, 'silent_install.bat');+ if (!fs.existsSync(bat)) {+ const r = await runtime.provisioner.installAehd(+ (x) => send('provision:progress', { ...x, component: 'aehd' }),+ );+ if (!fs.existsSync(bat)) throw new Error(r.error || 'AEHD 驱动包未就绪');+ }++ await new Promise((resolve, reject) => {+ const { spawn: sp } = require('child_process');+ const esc = bat.replace(/'/g, "''");+ const ps = `try { $p = Start-Process -FilePath '${esc}' -WorkingDirectory '${path.dirname(bat).replace(/'/g, "''")}' -Verb RunAs -Wait -PassThru; exit $p.ExitCode } catch { exit 2 }`;+ const proc = sp('powershell', ['-NoProfile', '-NonInteractive', '-Command', ps], {+ windowsHide: true,+ });+ proc.on('exit', (code) => (code === 0 ? resolve() : reject(new Error(+ code === 2 ? '已取消管理员授权(需要点「是」才能安装驱动)' : `驱动安装失败(退出码 ${code})`,+ ))));+ proc.on('error', (e) => reject(e));+ });++ const accel = await runtime.provisioner.emulatorAccel();+ return { ok: accel.ok, accel, error: accel.ok ? '' : accel.note };+ } catch (e) {+ return { ok: false, error: e.message };+ }+ });+ipcMain.handle('provision:installAdb', async () => {try {const r = await runtime.provisioner.installAdb((p) => send('provision:progress', { ...p, component: 'adb' }));@@ -449,6 +514,12 @@ if (!gotLock) {mainWindow.webContents.once('did-finish-load', () => {setTimeout(async () => {try {+ if (process.argv.includes('--setup')) {+ await mainWindow.webContents.executeJavaScript(+ "document.getElementById('btnRuntime').click(); true;",+ );+ await new Promise((r) => setTimeout(r, 2500));+ }const img = await mainWindow.webContents.capturePage();fs.writeFileSync(out, img.toPNG());} catch (e) {@@ -456,7 +527,7 @@ if (!gotLock) {}quitting = true;app.quit();- }, 3500);+ }, 6500);});}diff --git a/src/preload.js b/src/preload.jsindex 7aa69da..e533f43 100644--- a/src/preload.js+++ b/src/preload.js@@ -33,6 +33,10 @@ contextBridge.exposeInMainWorld('apkstart', {provisionProbeSources: () => invoke('provision:probeSources'),installAdb: () => invoke('provision:installAdb'),installQemu: () => invoke('provision:installQemu'),+ installEmulator: () => invoke('provision:installEmulator'),+ installSysimg: () => invoke('provision:installSysimg'),+ installAehd: () => invoke('provision:installAehd'),+ enableAccel: () => invoke('provision:enableAccel'),downloadIso: () => invoke('provision:downloadIso'),createDisk: (gb) => invoke('provision:createDisk', gb),importIso: () => invoke('provision:importIso'),diff --git a/src/ui/app.js b/src/ui/app.jsindex 6c4d9d2..105630c 100644--- a/src/ui/app.js+++ b/src/ui/app.js@@ -168,9 +168,24 @@ async function refreshStatus() {tag.className = 'brand-tag ok';} else if (s.phase === 'booting' || s.vmStarting) {dot.className = 'dot warn';- text.textContent = '正在引导 Android…首次启动可能要几分钟';+ text.textContent = '正在引导 Android…';tag.textContent = '引导中';tag.className = 'brand-tag';+ } else if (s.needsSetup === 'accel') {+ dot.className = 'dot err';+ text.textContent = '还差一步:需要启用硬件加速 —— 点击右上角「运行时」';+ tag.textContent = '待启用加速';+ tag.className = 'brand-tag';+ } else if (s.needsSetup === 'sysimg') {+ dot.className = 'dot err';+ text.textContent = '缺少 Android 系统镜像 —— 点击右上角「运行时」下载(约 645MB)';+ tag.textContent = '待下载镜像';+ tag.className = 'brand-tag';+ } else if (s.needsSetup === 'emulator') {+ dot.className = 'dot err';+ text.textContent = '运行时引擎未安装 —— 点击右上角「运行时」一键部署';+ tag.textContent = '需要部署';+ tag.className = 'brand-tag';} else if (s.installing) {dot.className = 'dot warn';text.textContent = '安装程序运行中 —— 请在虚拟机窗口里完成安装';@@ -222,6 +237,7 @@ function renderSetup(s) {if (!s) return;const env = s.env || {};const hv = env.hypervisor || {};+ const accel = env.accel || s.accel || {};const needSetup = !!s.needsSetup;// 自动进入部署页:还没装过应用、且运行时未就绪@@ -229,13 +245,15 @@ function renderSetup(s) {showSetup(true);}- $('setupHv').textContent = hv.whpx ? 'WHPX 硬件加速:已启用' : 'WHPX:未启用(软件模拟)';- $('setupHv').className = `setup-hv ${hv.whpx ? 'ok' : ''}`;- $('setupHv').title = hv.note || '';+ const accelOk = accel.ok || hv.whpx;+ $('setupHv').textContent = accelOk+ ? `${accel.kind === 'whpx' || hv.whpx ? 'WHPX' : 'AEHD'} 硬件加速:已启用`+ : '硬件加速:未启用';+ $('setupHv').className = `setup-hv ${accelOk ? 'ok' : ''}`;+ $('setupHv').title = accel.note || hv.note || '';- const isoDone = !!(env.iso && env.iso.ok);- const diskDone = !!(env.disk && env.disk.ok);- const installed = !!s.installed;+ const emuDone = !!(env.emulator && env.emulator.ok);+ const imgDone = !!(env.sysimg && env.sysimg.ok);const busy = state.setupBusy;const booting = s.phase === 'booting';@@ -245,7 +263,6 @@ function renderSetup(s) {index: 1,title: 'adb 工具链',tag: '必需',- req: true,done: !!(env.adb && env.adb.ok),busy: busy === 'adb',desc: env.adb && env.adb.ok@@ -254,77 +271,68 @@ function renderSetup(s) {actions: env.adb && env.adb.ok ? '' : '<button class="btn ghost sm" data-act="adb">下载</button>',},{- key: 'qemu',+ key: 'emulator',index: 2,- title: 'QEMU 虚拟机引擎',+ title: 'Android 运行时引擎',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>',+ done: emuDone,+ busy: busy === 'emulator',+ desc: emuDone+ ? `Android Emulator ${env.emulator.version} · ${(env.emulator.path || '').replace(/\\emulator\.exe$/i, '')}`+ : 'Google 官方 Android 运行时(约 440 MB,走高速官方源,通常 1 分钟内下完)',+ actions: emuDone ? '' : '<button class="btn ghost sm" data-act="emulator">下载</button>',},{- key: 'iso',+ key: 'sysimg',index: 3,title: 'Android 系统镜像',tag: '必需',- req: true,- done: isoDone,- busy: busy === 'iso',- desc: isoDone- ? `已就绪 ${fmtGB(env.iso.size)} · ${env.iso.path}`- : (env.iso && env.iso.size- ? `${env.iso.reason || '镜像不可用'},已下载 ${fmtGB(env.iso.size)}${env.iso.iso9660 ? '' : '(点「下载」可继续续传)'}`- : '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>',+ done: imgDone,+ busy: busy === 'sysimg',+ desc: imgDone+ ? `Android ${env.sysimg.api} AOSP · ${fmtGB(env.sysimg.size)} · 无需安装系统`+ : '官方 AOSP Android 11 镜像(约 645 MB)。镜像即系统,下完即可开机,不需要装系统',+ actions: imgDone ? '' : '<button class="btn ghost sm" data-act="sysimg">下载</button>',},{- key: 'disk',+ key: 'accel',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>',+ title: '硬件加速',+ tag: accelOk ? '已就绪' : '需要',+ done: accelOk,+ busy: busy === 'accel',+ desc: accelOk+ ? (accel.note || '硬件加速已启用,Android 冷启动约 20-40 秒')+ : '未启用时无法启动:点「启用」一键安装 AEHD 加速驱动(会弹一次管理员确认)',+ actions: accelOk ? '' : '<button class="btn primary sm" data-act="accel">启用</button>',},{- key: 'install',+ key: 'boot',index: 5,- title: '安装 Android 系统',- tag: installed ? '已完成' : '一次性操作',- done: installed,- desc: installed- ? (s.deviceOnline- ? `已完成${s.android ? ` · 当前 Android ${s.android}` : ''}`- : booting ? '正在引导 Android…首次启动(未启用 WHPX 时)可能需要几分钟' : '已完成,点击「启动运行时」')- : '在虚拟机窗口里走 6 步安装(ApkStart 会给出逐步提示),装好后永久免装',- actions: installed- ? (s.deviceOnline- ? `<button class="btn ghost sm" disabled>已启动</button>- <button class="btn ghost sm" data-act="vmStop">停止</button>`- : booting- ? `<button class="btn ghost sm" disabled>引导中…</button>- <button class="btn ghost sm" data-act="vmStop">中止</button>`- : '<button class="btn ghost sm" data-act="vmStart">启动运行时</button>')- : `<button class="btn primary sm" data-act="install" ${isoDone && diskDone ? '' : 'disabled'}>开始安装</button>`,+ title: '开机',+ tag: s.deviceOnline ? '运行中' : '随时',+ done: !!(s.deviceOnline || s.installed),+ desc: s.deviceOnline+ ? `Android ${s.android || ''} 已就绪${s.freeform ? ' · 独立窗口已启用' : ''}`+ : booting+ ? '正在引导 Android…'+ : '前三步就绪后点「启动」,之后每次双击桌面图标会自动拉起',+ actions: s.deviceOnline+ ? `<button class="btn ghost sm" disabled>已启动</button>+ <button class="btn ghost sm" data-act="vmStop">停止</button>`+ : booting+ ? `<button class="btn ghost sm" disabled>引导中…</button>+ <button class="btn ghost sm" data-act="vmStop">中止</button>`+ : `<button class="btn ghost sm" data-act="vmStart" ${emuDone && imgDone && accelOk ? '' : 'disabled'}>启动运行时</button>`,},];$('setupSteps').innerHTML = steps.map(stepRow).join('');$('btnDeployAll').disabled = !!busy;- $('btnDeployAll').textContent = busy ? '部署中…' : (installed ? '检查更新' : '一键部署');- $('setupNote').textContent = hv.note && !hv.whpx ? '提示:未启用 WHPX 时首次启动较慢(纯软件模拟)' : '';+ $('btnDeployAll').textContent = busy ? '部署中…' : (imgDone && emuDone ? '检查更新' : '一键部署');+ $('setupNote').textContent = accelOk+ ? ''+ : '提示:Android 在 Windows 上必须启用硬件加速(AEHD 或 WHPX),否则无法开机。';}function store_getDiskSize() {@@ -357,23 +365,40 @@ function updateStepProgress(component, p) {}async function deployAll() {- const steps = ['adb', 'qemu', 'iso', 'disk'];- for (const key of steps) {+ const order = ['adb', 'emulator', 'sysimg', 'accel'];+ const doneOf = (key, env) => (key === 'adb' ? env.adb && env.adb.ok+ : key === 'emulator' ? env.emulator && env.emulator.ok+ : key === 'sysimg' ? env.sysimg && env.sysimg.ok+ : (env.accel && env.accel.ok) || (env.hypervisor && env.hypervisor.whpx));++ for (const key of order) {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;+ if (doneOf(key, env)) continue;+ // eslint-disable-next-line no-await-in-loop+ if (key === 'accel' && (!env.emulator || !env.emulator.ok || !env.sysimg || !env.sysimg.ok)) continue;// eslint-disable-next-line no-await-in-loopconst r = await runStep(key);if (!r.ok) {+ if (key === 'accel') {+ toast({+ title: '还差最后一步:启用硬件加速',+ body: '请点第 4 步的「启用」并允许管理员权限;或手动在「Windows 功能」里勾选「虚拟机平台」后重启。',+ type: 'error',+ sticky: true,+ });+ return;+ }toast({ title: `${key} 部署失败`, body: r.error, type: 'error', sticky: true });return;}}await refreshStatus();- toast({ title: '运行时组件已就绪', body: '下一步:点击「开始安装」,在虚拟机窗口里完成 Android 安装。', type: 'ok' });+ const st = state.status || {};+ if (st.sysimgOk && st.emulatorOk && (st.accel && st.accel.ok)) {+ toast({ title: '运行时已就绪', body: '点第 5 步「启动运行时」,之后双击桌面图标即可直接打开应用。', type: 'ok' });+ } else {+ toast({ title: '部署完成', body: '还差硬件加速,请点第 4 步「启用」。', type: 'info' });+ }}async function runStep(key) {@@ -382,7 +407,19 @@ async function runStep(key) {let r;try {if (key === 'adb') r = await api.installAdb();- else if (key === 'qemu') r = await api.installQemu();+ else if (key === 'emulator') r = await api.installEmulator();+ else if (key === 'sysimg') r = await api.installSysimg();+ else if (key === 'accel') {+ const t = toast({+ title: '正在安装硬件加速驱动…',+ body: '请在弹出的是否允许窗口点「是」',+ sticky: true,+ spinner: true,+ });+ r = await api.enableAccel();+ if (r.ok) t.update({ title: '硬件加速已启用', type: 'ok' });+ else t.update({ title: '加速未启用', body: r.error, type: 'error', sticky: true });+ } 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: '未知步骤' };@@ -695,7 +732,8 @@ function bindEvents() {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') {+ if (act === 'emulator' || act === 'sysimg' || act === 'accel'+ || 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;diff --git a/src/ui/index.html b/src/ui/index.htmlindex eb3442b..7aaaaf6 100644--- a/src/ui/index.html+++ b/src/ui/index.html@@ -65,7 +65,7 @@<header class="setup-head"><div><h1>准备 ApkStart 运行时</h1>- <p>ApkStart 自带完整的安卓运行时(adb + QEMU + Android-x86),<b>不需要安装任何第三方模拟器</b>。</p>+ <p>ApkStart 自带完整的安卓运行时(官方 Android 运行时 + AOSP 系统镜像),<b>不需要安装任何第三方模拟器</b>。全部走 Google 官方高速源,通常几分钟内完成。</p></div><div class="setup-hv" id="setupHv"></div></header>diff --git a/test/engine-test.js b/test/engine-test.jsindex 34136f0..877f97b 100644--- a/test/engine-test.js+++ b/test/engine-test.js@@ -189,7 +189,7 @@ function assert(cond, msg) { if (!cond) throw new Error(msg || '断言失败');const out = path.join(TMP, 'unzip');const p = new Provisioner(TMP);- p.extractZip(zipPath, out);+ await 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 读取异常');});