AnyBot/mobile/trackpad.js

221 lines
9.9 KiB
JavaScript
Raw Normal View History

手機操作電腦補上虛擬觸控板和按鍵列:一指移游標、點一下按、點兩下按住拖曳、兩指捲動或右鍵;Ctrl/Alt/Shift/❖(Mac 是 ⌘⌥⌃⇧)點一下按住、點兩下鎖住;「快捷鍵」面板一格一個名字(下一個分頁、切換視窗、拷貝…);手機「接管」真的讓 Bot 停手。 - mobile/trackpad.js(新):觸控板手勢和按鍵列的狀態,Bot 的電腦(mobile/screen.html,noVNC)和「這台 Mac」(mobile/index.html #v-screen)共用一份;大腦(src/remote.rs)和帳號伺服器(relay/)都在 /trackpad.js 給它。手勢參考 OpenBot 手機 App 的觸控板模式(只借做法,不抄程式碼)。 - Bot 的電腦:接管後下方一排「觸控板|Ctrl Alt Shift ❖|Esc Tab ← ↑ ↓ → ⌫ Del ⏎ Home End PgUp PgDn|快捷鍵 ⌨ 打字」;觸控板經 noVNC 自己的 _handleMouse*(游標自己畫);關掉觸控板回到 noVNC 原本的點哪裡按哪裡。修飾鍵按著時打一個字=那組快捷鍵。 - 接管會鎖住螢幕(新 POST api/box/hold,跟螢幕電腦的 api/sync/screen hold 同一件事):交還、關畫面、手機鎖住或切走就放開,回來再鎖上。以前手機的接管只有點擊或按鍵後 8 秒 Bot 才停。 - 小畫面(GET api/box/thumb?bot=)是那個 Bot 自己的螢幕,對話詳細資訊和需要處理卡帶上 bot(以前一律是共用的)。 - 這台 Mac:大腦的 api/screen/mac 多了 move(移游標)、drag(整條路徑)和點擊的 modifiers(只收 cmd/shift/option/ctrl/alt),組合鍵照用 press_key 的「cmd+tab」;手機頁面換成同一套觸控板、⌘⌥⌃⇧、Mac 版快捷鍵;拿掉「右鍵:開」(兩指點就是右鍵),修好快點兩下會多送一兩下點擊。 - 測試:mobile/trackpad.test.mjs(點一下、滑動、兩指點、兩指捲動、點兩下拖曳、連點、長按、修飾鍵一次/鎖住、快捷鍵的字),cargo test 有 node 時跑它(remote::tests::the_touchpad_turns_fingers_into_mouse_and_keys)。 - 功能地圖 box.md 加 box-phone-drive 和一步驗證;FEATURES.md 加「手機接手:觸控板和按鍵列」。 已驗證: cargo test 877 個全過;relay 的 cargo test 27 個全過;clippy 沒有新警告;node mobile/trackpad.test.mjs 13 項 OK;scratch 手機頁面打開 screen#…&control=1:按鍵列、快捷鍵面板(Alt+Tab 等 18 格)、Ctrl 點一下變亮;「這台 Mac」頁面:⌘ 點兩下鎖住、Mac 版快捷鍵面板。 未驗證: 觸控板動到真的畫面——Bot 的電腦要 Docker(scratch 沒有、不准碰使用者的),這台 Mac 會動到使用者正在用的螢幕,所以兩邊的實際點擊、拖曳、捲動、鎖住都沒有實機跑;這碰到 computer 的路徑(新的 move/drag/修飾鍵),照規定要實機測試加你簽名才能發佈。帳號伺服器要 make update-server 才有 /trackpad.js(沒更新前經帳號開的畫面頁會載不到觸控板)。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha2uBHmbnuWBhNzjbJm
2026-11-22 00:48:31 +00:00
// 虛擬觸控板:在手機上操作一台電腦的畫面,像用筆電的觸控板,不是用手指去戳小小的畫面。
// 用在 Bot 的電腦(screen.html,noVNC)和這台 Mac 的畫面(index.html #v-screen)。
//
// 一指滑動 移動游標(滑得快走得遠)
// 點一下 在游標的位置按左鍵
// 點兩下 連點(點兩下、第二下按住不放再滑:拖曳)
// 兩指滑動 捲動(上下左右)
// 兩指點 右鍵;長按也是右鍵
//
// The page gives a `host` that knows its own screen:
// bounds() → {w, h}: the picture's size, in the same units as the pointer
// move(x, y) the pointer moved (no button change)
// down(x, y, button) a button went down ("left" | "right")
// up(x, y, button) …and up
// click(x, y, button, n) n clicks there
// scroll(x, y, dx, dy) whole wheel notches (positive dy: the page goes down)
// show(x, y) draw the pointer there
// and an element `pad` laid over the picture that takes the touches.
const SLOP = 7; // px a finger may wander and still be a tap
const TAP_MS = 260; // a tap is quicker than this
const DOUBLE_MS = 320; // the second tap of a double tap comes within this
const DOUBLE_SLOP = 40; // …and this near the first
const HOLD_MS = 560; // a press this long without moving is a right click
const NOTCH = 22; // px of two-finger travel per wheel notch
const GAIN = 1.15; // pointer px per finger px, slowly
const ACCEL_FROM = 0.3; // finger px/ms where it starts to speed up
const ACCEL_MAX = 1.6; // at most this much extra gain
export function trackpad(pad, host) {
const pos = { x: 0, y: 0 };
const fingers = new Map();
let mode = null; // "tap" | "move" | "second" | "drag" | "two" | "scroll" | "done"
let lastTap = null; // {t, x, y} of the last single tap (where the finger was)
let holdTimer = 0;
let twoAt = 0, twoMoved = false, acc = { x: 0, y: 0 }, prevMid = null;
let enabled = true;
const now = () => performance.now();
const clamp = () => {
const b = host.bounds();
pos.x = Math.max(0, Math.min(b.w - 1, pos.x));
pos.y = Math.max(0, Math.min(b.h - 1, pos.y));
};
const center = () => {
const b = host.bounds();
pos.x = b.w / 2; pos.y = b.h / 2;
host.show(pos.x, pos.y);
};
const mid = () => {
const a = [...fingers.values()];
return { x: a.reduce((s, f) => s + f.x, 0) / a.length, y: a.reduce((s, f) => s + f.y, 0) / a.length };
};
const stopHold = () => { clearTimeout(holdTimer); holdTimer = 0; };
function onDown(e) {
if (!enabled) return;
e.preventDefault();
try { pad.setPointerCapture(e.pointerId); } catch (_) {}
const t = now();
fingers.set(e.pointerId, { x: e.clientX, y: e.clientY, sx: e.clientX, sy: e.clientY, lx: e.clientX, ly: e.clientY, lt: t, t });
if (fingers.size === 1) {
const near = lastTap && t - lastTap.t < DOUBLE_MS && Math.hypot(e.clientX - lastTap.x, e.clientY - lastTap.y) < DOUBLE_SLOP;
mode = near ? "second" : "tap";
stopHold();
if (!near) holdTimer = setTimeout(() => {
if (mode === "tap") { host.click(pos.x, pos.y, "right", 1); mode = "done"; navigator.vibrate?.(10); }
}, HOLD_MS);
} else if (fingers.size === 2) {
stopHold();
if (mode === "drag") host.up(pos.x, pos.y, "left");
mode = "two"; twoAt = t; twoMoved = false; acc = { x: 0, y: 0 }; prevMid = mid();
}
}
function onMove(e) {
const f = fingers.get(e.pointerId);
if (!f || !enabled) return;
e.preventDefault();
const t = now();
f.x = e.clientX; f.y = e.clientY;
if (fingers.size === 1) {
const far = Math.hypot(f.x - f.sx, f.y - f.sy) > SLOP;
if (mode === "tap" && far) { mode = "move"; stopHold(); }
if (mode === "second" && far) { mode = "drag"; host.down(pos.x, pos.y, "left"); }
if (mode === "move" || mode === "drag") {
const dx = f.x - f.lx, dy = f.y - f.ly, dt = Math.max(1, t - f.lt);
const speed = Math.hypot(dx, dy) / dt;
const gain = GAIN * (1 + Math.min(ACCEL_MAX, Math.max(0, speed - ACCEL_FROM) * 1.2));
pos.x += dx * gain; pos.y += dy * gain;
clamp();
host.move(pos.x, pos.y);
host.show(pos.x, pos.y);
}
} else if (fingers.size === 2 && (mode === "two" || mode === "scroll")) {
const m = mid();
const dx = m.x - prevMid.x, dy = m.y - prevMid.y;
prevMid = m;
if (!twoMoved && Math.hypot(acc.x + dx, acc.y + dy) > SLOP) { twoMoved = true; mode = "scroll"; }
acc.x += dx; acc.y += dy;
if (mode === "scroll") {
// Natural scrolling, like a Mac's trackpad: fingers up, the page goes down.
const nx = Math.trunc(acc.x / NOTCH), ny = Math.trunc(acc.y / NOTCH);
if (nx || ny) {
host.scroll(pos.x, pos.y, -nx, -ny);
acc.x -= nx * NOTCH; acc.y -= ny * NOTCH;
}
}
}
f.lx = f.x; f.ly = f.y; f.lt = t;
}
function onUp(e) {
const f = fingers.get(e.pointerId);
if (!f) return;
e.preventDefault();
const t = now();
fingers.delete(e.pointerId);
stopHold();
if (mode === "tap" && fingers.size === 0 && t - f.t < TAP_MS) {
host.click(pos.x, pos.y, "left", 1);
lastTap = { t, x: f.sx, y: f.sy };
mode = null;
return;
}
if (mode === "second" && fingers.size === 0) {
// The second tap of a double tap: the first click went already, this is the other one.
host.click(pos.x, pos.y, "left", 1);
lastTap = null;
mode = null;
return;
}
if (mode === "drag" && fingers.size === 0) host.up(pos.x, pos.y, "left");
if (mode === "two" && !twoMoved && t - twoAt < TAP_MS * 1.5) {
host.click(pos.x, pos.y, "right", 1);
mode = "done";
}
if (fingers.size === 0) { mode = null; lastTap = null; }
}
pad.addEventListener("pointerdown", onDown);
pad.addEventListener("pointermove", onMove);
pad.addEventListener("pointerup", onUp);
pad.addEventListener("pointercancel", onUp);
// (No page zoom, no text selection, no long-press menu while the fingers are the mouse.)
pad.addEventListener("contextmenu", (e) => e.preventDefault());
pad.style.touchAction = "none";
return {
center,
get pos() { return { ...pos }; },
set enabled(v) { enabled = !!v; fingers.clear(); mode = null; stopHold(); },
get enabled() { return enabled; },
};
}
// ── The key bar: modifier keys you tap instead of hold, and the keys a phone keyboard lacks ──
// A modifier tapped once is held for the next key or click, then lets go; tapped twice it
// stays held (locked) until tapped again. `kind`: "linux" (Ctrl Alt Shift Super) or "mac"
// (⌘ ⌥ ⌃ ⇧).
export const MODS = {
linux: [["ctrl", "Ctrl"], ["alt", "Alt"], ["shift", "Shift"], ["super", "❖"]],
mac: [["cmd", "⌘"], ["option", "⌥"], ["ctrl", "⌃"], ["shift", "⇧"]],
};
export const KEYS = [
["Escape", "Esc"], ["Tab", "Tab"], ["Left", "←"], ["Up", "↑"], ["Down", "↓"], ["Right", "→"],
["BackSpace", "⌫"], ["Delete", "Del"], ["Return", "⏎"], ["Home", "Home"], ["End", "End"], ["PageUp", "PgUp"], ["PageDown", "PgDn"],
];
// The shortcuts people reach for, by name (no one should have to find Ctrl and Tab at once).
export const COMBOS = {
linux: [
["切換視窗", ["alt"], "Tab"], ["下一個分頁", ["ctrl"], "Tab"], ["上一個分頁", ["ctrl", "shift"], "Tab"],
["新分頁", ["ctrl"], "t"], ["關閉分頁", ["ctrl"], "w"], ["網址列", ["ctrl"], "l"],
["上一頁", ["alt"], "Left"], ["下一頁", ["alt"], "Right"], ["重新整理", ["ctrl"], "r"],
["拷貝", ["ctrl"], "c"], ["貼上", ["ctrl"], "v"], ["剪下", ["ctrl"], "x"],
["全選", ["ctrl"], "a"], ["復原", ["ctrl"], "z"], ["重做", ["ctrl", "shift"], "z"],
["尋找", ["ctrl"], "f"], ["存檔", ["ctrl"], "s"], ["全螢幕", [], "F11"],
],
mac: [
["切換 App", ["cmd"], "Tab"], ["下一個分頁", ["ctrl"], "Tab"], ["上一個分頁", ["ctrl", "shift"], "Tab"],
["新分頁", ["cmd"], "t"], ["關閉分頁", ["cmd"], "w"], ["網址列", ["cmd"], "l"],
["上一頁", ["cmd"], "["], ["下一頁", ["cmd"], "]"], ["重新整理", ["cmd"], "r"],
["拷貝", ["cmd"], "c"], ["貼上", ["cmd"], "v"], ["剪下", ["cmd"], "x"],
["全選", ["cmd"], "a"], ["復原", ["cmd"], "z"], ["重做", ["cmd", "shift"], "z"],
["尋找", ["cmd"], "f"], ["存檔", ["cmd"], "s"], ["Spotlight", ["cmd"], "space"],
],
};
const MOD_SIGN = { ctrl: "⌃", alt: "⌥", option: "⌥", shift: "⇧", super: "❖", cmd: "⌘" };
const MOD_WORD = { ctrl: "Ctrl", alt: "Alt", shift: "Shift", super: "Super" };
const KEY_SIGN = { Tab: "⇥", Left: "←", Right: "→", Up: "↑", Down: "↓", space: "空白" };
// How a shortcut is written under its name: the Mac's signs (⌘⇧Z), or Linux's words (Ctrl+Shift+Z).
export function comboLabel(mods, key, kind = "mac") {
const k = kind === "linux" && key === "Tab" ? "Tab" : (KEY_SIGN[key] || (key.length === 1 ? key.toUpperCase() : key));
return kind === "linux" ? [...mods.map((m) => MOD_WORD[m] || m), k].join("+") : mods.map((m) => MOD_SIGN[m] || m).join("") + k;
}
// The bar's state: which modifiers are held for the next key ("once") or locked ("lock").
export function modState(onChange) {
const held = new Map();
let lastTap = { m: "", t: 0 };
return {
tap(m) {
const t = performance.now();
const was = held.get(m);
if (was === "lock") held.delete(m);
else if (was === "once" && lastTap.m === m && t - lastTap.t < 400) held.set(m, "lock");
else if (was === "once") held.delete(m);
else held.set(m, "once");
lastTap = { m, t };
onChange();
},
get(m) { return held.get(m) || ""; },
list() { return [...held.keys()]; },
// After a key or a click: the once-held let go, the locked stay.
used() { let any = false; for (const [m, v] of held) if (v === "once") { held.delete(m); any = true; } if (any) onChange(); },
};
}