手機操作電腦補上虛擬觸控板和按鍵列:一指移游標、點一下按、點兩下按住拖曳、兩指捲動或右鍵;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
This commit is contained in:
王性驊 2026-11-22 08:48:31 +08:00
parent 5845986227
commit 33b3fb8cab
8 changed files with 631 additions and 60 deletions

View File

@ -956,7 +956,15 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。
- 票會出現在網址裡(瀏覽紀錄、記錄檔),所以:網頁一打開就把連結裡的票換成新的,連結裡那張當場作廢;每次斷線重連前再換一張;票只在發出後 10 分鐘內能開新的連線,已經連上的畫面只要當初要票的手機還登入著(或那台電腦還在帳號裡)就一直開著。斷線後 10 分鐘內回來換得到新票;超過 10 分鐘,手機網頁用自己的登入重新要,電腦開的網頁則顯示「這個畫面連結已過期」(不再一直重試),回 AnyBot 再開一次就好。「登出所有裝置」會讓所有畫面立刻斷掉。 - 票會出現在網址裡(瀏覽紀錄、記錄檔),所以:網頁一打開就把連結裡的票換成新的,連結裡那張當場作廢;每次斷線重連前再換一張;票只在發出後 10 分鐘內能開新的連線,已經連上的畫面只要當初要票的手機還登入著(或那台電腦還在帳號裡)就一直開著。斷線後 10 分鐘內回來換得到新票;超過 10 分鐘,手機網頁用自己的登入重新要,電腦開的網頁則顯示「這個畫面連結已過期」(不再一直重試),回 AnyBot 再開一次就好。「登出所有裝置」會讓所有畫面立刻斷掉。
- 同一個網路的手機(不經帳號伺服器):同一個網頁,連 AnyBot 自己的 `/api/vnc`。 - 同一個網路的手機(不經帳號伺服器):同一個網頁,連 AnyBot 自己的 `/api/vnc`。
- 這台電腦自己的 Bot 的電腦:直接開它的 noVNC。 - 這台電腦自己的 Bot 的電腦:直接開它的 noVNC。
- **網頁**:最上面是返回、電腦名稱、狀態(即時觀看/你在操作)和「接管/交還給 Bot」。預設只看,按「接管」才會把你的滑鼠鍵盤送過去;需要處理卡片的「接管」直接打開接管。接管時有「打字」:打中文或任何語言(貼進目前的視窗,就是畫面上這個螢幕:那個 Bot 的螢幕沒開、看到的是共用桌面時就打在共用桌面;畫面關掉後打的字不會另外開一個看不到的螢幕),還有 Enter、Esc、Tab、⌫。斷線會自己重連(每次用新的票)。 - **網頁**:最上面是返回、電腦名稱、狀態(即時觀看/你在操作)和「接管/交還給 Bot」。預設只看,按「接管」才會把你的滑鼠鍵盤送過去;需要處理卡片的「接管」直接打開接管。接管時下方出現按鍵列(見下面「手機接手:觸控板和按鍵列」),其中「⌨ 打字」打中文或任何語言(貼進目前的視窗,就是畫面上這個螢幕:那個 Bot 的螢幕沒開、看到的是共用桌面時就打在共用桌面;畫面關掉後打的字不會另外開一個看不到的螢幕)。斷線會自己重連(每次用新的票)。
- **手機接手:觸控板和按鍵列**(照 OpenBot 手機 App 的觸控板模式;`mobile/trackpad.js`,Bot 的電腦和「這台 Mac」共用一份):
- 預設是**虛擬觸控板**,像筆電的觸控板,不用手指去戳縮小的畫面:一指滑動移游標(滑得快走得遠),點一下在游標的位置按左鍵,點兩下是連點,點兩下第二下按住再滑是拖曳,兩指滑動捲動(自然捲動:手指往上、頁面往下;Bot 的電腦上下左右都可以),兩指點一下或長按是右鍵。游標是畫面上自己畫的白色箭頭,打開時在正中間。頭三次接手時下方提示一次手勢。按鍵列最前面的「觸控板」關掉,改成點哪裡按哪裡(noVNC 自己的觸控,或「這台 Mac」的點一下左鍵、長按右鍵、快點兩下雙擊);選擇記在這支手機。
- **修飾鍵不用按住**:Bot 的電腦是 Ctrl、Alt、Shift、❖(Super),這台 Mac 是 ⌘ ⌥ ⌃ ⇧。點一下變淡色=下一個鍵或下一次點擊時按著,用過就放開;點兩下變實心=鎖住,直到再點一下。所以 Ctrl+Tab 是點 Ctrl 再點 Tab,⌘+點擊是點 ⌘ 再在觸控板點一下。
- 手機鍵盤沒有的鍵:Esc、Tab、← ↑ ↓ →、⌫、Del、⏎、Home、End、PgUp、PgDn(一排,左右滑)。
- **快捷鍵**面板:一格一個名字,下面寫按法——切換視窗/切換 App、下一個分頁、上一個分頁、新分頁、關閉分頁、網址列、上一頁、下一頁、重新整理、拷貝、貼上、剪下、全選、復原、重做、尋找、存檔、全螢幕(Linux)/Spotlight(Mac)。Linux 寫字(Ctrl+Shift+Tab),Mac 寫符號(⌘⇧Z)。
- 「⌨ 打字」:打字列;修飾鍵按著時只打一個字就送那組快捷鍵(點 Ctrl、打 c=Ctrl+C),不是打出那個字。
- **接管會鎖住那個螢幕**:手機按「接管」,Bot 在那個螢幕上的滑鼠鍵盤步驟等你(跟電腦版和需要處理卡的接管一樣),按「交還給 Bot」、關掉畫面、手機鎖住或切到別的 App 就放開,回來還在接管就再鎖上。以前手機的接管只把畫面切成可操作,Bot 只在你點擊或按鍵後停 8 秒,單純移動游標時它照做。
- 「這台 Mac」的觸控板經大腦的 `api/screen/mac`:移動游標(最多每 150 毫秒送一次)、拖曳放開時整條路徑送出、點擊和組合鍵帶著修飾鍵。
- **你在操作時 Bot 會等**:你點擊或按鍵後 8 秒內,在你正在看的那個螢幕上做事的 Bot,滑鼠鍵盤操作會收到「使用者正在自己操作這台電腦」(別的螢幕上的 Bot 照做)。開著看畫面的螢幕不算閒置、不會被收掉,不管從哪裡開的(第 13 版起 Bot 的電腦自己看有沒有人連著)。不用另外按什麼;停下 8 秒它就繼續。需要處理卡片的「接管」會讓 Bot 一直等,直到你按「我完成了」或「跳過」。 - **你在操作時 Bot 會等**:你點擊或按鍵後 8 秒內,在你正在看的那個螢幕上做事的 Bot,滑鼠鍵盤操作會收到「使用者正在自己操作這台電腦」(別的螢幕上的 Bot 照做)。開著看畫面的螢幕不算閒置、不會被收掉,不管從哪裡開的(第 13 版起 Bot 的電腦自己看有沒有人連著)。不用另外按什麼;停下 8 秒它就繼續。需要處理卡片的「接管」會讓 Bot 一直等,直到你按「我完成了」或「跳過」。
- **VNC 密碼不出大腦**:大腦用 Bot 的電腦自己的 VNC 密碼登入,給看的人的是「不用密碼」;能連到這裡的人已經過帳號伺服器(或手機密碼)。 - **VNC 密碼不出大腦**:大腦用 Bot 的電腦自己的 VNC 密碼登入,給看的人的是「不用密碼」;能連到這裡的人已經過帳號伺服器(或手機密碼)。
- 以前的做法(每 0.45~1 秒拍一張 1 MB 的圖、解開再壓、經過帳號伺服器傳;點擊另走一條路)已經拆掉。 - 以前的做法(每 0.45~1 秒拍一張 1 MB 的圖、解開再壓、經過帳號伺服器傳;點擊另走一條路)已經拆掉。
@ -2315,8 +2323,9 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開)
- 看電腦畫面: - 看電腦畫面:
- 「Bot 的電腦」每秒更新一次畫面;在休眠時按「叫醒」。 - 「Bot 的電腦」每秒更新一次畫面;在休眠時按「叫醒」。
- 「這台 Mac」要先在設定裡打開才會出現。 - 「這台 Mac」要先在設定裡打開才會出現。
- 操作方式:點一下是左鍵;長按是右鍵;點兩下是雙擊;「右鍵:開」之後每次點都是右鍵。 - 操作方式:預設是虛擬觸控板,下面一排按鍵列和「快捷鍵」面板(見「手機接手:觸控板和按鍵列」);關掉觸控板時點一下是左鍵、長按是右鍵、快點兩下是雙擊(以前點兩下會多送一兩下點擊;「右鍵:開」拿掉了,兩指點就是右鍵)。
- 「⌨︎ 打字」可以打中文,會打進目前的視窗;還有 Enter、Esc、Tab、⌫ 和捲動按鈕。 - 「⌨ 打字」可以打中文,會打進目前的視窗。
- 對話詳細資訊、需要處理卡上的小畫面是那個 Bot 自己的螢幕(以前一律是共用的那個)。
- 右上角頭像:傳送到其他裝置(只有擁有者有,見下面「傳送到其他裝置」)、通知(開關、要通知哪幾種、送一則測試通知;開關顯示的是帳號伺服器上這支手機的狀態,按下去就照它顯示的開或關——帳號伺服器已經沒有這支手機的訂閱時顯示「關閉中」,打開會重新訂閱;連不上帳號伺服器時照這支手機上的設定,種類和測試等連上再改;直接連線的手機會說明收不到推播;iPhone 要先加入主畫面)、安裝成 App(還沒裝時才有)、切換到別台 AnyBot、登出這支手機。 - 右上角頭像:傳送到其他裝置(只有擁有者有,見下面「傳送到其他裝置」)、通知(開關、要通知哪幾種、送一則測試通知;開關顯示的是帳號伺服器上這支手機的狀態,按下去就照它顯示的開或關——帳號伺服器已經沒有這支手機的訂閱時顯示「關閉中」,打開會重新訂閱;連不上帳號伺服器時照這支手機上的設定,種類和測試等連上再改;直接連線的手機會說明收不到推播;iPhone 要先加入主畫面)、安裝成 App(還沒裝時才有)、切換到別台 AnyBot、登出這支手機。
- 手機做的事都交給電腦版原本的功能處理(同一套規則、同一份資料),不是另外寫一套。 - 手機做的事都交給電腦版原本的功能處理(同一套規則、同一份資料),不是另外寫一套。
- 團隊(用帳號伺服器分享時)權限跟以前一樣: - 團隊(用帳號伺服器分享時)權限跟以前一樣:

View File

@ -8,6 +8,7 @@
- `box-desktop` 畫面(「開啟電腦」):下方工作列由左到右是「應用程式」選單、「瀏覽器」、「檔案管理員」、「終端機」、開著的視窗、時鐘;桌面按右鍵也有應用程式選單(瀏覽器、檔案管理員、終端機、文字編輯器、影像檢視器,Bot 裝的程式在「其他」)。瀏覽器開機就開好(第一次是說明頁),跟 Bot 的瀏覽器工具是同一個、登入共用。檔案管理員側邊欄的「下載」是 Bot 下載的檔案;檔案按兩下用對的程式開。 - `box-desktop` 畫面(「開啟電腦」):下方工作列由左到右是「應用程式」選單、「瀏覽器」、「檔案管理員」、「終端機」、開著的視窗、時鐘;桌面按右鍵也有應用程式選單(瀏覽器、檔案管理員、終端機、文字編輯器、影像檢視器,Bot 裝的程式在「其他」)。瀏覽器開機就開好(第一次是說明頁),跟 Bot 的瀏覽器工具是同一個、登入共用。檔案管理員側邊欄的「下載」是 Bot 下載的檔案;檔案按兩下用對的程式開。
- `box-manage` 管理:狀態、更新、自動更新、快照、重設、磁碟;終端機與環境密鑰;在哪裡執行(Docker 主機、容器隔離)。 - `box-manage` 管理:狀態、更新、自動更新、快照、重設、磁碟;終端機與環境密鑰;在哪裡執行(Docker 主機、容器隔離)。
- `box-account-view` 從帳號看畫面:手機或另一台電腦經帳號伺服器看 Bot 電腦的畫面,只要開著就不會斷。 - `box-account-view` 從帳號看畫面:手機或另一台電腦經帳號伺服器看 Bot 電腦的畫面,只要開著就不會斷。
- `box-phone-drive` 手機接手(畫面右上「接管」):Bot 在那個螢幕的步驟等你(「交還給 Bot」、關掉畫面、手機鎖住或切走都放開)。預設是虛擬觸控板:一指移游標、點一下按、點兩下按住拖曳、兩指捲動、兩指點或長按右鍵(下方「觸控板」關掉改成點哪裡按哪裡)。下方按鍵列:Ctrl、Alt、Shift、❖ 點一下按住給下一個鍵或點擊,點兩下鎖住;Esc、Tab、方向鍵、⌫、Del、⏎、Home、End、PgUp、PgDn;「快捷鍵」一格格寫名字(切換視窗 Alt+Tab、下一個分頁 Ctrl+Tab、拷貝、貼上…);「⌨ 打字」可打中文,按住修飾鍵打一個字就是那組快捷鍵。手機看「這台 Mac」(要開「從手機看這台電腦的螢幕並操作」)是同一套,修飾鍵是 ⌘⌥⌃⇧。
## 使用者怎麼到 ## 使用者怎麼到
@ -26,6 +27,7 @@
- **沒有 Docker 時**(covers `box-machine`、`box-manage`):首頁點「電腦」。指令:`$CTL phone wait-text 0/1 --in '#quick' && $CTL phone click '#quick [data-q="computers"]' && $CTL phone wait-text '沒有 Docker' && $CTL phone wait-text '沒有 Docker,現在沒有這台電腦' && $CTL phone shot box-nodocker && $CTL api GET '/api/state?since=0' --jq '{box, box_available}' && $CTL api GET /api/settings --jq '.box | {state, available, version, runtime, snapshot, auto_update}'`。看到:「驗證小幫手 的電腦 · 沒有 Docker」,沒有畫面小圖;按鈕列、「更新 Bot 的電腦:沒有 Docker,現在沒有這台電腦」「自動更新:關」「容器隔離:標準」(不說主機有沒有 gVisor)「上次快照:還沒有」「重設電腦」;API 是 box「沒有 Docker」、available false、runtime runc。 - **沒有 Docker 時**(covers `box-machine`、`box-manage`):首頁點「電腦」。指令:`$CTL phone wait-text 0/1 --in '#quick' && $CTL phone click '#quick [data-q="computers"]' && $CTL phone wait-text '沒有 Docker' && $CTL phone wait-text '沒有 Docker,現在沒有這台電腦' && $CTL phone shot box-nodocker && $CTL api GET '/api/state?since=0' --jq '{box, box_available}' && $CTL api GET /api/settings --jq '.box | {state, available, version, runtime, snapshot, auto_update}'`。看到:「驗證小幫手 的電腦 · 沒有 Docker」,沒有畫面小圖;按鈕列、「更新 Bot 的電腦:沒有 Docker,現在沒有這台電腦」「自動更新:關」「容器隔離:標準」(不說主機有沒有 gVisor)「上次快照:還沒有」「重設電腦」;API 是 box「沒有 Docker」、available false、runtime runc。
- **聊天裡的電腦**(covers `box-machine`):Bot 在自己的電腦寫檔,再看對話詳細資訊的「電腦」。指令:`$CTL phone click '[data-back]' && $CTL phone click '.row[data-bot="1"]' && $CTL phone send '[[call shell {"command":"echo hi > box.txt; ls"}]]' && $CTL phone wait-text '的電腦] box.txt' && $CTL phone click '#b-chatmore' && $CTL phone click '#sheet-in .opt' --text 對話詳細資訊 && $CTL phone click '[data-tab="computer"]' && $CTL phone wait-text 沒有畫面 --in '#details' && $CTL botfile box.txt && $CTL api GET /api/bots/1 --jq '[.messages[].tools[]? | .status]'`。看到:沒有卡片就跑完(自己的電腦不用問),回覆裡有 box.txt;「電腦」分頁是「驗證小幫手 的電腦 · 沒有 Docker」「沒有畫面」;檔案內容 hi。 - **聊天裡的電腦**(covers `box-machine`):Bot 在自己的電腦寫檔,再看對話詳細資訊的「電腦」。指令:`$CTL phone click '[data-back]' && $CTL phone click '.row[data-bot="1"]' && $CTL phone send '[[call shell {"command":"echo hi > box.txt; ls"}]]' && $CTL phone wait-text '的電腦] box.txt' && $CTL phone click '#b-chatmore' && $CTL phone click '#sheet-in .opt' --text 對話詳細資訊 && $CTL phone click '[data-tab="computer"]' && $CTL phone wait-text 沒有畫面 --in '#details' && $CTL botfile box.txt && $CTL api GET /api/bots/1 --jq '[.messages[].tools[]? | .status]'`。看到:沒有卡片就跑完(自己的電腦不用問),回覆裡有 box.txt;「電腦」分頁是「驗證小幫手 的電腦 · 沒有 Docker」「沒有畫面」;檔案內容 hi。
- **畫面、更新、重設**(covers `box-desktop`、`box-manage`):指令:要開視窗——`$CTL stop && ABV_ALLOW_WINDOW=1 $CTL desktop-shot box ANYBOT_SHOT_REAL=1 ANYBOT_SHOT_VIEW=computers`;畫面本身走不到——要 Docker(scratch 不准碰使用者的 Docker、Lima)。看到:設定 › 電腦「Bot 的電腦」一段沒有 Docker 時的樣子;桌面、工作列、檔案視窗、更新排隊靠下面要 Docker 的實機測試。`make update-box` 也不跑:它找的是裝好的那台 AnyBot。 - **畫面、更新、重設**(covers `box-desktop`、`box-manage`):指令:要開視窗——`$CTL stop && ABV_ALLOW_WINDOW=1 $CTL desktop-shot box ANYBOT_SHOT_REAL=1 ANYBOT_SHOT_VIEW=computers`;畫面本身走不到——要 Docker(scratch 不准碰使用者的 Docker、Lima)。看到:設定 › 電腦「Bot 的電腦」一段沒有 Docker 時的樣子;桌面、工作列、檔案視窗、更新排隊靠下面要 Docker 的實機測試。`make update-box` 也不跑:它找的是裝好的那台 AnyBot。
- **手機接手的按鍵列**(covers `box-phone-drive`):打開畫面頁接手(scratch 沒有 Docker,連不上畫面,看得到列)。指令:`$CTL phone js 'location.href = "screen#lan=1&control=1&bot=1"; 1' && $CTL phone wait-text 快捷鍵 --in '#bar' && $CTL phone click '#bar button' --text 快捷鍵 && $CTL phone click '#bar button[data-mod="ctrl"]' && $CTL phone shot box-drive && node mobile/trackpad.test.mjs`。看到:列上「觸控板、Ctrl、Alt、Shift、❖、Esc、Tab、←…」,快捷鍵面板「切換視窗 Alt+Tab」等 18 格,Ctrl 變亮;手勢測試全部 OK。觸控板動到真的畫面走不到——要 Docker。
- **從帳號看畫面**(covers `box-account-view`):指令:走不到——要帳號伺服器和 Docker。看到:最接近的真路是 `relay/` 的 `cargo test` 和 `cargo test remote::`(畫面的票)。 - **從帳號看畫面**(covers `box-account-view`):指令:走不到——要帳號伺服器和 Docker。看到:最接近的真路是 `relay/` 的 `cargo test` 和 `cargo test remote::`(畫面的票)。
- 自動測試:`cargo test cloudbox::`、`cargo test tools::`、`cargo test remote::`;要 Docker 的實機測試(會建一台 box):`cargo test cloudbox:: -- --ignored`(`box_end_to_end`、`each_bot_has_its_own_screen`、`box_update_keeps_files`…),只在有 Docker、不是使用者正在用的那台上跑。 - 自動測試:`cargo test cloudbox::`、`cargo test tools::`、`cargo test remote::`;要 Docker 的實機測試(會建一台 box):`cargo test cloudbox:: -- --ignored`(`box_end_to_end`、`each_bot_has_its_own_screen`、`box_update_keeps_files`…),只在有 Docker、不是使用者正在用的那台上跑。

View File

@ -570,8 +570,26 @@ textarea.field{min-height:96px;line-height:1.5}
.stage .msg{color:var(--on-stage);font-size:var(--fs-ui);padding:20px;text-align:center} .stage .msg{color:var(--on-stage);font-size:var(--fs-ui);padding:20px;text-align:center}
.stage .tapdot{position:absolute;width:26px;height:26px;margin:-13px 0 0 -13px;border-radius:50%;background:color-mix(in srgb,var(--accent) 53%,transparent);pointer-events:none;animation:fade .6s forwards} .stage .tapdot{position:absolute;width:26px;height:26px;margin:-13px 0 0 -13px;border-radius:50%;background:color-mix(in srgb,var(--accent) 53%,transparent);pointer-events:none;animation:fade .6s forwards}
@keyframes fade{to{opacity:0;transform:scale(1.8)}} @keyframes fade{to{opacity:0;transform:scale(1.8)}}
.tools{display:flex;gap:6px;padding:8px 10px calc(var(--safe-b) + 8px);overflow-x:auto;flex:none;background:var(--chrome)} .tools{display:flex;gap:6px;padding:8px 10px calc(var(--safe-b) + 8px);overflow-x:auto;flex:none;background:var(--chrome);scrollbar-width:none}
.tools .btn{flex:none} .tools::-webkit-scrollbar{display:none}
.tools .btn{flex:none;height:36px;min-width:40px;padding:0 10px;border-radius:var(--r-m)}
.tools .sep{width:1px;background:var(--line);margin:4px 2px;flex:none}
.tools .btn.once{background:color-mix(in srgb,var(--accent) 18%,transparent);color:var(--accent-ink)}
.tools .btn.lock{background:var(--accent);color:var(--on-color)}
.tools .btn.on{background:var(--primary);color:var(--on-primary)}
/* 虛擬觸控板 over this Mac's screen: a layer that takes the fingers, and the pointer drawn on it. */
.stagewrap{flex:1;min-height:0;position:relative;display:flex}
.pad{position:absolute;inset:0;display:none;touch-action:none;-webkit-user-select:none;user-select:none;-webkit-touch-callout:none}
.pad.on{display:block}
.ptr{position:absolute;width:20px;height:20px;margin:-2px 0 0 -3px;pointer-events:none;display:none;filter:drop-shadow(0 1px 2px #0009)}
.ptr.on{display:block}
.padtip{position:absolute;left:50%;bottom:12px;transform:translateX(-50%);max-width:calc(100% - 24px);background:var(--elev);border-radius:var(--r-l);padding:9px 12px;font-size:var(--fs-small);line-height:1.6;box-shadow:0 2px 10px -2px var(--shade);pointer-events:none;opacity:0;transition:opacity .3s}
.padtip.on{opacity:1}
.padtip b{font-weight:600;color:var(--accent-ink)}
.combos{display:none;grid-template-columns:repeat(3,1fr);gap:6px;padding:10px;background:var(--chrome);max-height:40vh;overflow-y:auto;flex:none}
.combos.on{display:grid}
.combos .btn{height:auto;min-height:48px;flex-direction:column;gap:2px;border-radius:var(--r-l);padding:6px 4px}
.combos .btn small{color:var(--text3);font-size:var(--fs-caption);font-weight:400}
.typebar{display:none;gap:6px;padding:8px 10px 0;background:var(--chrome)} .typebar{display:none;gap:6px;padding:8px 10px 0;background:var(--chrome)}
.typebar.on{display:flex} .typebar.on{display:flex}
.typebar input{flex:1} .typebar input{flex:1}
@ -746,18 +764,10 @@ button,.row,.ib,.island,.opt,.chip,.tab,label.sw,[role="button"]{-webkit-user-se
<!-- this Mac's screen --> <!-- this Mac's screen -->
<section class="view" id="v-screen"> <section class="view" id="v-screen">
<div class="bar"><button class="ib" data-back title="返回" aria-label=""></button><h1>這台 Mac</h1><span class="pill" id="screen-live"></span></div> <div class="bar"><button class="ib" data-back title="返回" aria-label=""></button><h1>這台 Mac</h1><span class="pill" id="screen-live"></span></div>
<div class="stage" id="stage"><div class="msg">載入中…</div></div> <div class="stagewrap"><div class="stage" id="stage"><div class="msg">載入中…</div></div><div class="pad" id="mac-pad"></div><svg class="ptr" id="mac-ptr" viewBox="0 0 20 20"><path d="M3 2 L3 16 L7 12.5 L9.6 18 L12 17 L9.5 11.6 L14.5 11.6 Z" fill="#fff" stroke="#111" stroke-width="1.2" stroke-linejoin="round"/></svg><div class="padtip" id="mac-tip"></div></div>
<div class="combos" id="mac-combos"></div>
<div class="typebar" id="typebar"><input class="field" id="typein" placeholder="要打的字(會打進目前的視窗)" enterkeyhint="send"><button class="btn main" id="b-type">送出</button></div> <div class="typebar" id="typebar"><input class="field" id="typein" placeholder="要打的字(會打進目前的視窗)" enterkeyhint="send"><button class="btn main" id="b-type">送出</button></div>
<div class="tools"> <div class="tools" id="mac-bar"></div>
<button class="btn sm" id="k-type">打字</button>
<button class="btn sm" data-key="Return">Enter</button>
<button class="btn sm" data-key="Escape">Esc</button>
<button class="btn sm" data-key="Tab">Tab</button>
<button class="btn sm" data-key="BackSpace">刪除</button>
<button class="btn sm" data-scroll="up">↑ 捲動</button>
<button class="btn sm" data-scroll="down">↓ 捲動</button>
<button class="btn sm" id="k-right">右鍵:關</button>
</div>
</section> </section>
</div> </div>
<div class="toast" id="toast"></div> <div class="toast" id="toast"></div>
@ -1134,7 +1144,7 @@ function draw(v, arg) {
else if (v === "botset") renderBotset(arg.bot); else if (v === "botset") renderBotset(arg.bot);
else if (v === "list") renderList(arg); else if (v === "list") renderList(arg);
else if (v === "page") openPage(arg.id, arg.rev); else if (v === "page") openPage(arg.id, arg.rev);
else if (v === "screen") startFrames(); else if (v === "screen") { startFrames(); macTools(); }
} }
const cur = () => NAV[NAV.length - 1] || {v: "home", arg: {}}; const cur = () => NAV[NAV.length - 1] || {v: "home", arg: {}};
@ -2218,7 +2228,7 @@ function renderDock() {
const own = /的電腦$/.test(a.computer || "") && S.boxOn; const own = /的電腦$/.test(a.computer || "") && S.boxOn;
$("ask").innerHTML = `<div class="ask"><div class="q">${ic("hand", 16)} 需要處理 · ${esc(a.computer || "")}</div><div class="why">${esc(a.reason)}</div>${own ? `<img class="thumb" id="hand-thumb" alt="">` : ""}<div class="btns"><button class="btn" data-screen="1">${ic("monitor", 15)} 接管</button><button class="btn main" data-a="once">我完成了</button><button class="btn" data-a="reject">跳過</button></div></div>`; $("ask").innerHTML = `<div class="ask"><div class="q">${ic("hand", 16)} 需要處理 · ${esc(a.computer || "")}</div><div class="why">${esc(a.reason)}</div>${own ? `<img class="thumb" id="hand-thumb" alt="">` : ""}<div class="btns"><button class="btn" data-screen="1">${ic("monitor", 15)} 接管</button><button class="btn main" data-a="once">我完成了</button><button class="btn" data-a="reject">跳過</button></div></div>`;
$("ask").querySelector("[data-screen]").onclick = () => openBox(true); $("ask").querySelector("[data-screen]").onclick = () => openBox(true);
if (own) { const load = () => boxThumb($("hand-thumb")); load(); thumbTimer = setInterval(load, 3000); } if (own) { const load = () => boxThumb($("hand-thumb"), b.id); load(); thumbTimer = setInterval(load, 3000); }
} else { } else {
// 智慧模式開著時主按鈕是「這輪都准」(这一轮同类不再问,比「一律允許」小一格);否则主按鈕是「允許一次」。 // 智慧模式開著時主按鈕是「這輪都准」(这一轮同类不再问,比「一律允許」小一格);否则主按鈕是「允許一次」。
const yes = a.can_scope ? `<button class="btn main" data-a="scope">這輪都准</button><button class="btn" data-a="once">允許一次</button>` : `<button class="btn main" data-a="once">允許一次</button>`; const yes = a.can_scope ? `<button class="btn main" data-a="scope">這輪都准</button><button class="btn" data-a="once">允許一次</button>` : `<button class="btn main" data-a="once">允許一次</button>`;
@ -2321,10 +2331,11 @@ function renderDockRest(b) {
renderSendBtn(); renderSendBtn();
} }
const BOXIMG = {}; const BOXIMG = {};
async function boxThumb(img) { // (Of this bot's own screen when it has one open; else the shared one.)
async function boxThumb(img, bot) {
if (!img) return; if (!img) return;
try { try {
const r = await api(base() + "api/box/thumb", {raw: true}); const r = await api(base() + "api/box/thumb" + (bot ? "?bot=" + bot : ""), {raw: true});
if (!r.ok) throw new Error(); if (!r.ok) throw new Error();
const u = URL.createObjectURL(await safeBlob(r)); const u = URL.createObjectURL(await safeBlob(r));
if (BOXIMG.last) URL.revokeObjectURL(BOXIMG.last); if (BOXIMG.last) URL.revokeObjectURL(BOXIMG.last);
@ -2824,7 +2835,7 @@ function wireDetails(b, d) {
ids.has(id) ? ids.delete(id) : ids.add(id); ids.has(id) ? ids.delete(id) : ids.add(id);
if (await act("bot", {bot: b.id, key: "members", value: [...ids]}, "已更新成員")) { delete S.detail[b.id]; renderDetails(b.id, S.tab); } if (await act("bot", {bot: b.id, key: "members", value: [...ids]}, "已更新成員")) { delete S.detail[b.id]; renderDetails(b.id, S.tab); }
})); }));
const t = $("box-thumb"); if (t) boxThumb(t); const t = $("box-thumb"); if (t) boxThumb(t, b.id);
el.querySelectorAll(".files [data-img]").forEach(async (f) => { if (f.querySelector("img")) return; try { const u = await fileUrl(f.dataset.file); f.innerHTML = `<img src="${u}">`; } catch (_) {} }); el.querySelectorAll(".files [data-img]").forEach(async (f) => { if (f.querySelector("img")) return; try { const u = await fileUrl(f.dataset.file); f.innerHTML = `<img src="${u}">`; } catch (_) {} });
el.querySelectorAll(".files [data-img]").forEach((f) => f.onclick = async () => { try { window.open(await fileUrl(f.dataset.file), "_blank"); } catch (e) { toast(e.message); } }); el.querySelectorAll(".files [data-img]").forEach((f) => f.onclick = async () => { try { window.open(await fileUrl(f.dataset.file), "_blank"); } catch (e) { toast(e.message); } });
} }
@ -4068,11 +4079,11 @@ async function frames(run) {
try { try {
const r = await api(base() + "api/screen/mac", {raw: true}); const r = await api(base() + "api/screen/mac", {raw: true});
if (S.frameRun !== run) return; if (S.frameRun !== run) return;
if (!r.ok) { const v = await r.json().catch(() => ({})); $("stage").innerHTML = `<div class="msg">${esc(v.error || "看不到畫面")}</div>`; $("screen-live").textContent = ""; await nap(1500); continue; } if (!r.ok) { const v = await r.json().catch(() => ({})); $("stage").innerHTML = `<div class="msg">${esc(v.error || "看不到畫面")}</div>`; $("screen-live").textContent = ""; macShowPad(); await nap(1500); continue; }
S.size = (r.headers.get("X-Size") || "0x0").split("x").map(Number); S.size = (r.headers.get("X-Size") || "0x0").split("x").map(Number);
const url = URL.createObjectURL(await safeBlob(r)); const url = URL.createObjectURL(await safeBlob(r));
let img = $("stage").querySelector("img"); let img = $("stage").querySelector("img");
if (!img) { $("stage").innerHTML = ""; img = document.createElement("img"); img.draggable = false; $("stage").appendChild(img); bindStage(img); } if (!img) { $("stage").innerHTML = ""; img = document.createElement("img"); img.draggable = false; $("stage").appendChild(img); bindStage(img); img.onload = () => { img.onload = null; macShowPad(); }; }
img.src = url; if (lastUrl) URL.revokeObjectURL(lastUrl); lastUrl = url; img.src = url; if (lastUrl) URL.revokeObjectURL(lastUrl); lastUrl = url;
$("screen-live").innerHTML = `<span class="live"></span>即時`; $("screen-live").innerHTML = `<span class="live"></span>即時`;
await nap(700); await nap(700);
@ -4084,25 +4095,131 @@ function point(img, e) {
const w = S.size[0] || img.naturalWidth, h = S.size[1] || img.naturalHeight; const w = S.size[0] || img.naturalWidth, h = S.size[1] || img.naturalHeight;
return {x: Math.round((e.clientX - r.left) / r.width * w), y: Math.round((e.clientY - r.top) / r.height * h), cx: e.clientX - $("stage").getBoundingClientRect().left, cy: e.clientY - $("stage").getBoundingClientRect().top}; return {x: Math.round((e.clientX - r.left) / r.width * w), y: Math.round((e.clientY - r.top) / r.height * h), cx: e.clientX - $("stage").getBoundingClientRect().left, cy: e.clientY - $("stage").getBoundingClientRect().top};
} }
// Without the touchpad: a tap clicks where it lands, a long press right-clicks, two quick taps
// are a double click.
function bindStage(img) { function bindStage(img) {
let pressTimer = null, long = false; let pressTimer = null, long = false, last = 0;
img.addEventListener("pointerdown", (e) => { long = false; pressTimer = setTimeout(() => { long = true; tap(img, e, "right"); }, 550); }); img.addEventListener("pointerdown", (e) => { if (MAC.padOn) return; long = false; pressTimer = setTimeout(() => { long = true; tap(img, e, "right"); }, 550); });
img.addEventListener("pointerup", (e) => { clearTimeout(pressTimer); if (!long) tap(img, e, S.right ? "right" : "left"); }); img.addEventListener("pointerup", (e) => {
clearTimeout(pressTimer);
if (MAC.padOn || long) return;
const t = Date.now();
if (t - last < 320) { const p = point(img, e); screenInput({kind: "click", x: p.x, y: p.y, count: 2, modifiers: MAC.mods ? MAC.mods.list() : []}); last = 0; return; }
last = t;
tap(img, e, "left");
});
img.addEventListener("pointercancel", () => clearTimeout(pressTimer)); img.addEventListener("pointercancel", () => clearTimeout(pressTimer));
img.addEventListener("dblclick", (e) => { const p = point(img, e); screenInput({kind: "click", x: p.x, y: p.y, count: 2}); });
} }
function tap(img, e, button) { function tap(img, e, button) {
const p = point(img, e); const p = point(img, e);
const d = document.createElement("div"); d.className = "tapdot"; d.style.left = p.cx + "px"; d.style.top = p.cy + "px"; $("stage").appendChild(d); setTimeout(() => d.remove(), 600); const d = document.createElement("div"); d.className = "tapdot"; d.style.left = p.cx + "px"; d.style.top = p.cy + "px"; $("stage").appendChild(d); setTimeout(() => d.remove(), 600);
screenInput({kind: "click", x: p.x, y: p.y, button}); screenInput({kind: "click", x: p.x, y: p.y, button, modifiers: MAC.mods ? MAC.mods.list() : []});
MAC.mods?.used();
} }
async function screenInput(body) { try { await api(base() + "api/screen/mac", {json: body}); } catch (e) { toast(e.message); } } async function screenInput(body) { try { await api(base() + "api/screen/mac", {json: body}); } catch (e) { toast(e.message); } }
document.querySelectorAll("[data-key]").forEach((b) => b.onclick = () => screenInput({kind: "key", key: b.dataset.key}));
document.querySelectorAll("[data-scroll]").forEach((b) => b.onclick = () => screenInput({kind: "scroll", x: Math.round(S.size[0] / 2), y: Math.round(S.size[1] / 2), direction: b.dataset.scroll, amount: 5})); // 虛擬觸控板 and the key bar on this Mac's screen (mobile/trackpad.js, shared with the bots'
$("k-type").onclick = () => { $("typebar").classList.toggle("on"); if ($("typebar").classList.contains("on")) $("typein").focus(); }; // computer): the pointer lives in the shown picture's pixels and is sent in the screenshot's.
$("b-type").onclick = () => { const t = $("typein").value; if (!t) return; $("typein").value = ""; screenInput({kind: "type", text: t}); }; const MAC = {padOn: localStorage.getItem("anybot.pad") !== "0", pad: null, mods: null, T: null, path: null, moveAt: 0, moveTimer: 0};
const MAC_KEY = {Delete: "forwarddelete", BackSpace: "backspace", Return: "return", PageUp: "pageup", PageDown: "pagedown", "[": "bracketleft", "]": "bracketright"};
const macKey = (k) => MAC_KEY[k] || k.toLowerCase();
function macShot(x, y) {
const img = $("stage").querySelector("img");
if (!img || !img.clientWidth) return {x: 0, y: 0};
const w = S.size[0] || img.naturalWidth, h = S.size[1] || img.naturalHeight;
return {x: Math.round(x / img.clientWidth * w), y: Math.round(y / img.clientHeight * h)};
}
function macPlace(x, y) {
const img = $("stage").querySelector("img");
if (!img) return;
const ir = img.getBoundingClientRect(), wr = $("mac-pad").getBoundingClientRect();
$("mac-ptr").style.left = (ir.left - wr.left + x) + "px";
$("mac-ptr").style.top = (ir.top - wr.top + y) + "px";
}
function macPress(key, extra = []) {
const list = [...new Set([...(MAC.mods ? MAC.mods.list() : []), ...extra])];
screenInput({kind: "key", key: [...list, macKey(key)].join("+")});
MAC.mods?.used();
}
async function macTools() {
if (!MAC.T) {
try { MAC.T = await import("./trackpad.js"); } catch (_) { MAC.padOn = false; renderMacBar(); return; }
const T = MAC.T;
MAC.mods = T.modState(() => renderMacBar());
MAC.pad = T.trackpad($("mac-pad"), {
bounds() { const img = $("stage").querySelector("img"); return img ? {w: img.clientWidth || 1, h: img.clientHeight || 1} : {w: 1, h: 1}; },
move(x, y) {
if (MAC.path) { const p = macShot(x, y), l = MAC.path[MAC.path.length - 1]; if (Math.hypot(p.x - l.x, p.y - l.y) > 10 && MAC.path.length < 80) MAC.path.push(p); return; }
// (At most every 150 ms, the last place always sent.)
clearTimeout(MAC.moveTimer);
const go = () => { MAC.moveAt = Date.now(); const p = macShot(x, y); screenInput({kind: "move", x: p.x, y: p.y}); };
if (Date.now() - MAC.moveAt > 150) go(); else MAC.moveTimer = setTimeout(go, 150);
},
down(x, y) { MAC.path = [macShot(x, y)]; },
up(x, y) {
const path = MAC.path || []; MAC.path = null;
path.push(macShot(x, y));
if (path.length >= 2) screenInput({kind: "drag", path, modifiers: MAC.mods.list()});
MAC.mods.used();
},
click(x, y, button, count) { const p = macShot(x, y); screenInput({kind: "click", x: p.x, y: p.y, button, count, modifiers: MAC.mods.list()}); MAC.mods.used(); },
scroll(x, y, dx, dy) { if (!dy) return; const p = macShot(x, y); screenInput({kind: "scroll", x: p.x, y: p.y, direction: dy > 0 ? "down" : "up", amount: Math.min(20, Math.abs(dy) * 2)}); },
show: macPlace,
});
$("mac-combos").innerHTML = T.COMBOS.mac.map(([name, ms, k], i) => `<button class="btn" data-combo="${i}">${esc(name)}<small>${esc(T.comboLabel(ms, k))}</small></button>`).join("");
}
macShowPad();
renderMacBar();
}
function macShowPad() {
const on = MAC.padOn && !!MAC.pad && !!$("stage").querySelector("img");
$("mac-pad").classList.toggle("on", on);
$("mac-ptr").classList.toggle("on", on);
if (MAC.pad) MAC.pad.enabled = on;
if (on && !MAC.centered) { MAC.centered = true; MAC.pad.center(); macTip(); }
}
function macTip() {
const n = Number(localStorage.getItem("anybot.padTip") || 0);
if (n >= 3) return;
localStorage.setItem("anybot.padTip", String(n + 1));
$("mac-tip").innerHTML = "<b>一指</b>移動游標・<b>點一下</b>按・<b>點兩下按住</b>拖曳・<b>兩指</b>捲動・<b>兩指點</b>右鍵";
$("mac-tip").classList.add("on");
setTimeout(() => $("mac-tip").classList.remove("on"), 5000);
}
// 觸控板 | ⌘ ⌥ ⌃ ⇧ | Esc Tab ← ↑ ↓ → ⌫ Del ⏎ … | 快捷鍵 ⌨ 打字
function renderMacBar() {
const T = MAC.T;
const b = (attrs, label, cls = "") => `<button class="btn ${cls}" ${attrs}>${label}</button>`;
$("mac-bar").innerHTML = b('data-pad="1"', "觸控板", MAC.padOn ? "on" : "") + '<span class="sep"></span>'
+ (T ? T.MODS.mac.map(([m, l]) => b(`data-mod="${m}"`, l, MAC.mods.get(m))).join("") + '<span class="sep"></span>' + T.KEYS.map(([k, l]) => b(`data-key="${k}"`, esc(l))).join("") + '<span class="sep"></span>' : "")
+ (T ? b('data-combos="1"', "快捷鍵", $("mac-combos").classList.contains("on") ? "on" : "") : "")
+ b('data-kb="1"', "⌨ 打字", $("typebar").classList.contains("on") ? "on" : "");
}
$("mac-bar").onclick = (e) => {
const t = e.target.closest("button");
if (!t) return;
if (t.dataset.pad) { MAC.padOn = !MAC.padOn; localStorage.setItem("anybot.pad", MAC.padOn ? "1" : "0"); macShowPad(); }
else if (t.dataset.mod) MAC.mods.tap(t.dataset.mod);
else if (t.dataset.key) macPress(t.dataset.key);
else if (t.dataset.combos) $("mac-combos").classList.toggle("on");
else if (t.dataset.kb) { $("typebar").classList.toggle("on"); if ($("typebar").classList.contains("on")) $("typein").focus(); }
renderMacBar();
};
$("mac-combos").onclick = (e) => {
const c = e.target.closest("[data-combo]");
if (!c || !MAC.T) return;
const [, ms, k] = MAC.T.COMBOS.mac[Number(c.dataset.combo)];
macPress(k, ms);
navigator.vibrate?.(8);
};
$("b-type").onclick = () => {
const t = $("typein").value; if (!t) return; $("typein").value = "";
// A modifier held and one letter typed: that shortcut (⌘, then c → ⌘C), not the letter.
if (MAC.mods && MAC.mods.list().length && [...t].length === 1) macPress(t);
else screenInput({kind: "type", text: t});
};
$("typein").addEventListener("keydown", (e) => { if (e.key === "Enter" && !e.isComposing) { e.preventDefault(); $("b-type").click(); } }); $("typein").addEventListener("keydown", (e) => { if (e.key === "Enter" && !e.isComposing) { e.preventDefault(); $("b-type").click(); } });
$("k-right").onclick = () => { S.right = !S.right; $("k-right").textContent = "右鍵:" + (S.right ? "開" : "關"); }; window.addEventListener("resize", () => { if (MAC.pad && $("mac-pad").classList.contains("on")) { const p = MAC.pad.pos; macPlace(p.x, p.y); } });
// ---------- 傳送: a file or a few words to another device of the account ---------- // ---------- 傳送: a file or a few words to another device of the account ----------
// The brain carries it (src/drops.rs): to a computer it lands in 下載/AnyBot (words: on its // The brain carries it (src/drops.rs): to a computer it lands in 下載/AnyBot (words: on its

View File

@ -66,8 +66,38 @@
background: #0e0e0e; border: 1px solid var(--line); border-radius: 10px; padding: 0 10px; outline: none; background: #0e0e0e; border: 1px solid var(--line); border-radius: 10px; padding: 0 10px; outline: none;
} }
#type input:focus { border-color: var(--accent); } #type input:focus { border-color: var(--accent); }
.key-group { display: flex; gap: 4px; flex-wrap: wrap; } /* 虛擬觸控板: a layer over the picture that takes the fingers; the pointer drawn on it. */
.key-group button { height: 28px; padding: 0 9px; border-radius: 8px; font-size: 12px; } #pad { position: absolute; inset: 0; z-index: 5; display: none; touch-action: none; -webkit-user-select: none; user-select: none; -webkit-touch-callout: none; }
#pad.on { display: block; }
#ptr { position: absolute; z-index: 6; width: 20px; height: 20px; margin: -2px 0 0 -3px; pointer-events: none; display: none; filter: drop-shadow(0 1px 2px rgba(0,0,0,0.6)); }
#ptr.on { display: block; }
#tip {
position: absolute; z-index: 7; left: 50%; bottom: 12px; transform: translateX(-50%); max-width: calc(100% - 24px);
background: rgba(30, 29, 27, 0.92); border: 1px solid var(--line); border-radius: 14px; padding: 9px 12px;
font-size: 12.5px; line-height: 1.6; color: var(--text); pointer-events: none; opacity: 0; transition: opacity 0.3s;
}
#tip.on { opacity: 1; }
#tip b { font-weight: 600; color: var(--accent); }
/* The key bar: modifiers you tap (once: the next key; twice: locked), and the keys a phone lacks. */
#bar {
display: none; gap: 6px; padding: 8px 10px; padding-bottom: max(8px, env(safe-area-inset-bottom));
background: var(--bar); border-top: 1px solid var(--line); overflow-x: auto; scrollbar-width: none; flex: none;
}
#bar::-webkit-scrollbar { display: none; }
#bar.on { display: flex; }
#bar button { height: 36px; min-width: 40px; padding: 0 10px; border-radius: 10px; flex: none; font-size: 13px; }
#bar .sep { width: 1px; background: var(--line); margin: 4px 2px; flex: none; }
#bar button.once { background: rgba(216, 131, 102, 0.22); border-color: var(--accent); color: var(--accent); }
#bar button.lock { background: var(--accent); border-color: var(--accent); color: #fff; }
#bar button.on { background: var(--text); border-color: var(--text); color: var(--bar); }
#combos {
display: none; grid-template-columns: repeat(3, 1fr); gap: 6px; padding: 10px; background: var(--bar);
border-top: 1px solid var(--line); max-height: 40vh; overflow-y: auto; flex: none;
}
#combos.on { display: grid; }
#combos button { height: auto; min-height: 48px; flex-direction: column; gap: 2px; border-radius: 12px; padding: 6px 4px; }
#combos button small { color: var(--dim); font-size: 11px; font-weight: 400; letter-spacing: 0.5px; }
body.has-bar #type { padding-bottom: 8px; }
</style> </style>
</head> </head>
<body> <body>
@ -77,25 +107,19 @@
<div class="name" id="name">Bot 的電腦</div> <div class="name" id="name">Bot 的電腦</div>
<div class="state"><span class="dot" id="dot"></span><span id="state">連線中…</span></div> <div class="state"><span class="dot" id="dot"></span><span id="state">連線中…</span></div>
</div> </div>
<button id="kb" title="輸入文字(支援中文與貼上)">打字</button>
<button class="main" id="take">接管</button> <button class="main" id="take">接管</button>
<button class="icon" id="popout" title="在新分頁打開" style="display:none">↗</button> <button class="icon" id="popout" title="在新分頁打開" style="display:none">↗</button>
</header> </header>
<div id="screen"><div id="msg">正在連接畫面…</div></div> <div id="screen"><div id="msg">正在連接畫面…</div><div id="pad"></div><svg id="ptr" viewBox="0 0 20 20"><path d="M3 2 L3 16 L7 12.5 L9.6 18 L12 17 L9.5 11.6 L14.5 11.6 Z" fill="#fff" stroke="#111" stroke-width="1.2" stroke-linejoin="round"/></svg><div id="tip"></div></div>
<div id="combos"></div>
<div id="type"> <div id="type">
<input id="text" placeholder="輸入文字(支援中文輸入法),按 Enter 送出到電腦" autocomplete="off" enterkeyhint="send"> <input id="text" placeholder="輸入文字(支援中文輸入法),按 Enter 送出到電腦" autocomplete="off" enterkeyhint="send">
<button class="main" id="send">送出</button> <button class="main" id="send">送出</button>
<div class="key-group">
<button data-k="Return">Enter</button>
<button data-k="Escape">Esc</button>
<button data-k="Tab">Tab</button>
<button data-k="BackSpace">⌫</button>
<button data-k="Up">↑</button>
<button data-k="Down">↓</button>
</div>
</div> </div>
<div id="bar"></div>
<script type="module"> <script type="module">
import RFB from "./novnc.js"; import RFB from "./novnc.js";
import { trackpad, MODS, KEYS, COMBOS, comboLabel, modState } from "./trackpad.js";
const q = new URLSearchParams(location.hash.slice(1)); const q = new URLSearchParams(location.hash.slice(1));
const sq = new URLSearchParams(location.search); const sq = new URLSearchParams(location.search);
@ -174,16 +198,124 @@ if (embed) {
} }
let rfb = null, ws = null, control = q.get("control") === "1", tries = 0, connected = false, closed = false; let rfb = null, ws = null, control = q.get("control") === "1", tries = 0, connected = false, closed = false;
const KEYS = { Return: 0xff0d, Escape: 0xff1b, Tab: 0xff09, BackSpace: 0xff08, Up: 0xff52, Down: 0xff54 }; // X11 keysyms (the bots' computer is Linux) and the browser key codes noVNC sends beside them.
const SYM = { Return: 0xff0d, Escape: 0xff1b, Tab: 0xff09, BackSpace: 0xff08, Delete: 0xffff, Up: 0xff52, Down: 0xff54, Left: 0xff51, Right: 0xff53, Home: 0xff50, End: 0xff57, PageUp: 0xff55, PageDown: 0xff56, F11: 0xffc8, space: 0x20, ctrl: 0xffe3, alt: 0xffe9, shift: 0xffe1, super: 0xffeb };
const CODE = { Return: "Enter", Escape: "Escape", Tab: "Tab", BackSpace: "Backspace", Delete: "Delete", Up: "ArrowUp", Down: "ArrowDown", Left: "ArrowLeft", Right: "ArrowRight", Home: "Home", End: "End", PageUp: "PageUp", PageDown: "PageDown", F11: "F11", space: "Space", ctrl: "ControlLeft", alt: "AltLeft", shift: "ShiftLeft", super: "MetaLeft" };
const symOf = (k) => SYM[k] !== undefined ? SYM[k] : k.length === 1 ? k.toLowerCase().charCodeAt(0) : 0;
const codeOf = (k) => CODE[k] || (/^[a-z]$/i.test(k) ? "Key" + k.toUpperCase() : /^[0-9]$/.test(k) ? "Digit" + k : "");
const mods = modState(() => renderBar());
// Hold the modifiers down around `fn` (a key or a click), then let the once-held ones go.
function withMods(list, fn) {
if (!rfb) return;
for (const m of list) rfb.sendKey(SYM[m], CODE[m], true);
fn();
for (const m of [...list].reverse()) rfb.sendKey(SYM[m], CODE[m], false);
}
function press(key, extra = []) {
const list = [...new Set([...mods.list(), ...extra])];
withMods(list, () => rfb.sendKey(symOf(key), codeOf(key)));
mods.used();
}
// 虛擬觸控板 over noVNC: the pointer lives in the canvas's own (shown) pixels; noVNC turns them
// into the remote screen's. (Its _handleMouse* are the same calls its own mouse handling makes.)
let mask = 0, padOn = localStorage.getItem("anybot.pad") !== "0";
const BIT = { left: 1, right: 4 };
const canvas = () => rfb && rfb._canvas;
function placePtr(x, y) {
const c = canvas();
if (!c) return;
const cr = c.getBoundingClientRect(), sr = $("screen").getBoundingClientRect();
$("ptr").style.left = (cr.left - sr.left + x) + "px";
$("ptr").style.top = (cr.top - sr.top + y) + "px";
}
const pad = trackpad($("pad"), {
bounds() { const c = canvas(); return c ? { w: c.clientWidth || 1, h: c.clientHeight || 1 } : { w: 1, h: 1 }; },
move(x, y) { rfb?._handleMouseMove(x, y); },
down(x, y, b) { if (!rfb) return; mask |= BIT[b]; rfb._handleMouseButton(x, y, mask); },
up(x, y, b) { if (!rfb) return; mask &= ~BIT[b]; rfb._handleMouseButton(x, y, mask); },
click(x, y, b, n) {
if (!rfb) return;
withMods(mods.list(), () => { for (let i = 0; i < n; i++) { rfb._handleMouseButton(x, y, mask | BIT[b]); rfb._handleMouseButton(x, y, mask); } });
mods.used();
},
scroll(x, y, dx, dy) {
if (!rfb) return;
const notch = (bit, n) => { for (let i = 0; i < Math.abs(n); i++) { rfb._handleMouseButton(x, y, mask | bit); rfb._handleMouseButton(x, y, mask); } };
if (dy) notch(dy > 0 ? 16 : 8, dy);
if (dx) notch(dx > 0 ? 64 : 32, dx);
},
show: placePtr,
});
function tip() {
const n = Number(localStorage.getItem("anybot.padTip") || 0);
if (n >= 3) return;
localStorage.setItem("anybot.padTip", String(n + 1));
$("tip").innerHTML = "<b>一指</b>移動游標・<b>點一下</b>按・<b>點兩下按住</b>拖曳・<b>兩指</b>捲動・<b>兩指點</b>右鍵";
$("tip").classList.add("on");
setTimeout(() => $("tip").classList.remove("on"), 5000);
}
function showPad() {
const on = control && padOn && connected;
$("pad").classList.toggle("on", on);
$("ptr").classList.toggle("on", on);
pad.enabled = on;
if (on) { pad.center(); tip(); }
}
// The bar: 觸控板 | Ctrl Alt Shift ❖ | Esc Tab ← ↑ ↓ → ⌫ Del ⏎ Home End PgUp PgDn | 快捷鍵 ⌨
function renderBar() {
const b = $("bar");
const btn = (attrs, label, cls = "") => `<button ${attrs} class="${cls}">${label}</button>`;
b.innerHTML = btn('data-pad="1" title="觸控板:手指移動游標;關掉改成點哪裡按哪裡"', "觸控板", padOn ? "on" : "")
+ '<span class="sep"></span>'
+ MODS.linux.map(([m, l]) => btn(`data-mod="${m}"`, l, mods.get(m))).join("")
+ '<span class="sep"></span>'
+ KEYS.map(([k, l]) => btn(`data-key="${k}"`, l)).join("")
+ '<span class="sep"></span>'
+ btn('data-combos="1"', "快捷鍵", $("combos").classList.contains("on") ? "on" : "")
+ btn('data-kb="1" title="輸入文字(支援中文與貼上)"', "⌨ 打字", $("type").classList.contains("on") ? "on" : "");
}
$("combos").innerHTML = COMBOS.linux.map(([name, ms, k], i) => `<button data-combo="${i}">${name}<small>${comboLabel(ms, k, "linux")}</small></button>`).join("");
$("combos").onclick = (e) => {
const c = e.target.closest("[data-combo]");
if (!c) return;
const [, ms, k] = COMBOS.linux[Number(c.dataset.combo)];
press(k, ms);
navigator.vibrate?.(8);
};
$("bar").onclick = (e) => {
const t = e.target.closest("button");
if (!t) return;
if (t.dataset.pad) { padOn = !padOn; localStorage.setItem("anybot.pad", padOn ? "1" : "0"); showPad(); }
else if (t.dataset.mod) mods.tap(t.dataset.mod);
else if (t.dataset.key) press(t.dataset.key);
else if (t.dataset.combos) $("combos").classList.toggle("on");
else if (t.dataset.kb) { $("type").classList.toggle("on"); if ($("type").classList.contains("on")) $("text").focus(); }
renderBar();
};
function state(text, kind) { $("state").textContent = text; $("dot").className = "dot" + (kind ? " " + kind : ""); } function state(text, kind) { $("state").textContent = text; $("dot").className = "dot" + (kind ? " " + kind : ""); }
function message(text) { $("msg").textContent = text; $("msg").style.display = text ? "" : "none"; } function message(text) { $("msg").textContent = text; $("msg").style.display = text ? "" : "none"; }
// 接管 holds the bot's screen: its steps there wait while you drive (交還給 Bot lets them go on).
const apiBase = lan ? "" : "h/" + encodeURIComponent(host) + "/";
let holding = false;
function hold(on) {
if (on === holding || !token) return;
holding = on;
const bot = /^\d+$/.test(q.get("bot") || "") ? Number(q.get("bot")) : null;
fetch(apiBase + "api/box/hold", { method: "POST", keepalive: true, headers: { Authorization: "Bearer " + token, "Content-Type": "application/json" }, body: JSON.stringify({ bot, on }) }).catch(() => {});
}
function showControl() { function showControl() {
$("take").textContent = control ? "交還給 Bot" : "接管"; $("take").textContent = control ? "交還給 Bot" : "接管";
$("take").className = control ? "hold-on" : "main"; $("take").className = control ? "hold-on" : "main";
$("kb").style.display = control ? "" : "none"; $("bar").classList.toggle("on", control);
if (!control) $("type").classList.remove("on"); document.body.classList.toggle("has-bar", control);
if (rfb) { rfb.viewOnly = !control; if (control) rfb.focus(); } if (!control) { $("type").classList.remove("on"); $("combos").classList.remove("on"); }
renderBar();
hold(control && connected);
showPad();
if (rfb) { rfb.viewOnly = !control; if (control && !padOn) rfb.focus(); }
if (connected) state(control ? "你在操作(Bot 會等你完成)" : "即時觀看", control ? "hold" : "live"); if (connected) state(control ? "你在操作(Bot 會等你完成)" : "即時觀看", control ? "hold" : "live");
if (embed && window.parent !== window) { if (embed && window.parent !== window) {
try { window.parent.postMessage({ anybotScreen: "control", control }, location.origin); } catch (_) {} try { window.parent.postMessage({ anybotScreen: "control", control }, location.origin); } catch (_) {}
@ -219,25 +351,26 @@ async function connect() {
rfb.viewOnly = !control; rfb.viewOnly = !control;
rfb.addEventListener("connect", () => { tries = 0; connected = true; message(""); showControl(); }); rfb.addEventListener("connect", () => { tries = 0; connected = true; message(""); showControl(); });
rfb.addEventListener("disconnect", () => { rfb.addEventListener("disconnect", () => {
rfb = null; connected = false; rfb = null; connected = false; showPad();
if (closed) return; if (closed) return;
retry(); retry();
}); });
} }
$("take").onclick = () => { control = !control; showControl(); }; $("take").onclick = () => { control = !control; showControl(); };
$("kb").onclick = () => { $("type").classList.toggle("on"); if ($("type").classList.contains("on")) $("text").focus(); };
function send() { function send() {
const t = $("text").value; const t = $("text").value;
if (!t || !ws || ws.readyState !== 1) return; if (!t || !ws || ws.readyState !== 1) return;
ws.send(t); // A modifier held and one letter typed: that shortcut (Ctrl, then c → Ctrl+C), not the letter.
if (mods.list().length && [...t].length === 1) press(t);
else ws.send(t);
$("text").value = ""; $("text").value = "";
} }
$("send").onclick = send; $("send").onclick = send;
$("text").addEventListener("keydown", (e) => { if (e.key === "Enter" && !e.isComposing) { e.preventDefault(); send(); } }); $("text").addEventListener("keydown", (e) => { if (e.key === "Enter" && !e.isComposing) { e.preventDefault(); send(); } });
document.querySelectorAll("[data-k]").forEach((b) => b.onclick = () => { if (rfb) rfb.sendKey(KEYS[b.dataset.k], b.dataset.k); });
$("back").onclick = () => { $("back").onclick = () => {
closed = true; closed = true;
hold(false);
if (rfb) { try { rfb.disconnect(); } catch (_) {} } if (rfb) { try { rfb.disconnect(); } catch (_) {} }
if (embed && window.parent !== window) { if (embed && window.parent !== window) {
window.parent.postMessage({ anybotScreen: "close" }, location.origin); window.parent.postMessage({ anybotScreen: "close" }, location.origin);
@ -256,6 +389,11 @@ window.addEventListener("message", (e) => {
} }
}); });
// Away from the page (the phone locked, another app): let the bot go on; back again, hold again.
document.addEventListener("visibilitychange", () => hold(control && connected && !document.hidden));
window.addEventListener("pagehide", () => hold(false));
window.addEventListener("resize", () => { if ($("pad").classList.contains("on")) { const p = pad.pos; placePtr(p.x, p.y); } });
showControl(); showControl();
connect(); connect();
</script> </script>

220
mobile/trackpad.js Normal file
View File

@ -0,0 +1,220 @@
// 虛擬觸控板:在手機上操作一台電腦的畫面,像用筆電的觸控板,不是用手指去戳小小的畫面。
// 用在 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(); },
};
}

44
mobile/trackpad.test.mjs Normal file
View File

@ -0,0 +1,44 @@
// 虛擬觸控板的手勢(mobile/trackpad.js):手指怎麼變成滑鼠和按鍵。`node mobile/trackpad.test.mjs`;
// cargo test 的 remote::tests::the_touchpad_turns_fingers_into_mouse_and_keys 也跑它(有 node 時)。
import { trackpad, modState, comboLabel } from "./trackpad.js";
const L = {}; const pad = { addEventListener: (t, f) => (L[t] = f), setPointerCapture() {}, style: {} };
let calls = [];
const host = { bounds: () => ({ w: 400, h: 300 }), move: (x, y) => calls.push(["move", Math.round(x), Math.round(y)]), down: (x, y, b) => calls.push(["down", b]), up: (x, y, b) => calls.push(["up", b]), click: (x, y, b, n) => calls.push(["click", b, n]), scroll: (x, y, dx, dy) => calls.push(["scroll", dx, dy]), show() {} };
const tp = trackpad(pad, host); tp.center();
const ev = (id, x, y) => ({ pointerId: id, clientX: x, clientY: y, preventDefault() {} });
const wait = (ms) => new Promise((r) => setTimeout(r, ms));
const ok = (name, cond) => { console.log((cond ? "OK " : "FAIL ") + name, cond ? "" : JSON.stringify(calls)); if (!cond) process.exitCode = 1; };
// 1. tap
calls = []; L.pointerdown(ev(1, 100, 100)); await wait(50); L.pointerup(ev(1, 100, 100));
ok("點一下=左鍵一下", JSON.stringify(calls) === '[["click","left",1]]');
await wait(400);
// 2. one-finger move
calls = []; L.pointerdown(ev(1, 100, 100)); for (let i = 1; i <= 10; i++) { await wait(16); L.pointermove(ev(1, 100 + i * 5, 100)); } L.pointerup(ev(1, 150, 100));
ok("一指滑動=移動游標、不按", calls.length > 0 && calls.every((c) => c[0] === "move") && tp.pos.x > 250);
await wait(400);
// 3. two-finger tap
calls = []; L.pointerdown(ev(1, 100, 100)); L.pointerdown(ev(2, 160, 100)); await wait(60); L.pointerup(ev(1, 100, 100)); L.pointerup(ev(2, 160, 100));
ok("兩指點=右鍵", JSON.stringify(calls) === '[["click","right",1]]');
await wait(400);
// 4. two-finger scroll up (fingers move up → page goes down: dy > 0)
calls = []; L.pointerdown(ev(1, 100, 200)); L.pointerdown(ev(2, 160, 200)); for (let i = 1; i <= 10; i++) { await wait(16); L.pointermove(ev(1, 100, 200 - i * 8)); L.pointermove(ev(2, 160, 200 - i * 8)); } L.pointerup(ev(1, 100, 120)); L.pointerup(ev(2, 160, 120));
ok("兩指往上滑=往下捲", calls.length > 0 && calls.every((c) => c[0] === "scroll" && c[2] > 0) && !calls.some((c) => c[0] === "click"));
await wait(400);
// 5. double tap and drag
calls = []; L.pointerdown(ev(1, 200, 150)); await wait(40); L.pointerup(ev(1, 200, 150)); await wait(80);
L.pointerdown(ev(1, 202, 151)); for (let i = 1; i <= 6; i++) { await wait(16); L.pointermove(ev(1, 202 + i * 6, 151)); } L.pointerup(ev(1, 238, 151));
const kinds = calls.map((c) => c[0]);
ok("點兩下按住滑=拖曳", kinds[0] === "click" && kinds[1] === "down" && kinds.includes("move") && kinds[kinds.length - 1] === "up");
await wait(400);
// 6. double tap (no drag) = two clicks
calls = []; L.pointerdown(ev(1, 200, 150)); await wait(40); L.pointerup(ev(1, 200, 150)); await wait(80); L.pointerdown(ev(1, 201, 150)); await wait(40); L.pointerup(ev(1, 201, 150));
ok("點兩下=連點兩下", JSON.stringify(calls) === '[["click","left",1],["click","left",1]]');
await wait(400);
// 7. long press = right click, no left click after
calls = []; L.pointerdown(ev(1, 120, 120)); await wait(650); L.pointerup(ev(1, 120, 120));
ok("長按=右鍵", JSON.stringify(calls) === '[["click","right",1]]');
// 8. modifiers: once, lock, used
let n = 0; const m = modState(() => n++);
m.tap("ctrl"); ok("點一下修飾鍵=下一下按住", m.get("ctrl") === "once"); m.used(); ok("用過就放開", m.get("ctrl") === "");
m.tap("cmd"); m.tap("cmd"); ok("點兩下=鎖住", m.get("cmd") === "lock"); m.used(); ok("鎖住的用過不放開", m.get("cmd") === "lock"); m.tap("cmd"); ok("再點一下放開", m.get("cmd") === "");
ok("組合鍵的字", comboLabel(["ctrl", "shift"], "Tab") === "⌃⇧⇥" && comboLabel(["cmd"], "c") === "⌘C" && comboLabel(["ctrl", "shift"], "Tab", "linux") === "Ctrl+Shift+Tab" && comboLabel(["alt"], "Left", "linux") === "Alt+←");

View File

@ -32,6 +32,8 @@ const PAGE: &str = include_str!("../../mobile/index.html");
/// The bots' computer, watched and used in a browser (noVNC). /// The bots' computer, watched and used in a browser (noVNC).
const SCREEN_PAGE: &str = include_str!("../../mobile/screen.html"); const SCREEN_PAGE: &str = include_str!("../../mobile/screen.html");
const NOVNC: &str = include_str!("../../mobile/novnc.js"); const NOVNC: &str = include_str!("../../mobile/novnc.js");
/// 虛擬觸控板 and the key bar, shared by the screen page and the phone page.
const TRACKPAD: &str = include_str!("../../mobile/trackpad.js");
/// The phone app's manifest and service worker (notifications), shared with the desktop's own /// The phone app's manifest and service worker (notifications), shared with the desktop's own
/// phone page (src/remote.rs). /// phone page (src/remote.rs).
const MANIFEST: &str = include_str!("../../mobile/manifest.webmanifest"); const MANIFEST: &str = include_str!("../../mobile/manifest.webmanifest");
@ -1003,6 +1005,7 @@ impl Relay {
.with_header("Content-Security-Policy", &format!("default-src 'self'; img-src 'self' blob: data:; style-src 'self' 'unsafe-inline'; {}; connect-src 'self' wss: ws:; base-uri 'none'; object-src 'none'; frame-ancestors 'self'", httpd::script_src(SCREEN_PAGE))) .with_header("Content-Security-Policy", &format!("default-src 'self'; img-src 'self' blob: data:; style-src 'self' 'unsafe-inline'; {}; connect-src 'self' wss: ws:; base-uri 'none'; object-src 'none'; frame-ancestors 'self'", httpd::script_src(SCREEN_PAGE)))
.with_header("Strict-Transport-Security", "max-age=31536000"), .with_header("Strict-Transport-Security", "max-age=31536000"),
("GET", ["novnc.js"]) => Resp::bytes("text/javascript; charset=utf-8", NOVNC.as_bytes().to_vec()).with_header("Cache-Control", "public, max-age=86400"), ("GET", ["novnc.js"]) => Resp::bytes("text/javascript; charset=utf-8", NOVNC.as_bytes().to_vec()).with_header("Cache-Control", "public, max-age=86400"),
("GET", ["trackpad.js"]) => Resp::bytes("text/javascript; charset=utf-8", TRACKPAD.as_bytes().to_vec()).with_header("Cache-Control", "no-cache"),
// A link for this account's browser to watch one of its AnyBots' computer (the app // A link for this account's browser to watch one of its AnyBots' computer (the app
// opens it; the browser has no session of its own). // opens it; the browser has no session of its own).
("POST", ["relay", "screen-ticket"]) => { ("POST", ["relay", "screen-ticket"]) => {

View File

@ -605,6 +605,8 @@ pub fn handle(req: Req, via_relay: bool) -> Resp {
("GET", []) | ("GET", ["index.html"]) => return page(&req), ("GET", []) | ("GET", ["index.html"]) => return page(&req),
("GET", ["screen"]) => return Resp::bytes("text/html; charset=utf-8", SCREEN_PAGE.as_bytes().to_vec()).with_header("Content-Security-Policy", &format!("default-src 'self'; img-src 'self' blob: data:; style-src 'self' 'unsafe-inline'; {}; connect-src 'self' ws: wss:; base-uri 'none'; object-src 'none'; frame-ancestors 'self'", httpd::script_src(SCREEN_PAGE))), ("GET", ["screen"]) => return Resp::bytes("text/html; charset=utf-8", SCREEN_PAGE.as_bytes().to_vec()).with_header("Content-Security-Policy", &format!("default-src 'self'; img-src 'self' blob: data:; style-src 'self' 'unsafe-inline'; {}; connect-src 'self' ws: wss:; base-uri 'none'; object-src 'none'; frame-ancestors 'self'", httpd::script_src(SCREEN_PAGE))),
("GET", ["novnc.js"]) => return Resp::bytes("text/javascript; charset=utf-8", NOVNC.as_bytes().to_vec()).with_header("Cache-Control", "public, max-age=86400"), ("GET", ["novnc.js"]) => return Resp::bytes("text/javascript; charset=utf-8", NOVNC.as_bytes().to_vec()).with_header("Cache-Control", "public, max-age=86400"),
// (The touchpad and key bar both screens use; asked fresh, so it matches the page.)
("GET", ["trackpad.js"]) => return Resp::bytes("text/javascript; charset=utf-8", TRACKPAD.as_bytes().to_vec()).with_header("Cache-Control", "no-cache"),
("GET", ["manifest.webmanifest"]) => return Resp::bytes("application/manifest+json", MANIFEST.as_bytes().to_vec()), ("GET", ["manifest.webmanifest"]) => return Resp::bytes("application/manifest+json", MANIFEST.as_bytes().to_vec()),
// (Keeps the page and its icons on the phone; see mobile/sw.js.) // (Keeps the page and its icons on the phone; see mobile/sw.js.)
("GET", ["sw.js"]) => return Resp::bytes("text/javascript; charset=utf-8", SW.as_bytes().to_vec()), ("GET", ["sw.js"]) => return Resp::bytes("text/javascript; charset=utf-8", SW.as_bytes().to_vec()),
@ -861,7 +863,15 @@ pub fn handle(req: Req, via_relay: bool) -> Resp {
// 個人資料與用量 (the owner's): the year in figures, worked out on the brain (stats.rs). // 個人資料與用量 (the owner's): the year in figures, worked out on the brain (stats.rs).
("GET", ["api", "stats"]) => phone_act("stats", json!({}), &role), ("GET", ["api", "stats"]) => phone_act("stats", json!({}), &role),
("GET", ["api", "sync", "stats"]) => phone_act_for("stats", json!({}), "owner", 40), ("GET", ["api", "sync", "stats"]) => phone_act_for("stats", json!({}), "owner", 40),
("GET", ["api", "box", "thumb"]) => box_thumb(), ("GET", ["api", "box", "thumb"]) => box_thumb(req.query.get("bot").map(String::as_str).unwrap_or("")),
// 接管 from the phone: while the person drives the bot's screen, the bot's steps on it wait
// (as 接管 on a screen of this brain does); 交還給 Bot lets them go on.
("POST", ["api", "box", "hold"]) => {
let v = req.json();
let bot = v["bot"].as_u64().map(|b| b.to_string()).unwrap_or_default();
crate::cloudbox::hold(&crate::cloudbox::screen_for_bot(&bot), v["on"].as_bool().unwrap_or(false));
Resp::json(&json!({"ok": true}))
}
// 看畫面 on 區網: a ticket for the screen's connection, so the login isn't in its address. // 看畫面 on 區網: a ticket for the screen's connection, so the login isn't in its address.
("POST", ["api", "vnc", "ticket"]) if !via_relay => { ("POST", ["api", "vnc", "ticket"]) if !via_relay => {
let t = httpd::random_hex(24); let t = httpd::random_hex(24);
@ -1319,9 +1329,11 @@ fn voice_speech(req: &Req) -> Resp {
} }
} }
/// The bots' computer's screen, small (the phone's 電腦 card and a hand-off), as JPEG. /// The bots' computer's screen, small (the phone's 電腦 card and a hand-off), as JPEG: the screen
fn box_thumb() -> Resp { /// of the bot asked about (`?bot=`; its own when it has one open), else the shared one.
let Some(img) = crate::cloudbox::thumbnail(480) else { return Resp::error(404, "Bot 的電腦沒有開著") }; fn box_thumb(bot: &str) -> Resp {
let own = (!bot.is_empty()).then(|| crate::cloudbox::thumbnail_of(&crate::cloudbox::screen_for_bot(bot), 480)).flatten();
let Some(img) = own.or_else(|| crate::cloudbox::thumbnail(480)) else { return Resp::error(404, "Bot 的電腦沒有開著") };
let mut out = std::io::Cursor::new(vec![]); let mut out = std::io::Cursor::new(vec![]);
match image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, 72).encode_image(&image::DynamicImage::ImageRgba8(img).to_rgb8()) { match image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, 72).encode_image(&image::DynamicImage::ImageRgba8(img).to_rgb8()) {
Ok(()) => Resp::bytes("image/jpeg", out.into_inner()), Ok(()) => Resp::bytes("image/jpeg", out.into_inner()),
@ -1738,17 +1750,25 @@ fn screen(which: &str, s: &Settings) -> Resp {
} }
} }
/// The phone taps, types or scrolls on this Mac's screen, as the person, in the pixels of the /// The phone taps, types, scrolls, moves the pointer or drags on this Mac's screen, as the
/// picture it was sent (shot_size). The bots' computer takes the person's input through VNC. /// person, in the pixels of the picture it was sent (shot_size). The bots' computer takes the
/// person's input through VNC.
fn screen_input(which: &str, v: &Value, s: &Settings) -> Resp { fn screen_input(which: &str, v: &Value, s: &Settings) -> Resp {
// The held modifier keys, only the ones a click knows.
let mods = |v: &Value| -> Value { json!(v["modifiers"].as_array().map(|a| a.iter().filter(|m| matches!(m.as_str(), Some("cmd" | "shift" | "option" | "ctrl" | "alt"))).cloned().collect::<Vec<_>>()).unwrap_or_default()) };
let (x, y) = (v["x"].as_f64().unwrap_or(0.0), v["y"].as_f64().unwrap_or(0.0)); let (x, y) = (v["x"].as_f64().unwrap_or(0.0), v["y"].as_f64().unwrap_or(0.0));
let down = v["direction"].as_str().unwrap_or("down") != "up"; let down = v["direction"].as_str().unwrap_or("down") != "up";
let amount = v["amount"].as_i64().unwrap_or(3).clamp(1, 20); let amount = v["amount"].as_i64().unwrap_or(3).clamp(1, 20);
match which { match which {
"mac" if s.mac_from_phone => { "mac" if s.mac_from_phone => {
let (name, args) = match v["kind"].as_str().unwrap_or("") { let (name, args) = match v["kind"].as_str().unwrap_or("") {
"click" => ("computer_use_click", json!({"x": x, "y": y, "button": v["button"].as_str().unwrap_or("left"), "count": v["count"].as_u64().unwrap_or(1)})), // (With the key bar's held keys: ⌘-click, ⇧-click…)
"click" => ("computer_use_click", json!({"x": x, "y": y, "button": v["button"].as_str().unwrap_or("left"), "count": v["count"].as_u64().unwrap_or(1).clamp(1, 3), "modifier_keys": mods(v)})),
// 虛擬觸控板: the pointer moves (no click), and a drag goes along the finger's path.
"move" => ("computer_use_mouse_move", json!({"x": x, "y": y})),
"drag" => ("computer_use_drag", json!({"path": v["path"], "modifier_keys": mods(v)})),
"type" => ("computer_use_typing", json!({"value": v["text"]})), "type" => ("computer_use_typing", json!({"value": v["text"]})),
// (A combination too: "cmd+tab", from the key bar.)
"key" => ("computer_use_press_key", json!({"key": v["key"]})), "key" => ("computer_use_press_key", json!({"key": v["key"]})),
"scroll" => ("computer_use_scroll", json!({"x": x, "y": y, "direction": if down { "down" } else { "up" }, "amount": amount})), "scroll" => ("computer_use_scroll", json!({"x": x, "y": y, "direction": if down { "down" } else { "up" }, "amount": amount})),
_ => return Resp::error(400, "不認得的操作"), _ => return Resp::error(400, "不認得的操作"),
@ -3551,6 +3571,8 @@ const PAGE: &str = include_str!("../mobile/index.html");
/// The bots' computer, watched and used in a browser (noVNC; see vnc.rs). /// The bots' computer, watched and used in a browser (noVNC; see vnc.rs).
const SCREEN_PAGE: &str = include_str!("../mobile/screen.html"); const SCREEN_PAGE: &str = include_str!("../mobile/screen.html");
const NOVNC: &str = include_str!("../mobile/novnc.js"); const NOVNC: &str = include_str!("../mobile/novnc.js");
/// 虛擬觸控板 and the key bar (mobile/trackpad.js), shared by the screen page and the phone page.
pub const TRACKPAD: &str = include_str!("../mobile/trackpad.js");
pub const MANIFEST: &str = include_str!("../mobile/manifest.webmanifest"); pub const MANIFEST: &str = include_str!("../mobile/manifest.webmanifest");
/// The app's icon, the same drawing everywhere (icons/anybot.svg is the Mac/Linux one). /// The app's icon, the same drawing everywhere (icons/anybot.svg is the Mac/Linux one).
pub const ICON: &str = include_str!("../mobile/icon.svg"); pub const ICON: &str = include_str!("../mobile/icon.svg");
@ -3583,6 +3605,22 @@ pub fn page(req: &Req) -> Resp {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
/// 虛擬觸控板 (mobile/trackpad.js): a tap clicks, one finger moves the pointer, two fingers
/// scroll or right-click, double tap and slide drags, a long press right-clicks; the key
/// bar's modifiers hold for one key or lock. Run in node when it is there (the gestures are
/// the page's JavaScript; there is no browser in cargo test).
#[test]
fn the_touchpad_turns_fingers_into_mouse_and_keys() {
let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("mobile");
let Ok(out) = std::process::Command::new("node").arg("trackpad.test.mjs").current_dir(&dir).output() else {
eprintln!("(沒有 node:略過觸控板的手勢測試)");
return;
};
let text = String::from_utf8_lossy(&out.stdout);
assert!(out.status.success() && !text.contains("FAIL"), "{text}{}", String::from_utf8_lossy(&out.stderr));
assert!(text.matches("OK").count() >= 13, "{text}");
}
use super::*; use super::*;
/// A page holding a state is told only what changed: the keys that did, a bot that didn't as /// A page holding a state is told only what changed: the keys that did, a bot that didn't as