Windows 上的安卓应用运行器:双击 APK 即装,应用以独立窗口与桌面图标运行,自持 QEMU 运行时
feat(input): 左键确认、右键返回、滚轮平滑滑动,低开销前台限定鼠标映射
RoutineMikuc759c188c513
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 0869ced..bacf94c 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -31,3 +31,12 @@ jobs:- name: 运行测试run: npm test++ # 直接驱动 agent.ps1 内嵌 C# 的钩子回调,防止键位映射被改坏+ - name: 鼠标钩子逻辑冒烟测试+ shell: powershell+ run: |+ Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass -Force+ $out = & .\test\pointer-hook-logic.ps1+ $out | ForEach-Object { Write-Host $_ }+ if (-not ($out -contains 'POINTER_HOOK_LOGIC_OK')) { exit 1 }diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex a20ead9..b7d18b7 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -109,21 +109,44 @@ Windows 的每一次鼠标事件都要同步等这个线程回来,最长 4 秒前台几乎抢不到资源。修复:-- 全局钩子**默认关闭**(`engine.mouseSideButtons`),开启时改装在**专用消息线程**- (`GetMessage` 循环)上,窗口失焦/关闭立即卸载;+- 钩子不再无条件常驻:只装到**专用消息线程**(`GetMessage` 循环)上,且只在+ 应用窗口处于前台、至少一项鼠标映射开启时安装;失焦/关闭立即卸载;回调只处理+ 7 个目标消息,其余(含所有左键事件)一次 `CallNextHookEx` 直接放行;- 服务主循环 `Poll(4000)` → `Poll(50)`;- `EnumWindows` + `SetWindowPos(SWP_FRAMECHANGED)` 从「每 2 秒永久」改为「embed 后 8 秒内,且不再强制重算非客户区」;- 首次部署延后 20 秒,避免与冷启动抢 I/O。-### 可配置项(设置 → 性能与轻量容器)+### 鼠标键位(左键确认 / 右键返回 / 滚轮滑动)++应用窗口里嵌的是模拟器的 Qt 子窗口,原生映射如下:++| 输入 | Qt 原生行为 | ApkStart 的处理 |+| --- | --- | --- |+| 左键 | 手指点击 / 按住拖动 = 滑动 | **完全不拦截**,直接放行;这就是「确认」 |+| 右键 | 也被当成一次点击,容易误触 | 拦下 `WM_RBUTTONDOWN/UP/DBLCLK`,发 `input keyevent 4`(返回) |+| 滚轮 | 每格单独发一次触摸事件,画面抽搐 | 拦下 `WM_MOUSEWHEEL/MOUSEHWHEEL`,按 60~90ms 窗口合并成一条 `input swipe` |+| 侧键 | 无 | 可选:映射为返回 / 前进(默认关) |++滚轮的合并发生在 `win/agent.ps1`(`PushWheel` / `FlushWheel`),翻译发生在+`core/pointer.js`(`WheelRouter` → `wheelToSwipe`)。注入走 `AdbClient.input()`+的**常驻 `adb shell`**,用 `echo __APKSTART_<id>__` 做回包与背压,+不会每格滚动都 `execFile` 一个 adb 进程,也不会让滑动命令在 shell 里排长队。+坐标按光标在 LCD 内的归一化位置映射,横滚生成水平滑动,转屏后自动刷新分辨率。++钩子只在应用窗口前台时安装,切回桌面或关窗口即卸载;把右键返回、平滑滚轮、+侧键三项全关掉,就一个全局钩子都不装。++### 可配置项(设置 → 鼠标键位 / 性能与轻量容器)| 项 | 默认 | 说明 || --- | --- | --- |+| `engine.mouseRightBack` | `true` | 右键 = 安卓返回;关掉则恢复 Qt 的「右键也当点击」 |+| `engine.mouseWheelMode` | `smooth` | `smooth` 合并注入 / `native` 交给 Qt 逐格处理 / `off` 不拦截 |+| `engine.mouseSideButtons` | `false` | 侧键返回 / 前进;三项全关时不安装全局钩子 || `engine.liteMode` | `true` | 收敛 vCPU 配额;关掉后按机器配置自动分配更多核心 || `engine.priorityMode` | `balanced` | `performance` 时 qemu 用 Normal 优先级 || `engine.deepTrim` | `false` | 额外 `pm disable-user` 一批系统后台包;关闭时自动 `pm enable` 恢复 |-| `engine.mouseSideButtons` | `false` | 是否安装全局鼠标钩子(有系统级输入延迟风险) |深度裁剪刻意不动 `gms` / `systemui` / webview / 输入法等必需组件(见 `container.NEVER_TRIM`),避免依赖推送与登录的 App 反复弹错。diff --git a/src/core/adb.js b/src/core/adb.jsindex 1c4b990..242b03e 100644--- a/src/core/adb.js+++ b/src/core/adb.js@@ -3,7 +3,7 @@* adb 客户端封装* 只做 apkstart 需要的那部分:安装 / 启动 / 停止 / 卸载 / 文件同步 / 截图*/-const { execFile } = require('child_process');+const { execFile, spawn } = require('child_process');const fs = require('fs');const os = require('os');const path = require('path');@@ -131,6 +131,9 @@ class AdbClient {constructor({ adbPath, serial }) {this.adbPath = adbPath || 'adb';this.serial = serial || '';+ this._input = null; // 常驻 `adb shell` 进程+ this._inputSeq = 0;+ this._waiters = new Map(); // id -> { resolve, reject, timer, token }}static resolveAdb(explicit, appRoot) {@@ -151,6 +154,10 @@ class AdbClient {return a.concat(args);}+ _adbEnv() {+ return { ...process.env, ANDROID_ADB_SERVER_PORT: process.env.ANDROID_ADB_SERVER_PORT || '5044' };+ }+exec(args, { timeout = 30000, withSerial = true, binary = false } = {}) {return new Promise((resolve, reject) => {const finalArgs = this._args(args, withSerial);@@ -161,7 +168,7 @@ class AdbClient {windowsHide: true,// 与运行时模拟器共用专用 adb server 端口(默认 5044),与 5037 上的// WSA / 第三方模拟器 adb 隔离,避免注册被反复踢掉导致设备 offline- env: { ...process.env, ANDROID_ADB_SERVER_PORT: process.env.ANDROID_ADB_SERVER_PORT || '5044' },+ env: this._adbEnv(),}, (err, stdout, stderr) => {if (err) {// adb install 的失败原因写在 stdout 且退出码非 0;@@ -182,6 +189,98 @@ class AdbClient {return typeof stdout === 'string' ? stdout.trim() : stdout;}+ /**+ * 常驻输入通道。+ * 滚轮/返回是高频输入:每格滚轮都 execFile 一个 adb 会起一堆进程,+ * 桌面会明显发顿。这里复用一条 `adb shell`,每行一条命令,并在末尾+ * echo 一个结束标记 —— 既知道命令何时真正跑完,也天然形成背压,+ * 不会让滑动命令在 shell 里排成一长队。+ */+ _inputSession() {+ const old = this._input;+ if (old && old.exitCode === null && !old.killed && old.stdin && old.stdin.writable) return old;+ if (old) this.disposeInput();++ const p = spawn(this.adbPath, this._args(['shell'], true), {+ stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true, env: this._adbEnv(),+ });+ this._input = p;+ let buf = '';+ p.stdout.setEncoding('utf8');+ p.stdout.on('data', (chunk) => {+ buf += chunk;+ let i;+ while ((i = buf.indexOf('\n')) >= 0) {+ const line = buf.slice(0, i).trim();+ buf = buf.slice(i + 1);+ for (const [id, w] of this._waiters) {+ // 必须整行等于标记:某些 shell 会把整条命令行回显出来,+ // 用 contains 会把「刚写进去」误判成「已执行完」,滑动就会堆积。+ if (line === w.token) {+ this._waiters.delete(id);+ clearTimeout(w.timer);+ w.resolve(true);+ break;+ }+ }+ }+ });+ p.stderr.on('data', () => { /* 忽略:设备离线等信息由调用方兜底 */ });+ p.stdin.on('error', () => { /* 断开时由 exit 统一清理 */ });+ p.on('error', () => { this._failWaiters(new Error('adb shell 启动失败')); });+ p.on('exit', () => {+ if (this._input === p) this._input = null;+ this._failWaiters(new Error('adb shell 已退出'));+ });+ return p;+ }++ _failWaiters(err) {+ for (const [, w] of this._waiters) {+ clearTimeout(w.timer);+ w.reject(err);+ }+ this._waiters.clear();+ }++ /** 执行一条白名单内的 input 命令;失败会回收会话,调用方可回退到一次性 adb */+ async input(cmd, { timeout = 4000 } = {}) {+ const { isInputCommand } = require('./pointer');+ if (!isInputCommand(cmd)) throw new Error('非法的输入命令');+ const p = this._inputSession();+ const id = ++this._inputSeq;+ const token = `__APKSTART_${id}__`;+ return new Promise((resolve, reject) => {+ const timer = setTimeout(() => {+ this._waiters.delete(id);+ this.disposeInput();+ reject(new Error('input 命令超时'));+ }, timeout);+ this._waiters.set(id, { resolve, reject, timer, token });+ try {+ p.stdin.write(`${cmd}; echo ${token}\n`);+ } catch (e) {+ this._waiters.delete(id);+ clearTimeout(timer);+ reject(e);+ }+ });+ }++ disposeInput() {+ const p = this._input;+ this._input = null;+ for (const [, w] of this._waiters) {+ clearTimeout(w.timer);+ w.reject(new Error('输入通道已关闭'));+ }+ this._waiters.clear();+ if (p) {+ try { p.stdin.end(); } catch (_) { /* ignore */ }+ try { p.kill(); } catch (_) { /* ignore */ }+ }+ }+async version() {const { stdout } = await this.exec(['version'], { withSerial: false });const m = /version\s+([\d.]+)/i.exec(stdout);@@ -636,14 +735,18 @@ class AdbClient {return true;}- /** 鼠标侧键 / 快捷键映射 */- async keyBack() {- await this.shell('input keyevent 4', { timeout: 6000 }).catch(() => {});+ /** 鼠标右键 / 侧键 / 快捷键映射:走常驻输入通道,右键返回不再有 100ms 级延迟 */+ async _key(code) {+ try {+ await this.input(`input keyevent ${code}`);+ } catch (_) {+ // 运行时刚重启、常驻 shell 还没连上时,退回一次性 adb,不能把这次点击丢掉+ await this.shell(`input keyevent ${code}`, { timeout: 6000 }).catch(() => {});+ }}- async keyForward() {- await this.shell('input keyevent 125', { timeout: 6000 }).catch(() => {});- }+ async keyBack() { return this._key(4); }+ async keyForward() { return this._key(125); }/*** 横竖屏切换。diff --git a/src/core/agent.js b/src/core/agent.jsindex d871895..ef3c5c0 100644--- a/src/core/agent.js+++ b/src/core/agent.js@@ -6,9 +6,10 @@* 每次起一个 powershell.exe 要 150~300ms,拖动就会一顿一顿的。* 这里只启动一次,之后走本机回环 TCP(一行一个 JSON),单次往返 <2ms。*- * 代理可选负责 WH_MOUSE_LL 鼠标钩子:鼠标侧键 → 安卓返回 / 前进。- * 该钩子是全局的,会介入系统里每一次鼠标事件,因此默认【不安装】,- * 只有用户在设置里显式打开侧键映射时才启用;见 setHook()。+ * 代理可选负责 WH_MOUSE_LL 鼠标钩子:右键返回 / 滚轮滑动 / 侧键前进后退。+ * 该钩子是全局的,会介入系统里每一次鼠标事件,因此只在「应用窗口处于前台」+ * 且至少启用一项映射时安装,失焦立即卸载;回调只处理我们关心的 7 个消息。+ * 见 setHook(on, opts)。*/const { spawn } = require('child_process');const net = require('net');@@ -30,6 +31,7 @@ class WinAgent extends EventEmitter {this.pending = [];this.dead = false;this.hooked = false;+ this.hookConf = null;}get available() { return process.platform === 'win32' && fs.existsSync(SCRIPT); }@@ -70,6 +72,7 @@ class WinAgent extends EventEmitter {this.sock = null;this.ready = null;this.hooked = false;+ this.hookConf = null;this._failAll('窗口代理已退出');if (wasReady) this.emit('exit');fail(new Error('窗口代理启动失败'));@@ -105,7 +108,8 @@ class WinAgent extends EventEmitter {if (!line) continue;let msg = null;try { msg = JSON.parse(line); } catch (_) { continue; }- if (msg.ev) { this.emit(msg.ev); continue; }+ // 事件带负载(滚轮的 dx/dy/nx/ny),老监听器忽略多余参数即可+ if (msg.ev) { this.emit(msg.ev, msg); continue; }const p = this.pending.shift();if (p) { clearTimeout(p.timer); p.resolve(msg); }}@@ -158,19 +162,34 @@ class WinAgent extends EventEmitter {/*** 全局鼠标钩子开关(幂等)。- * 默认关闭:这个钩子会影响整个 Windows 的输入响应,收益只是侧键返回,- * 不该让每个用户都为它付出代价。开启/关闭都只发一次命令,避免窗口反复- * focus 时重复安装。+ * 只在应用窗口前台、且至少一项映射开启时才安装;opts 变化时不重装线程,+ * 只把新开关发给常驻代理,避免窗口反复 focus / 改设置时反复装卸钩子。+ * @param {boolean} on+ * @param {{rightBack?:boolean, wheel?:boolean, side?:boolean}} opts*/- async setHook(on) {+ async setHook(on, opts = {}) {const want = !!on;- if (want === this.hooked) return { ok: true, hooked: this.hooked };+ const conf = {+ right: !!(opts && opts.rightBack),+ wheel: !!(opts && opts.wheel),+ side: !!(opts && opts.side),+ };+ // 默认关闭状态下不为了「关」而拉起 PowerShell 进程(冷启动零开销)+ if (!want && !this.hooked) return { ok: true, hooked: false };+ const sameConf = this.hookConf+ && this.hookConf.right === conf.right+ && this.hookConf.wheel === conf.wheel+ && this.hookConf.side === conf.side;+ if (want === this.hooked && sameConf) return { ok: true, hooked: this.hooked };+ const req = { cmd: 'hook', on: want ? 1 : 0, right: conf.right ? 1 : 0, wheel: conf.wheel ? 1 : 0, side: conf.side ? 1 : 0 };if (!want) {this.hooked = false;- return this.call({ cmd: 'hook', on: 0 }, 3000).catch(() => ({ ok: false, hooked: false }));+ this.hookConf = null;+ return this.call(req, 3000).catch(() => ({ ok: false, hooked: false }));}- const r = await this.call({ cmd: 'hook', on: 1 }, 3000).catch(() => null);+ const r = await this.call(req, 3000).catch(() => null);this.hooked = !!(r && r.hooked !== false);+ this.hookConf = this.hooked ? conf : null;return { ok: this.hooked, hooked: this.hooked };}@@ -180,6 +199,7 @@ class WinAgent extends EventEmitter {try { this.sock.write('{"cmd":"hook","on":0}\n'); } catch (_) { /* ignore */ }}this.hooked = false;+ this.hookConf = null;try { this.sock?.end(); } catch (_) { /* ignore */ }try { this.sock?.destroy(); } catch (_) { /* ignore */ }try { this.proc?.kill(); } catch (_) { /* ignore */ }diff --git a/src/core/appwin.js b/src/core/appwin.jsindex 27547a7..572451c 100644--- a/src/core/appwin.js+++ b/src/core/appwin.js@@ -9,6 +9,7 @@const { BrowserWindow, screen, nativeImage } = require('electron');const fs = require('fs');const path = require('path');+const { hookOptions } = require('./pointer');const TITLEBAR_H = 38;/**@@ -25,11 +26,13 @@ function iconUrl(p) {}class AppWindow {- constructor({ agent, setOrientation, mouseHook = false }) {+ constructor({ agent, setOrientation, mouseHook = false, pointerConfig = null }) {this.agent = agent;this.setOrientation = setOrientation || null;- // 全局鼠标钩子是可选功能,默认关闭。传函数可在设置变化时实时生效。+ // 全局鼠标钩子只在「应用窗口前台 + 至少一项映射开启」时安装。+ // pointerConfig 传函数:设置页改了开关,下一次 focus 就生效,不用重启。this.mouseHook = mouseHook;+ this.pointerConfig = pointerConfig;this.win = null;this.pkg = null;this.state = { label: '', tip: '', ready: false, landscape: false };@@ -147,7 +150,7 @@ class AppWindow {this._closing = false;if (this._closedCb) this._closedCb(pkg);});- // 只在「应用窗口真正处于前台」且用户显式开启侧键映射时装全局钩子;+ // 只在「应用窗口真正处于前台」且至少一项鼠标映射开启时装全局钩子;// 失焦/关闭立即卸载,绝不让 ApkStart 在后台拖慢整个系统的鼠标。this.win.on('focus', () => this._syncHook(true));this.win.on('blur', () => this._syncHook(false));@@ -156,18 +159,33 @@ class AppWindow {return this.win;}- _wantHook() {- const v = typeof this.mouseHook === 'function' ? this.mouseHook() : this.mouseHook;- return !!v;+ _pointerOptions() {+ const getter = this.pointerConfig || this.mouseHook;+ const raw = typeof getter === 'function' ? getter() : getter;+ return hookOptions(raw);}_syncHook(active) {- const on = !!active && this._wantHook();+ const opts = this._pointerOptions();+ const on = !!active && opts.enabled;if (this.agent && typeof this.agent.setHook === 'function') {- this.agent.setHook(on).catch(() => {});+ this.agent.setHook(on, opts).catch(() => {});}}+ /** 设置页改了鼠标映射:按当前焦点重新同步一次(不重装钩子线程) */+ refreshPointer() {+ const focused = this.isOpen && !!this.win.isFocused();+ if (!focused) {+ // 窗口没在前台:只卸载,别让钩子在后台空转+ if (this.agent && typeof this.agent.setHook === 'function') {+ this.agent.setHook(false).catch(() => {});+ }+ return;+ }+ this._syncHook(true);+ }+setState(patch) {this.state = { ...this.state, ...patch };this._push();diff --git a/src/core/engine.js b/src/core/engine.jsindex f39c682..8d60f55 100644--- a/src/core/engine.js+++ b/src/core/engine.js@@ -89,6 +89,8 @@ class Runtime {|| (this.settings.engine.mode === 'attach' ? this.settings.device : this.emuSerial);const adbPath = this.adbPath();if (!this._client || this._client.serial !== useSerial || this._client.adbPath !== adbPath) {+ // 换端口/换 adb 时别把旧的常驻 adb shell 留在后台占着连接+ if (this._client && this._client.disposeInput) this._client.disposeInput();this._client = new AdbClient({ adbPath, serial: useSerial });}return this._client;@@ -915,6 +917,7 @@ class Runtime {dispose() {if (this._watchdog) clearInterval(this._watchdog);+ if (this._client && this._client.disposeInput) this._client.disposeInput();if (this.emulator.running()) {try { this.emulator.proc.kill(); } catch (_) { /* ignore */ }}diff --git a/src/core/pointer.js b/src/core/pointer.jsnew file mode 100644index 0000000..e8d35fb--- /dev/null+++ b/src/core/pointer.js@@ -0,0 +1,174 @@+'use strict';+/**+ * 鼠标键位映射(纯计算,不依赖 Electron / adb,便于单测)+ *+ * 应用窗口里嵌的是 Android Emulator 的 Qt 子窗口,原生行为是:+ * 左键 = 手指点击(正好就是「确认」,不需要我们介入)+ * 右键 = 也当成一次手指点击(会误触,必须拦下来改成「返回」)+ * 滚轮 = 单指滑动,但 Qt 每一格都单独发一次触摸事件,画面会抽搐+ *+ * 因此 ApkStart 只在「应用窗口处于前台」时装一个专用线程上的低级钩子,+ * 拦下右键与滚轮;滚轮按时间窗合并后翻译成一条 `input swipe`,+ * 既平滑又不会每次滚动都拉起一个 adb 进程。+ */++const WHEEL_NOTCH = 120;++function clamp(v, lo, hi) {+ const n = Number(v);+ if (!Number.isFinite(n)) return lo;+ return Math.max(lo, Math.min(hi, n));+}++function clampInt(v, lo, hi) { return Math.round(clamp(v, lo, hi)); }++/**+ * 读取设置,得到钩子需要的开关。+ * 老配置里没有这些键时,按「右键返回 + 平滑滚轮、侧键关闭」迁移。+ */+function pointerOptions(settings = {}) {+ const e = (settings && settings.engine) || {};+ const rightBack = e.mouseRightBack !== false;+ const wheel = e.mouseWheelMode === 'native' || e.mouseWheelMode === 'off'+ ? e.mouseWheelMode : 'smooth';+ const side = !!e.mouseSideButtons;+ return { rightBack, wheel, side, enabled: rightBack || wheel === 'smooth' || side };+}++/** 把任意来源的配置收敛成 agent 能直接消费的 0/1 组合 */+function hookOptions(raw = {}) {+ let v = raw;+ // 兼容旧的布尔写法:true = 只开侧键映射+ if (typeof v === 'boolean') v = { enabled: v, rightBack: false, wheel: 'off', side: v };+ if (typeof v === 'function') v = v();+ if (!v || typeof v !== 'object') v = {};+ const rightBack = !!v.rightBack;+ const wheel = v.wheel === 'smooth' || v.wheel === true;+ const side = !!v.side;+ const enabled = 'enabled' in v ? !!v.enabled : (rightBack || wheel || side);+ return {+ enabled,+ rightBack: enabled && rightBack,+ wheel: enabled && wheel,+ side: enabled && side,+ };+}++/** 只允许我们自己在内部拼出来的 input 命令进 adb shell,杜绝命令注入 */+const INPUT_RE = /^input (?:keyevent \d{1,3}|swipe -?\d+ -?\d+ -?\d+ -?\d+ \d{1,4}|tap -?\d+ -?\d+)$/;+function isInputCommand(cmd) { return INPUT_RE.test(String(cmd || '')); }++/**+ * 把一批滚轮位移翻译成一次滑动手势。+ * @param {object} o { dx, dy, nx, ny, width, height } —— nx/ny 是光标在 LCD 内的归一化位置+ * @returns {{x1:number,y1:number,x2:number,y2:number,duration:number}|null}+ */+function wheelToSwipe({ dx = 0, dy = 0, nx = 0.5, ny = 0.5, width = 900, height = 1600 } = {}) {+ const w = clampInt(width, 240, 4096);+ const h = clampInt(height, 320, 4096);+ const vertical = Math.abs(Number(dy) || 0) >= Math.abs(Number(dx) || 0);+ const delta = vertical ? (Number(dy) || 0) : (Number(dx) || 0);+ if (!delta) return null;++ // 一格滚轮 = 约 30% 屏宽的滑动;连续快滚合并成一次更长的滑动(最多 78% 屏宽)+ const steps = clamp(Math.abs(delta) / WHEEL_NOTCH, 0.6, 6);+ const axis = vertical ? h : w;+ const span = clamp(Math.round(axis * 0.30 * steps), 80, Math.round(axis * 0.78));+ const half = Math.round(span / 2);+ const cx = clampInt(clamp(nx, 0, 1) * w, 8, w - 8);+ const cy = clampInt(clamp(ny, 0, 1) * h, 8, h - 8);++ let x1 = cx, y1 = cy, x2 = cx, y2 = cy;+ if (vertical) {+ // dy > 0(滚轮向上/远离)→ 手指向下滑,内容往顶部滚+ const dir = delta > 0 ? 1 : -1;+ y1 = clampInt(cy - half * dir, 1, h - 1);+ y2 = clampInt(cy + half * dir, 1, h - 1);+ } else {+ // dx > 0(横向滚轮向右)→ 手指向左滑+ const dir = delta > 0 ? -1 : 1;+ x1 = clampInt(cx - half * dir, 1, w - 1);+ x2 = clampInt(cx + half * dir, 1, w - 1);+ }+ const duration = clampInt(100 + 22 * steps, 100, 240);+ return { x1, y1, x2, y2, duration };+}++function swipeToCommand(swipe) {+ if (!swipe) return '';+ return `input swipe ${swipe.x1} ${swipe.y1} ${swipe.x2} ${swipe.y2} ${swipe.duration}`;+}++/**+ * 滚轮合并器:一个时间窗内的所有滚动只产生一条滑动命令。+ * 注入是异步的(adb shell 里 input swipe 要跑完整个手势),期间继续累计,+ * 完成后再补发一次,避免命令在 shell 里排队造成越滚越卡。+ */+class WheelRouter {+ constructor({ inject, getSize, flushMs = 80 } = {}) {+ this.inject = inject || (() => Promise.resolve());+ this.getSize = getSize || (() => ({ width: 900, height: 1600 }));+ this.flushMs = flushMs;+ this._acc = { dx: 0, dy: 0, nx: 0.5, ny: 0.5 };+ this._timer = null;+ this._busy = false;+ this._closed = false;+ }++ push(ev = {}) {+ if (this._closed) return;+ const dx = Number(ev.dx) || 0;+ const dy = Number(ev.dy) || 0;+ if (!dx && !dy) return;+ this._acc.dx += dx;+ this._acc.dy += dy;+ this._acc.nx = clamp(ev.nx, 0, 1);+ this._acc.ny = clamp(ev.ny, 0, 1);+ this._schedule();+ }++ _schedule() {+ if (this._closed || this._timer) return;+ this._timer = setTimeout(() => {+ this._timer = null;+ this._flush();+ }, this.flushMs);+ if (this._timer.unref) this._timer.unref();+ }++ _take() {+ const b = this._acc;+ this._acc = { dx: 0, dy: 0, nx: 0.5, ny: 0.5 };+ return (b.dx || b.dy) ? b : null;+ }++ async flush() { return this._flush(); }++ async _flush() {+ if (this._closed || this._busy) return;+ const batch = this._take();+ if (!batch) return;+ this._busy = true;+ try {+ const size = await this.getSize();+ const cmd = swipeToCommand(wheelToSwipe({ ...batch, width: size.width, height: size.height }));+ if (cmd && isInputCommand(cmd)) await this.inject(cmd);+ } catch (_) { /* 输入注入失败不能影响鼠标钩子 */ }+ finally {+ this._busy = false;+ if (!this._closed && (this._acc.dx || this._acc.dy)) this._schedule();+ }+ }++ dispose() {+ this._closed = true;+ if (this._timer) clearTimeout(this._timer);+ this._timer = null;+ this._acc = { dx: 0, dy: 0, nx: 0.5, ny: 0.5 };+ }+}++module.exports = {+ WHEEL_NOTCH, clamp, pointerOptions, hookOptions,+ isInputCommand, wheelToSwipe, swipeToCommand, WheelRouter,+};diff --git a/src/core/store.js b/src/core/store.jsindex 44beac4..33e4a25 100644--- a/src/core/store.js+++ b/src/core/store.js@@ -32,7 +32,11 @@ const DEFAULT_SETTINGS = {forceTcg: false, // 保留给高级排障;正常路径已由 doctor 自动回退// ---- 轻量容器(默认全开省资源,用户可逐项关掉)----liteMode: true, // 收敛 vCPU 配额,避免 qemu 占满物理核拖慢 Windows- mouseSideButtons: false, // 全局 WH_MOUSE_LL 钩子:默认关闭,开启才有侧键返回+ // 鼠标键位:左键由模拟器原生映射为「确认/点击」,无需开关。+ // 右键返回与平滑滚轮需要低级钩子,但只在应用窗口前台时装,失焦即卸载。+ mouseRightBack: true, // 右键 = 安卓返回(拦下 Qt 默认的「右键也当点击」误触)+ mouseWheelMode: 'smooth', // smooth = 合并后注入一次滑动 | native = 交给 Qt | off = 不处理+ mouseSideButtons: false, // 侧键返回/前进:默认关闭,开启才多装一项映射deepTrim: false, // 深度裁剪系统后台包(Play 商店/向导等),默认不动系统priorityMode: 'balanced', // balanced=让出前台 | performance=qemu 用 Normal 优先级},diff --git a/src/core/win/agent.ps1 b/src/core/win/agent.ps1index c0bddcd..b3fbc37 100644--- a/src/core/win/agent.ps1+++ b/src/core/win/agent.ps1@@ -4,7 +4,9 @@# no emulator sidebar, no emulator title bar);# * hides the floating emulator toolbar window that shows the volume/camera/back rail;# * rotates the device with Ctrl+Left / Ctrl+Right and reports the new window size;-# * runs a WH_MOUSE_LL hook so mouse side buttons become Android BACK / FORWARD.+# * runs an opt-in WH_MOUSE_LL hook so right click becomes Android BACK, wheel+# becomes a coalesced swipe, and (optionally) side buttons become BACK / FORWARD.+# Left click is deliberately left alone: Qt already maps it to a finger tap.# Everything is P/Invoke from the .NET Framework that ships with Windows 10/11,# so there is no native binary to compile, sign or ship.# Protocol: TCP on 127.0.0.1, one JSON object per line. First stdout line is "PORT=<n>".@@ -14,6 +16,8 @@ $ErrorActionPreference = 'Stop'$src = @'using System;using System.Collections.Concurrent;+using System.Diagnostics;+using System.Globalization;using System.Net;using System.Net.Sockets;using System.Runtime.InteropServices;@@ -60,6 +64,7 @@ public class ApkAgent[DllImport("user32.dll")] static extern IntPtr SetFocus(IntPtr h);[DllImport("user32.dll")] static extern IntPtr WindowFromPoint(POINT p);[DllImport("user32.dll")] static extern bool ScreenToClient(IntPtr h, ref POINT p);+ [DllImport("user32.dll")] static extern IntPtr GetAncestor(IntPtr h, uint flags);const int GWL_STYLE = -16;const int GWL_EXSTYLE = -20;@@ -96,6 +101,20 @@ public class ApkAgentstatic long _lastToolSweep = 0;static long _embedAt = 0;+ // Hook options. All three default to OFF: an "hook on" without options must+ // never swallow anybody's clicks. JS sends the real config on every enable.+ static volatile int _optRight = 0;+ static volatile int _optWheel = 0;+ static volatile int _optSide = 0;++ // Wheel coalescing: Qt would turn every single notch into a separate touch+ // gesture (visible stutter). We accumulate deltas for a short window and+ // hand one normalized position to the JS side, which injects a single swipe.+ static readonly object _wheelLock = new object();+ static int _wheelDx = 0, _wheelDy = 0;+ static double _wheelNx = 0.5, _wheelNy = 0.5;+ static long _wheelFirst = 0, _wheelLast = 0;+// ------------------------------------------------------------------ window discoverystatic string ClassOf(IntPtr h){@@ -240,24 +259,120 @@ public class ApkAgent}}- // ------------------------------------------------------------------ mouse hook+ // ------------------------------------------------------------------ mouse mapping+ const int WM_RBUTTONDOWN = 0x0204;+ const int WM_RBUTTONUP = 0x0205;+ const int WM_RBUTTONDBLCLK = 0x0206;+ const int WM_MOUSEWHEEL = 0x020A;+ const int WM_XBUTTONDOWN = 0x020B;+ const int WM_XBUTTONUP = 0x020C;+ const int WM_MOUSEHWHEEL = 0x020E;++ static readonly Stopwatch _clock = Stopwatch.StartNew();+ static long NowMs() { return _clock.ElapsedMilliseconds; }++ // Only react inside the embedded LCD while OUR window is the foreground root.+ // GetAncestor(GA_ROOT) covers Chromium child windows and the Qt framebuffer.+ static bool InOurLcd(POINT pt, out RECT r)+ {+ r = new RECT();+ IntPtr fg = GetForegroundWindow();+ if (fg == IntPtr.Zero || _host == IntPtr.Zero) return false;+ if (GetAncestor(fg, 2) != _host) return false; // 2 = GA_ROOT+ IntPtr e = _emu;+ if (e != IntPtr.Zero && GetWindowRect(e, out r))+ {+ // Qt keeps an 8px grey pad around the real LCD; embed() pushes it out.+ return pt.X >= r.L + 8 && pt.X <= r.R - 8 && pt.Y >= r.T + 8 && pt.Y <= r.B - 8;+ }+ // Before embed (or if FindEmulator failed) fall back to the host window+ // minus its 38px title bar. Approximate on HiDPI, but only a fallback.+ if (!GetWindowRect(_host, out r)) return false;+ return pt.X >= r.L + 4 && pt.X <= r.R - 4 && pt.Y >= r.T + 40 && pt.Y <= r.B - 4;+ }++ static string Num(double v) { return v.ToString("0.####", CultureInfo.InvariantCulture); }++ static void PushWheel(int dx, int dy, POINT pt, RECT r)+ {+ int w = r.R - r.L - 16, h = r.B - r.T - 16;+ double nx = w > 0 ? (pt.X - r.L - 8.0) / w : 0.5;+ double ny = h > 0 ? (pt.Y - r.T - 8.0) / h : 0.5;+ if (nx < 0) nx = 0; if (nx > 1) nx = 1;+ if (ny < 0) ny = 0; if (ny > 1) ny = 1;+ long now = NowMs();+ lock (_wheelLock)+ {+ if (_wheelDx == 0 && _wheelDy == 0) _wheelFirst = now;+ _wheelDx += dx;+ _wheelDy += dy;+ _wheelNx = nx;+ _wheelNy = ny;+ _wheelLast = now;+ }+ }++ // Drained from the socket loop. Emit after 60ms of quiet, but never let a+ // continuous spin starve the queue (hard cap 90ms from the first notch).+ static void FlushWheel(bool force)+ {+ int dx = 0, dy = 0;+ double nx = 0.5, ny = 0.5;+ long now = NowMs();+ lock (_wheelLock)+ {+ if (_wheelDx == 0 && _wheelDy == 0) return;+ if (!force && now - _wheelLast < 60 && now - _wheelFirst < 90) return;+ dx = _wheelDx; dy = _wheelDy; nx = _wheelNx; ny = _wheelNy;+ _wheelDx = 0; _wheelDy = 0;+ }+ _events.Enqueue("{\"ev\":\"wheel\",\"dx\":" + dx + ",\"dy\":" + dy+ + ",\"nx\":" + Num(nx) + ",\"ny\":" + Num(ny) + "}");+ }++ static void ResetWheel()+ {+ lock (_wheelLock) { _wheelDx = 0; _wheelDy = 0; }+ }++ // The callback must stay microscopic: Windows synchronously waits for it on+ // EVERY mouse event of EVERY process. Anything not one of our 7 messages+ // (including all left-button events) is a single CallNextHookEx.static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam){if (nCode >= 0){- int msg = (int)wParam; // 0x020B = WM_XBUTTONDOWN- if (msg == 0x020B)+ int msg = (int)wParam;+ bool right = msg == WM_RBUTTONDOWN || msg == WM_RBUTTONUP || msg == WM_RBUTTONDBLCLK;+ bool wheel = msg == WM_MOUSEWHEEL || msg == WM_MOUSEHWHEEL;+ bool xbut = msg == WM_XBUTTONDOWN || msg == WM_XBUTTONUP;+ if (!right && !wheel && !xbut) return CallNextHookEx(_hook, nCode, wParam, lParam);+ if ((right && _optRight == 0) || (wheel && _optWheel == 0) || (xbut && _optSide == 0))+ return CallNextHookEx(_hook, nCode, wParam, lParam);++ MSLLHOOKSTRUCT d = (MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(MSLLHOOKSTRUCT));+ RECT r;+ if (!InOurLcd(d.Pt, out r)) return CallNextHookEx(_hook, nCode, wParam, lParam);++ if (right)+ {+ // Qt maps a right click to a plain finger tap: swallow it, emit BACK.+ if (msg == WM_RBUTTONDOWN) _events.Enqueue("{\"ev\":\"back\"}");+ return (IntPtr)1;+ }+ if (wheel)+ {+ int delta = (short)((d.MouseData >> 16) & 0xFFFF);+ if (msg == WM_MOUSEWHEEL) PushWheel(0, delta, d.Pt, r);+ else PushWheel(delta, 0, d.Pt, r);+ return (IntPtr)1;+ }+ if (msg == WM_XBUTTONDOWN){- MSLLHOOKSTRUCT d = (MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(MSLLHOOKSTRUCT));int button = (d.MouseData >> 16) & 0xFFFF;- IntPtr fg = GetForegroundWindow();- bool ours = (fg != IntPtr.Zero) && (_host != IntPtr.Zero) && (fg == _host || GetParent(fg) == _host || fg == _emu);- if (ours)- {- _events.Enqueue(button == 1 ? "back" : "forward");- return (IntPtr)1; // swallow so the app never sees a raw side click- }+ _events.Enqueue(button == 1 ? "{\"ev\":\"back\"}" : "{\"ev\":\"forward\"}");}+ return (IntPtr)1;}return CallNextHookEx(_hook, nCode, wParam, lParam);}@@ -266,8 +381,8 @@ public class ApkAgent// EVERY mouse event of EVERY application. It must therefore live on a thread whose// only job is pumping messages. Installing it on the socket-serving thread (which// used to block up to 4s in Poll) made the whole desktop pointer lag and drift.- // It is opt-in now: the JS side only calls "hook on" when the user explicitly- // enables mouse side buttons in settings. Default = no global hook at all.+ // It is scoped now: JS installs it only while an app window is foreground, and+ // the callback ignores events outside the embedded LCD.static void HookThreadProc(){_hookTid = GetCurrentThreadId();@@ -299,6 +414,8 @@ public class ApkAgentstatic void HookOff(){_hookRun = false;+ _optRight = 0; _optWheel = 0; _optSide = 0;+ ResetWheel();if (_hook != IntPtr.Zero) { UnhookWindowsHookEx(_hook); _hook = IntPtr.Zero; }if (_hookTid != 0) PostThreadMessage(_hookTid, 0x0012, IntPtr.Zero, IntPtr.Zero); // WM_QUIT_hookThread = null;@@ -370,6 +487,7 @@ public class ApkAgentwhile (run){Pump();+ FlushWheel(false);string ev;while (_events.TryDequeue(out ev))@@ -444,6 +562,11 @@ public class ApkAgent}else if (cmd == "hook"){+ // Options are re-sent on every enable, so changing settings+ // while the hook is live needs no reinstall / no thread churn.+ _optRight = L(line, "right") == 1 ? 1 : 0;+ _optWheel = L(line, "wheel") == 1 ? 1 : 0;+ _optSide = L(line, "side") == 1 ? 1 : 0;if (L(line, "on") == 1) HookOn(); else HookOff();Reply(sock, "{\"ok\":true,\"hooked\":" + (_hook != IntPtr.Zero ? "true" : "false") + "}");}diff --git a/src/main.js b/src/main.jsindex 1d9a83d..468ffa6 100644--- a/src/main.js+++ b/src/main.js@@ -31,6 +31,7 @@ const assoc = require('./core/assoc');const windowctl = require('./core/windowctl');const display = require('./core/display');const { WinAgent } = require('./core/agent');+const pointer = require('./core/pointer');const { AppWindow, TITLEBAR_H } = require('./core/appwin');const { NotifyBridge } = require('./core/notify');const { AndroidSettings } = require('./core/android');@@ -227,12 +228,31 @@ function screenRect() {}let currentAppPkg = null;+let wheelRouter = null;+const deviceSize = { value: null };++/** 滚轮注入需要知道 Android 侧分辨率;缓存一次,转屏/重启运行时后失效 */+async function getDeviceSize() {+ if (deviceSize.value) return deviceSize.value;+ try { deviceSize.value = await runtime.client().wmSize(); } catch (_) { /* 运行时还没起来 */ }+ if (!deviceSize.value || !deviceSize.value.width || !deviceSize.value.height) {+ const p = portraitSize();+ deviceSize.value = { width: p.w, height: p.h };+ }+ return deviceSize.value;+}function portraitSize() {const d = displaySettings();return display.portraitSize(d.portrait || '540x960');}+/** 设置页改动鼠标键位后,立刻按当前窗口焦点同步一次钩子配置 */+function refreshPointerMapping() {+ if (appWin && appWin.isOpen) appWin.refreshPointer();+ else if (winAgent && winAgent.hooked) winAgent.setHook(false).catch(() => {});+}+/** 打开(或复用)那个「一个应用一个干净窗口」 */function openAppWindow(pkg, tip) {const rec = store.getApp(pkg);@@ -453,8 +473,10 @@ async function runLaunch(pkg) {mark('embedded');appWin.setState({ ready: true, tip: '' });// 容器会话:环境已经就绪,这里只做「按应用裁剪 + 打开后台轮询」,- // 不再为这个 App 重新引导一遍 Android。全局鼠标钩子由窗口 focus 事件- // 按设置决定,默认不安装。+ // 不再为这个 App 重新引导一遍 Android。鼠标键位钩子由窗口 focus 事件+ // 按设置决定,失焦即卸载。+ deviceSize.value = null;+ appWin.refreshPointer();await runtime.beginApp(pkg, { onActive: onContainerActive }).catch(() => {});send('app:launched', { package: pkg, engine: r.engine });appLog(`launch ok ${pkg} embedded=${embedded}`);@@ -601,6 +623,12 @@ function registerIpc() {if (patch && (patch.createStartMenuShortcut === true || patch.createShortcutOnInstall === true)) {installer.ensureShortcuts().catch(() => {});}+ // 鼠标键位变了:立刻按当前焦点重装/卸载钩子,不用等下次切窗口+ if (patch && patch.engine && (+ 'mouseRightBack' in patch.engine || 'mouseWheelMode' in patch.engine || 'mouseSideButtons' in patch.engine+ )) {+ refreshPointerMapping();+ }return next;});@@ -629,11 +657,10 @@ function registerIpc() {ipcMain.handle('runtime:autoDeploy', () => autoDeploy());// 关闭「深度裁剪」时把被 pm disable-user 的系统包恢复回来ipcMain.handle('settings:restoreSystem', async () => runtime.restoreSystemApps());- // 关闭「鼠标侧键」时立刻卸载全局钩子,不用等窗口失焦- ipcMain.handle('settings:unhook', async () => {- if (winAgent && winAgent.hooked) await winAgent.setHook(false).catch(() => {});- return true;- });+ // 鼠标键位改变:只同步配置,不再无条件卸载(右键返回/滚轮可能仍需要钩子)+ ipcMain.handle('settings:refreshPointer', async () => { refreshPointerMapping(); return true; });+ // 兼容旧界面:语义已改为「按设置重新同步」+ ipcMain.handle('settings:unhook', async () => { refreshPointerMapping(); return true; });ipcMain.handle('runtime:status', async () => runtime.status());ipcMain.handle('runtime:probe', async () => runtime.probe());@@ -996,23 +1023,46 @@ if (!gotLock) {sharer = new Sharer(runtime);androidSet = new AndroidSettings(runtime);- // 窗口代理:只负责内嵌模拟器窗口。全局鼠标钩子默认不装(见 setHook)。+ // 滚轮合并器:一个时间窗内的滚动只注入一条 input swipe,走常驻 adb shell。+ wheelRouter = new pointer.WheelRouter({+ getSize: getDeviceSize,+ inject: (cmd) => runtime.client().input(cmd),+ });++ // 窗口代理:只负责内嵌模拟器窗口。全局鼠标钩子只在应用窗口前台时按配置安装。winAgent = new WinAgent();appWin = new AppWindow({agent: winAgent,// 旋转要改 Android 的逻辑分辨率,交给 adb 客户端做- setOrientation: (landscape) => runtime.client().setOrientation(landscape),- // 传 getter:设置页改了开关,下一次窗口 focus 就生效,不用重启- mouseHook: () => !!store.getSettings().engine.mouseSideButtons,+ setOrientation: async (landscape) => {+ deviceSize.value = null;+ return runtime.client().setOrientation(landscape);+ },+ // 传 getter:设置页改了键位,下一次窗口 focus / 刷新就生效,不用重启+ pointerConfig: () => pointer.pointerOptions(store.getSettings()),});appWin.onCloseApp((pkg) => {// 关窗口 = 停这个应用;最后一个窗口关掉时容器停放(降优先级、停轮询),// 但 Android 环境留着,下次点开是秒进而非重新冷启动。runtime?.endApp(pkg, { onIdle: onContainerActive }).catch(() => {});});- winAgent.on('back', () => { runtime.client().keyBack().catch(() => {}); });- winAgent.on('forward', () => { runtime.client().keyForward().catch(() => {}); });- winAgent.on('exit', () => { winAgent = new WinAgent(); appWin.agent = winAgent; });++ // 代理进程意外退出后会重建,事件监听必须一起重新挂上(旧版会在这里丢掉+ // 右键返回与滚轮,表现是「用一会儿就没反应了」)。+ const attachAgentEvents = (agent) => {+ agent.on('back', () => { runtime.client().keyBack().catch(() => {}); });+ agent.on('forward', () => { runtime.client().keyForward().catch(() => {}); });+ agent.on('wheel', (m) => {+ if (pointer.pointerOptions(store.getSettings()).wheel === 'smooth') wheelRouter.push(m);+ });+ agent.on('exit', () => {+ const next = new WinAgent();+ winAgent = next;+ appWin.agent = next;+ attachAgentEvents(next);+ });+ };+ attachAgentEvents(winAgent);registerIpc();createWindow({ show: !parseArgs(process.argv).silent });@@ -1118,6 +1168,7 @@ if (!gotLock) {notifier?.stop();try { appWin?.close({ keepApp: false }); } catch (_) { /* ignore */ }try { winAgent?.dispose(); } catch (_) { /* ignore */ }+ try { wheelRouter?.dispose(); } catch (_) { /* ignore */ }runtime?.dispose();// 隐藏的图标解码窗口也算一个窗口,不关掉会让 window-all-closed 永远不触发try { if (decodeWindow && !decodeWindow.isDestroyed()) decodeWindow.destroy(); } catch (_) { /* ignore */ }diff --git a/src/preload.js b/src/preload.jsindex d0ac83c..f07e899 100644--- a/src/preload.js+++ b/src/preload.js@@ -20,6 +20,7 @@ contextBridge.exposeInMainWorld('apkstart', {getSettings: () => invoke('settings:get'),setSettings: (patch) => invoke('settings:set', patch),restoreSystemApps: () => invoke('settings:restoreSystem'),+ refreshPointerMapping: () => invoke('settings:refreshPointer'),restoreMouseHook: () => invoke('settings:unhook'),runtimeStatus: () => invoke('runtime:status'),diff --git a/src/ui/app.js b/src/ui/app.jsindex 0a86903..c21097e 100644--- a/src/ui/app.js+++ b/src/ui/app.js@@ -632,6 +632,9 @@ function fillSettings(s) {$('setLiteMode').checked = s.engine.liteMode !== false;$('setPriorityMode').value = s.engine.priorityMode === 'performance' ? 'performance' : 'balanced';$('setDeepTrim').checked = !!s.engine.deepTrim;+ $('setMouseRightBack').checked = s.engine.mouseRightBack !== false;+ $('setMouseWheelMode').value = ['smooth', 'native', 'off'].includes(s.engine.mouseWheelMode)+ ? s.engine.mouseWheelMode : 'smooth';$('setMouseSideButtons').checked = !!s.engine.mouseSideButtons;$('setCompat').checked = !!(s.runtime && s.runtime.compatImage);$('setAutoShortcut').checked = !!s.createShortcutOnInstall;@@ -692,10 +695,14 @@ function bindSettings() {$('setIdle').addEventListener('change', (e) => save({ engine: { idleShutdownMinutes: Number(e.target.value) || 0 } }));$('setLiteMode').addEventListener('change', (e) => save({ engine: { liteMode: e.target.checked } }));$('setPriorityMode').addEventListener('change', (e) => save({ engine: { priorityMode: e.target.value } }));- $('setMouseSideButtons').addEventListener('change', (e) => {- save({ engine: { mouseSideButtons: e.target.checked } });- if (!e.target.checked) api.restoreMouseHook().catch(() => {});- });+ const savePointer = async (patch) => {+ await save({ engine: patch });+ // 立刻按当前窗口焦点重装/卸载钩子,不用等下次切窗口+ api.refreshPointerMapping().catch(() => {});+ };+ $('setMouseRightBack').addEventListener('change', (e) => savePointer({ mouseRightBack: e.target.checked }));+ $('setMouseWheelMode').addEventListener('change', (e) => savePointer({ mouseWheelMode: e.target.value }));+ $('setMouseSideButtons').addEventListener('change', (e) => savePointer({ mouseSideButtons: e.target.checked }));$('setDeepTrim').addEventListener('change', async (e) => {await save({ engine: { deepTrim: e.target.checked } });// 关掉深度裁剪必须把之前 pm disable-user 的包恢复回来,否则影响是持久的diff --git a/src/ui/index.html b/src/ui/index.htmlindex 6a91a2f..65ea5e7 100644--- a/src/ui/index.html+++ b/src/ui/index.html@@ -191,6 +191,40 @@</div></div>+ <div class="group">+ <div class="group-title">鼠标键位</div>+ <div class="field">+ <label>左键 · 确认 / 点击</label>+ <span class="sub">模拟器原生把左键当成手指点击,按住拖动就是滑动,无需额外设置。</span>+ </div>+ <div class="field switch-field">+ <div>+ <label>右键 · 安卓返回</label>+ <span class="sub">模拟器默认把右键也当成一次点击(容易误触)。开启后右键只执行返回,不再触发点击。</span>+ </div>+ <input type="checkbox" id="setMouseRightBack" class="switch" />+ </div>+ <div class="field">+ <label>滚轮 · 滑动</label>+ <select id="setMouseWheelMode">+ <option value="smooth">平滑(推荐)· 合并多次滚动为一次流畅滑动</option>+ <option value="native">原生 · 交给模拟器逐格处理</option>+ <option value="off">关闭 · 不拦截滚轮</option>+ </select>+ <span class="sub">平滑模式把一小段时间内的滚动合并成一次滑动手势,避免逐格抽搐,也不会每格都拉起一个 adb 进程。</span>+ </div>+ <div class="field switch-field">+ <div>+ <label>鼠标侧键 · 返回 / 前进(默认关闭)</label>+ <span class="sub">侧键映射需要全局鼠标钩子。钩子只在 ApkStart 应用窗口处于前台时安装,失焦或关闭立即卸载,不会拖慢桌面。</span>+ </div>+ <input type="checkbox" id="setMouseSideButtons" class="switch" />+ </div>+ <div class="field">+ <span class="sub">以上映射只在应用窗口前台生效;切回桌面或关闭窗口后,鼠标行为完全恢复 Windows 原生。</span>+ </div>+ </div>+<div class="group"><div class="group-title">性能与轻量容器</div><div class="field switch-field">@@ -215,13 +249,6 @@</div><input type="checkbox" id="setDeepTrim" class="switch" /></div>- <div class="field switch-field">- <div>- <label>鼠标侧键返回(默认关闭)</label>- <span class="sub">需要安装全局鼠标钩子,会介入整个 Windows 的每一次鼠标事件。仅在你确实要用侧键返回时开启;窗口失焦会自动卸载。默认关闭可避免鼠标漂移。</span>- </div>- <input type="checkbox" id="setMouseSideButtons" class="switch" />- </div><div class="field"><span class="sub">安卓环境只开机一次并常驻;之后打开应用不再重跑整个系统,只启动该应用并停掉其他应用进程。关掉最后一个窗口会清后台、停放容器,下次点开仍是秒进。</span></div>diff --git a/src/ui/shell.js b/src/ui/shell.jsindex ea49a7d..b33f8be 100644--- a/src/ui/shell.js+++ b/src/ui/shell.js@@ -15,6 +15,10 @@ btn.min.addEventListener('click', () => api.shell.minimize());btn.max.addEventListener('click', () => api.shell.maximize());btn.close.addEventListener('click', () => api.shell.close());+// 标题栏上右键不要弹出 Chromium 的网页菜单;画面区域的右键已由主进程+// 拦下并映射成「安卓返回」,这里补掉外壳这一圈。+window.addEventListener('contextmenu', (e) => e.preventDefault());+// Ctrl+R 旋转,F11 最大化(和 Windows 习惯一致)window.addEventListener('keydown', (e) => {if (e.ctrlKey && (e.key === 'r' || e.key === 'R')) { e.preventDefault(); api.shell.rotate(); }diff --git a/test/auto-test.js b/test/auto-test.jsindex 15f9a33..e6de3ea 100644--- a/test/auto-test.js+++ b/test/auto-test.js@@ -23,7 +23,8 @@ function assert(c, m) { if (!c) throw new Error(m || '断言失败'); }const doctor = require('../src/core/doctor');const layers = require('../src/core/layers');-const { friendlyInstallError, friendlyLaunchError } = require('../src/core/adb');+const pointer = require('../src/core/pointer');+const { AdbClient, friendlyInstallError, friendlyLaunchError } = require('../src/core/adb');(async () => {console.log('\n[doctor.js 自动参数]');@@ -546,6 +547,128 @@ const { friendlyInstallError, friendlyLaunchError } = require('../src/core/adb')assert(a.ready === null, '默认关闭时不能为此启动常驻代理进程');});+ console.log('\n[鼠标键位映射]');++ await test('默认与旧配置迁移:右键返回 + 平滑滚轮开启,侧键关闭', () => {+ const store = require('../src/core/store');+ const d = pointer.pointerOptions(store.getSettings());+ assert(d.rightBack === true, '右键返回默认开');+ assert(d.wheel === 'smooth', '滚轮默认平滑');+ assert(d.side === false, '侧键默认关');+ assert(d.enabled === true, '至少右键映射需要钩子');+ // 老 settings.json 里没有新键时也要得到同样的结果+ assert(pointer.pointerOptions({ engine: { liteMode: true } }).rightBack === true);+ const off = pointer.pointerOptions({ engine: { mouseRightBack: false, mouseWheelMode: 'off', mouseSideButtons: false } });+ assert(off.enabled === false, '全部关掉后不应再装钩子');+ const native = pointer.pointerOptions({ engine: { mouseRightBack: false, mouseWheelMode: 'native', mouseSideButtons: false } });+ assert(native.enabled === false, '原生滚轮不需要钩子');+ });++ await test('hookOptions 收敛配置,关闭时所有子开关一起归零', () => {+ const on = pointer.hookOptions({ enabled: true, rightBack: true, wheel: true, side: false });+ assert(on.rightBack && on.wheel && !on.side);+ const off = pointer.hookOptions({ enabled: false, rightBack: true, wheel: true, side: true });+ assert(!off.rightBack && !off.wheel && !off.side, 'enabled=false 必须彻底不拦事件');+ assert(pointer.hookOptions(true).side === true, '兼容旧布尔写法(侧键)');+ assert(pointer.hookOptions(false).enabled === false);+ });++ await test('滚轮方向:向下滚=手指上滑,向上滚=手指下滑,坐标不越界', () => {+ const down = pointer.wheelToSwipe({ dy: -120, nx: 0.5, ny: 0.5, width: 900, height: 1600 });+ assert(down && down.y1 > down.y2, '滚轮向下应让内容上移(手指上滑)');+ const up = pointer.wheelToSwipe({ dy: 120, nx: 0.5, ny: 0.5, width: 900, height: 1600 });+ assert(up && up.y1 < up.y2, '滚轮向上应让内容下移(手指下滑)');+ assert(pointer.wheelToSwipe({ dx: 0, dy: 0 }) === null, '零位移不产生命令');+ for (const s of [down, up]) {+ assert([s.x1, s.x2].every((v) => v >= 1 && v <= 899), 'x 不能越界');+ assert([s.y1, s.y2].every((v) => v >= 1 && v <= 1599), 'y 不能越界');+ assert(s.duration >= 100 && s.duration <= 240, '滑动时长应有上限');+ }+ const big = pointer.wheelToSwipe({ dy: -12000, nx: 0, ny: 0, width: 900, height: 1600 });+ assert(big.y1 - big.y2 <= Math.round(1600 * 0.78), '快滚不能无限拉长手势');+ const horiz = pointer.wheelToSwipe({ dx: 120, dy: 0, width: 900, height: 1600 });+ assert(horiz && horiz.x1 > horiz.x2 && horiz.y1 === horiz.y2, '横向滚轮应产生水平滑动');+ });++ await test('input 命令白名单:只放行内部拼出的命令,挡住注入', async () => {+ assert(pointer.isInputCommand('input keyevent 4'));+ assert(pointer.isInputCommand(pointer.swipeToCommand(pointer.wheelToSwipe({ dy: -120 }))));+ assert(!pointer.isInputCommand('input keyevent 4; rm -rf /sdcard'));+ assert(!pointer.isInputCommand('input swipe 1 2 3 4 100 && reboot'));+ assert(!pointer.isInputCommand('sh -c anything'));+ const c = new AdbClient({ adbPath: 'adb', serial: 'test' });+ let blocked = false;+ try { await c.input('input keyevent 4; rm -rf /'); } catch (e) { blocked = /非法/.test(e.message); }+ assert(blocked, '非法命令必须在拉起 adb 之前被挡下');+ assert(c._input === null, '被挡下的命令不能创建常驻会话');+ });++ await test('返回键优先走常驻输入通道,失败才回退一次性 adb', async () => {+ const c = new AdbClient({ adbPath: 'adb', serial: 'test' });+ const used = [];+ c.input = async (cmd) => { used.push(cmd); };+ c.shell = async () => { used.push('shell'); };+ await c.keyBack();+ assert(used[0] === 'input keyevent 4' && !used.includes('shell'), '正常路径不应 spawn adb');+ const c2 = new AdbClient({ adbPath: 'adb', serial: 'test' });+ const used2 = [];+ c2.input = async () => { throw new Error('offline'); };+ c2.shell = async (cmd) => { used2.push(cmd); return ''; };+ await c2.keyForward();+ assert(used2[0] === 'input keyevent 125', '常驻通道失败必须兜底,别丢掉这次点击');+ });++ await test('WheelRouter 把连续滚动合并成一条滑动命令', async () => {+ const cmds = [];+ const r = new pointer.WheelRouter({+ inject: async (cmd) => { cmds.push(cmd); },+ getSize: () => ({ width: 900, height: 1600 }),+ flushMs: 10,+ });+ r.push({ dx: 0, dy: -120, nx: 0.5, ny: 0.5 });+ r.push({ dx: 0, dy: -120, nx: 0.5, ny: 0.5 });+ r.push({ dx: 0, dy: -120, nx: 0.5, ny: 0.4 });+ await r.flush();+ assert(cmds.length === 1, `3 格滚动应合并成 1 条命令,实际 ${cmds.length}`);+ assert(pointer.isInputCommand(cmds[0]), '必须产出合法的 input swipe');+ const m = /^input swipe (\d+) (\d+) (\d+) (\d+)/.exec(cmds[0]);+ assert(m && Number(m[2]) > Number(m[4]), '合并后仍是向下滚的方向');+ r.dispose();+ r.push({ dy: -120 });+ await r.flush();+ assert(cmds.length === 1, 'dispose 后不能再注入');+ });++ await test('代理脚本:右键/滚轮拦截、滚轮合并、前台限定与专用线程', () => {+ const ps1 = fs.readFileSync(path.join(__dirname, '..', 'src', 'core', 'win', 'agent.ps1'), 'utf8');+ assert(/WM_RBUTTONDOWN/.test(ps1) && /WM_MOUSEWHEEL/.test(ps1), '必须处理右键与滚轮');+ assert(/WM_MOUSEHWHEEL/.test(ps1), '横向滚轮也要支持');+ assert(/PushWheel\(/.test(ps1) && /FlushWheel\(false\)/.test(ps1), '滚轮必须合并后上报');+ assert(/GetAncestor\(fg, 2\)/.test(ps1), '必须按前台根窗口限定作用域');+ assert(/new Thread\(HookThreadProc\)/.test(ps1) && /GetMessage\(out MSG/.test(ps1), '钩子必须在专用消息线程');+ assert(!/Poll\(4000,\s*SelectMode\.SelectRead\)/.test(ps1), '主循环不能长阻塞');+ assert(/_optRight == 0/.test(ps1) && /_optWheel == 0/.test(ps1), '未配置的映射不能拦事件');+ const appwinJs = fs.readFileSync(path.join(__dirname, '..', 'src', 'core', 'appwin.js'), 'utf8');+ assert(/pointerConfig/.test(appwinJs) && /refreshPointer/.test(appwinJs), '设置变化要能即时同步钩子');+ const uiHtml = fs.readFileSync(path.join(__dirname, '..', 'src', 'ui', 'index.html'), 'utf8');+ assert(/setMouseRightBack/.test(uiHtml) && /setMouseWheelMode/.test(uiHtml), '设置页需暴露键位开关');+ });++ await test('WinAgent.setHook 把键位配置一起下发,且关闭时不拉起代理', async () => {+ const { WinAgent } = require('../src/core/agent');+ const a = new WinAgent();+ const sent = [];+ a.call = async (obj) => { sent.push(obj); return { ok: true, hooked: true }; };+ const on = await a.setHook(true, { rightBack: true, wheel: true, side: false });+ assert(on.hooked === true && sent.length === 1, '开启应只发一次命令');+ assert(sent[0].right === 1 && sent[0].wheel === 1 && sent[0].side === 0, '配置必须随 hook 命令下发');+ await a.setHook(false);+ assert(sent[1].on === 0 && a.hooked === false, '关闭要卸载钩子');+ const b = new WinAgent();+ const r = await b.setHook(false);+ assert(r.hooked === false && b.ready === null, '默认关闭时不能启动 PowerShell');+ });+console.log(results.join('\n'));console.log(`\n结果:${passed} 通过,${failed} 失败\n`);try { fs.rmSync(TMP, { recursive: true, force: true }); } catch (_) { /* ignore */ }diff --git a/test/pointer-hook-logic.ps1 b/test/pointer-hook-logic.ps1new file mode 100644index 0000000..1bb242e--- /dev/null+++ b/test/pointer-hook-logic.ps1@@ -0,0 +1,125 @@+# Smoke-test the mouse mapping INSIDE agent.ps1 without starting a real emulator.+# Loads the embedded C# and drives the private hook callback via reflection.+# InOurLcd() needs a real foreground window, which a CI / non-interactive session+# has none of; the compiled copy therefore gets a test-only early return that+# fakes a fixed LCD rectangle. Everything else runs the production code as-is.+# Run: powershell -ExecutionPolicy Bypass -File test/pointer-hook-logic.ps1+$ErrorActionPreference = 'Stop'+Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass -Force++$path = Join-Path $PSScriptRoot '..\src\core\win\agent.ps1'+$text = Get-Content -Raw -LiteralPath $path+$m = [regex]::Match($text, "(?s)@'\r?\n(.*?)\r?\n'@")+if (-not $m.Success) { Write-Output 'FAIL=no-source'; exit 1 }+$src = $m.Groups[1].Value+$fake = @'+ static bool InOurLcd(POINT pt, out RECT r)+ {+ r = new RECT(); r.L = 100; r.T = 100; r.R = 620; r.B = 520;+ return pt.X >= 200 && pt.X <= 500 && pt.Y >= 200 && pt.Y <= 450;+ }+'@+$pat = '(?s) static bool InOurLcd\(POINT pt, out RECT r\).*?\r?\n \}'+$src2 = [regex]::Replace($src, $pat, $fake, 1)+if ($src2 -eq $src -or -not $src2.Contains('r.L = 100')) { Write-Output 'FAIL=InOurLcd not found'; exit 1 }+# Unique type name: agent-compile.ps1 may have defined ApkAgent in this process.+$src2 = $src2 -creplace 'public class ApkAgent', 'public class ApkAgentHookTest'+if (-not $src2.Contains('class ApkAgentHookTest')) { Write-Output 'FAIL=class rename'; exit 1 }+$defined = Add-Type -TypeDefinition $src2 -PassThru -ErrorAction Stop+$t = $defined | Where-Object { $_.Name -eq 'ApkAgentHookTest' } | Select-Object -First 1+if ($null -eq $t) { Write-Output 'FAIL=type not defined'; exit 1 }+$flags = [System.Reflection.BindingFlags]'NonPublic, Static'+function F($n) { return $t.GetField($n, $flags) }+function M($n) { return $t.GetMethod($n, $flags) }+function SetField($name, $value) { $f = F($name); $f.SetValue($null, $value) }+function SetOpt($right, $wheel, $side) {+ SetField '_optRight' ([int]$right)+ SetField '_optWheel' ([int]$wheel)+ SetField '_optSide' ([int]$side)+}+function DrainEvents {+ $qf = F('_events')+ $q = $qf.GetValue($null)+ $try = $q.GetType().GetMethod('TryDequeue')+ $out = @()+ $a = [object[]]@($null)+ while ($try.Invoke($q, $a)) { $out += $a[0]; $a[0] = $null }+ return ,$out+}+function Check($ok, $msg) { if (-not $ok) { Write-Output "FAIL=$msg"; exit 1 } }++# --- JSON config parsing used by the "hook" command ---+Check ((M 'L').Invoke($null, [object[]]@('{"cmd":"hook","on":1,"right":1,"wheel":1,"side":0}', 'right')) -eq 1) 'parse right'+Check ((M 'L').Invoke($null, [object[]]@('{"cmd":"hook","on":1,"right":1,"wheel":1,"side":0}', 'wheel')) -eq 1) 'parse wheel'+Check ((M 'L').Invoke($null, [object[]]@('{"cmd":"hook","on":1,"right":1,"wheel":1,"side":0}', 'side')) -eq 0) 'parse side'+Check ((M 'S').Invoke($null, [object[]]@('{"cmd":"hook","on":1}', 'cmd')) -eq 'hook') 'parse cmd'++SetField '_host' ([IntPtr]1)+SetField '_emu' ([IntPtr]::Zero)+$px = 300+$py = 300++# --- Helper to build a MSLLHOOKSTRUCT and invoke HookCallback ---+$msType = $t.GetNestedType('MSLLHOOKSTRUCT')+$ptType = $t.GetNestedType('POINT')+$hook = M 'HookCallback'+function InvokeHook([int]$msg, [int]$x, [int]$y, [int]$mouseData) {+ $pt = [Activator]::CreateInstance($ptType)+ $pt.GetType().GetField('X').SetValue($pt, $x)+ $pt.GetType().GetField('Y').SetValue($pt, $y)+ $ms = [Activator]::CreateInstance($msType)+ $ms.GetType().GetField('Pt').SetValue($ms, $pt)+ $ms.GetType().GetField('MouseData').SetValue($ms, $mouseData)+ $size = [System.Runtime.InteropServices.Marshal]::SizeOf($ms)+ $ptr = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($size)+ try {+ [System.Runtime.InteropServices.Marshal]::StructureToPtr($ms, $ptr, $false)+ return $hook.Invoke($null, [object[]]@([int]0, [IntPtr]$msg, $ptr)).ToInt64()+ } finally {+ [System.Runtime.InteropServices.Marshal]::FreeHGlobal($ptr)+ }+}++$wheelDown = [int](-120 * 65536) # high word = -120+$wheelUp = [int](120 * 65536)++# 1) Right click inside the LCD -> swallowed + one "back" event+SetOpt 1 0 0+DrainEvents | Out-Null+$r1 = InvokeHook 0x0204 $px $py 0+Check ($r1 -eq 1) 'right click must be swallowed'+$e = DrainEvents+Check ($e.Count -eq 1 -and $e[0] -match '"ev":"back"') 'right click must emit exactly one back event'++# 2) Right click OUTSIDE our window -> passed through, no event+$r2 = InvokeHook 0x0204 ($px + 9000) ($py + 9000) 0+Check ($r2 -ne 1) 'foreign right click must pass through'+Check ((DrainEvents).Count -eq 0) 'foreign right click must not emit events'++# 3) Wheel: three notches coalesce into ONE wheel event with normalized coords+SetOpt 0 1 0+DrainEvents | Out-Null+$w1 = InvokeHook 0x020A $px $py $wheelDown+$w2 = InvokeHook 0x020A $px $py $wheelDown+$w3 = InvokeHook 0x020E $px $py $wheelUp+Check ($w1 -eq 1 -and $w2 -eq 1 -and $w3 -eq 1) 'wheel events must be swallowed'+Check ((DrainEvents).Count -eq 0) 'wheel must not be emitted before coalescing'+(M 'FlushWheel').Invoke($null, [object[]]@($true)) | Out-Null+$e = DrainEvents+Check ($e.Count -eq 1) 'three notches must become one wheel event'+Check ($e[0] -match '"dy":-240') 'vertical deltas must be summed'+Check ($e[0] -match '"dx":120') 'horizontal delta must be kept'+Check ($e[0] -match '"nx":0\.\d+' -and $e[0] -match '"ny":0\.\d+') 'normalized cursor must be reported'+Check (-not ($e[0] -match 'NaN|Infinity')) 'normalized coords must be finite'++# 4) All options off -> absolutely nothing is intercepted+SetOpt 0 0 0+DrainEvents | Out-Null+$w4 = InvokeHook 0x020A $px $py $wheelDown+$r4 = InvokeHook 0x0204 $px $py 0+Check ($w4 -ne 1 -and $r4 -ne 1) 'disabled options must not swallow anything'+(M 'FlushWheel').Invoke($null, [object[]]@($true)) | Out-Null+Check ((DrainEvents).Count -eq 0) 'disabled options must not emit events'++(M 'HookOff').Invoke($null, [object[]]@()) | Out-Null+Write-Output 'POINTER_HOOK_LOGIC_OK'