From 98fbd310d221c429d1a0f1227ce5e9243df62619 Mon Sep 17 00:00:00 2001 From: ETWen Date: Thu, 2 Jul 2026 14:47:06 +0800 Subject: [PATCH] feat: v0.5.0 terminal search, keyword alerts, TeraTerm-compatible TTL Search (Ctrl+F): - in-terminal search bar over full scrollback + screen; all hits highlighted, current hit emphasized; Enter searches upward, Shift+Enter downward, F3/Esc shortcuts - hits anchored via ScreenBuffer.DroppedLines so positions stay correct as the ring buffer drops old lines Keyword highlighting & tab alerts: - new Settings -> Highlight page: user-defined keyword list with per-rule enable and a global toggle (AppSettings.KeywordRules) - keywords highlighted red in every terminal (visible rows only, case-insensitive); background tabs flash a red dot when a keyword appears, cleared when the tab is opened TTL engine (TeraTerm macro compatibility): - new TtlExpression parser: parens, and/or/xor/not, comparisons, * / % + -, hex literals (0x/$), string/int values; legacy fallback keeps old scripts working - control flow: goto, call/return (inline, usable inside loops), for/next, do/loop [while|until], until/enduntil, break, continue, end, exit, include, mpause; one-line "if " - waits: waitln, waitregex (matchstr/groupmatchstr1-9), recvln, multi-string wait (TeraTerm semantics), mtimeout - strings: strlen strcompare strconcat strcopy strinsert strremove strmatch strscan strreplace strtrim strsplit strjoin tolower toupper str2int int2str code2str str2code sprintf expandenv - files: fileopen filereadln filewrite(ln) fileclose filecreate filedelete filesearch basename dirname makepath foldercreate folderdelete foldersearch getdir setdir - misc: beep getdate gettime getenv setenv random exec getver getttdir uptime ifdefined clipb2var var2clipb inputbox yesnobox crc32 checksum8/16/32 dispstr - serial: sendbreak setbaud setdtr setrts sendfile (SerialChannel gains SendBreak/SetBaudRate/SetDtr/SetRts) - script Output (incl. dispstr) now echoed gray into the terminal - quote-aware comment stripping; case-insensitive variables Docs: - docs/ttl-script-reference.md rewritten: ETTerms-only commands first, then the TeraTerm-shared set, with examples Misc: - version 0.5.0; About changelog; CLAUDE.md v0.5.0 notes - restore ETTerms.PduCore ProjectReference in ETTerms/PduMcp csproj (was dropped in the working tree; required to compile) Co-Authored-By: Claude Fable 5 --- CLAUDE.md | 2 + docs/ttl-script-reference.md | 356 +++-- src/ETTerms/App/AboutView.cs | 9 + src/ETTerms/App/SettingsView.cs | 110 ++ src/ETTerms/App/Workspace/WorkspaceView.cs | 11 +- src/ETTerms/ETTerms.csproj | 6 +- src/ETTerms/Infrastructure/AppSettings.cs | 11 + src/ETTerms/Scripting/TTLInterpreter.cs | 1402 ++++++++++++++++++-- src/ETTerms/Scripting/TtlExpression.cs | 253 ++++ src/ETTerms/Sessions/SerialChannel.cs | 16 + src/ETTerms/Sessions/SessionPage.cs | 7 + src/ETTerms/Terminal/ScreenBuffer.cs | 8 +- src/ETTerms/Terminal/TerminalView.cs | 293 ++++ 13 files changed, 2255 insertions(+), 229 deletions(-) create mode 100644 src/ETTerms/Scripting/TtlExpression.cs diff --git a/CLAUDE.md b/CLAUDE.md index c39176a..b0f5c56 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -10,6 +10,8 @@ ETTerms 是一個 **C# .NET 8 WinForms** 的原生 Windows 終端機工作台, **進度:** Phase 1–5 ✅、Phase 6 ✅(TTL 引擎 + Group 同步,SSH 待驗收)、Phase 7 ✅(Settings/About)、Phase 8 ✅(PDU + Shell/ConPTY + SFTP + Settings 擴充)、Phase 9 ✅(Serial MCP server:**GUI 持有 COM port,MCP 經本機 named pipe 橋接**,AI 收發的資料即時以 `[AI]` 標色顯示在 GUI)。打包待指示。 +**v0.5.0:** 搜尋 / 關鍵字警示 / TTL 大擴充。**(1) Ctrl+F scrollback 搜尋** — `TerminalView` 內建搜尋列(Enter 往上找、Shift+Enter 往下、F3/Esc),全部命中黃底、目前命中橘底;命中以「絕對行號 = `ScreenBuffer.DroppedLines` + abs」錨定,環形緩衝丟舊行不漂移。**(2) 關鍵字高亮 + 分頁警示** — `AppSettings.KeywordRules`(`KeywordRule{Text,Enabled}` + 全域開關),Settings 新 **Highlight** 分頁可增刪/勾選;`TerminalView` 每次重繪只掃可見行標紅底(不分大小寫),`Feed` 路徑用獨立 Decoder+去 ANSI 偵測觸發 `KeywordAlert`(每關鍵字 2s 冷卻)→ `SessionPage` → `WorkspaceView` 把**非 active 分頁**的圓點標紅、切過去自動清除。**(3) TTL 對齊 TeraTerm** — 新 `TtlExpression` 運算式解析器(括號/邏輯/比較/十六進位 `0x`/`$`,失敗退回 legacy 規則相容舊腳本);新增控制流 `goto/call(行內執行,迴圈內可用)/return/for-next/do-loop/until-enduntil/break/continue/end/exit/include/mpause`、等待 `waitln/waitregex/recvln/wait 多字串(TeraTerm 語意:逾時 result=0 繼續)/mtimeout`、字串 `strlen/strcompare/strconcat/strcopy/strinsert/strremove/strmatch/strscan/strreplace/strtrim/strsplit/strjoin/tolower/toupper/str2int/int2str/code2str/str2code/sprintf(→inputstr)/expandenv`、檔案 `fileopen/filereadln(result=1 是 EOF)/filewrite(ln)/fileclose/filecreate/filedelete/filesearch/basename/dirname/makepath/foldercreate/folderdelete/foldersearch/getdir/setdir`、雜項 `beep/getdate/gettime(strftime 子集)/getenv/setenv/random/exec/getver/getttdir/uptime/ifdefined/clipb2var/var2clipb/inputbox/yesnobox/crc32/checksum8/16/32/dispstr`、serial 專用 `sendbreak/setbaud/setdtr/setrts/sendfile`(`SerialChannel` 新增對應方法);單行 `if ` 支援;`Preprocess` 引號內 `;` 不再被當註解;系統變數 `inputstr/matchstr/groupmatchstr1-9`;`_vars` 改大小寫不敏感;**單字串 `wait` 保留 ETTerms settle+逾時中止語意(勿改)**,多字串才是 TeraTerm 語意。`SessionPage` 把 `runner.Output`(含 `dispstr`)以灰色 echo 進終端機。指令表+範例:[docs/ttl-script-reference.md](docs/ttl-script-reference.md)(前段 ETTerms 獨有、後段與 TeraTerm 共有)。 + **v0.4.0:** 效能 / 穩定性總整理(來自全 codebase 審視)。**(1) 終端機繪製熱路徑去配置** — `TerminalView` 快取 4 種 Font 變體(Bold/Underline 組合)與單一可變色 `SolidBrush`,run 合併時每 cell 顏色只解析一次,`Dispose` 收掉 GDI 資源;**(2) scrollback 改環形緩衝** — `ScreenBuffer` 從 `List+RemoveRange(0,…)`(滿了每行 O(n) 搬移)改 O(1) ring buffer;**(3) UTF-8 跨 chunk 亂碼修正(3 處)** — `TTLInterpreter.OnData`、`SerialBridgeServer` rx 轉發、`SessionLogger.Write` 改用 stateful `Decoder`(比照 `AnsiParser` 原本的正確做法);**(4) PDU SNMP 批次查詢** — 新共用專案 **`src/ETTerms.PduCore/`** 取代 GUI 與 PduMcp 兩份複製的 `PduController`(log 走建構子委派),新增 `GetAllPortsStatus()` 一個 SNMP GET 帶 12 個 varbind,12 port 輪詢從 36 個 UDP 來回縮成 3 個(StatusView 與 `pdu_status` 都改用);**(5) ShellChannel 資源修正** — `DeleteProcThreadAttributeList`+`FreeHGlobal` 釋放 attribute list、`CloseHandle(pi.hProcess)`,shell 自行 exit 時顯示灰色 `[ETTerms] shell process exited` 提示;**(6) SSH 斷線可見** — 訂 `ErrorOccurred`/`ShellStream.Closed` 顯示提示,`Write` 例外不再炸 UI thread;**(7) 終端機行為** — 新輸出只在已貼底時跟隨(看歷史不被拉回底部)、alt screen 滾輪轉方向鍵(vim/htop 可滾)、回應 DSR `ESC[6n`/`ESC[5n` 與 DA `ESC[c`(TUI 查游標位置不再卡住);**(8) TTL** — `_recv` 上限 1MB、wait 輪詢長度沒變不重掃;**(9) 去重複** — `ScriptRunner` 兩個 Run 合併、`TtlScript` 共用選檔/group 指令檢查(SessionPage/WorkspaceView 三份流程收斂)、`ConnectionStore` 讀取改 InvariantCulture+RoundtripKind。註:group `waitall` 一個成員失敗其他成員停在 barrier 是**刻意行為**(使用者要求整組停下),勿「修」。 **v0.3.2:** **(1) 新增左側 `Status` rail view** — 位於 Terminal 與 Settings 之間(圖示 `⚡`,新增 `ActivityRail.RailView.Status` 列舉與 `Items`),獨立 `App/StatusView.cs`,沿用 `SettingsView` 的自繪 tab strip + panel 切換風格(避免 TabControl 白邊);`MainForm` 加 `_statusView` 欄位、佈局與 rail 切換可見性。目前只有 **PDU 分頁**,未來會再加分頁(`MakeTab(...)` 即可擴充)。**(2) PDU 搬到 Status 並改自動輪詢** — PDU 從 `SettingsView` 移到 `StatusView`,**移除手動 Refresh 按鈕**,連線成功後以 `System.Threading.Timer`(period 3000ms)在**背景執行緒**讀 SNMP、再 `BeginInvoke` 回 UI 更新表格(不卡 UI);`Interlocked` 旗標防止前一輪未讀完就重入;斷線 / 控制項 Dispose 時自動停掉 timer 與 `PduController`;表格下方顯示「last update HH:mm:ss」。`SettingsView` 移除 `BuildPduTab`/`RefreshPduGrid` 與 `ETTerms.Scripting.Pdu` import,現只剩 **Terminal / AI MCP** 兩分頁。**(2b) PDU 分頁加手動開關鈕** — 狀態表格新增 **Control** 欄(`DataGridViewButtonColumn`),每個 Port 一顆鈕,文字隨狀態切換(ON→「Turn OFF」、OFF→「Turn ON」、未知→「—」);點擊在背景執行緒呼叫 `PduController.SetPortOn/SetPortOff`(不卡 UI),等 ~400ms 後回讀刷新整表,失敗跳 `MessageBox`;未連線點擊會提示先 Connect,斷線時清空表格避免顯示過時狀態。**(3) 修 `ShellChannel` 啟動目錄 fallback** — 本機 Shell 的 `StartupDirectory` 若已不存在(外接碟拔除 / 資料夾被刪)會 `CreateProcess failed: 267 (ERROR_DIRECTORY)`;改為「為空 **或** `Directory.Exists` 為 false」即 fallback 到使用者家目錄(`Environment.SpecialFolder.UserProfile`,隨登入者變動,例如 `C:\Users\et_wen`),與 Windows PowerShell 行為一致。 diff --git a/docs/ttl-script-reference.md b/docs/ttl-script-reference.md index 29fef7d..03ccd96 100644 --- a/docs/ttl-script-reference.md +++ b/docs/ttl-script-reference.md @@ -1,178 +1,302 @@ # TTL Script Reference — ETTerms > ETTerms 的 TTL(Tera Term Language)腳本引擎移植自 MyTeraTerm,改為驅動原生 -> `ISessionChannel`(SSH / Serial 皆可)。在 **Scripts 檢視**載入 `.ttl` 腳本,對 -> **目前 active session** 執行(先在 Terminal 檢視開好連線)。 +> `ISessionChannel`(SSH / Serial / Shell 皆可)。在分頁上按 **▶ Script** 載入 `.ttl` +> 對該分頁執行;或用 toolbar 的 **▶ Run All** / **▶ Group1-3** 批次執行。 +> +> v0.5.0 起大幅對齊 [TeraTerm macro 指令集](https://teratermproject.github.io/manual/5/en/macro/command/index.html)。 +> 本文**前段是 ETTerms 獨有指令**,**後段是與 TeraTerm 共有的指令**。 執行於背景執行緒,可隨時按 **Stop** 中止;`wait` / `pause` 期間皆可取消。 +腳本的進度訊息(`[wait]`、`dispstr`、錯誤等)會以灰色顯示在該分頁的終端機裡。 --- ## 語法規則 - 一行一個指令;前後空白會被去除。 -- 註解:`;` 之後到行尾視為註解。 -- 字串引號 `'...'` 或 `"..."` 皆可,送出時引號會被去除。 -- 變數以 `名稱 = 值` 指派;名稱須符合 `^[a-zA-Z_][a-zA-Z0-9_]*$`。 -- 內建變數 `result`:`wait` 命中為 `1`、逾時為 `0`。 -- 換行:`sendln` 自動附加 `\r\n`。 +- 註解:`;` 之後到行尾(**引號內的 `;` 不算**)。 +- 字串引號 `'...'` 或 `"..."` 皆可。 +- Label:`:名稱` 一行,供 `goto` / `call` 跳轉。 +- 變數以 `名稱 = 運算式` 指派;名稱須符合 `[a-zA-Z_][a-zA-Z0-9_]*`,大小寫不分。 +- 運算式支援:整數(十進位 / `0x1F` / `$1F`)、字串、括號、`+ - * / %`、 + 比較 `= == <> != > < >= <=`、邏輯 `and or xor not`(同義 `&& || !`)。 + 比較時兩邊都是數字用數值比較,否則字串比較;未定義變數視為 `0`。 +- 單行 if:`if <條件> <指令>`(如 `if result = 0 goto retry`);區塊 if 用 `then ... endif`。 + +### 系統變數 + +| 變數 | 說明 | +|------|------| +| `result` | 多數指令的結果碼(各指令說明)。 | +| `inputstr` | `waitln` / `recvln` / `inputbox` / `sprintf` 的結果字串。 | +| `matchstr` | `waitregex` / `strmatch` 命中的整段文字。 | +| `groupmatchstr1`〜`9` | regex 群組(`waitregex` / `strmatch`)或 `strsplit` 的分段。 | +| `timeout` | wait 家族的逾時(秒),`timeout = 10`;0 = 無限等待。 | +| `mtimeout` | 逾時的毫秒部分,與 `timeout` 相加(`mtimeout = 500`)。 | --- -## 指令對照表 +# 一、ETTerms 獨有指令 + +## Group 同步(多分頁協同) + +以下指令**只能在 Run Group 模式**下使用(toolbar 的 `▶ Group1-3`)。 +`▶ Script` 和 `▶ Run All` 會拒絕含這些指令的腳本。 +Group 內的成員依序編為 **A, B, C...**(顯示在 cell footer,如 `[Group1-A]`)。 + +> ⚠ 刻意設計:group 同步時**一個成員停止(Stop / 逾時 / 錯誤),其他成員會停在 +> barrier 等**——整組一起停下來,避免半組繼續跑造成狀態不一致。 | 指令 | 語法 | 說明 | |------|------|------| -| `send` | `send '文字'` | 送出文字(不加換行)到 active session。 | -| `sendln` | `sendln '文字'` | 送出文字並附加 `\r\n`。 | -| `wait` | `wait '字串'` | **一直等到**接收緩衝出現指定字串才往下;預設無限等待(可按 Stop 取消)。命中後會再確認裝置「安靜」約 300ms(無新資料)才接受,以排除夾在輸出中途的回顯(如 `SVOS> help`),並消費到該字串**最後一次**出現(含)之前的內容,`result=1`。 | -| `pause` | `pause 秒數` | 暫停指定秒數(可被 Stop 中止)。 | -| `timeout` | `timeout = 秒數` | 設定 `wait` 的逾時秒數。預設 `0`=無限等待;若設為 `N>0`,`wait` 超過 N 秒仍未命中會**中止整個腳本並報錯**(不會略過 `wait` 往下做)。 | -| `flushrecv` | `flushrecv` | 清空接收緩衝區。 | -| `logopen` | `logopen '檔名'` | 開啟 log 檔(覆寫);`send` 與 `logwrite` 會寫入。 | -| `logwrite` | `logwrite '文字'` | 寫一行到 log 檔。 | -| `logclose` | `logclose` | 關閉 log 檔(腳本結束時自動關閉)。 | -| `messagebox` | `messagebox '訊息'` | 跳出訊息對話框。 | -| `sprintf2` | `sprintf2 變數 格式 [引數 ...]` | C `printf` 風格格式化,結果存入字串變數。詳見下方說明。 | -| `if` / `elseif` / `else` / `endif` | 見下 | 條件分支(可巢狀)。 | -| `while` / `endwhile` | 見下 | 迴圈(可巢狀,可被 Stop 中止)。 | -| `名稱 = 值` | `idx = 0` | 變數指派,支援 `+ - * /` 整數運算與字串。 | - -> **注意:** PDU 控制指令(`pductrl` / `pduconnect`)屬 Phase 7,本階段尚未提供。 - ---- - -## Group 同步指令 - -以下指令**只能在 Run Group 模式**下使用(toolbar 的 `▶ Group1` / `▶ Group2` / `▶ Group3`)。 -若在 `▶ Script`(分頁個別執行)或 `▶ Run All` 使用,會跳 Warning 並拒絕執行。 - -Group 內的成員依加入順序編為 **A, B, C, D...**,顯示在 cell footer(如 `[Group1-A]`)。 - -| 指令 | 語法 | 說明 | -|------|------|------| -| `waitall` | `waitall '字串'` | 各成員各自 `wait` 到指定字串出現後,再等其他成員也完成,全員到齊才繼續下一步。 | -| `sendlnall` | `sendlnall '文字'` | 等所有成員到達此行後,每人各自對自己的 channel `sendln` 同一段文字。 | -| `sendlngroup` | `sendlngroup A '文字'` | 只有指定 member(A/B/C...)會 `sendln`,其他成員跳過。用於 Group 內各設備需送不同指令的情境。 | - -### Group 範例:同步升級多台交換機 +| `waitall` | `waitall '字串'` | 各成員各自 `wait` 到字串出現,再等其他成員到齊才繼續。 | +| `sendlnall` | `sendlnall '文字'` | 等所有成員到達此行後,每人各自 `sendln` 同一段文字。 | +| `sendlngroup` | `sendlngroup A '文字'` | 只有指定 member(A/B/C...)`sendln`,其他成員跳過。 | ```ttl -; Group1 有 A=SW1, B=SW2, C=SW3 -; 每台各自等到 prompt 再同步 +; Group1 有 A=SW1, B=SW2, C=SW3 — 同步升級 waitall '#' - -; 各送不同指令 sendlngroup A 'copy tftp://10.0.0.1/sw1.bin flash:' sendlngroup B 'copy tftp://10.0.0.1/sw2.bin flash:' sendlngroup C 'copy tftp://10.0.0.1/sw3.bin flash:' - -; 等所有人下載完畢 waitall '#' - -; 全員一起 reload sendlnall 'reload' -waitall 'confirm' -sendlnall 'y' ``` -### Group 設定方式 +## PDU 電源控制(iPoMan II/III,SNMP) -1. 在分頁 Tab 上**右鍵** → 選擇 `Group 1` / `Group 2` / `Group 3`(或 `No Group` 取消) -2. 設定後 cell footer 會顯示 `[Group1-A]`、`[Group1-B]` 等標籤 -3. 點 toolbar 的 `▶ Group1` 載入 `.ttl` 檔,Group 內所有成員平行執行同一份腳本 +| 指令 | 語法 | 說明 | +|------|------|------| +| `pduconnect` | `pduconnect ` | 連 PDU 並驗證,`result` 1/0。device 為自訂編號。 | +| `pductrl` | `pductrl <0\|1>` | 指定插座 OFF(0)/ON(1),`result` 1/0。 | + +```ttl +pduconnect 1 192.168.1.21 +if result = 0 goto fail +pductrl 1 3 0 ; DUT 斷電 +pause 5 +pductrl 1 3 1 ; DUT 上電 +wait 'login:' +:fail +``` + +## 行為與 TeraTerm 不同之處(重要) + +| 項目 | ETTerms 行為 | +|------|--------------| +| `wait`(**單字串**) | 命中後需裝置**安靜 300ms**(無新資料)才接受,並取「最後一次」出現——排除輸出中途的指令回顯(如 `SVOS> help`)造成腳本搶跑。**逾時會中止腳本**(TeraTerm 是 `result=0` 繼續)。 | +| `wait`(**多字串**) | TeraTerm 相容:任一命中即繼續,`result` = 第幾個字串(1 起算);逾時 `result=0` **繼續執行**、無 settle。 | +| `goto` / 跨區塊跳轉 | `goto` 跳出 `if`/`while` 區塊後,該區塊的迴圈控制即結束(同層繼續直行)。避免 goto 跳「進」區塊中間。 | +| `call` | 可以在迴圈 / if 內使用(行內執行,返回後迴圈續跑)。 | +| `include` | 路徑須為絕對路徑,或相對於 ETTerms 的工作目錄。 | +| 浮點數 | TTL 無浮點型別;`sprintf/sprintf2` 的浮點引數以字串傳入(`'3.14'`)。 | --- -## 條件運算子 +# 二、與 TeraTerm 共有指令 -`if` / `elseif` / `while` 條件支援: +## 通訊 -| 運算子 | 類型 | 範例 | -|--------|------|------| -| `>=` `<=` `>` `<` | 數值 | `if idx >= 3 then` | -| `==` `!=` | 字串 / 數值 | `if result == 1 then` | -| `=` | 數值或字串相等 | `if result = 0 then` | -| (無運算子) | 非零為真 | `if result then` | +| 指令 | 語法 | 說明 | +|------|------|------| +| `send` | `send '文字'` | 送出文字(不加換行)。 | +| `sendln` | `sendln '文字'` | 送出文字 + `\r\n`。 | +| `sendfile` | `sendfile '路徑'` | 把整個檔案內容原樣送出(`result` 1/0)。 | +| `wait` | `wait '字串' ['字串2' ...]` | 等待字串出現(行為差異見上表)。 | +| `waitln` | `waitln '字串' ['字串2' ...]` | 等**包含**任一字串的完整一行;該行存入 `inputstr`,`result`=第幾個;逾時 0。 | +| `waitregex` | `waitregex '樣式' ['樣式2' ...]` | 等 regex 命中;`matchstr` / `groupmatchstr1-9` 設定,`result`=第幾個;逾時 0。 | +| `recvln` | `recvln` | 收下一行到 `inputstr`;`result` 1 成功 / 0 逾時。 | +| `flushrecv` | `flushrecv` | 清空接收緩衝。 | +| `dispstr` | `dispstr '文字' [更多...]` | 在終端機顯示訊息(灰色,不送出到裝置)。 | +| `sendbreak` | `sendbreak` | 送 serial break(**Serial 限定**,約 300ms)。 | +| `setbaud` | `setbaud 115200` | 執行中改 baud rate(**Serial 限定**)。 | +| `setdtr` / `setrts` | `setdtr 1` / `setrts 0` | 控制 DTR / RTS 腳位(**Serial 限定**)。 | -`then` 關鍵字可省略。 +## 控制流 + +| 指令 | 語法 | 說明 | +|------|------|------| +| `if` | `if <條件> <指令>` 或 `if <條件> then ... [elseif] [else] endif` | 單行或區塊,可巢狀。 | +| `while` / `endwhile` | `while <條件>` | 條件為真時重複。 | +| `until` / `enduntil` | `until <條件>` | 條件為**假**時重複。 | +| `for` / `next` | `for i 1 10` | i 從 1 到 10(含),自動 ±1。 | +| `do` / `loop` | `do [while\|until <條件>]` ... `loop [while\|until <條件>]` | 前測或後測迴圈;都不帶條件時為無限迴圈(用 `break` 離開)。 | +| `break` / `continue` | | 跳出 / 提前進入下一輪(while / until / for / do 皆可)。 | +| `goto` | `goto 標籤` | 跳到 `:標籤`。 | +| `call` / `return` | `call 標籤` | 呼叫副程式(`:標籤` 起,`return` 返回;可在迴圈內用)。 | +| `include` | `include '檔案.ttl'` | 執行另一個腳本檔(可巢狀 8 層;檔內 `exit` 只離開該檔)。 | +| `pause` | `pause 秒` | 暫停(可 Stop 取消)。 | +| `mpause` | `mpause 毫秒` | 毫秒級暫停。 | +| `end` | `end` | 結束腳本(成功)。 | +| `exit` | `exit` | include 檔內=離開該檔;主檔=同 `end`。 | +| `timeout` / `mtimeout` | `timeout = 10` | wait 家族逾時(秒 / 毫秒,兩者相加)。 | + +## 字串 + +| 指令 | 語法 | 說明 | +|------|------|------| +| `strlen` | `strlen ` | `result` = 長度。 | +| `strcompare` | `strcompare ` | `result` = -1 / 0 / 1。 | +| `strconcat` | `strconcat ` | strvar += str。 | +| `strcopy` | `strcopy ` | 取子字串(pos 1 起算)。 | +| `strinsert` / `strremove` | `strinsert ` / `strremove ` | 插入 / 刪除。 | +| `strscan` | `strscan ` | `result` = 位置(1 起算,0 = 沒找到)。 | +| `strmatch` | `strmatch ` | regex 比對:`result` = 位置,`matchstr` / `groupmatchstr1-9`。 | +| `strreplace` | `strreplace ` | 自 pos 起 regex 全部取代,`result` 1/0。 | +| `strtrim` | `strtrim ['字元集']` | 去頭尾字元(預設空白)。 | +| `strsplit` | `strsplit [count]` | 切成 `groupmatchstr1-9`,`result` = 個數。 | +| `strjoin` | `strjoin [count]` | 把 `groupmatchstr1..count` 接回一串。 | +| `tolower` / `toupper` | `tolower ` | 轉小寫 / 大寫。 | +| `str2int` / `int2str` | `str2int ` / `int2str ` | 字串 ↔ 整數(str2int 的 `result` 1/0)。 | +| `code2str` / `str2code` | `code2str 65` / `str2code 'A'` | 字元碼 ↔ 字元。 | +| `sprintf` | `sprintf <格式> [引數...]` | C printf 格式化 → **`inputstr`**。 | +| `sprintf2` | `sprintf2 <格式> [引數...]` | 同上但存到指定變數(詳見下節)。 | +| `expandenv` | `expandenv '%USERPROFILE%\x'` | 展開環境變數。 | + +## 檔案 / 資料夾 + +| 指令 | 語法 | 說明 | +|------|------|------| +| `fileopen` | `fileopen <路徑> [readonly 0\|1]` | 開檔;fh 存入變數(-1 失敗)。readonly=1 開來讀。 | +| `filecreate` | `filecreate <路徑>` | 建新檔(覆寫)供寫入。 | +| `filereadln` | `filereadln ` | 讀一行;`result` **1 = EOF**、0 = 成功(TeraTerm 相容)。 | +| `filewrite` / `filewriteln` | `filewrite ` | 寫入(ln 版加換行)。 | +| `fileclose` | `fileclose ` | 關檔(腳本結束會自動關)。 | +| `filedelete` | `filedelete <路徑>` | 刪檔,`result` 1/0。 | +| `filesearch` | `filesearch <路徑>` | `result` 1 = 檔案存在。 | +| `basename` / `dirname` | `basename <路徑>` | 取檔名 / 取目錄。 | +| `makepath` | `makepath ` | 合成路徑。 | +| `foldercreate` / `folderdelete` / `foldersearch` | `foldercreate <路徑>` | 建 / 刪(空)/ 查資料夾。 | +| `getdir` / `setdir` | `getdir ` / `setdir <路徑>` | 取得 / 變更工作目錄。 | +| `logopen` / `logwrite` / `logclose` | `logopen '檔名'` | 腳本專屬 log 檔(`send` 與 `logwrite` 會寫入)。 | + +## 對話框 / 雜項 + +| 指令 | 語法 | 說明 | +|------|------|------| +| `messagebox` | `messagebox '訊息' ['標題']` | 訊息框。 | +| `inputbox` | `inputbox '提示' ['標題'] [預設值]` | 輸入框 → `inputstr`(取消 `result=0`)。 | +| `yesnobox` | `yesnobox '訊息' ['標題']` | Yes/No → `result` 1/0。 | +| `beep` | `beep` | 系統提示音。 | +| `getdate` / `gettime` | `getdate ['%Y%m%d']` | 日期 / 時間字串(strftime 子集:`%Y %y %m %d %H %M %S %j %a %A %b`)。 | +| `getenv` / `setenv` | `getenv 'PATH' ` | 讀 / 寫環境變數(行程內)。 | +| `random` | `random ` | 0〜max(含)亂數。 | +| `exec` | `exec '記事本.exe 檔案' ['show'\|'hide'] [wait 0\|1]` | 啟動外部程式;wait=1 時 `result` = exit code。 | +| `getver` | `getver ` | ETTerms 版本字串。 | +| `getttdir` | `getttdir ` | ETTerms 執行檔目錄。 | +| `uptime` | `uptime ` | 系統開機至今毫秒數。 | +| `ifdefined` | `ifdefined ` | `result`:0 未定義 / 1 整數 / 2 字串。 | +| `clipb2var` / `var2clipb` | `clipb2var ` / `var2clipb ` | 剪貼簿 ↔ 變數。 | +| `crc32` | `crc32 ` | CRC-32。 | +| `checksum8/16/32` | `checksum8 ` | byte 加總(8/16/32 bit)。 | + +### 未支援(節錄) + +檔案傳輸協定(`xmodem*` / `zmodem*` / `kmt*` / `scp*`)、連線管理(`connect` / `disconnect` / +`closett`)、密碼系列(`getpassword` 等——ETTerms 密碼一律走 Windows Credential Manager)、 +陣列(`intdim` / `strdim`)、`waitevent` / `waitn` / `setecho` / `settitle` / `listbox` / `statusbox`。 --- ## sprintf2 格式化 -`sprintf2 變數 格式字串 [引數 ...]` 以 C 語言 `printf` 規則格式化,結果存入指定字串變數,與 -Tera Term 的 `sprintf2` 行為一致。 +`sprintf2 變數 格式字串 [引數 ...]` 以 C `printf` 規則格式化,與 Tera Term 一致。 ```ttl -sprintf2 ver 'Tera Term 4.%d' 51 ; ver = "Tera Term 4.51" -sprintf2 win 'Windows %d (+%s)' 2000 'SP4' ; win = "Windows 2000 (+SP4)" +sprintf2 ver 'Tera Term 4.%d' 51 ; ver = "Tera Term 4.51" sprintf2 test '%s=%d %s=0x%x' 'dec' 10 'hex' 33 ; test = "dec=10 hex=0x21" -messagebox test ``` -- **轉換型別**:`c d i o u x X e E f g G a A s` -- **旗標**:`-`(靠左)、`+`(顯示正負號)、`0`(補零)、`#`(替代格式,如 `0x`)、空白(正數前空格) -- **寬度/精度**:十進位整數,或用 `*` 從引數動態取得(如 `%*d`、`%.*f`) -- 浮點數須以**字串**傳入(TTL 無浮點型別),例 `sprintf2 s '%.2f' '3.14159'` -- **格式字串不展開變數**(保持字面值),僅各引數會展開變數,故可累加自身: - `sprintf2 s '%s,' s` 會把 `s` 接上 `,` - -執行後設定系統變數 `result`: - -| 值 | 狀態 | -|----|------| -| 0 | 格式化成功 | -| 1 | 缺少格式字串 | -| 2 | 格式無效 | -| 3 | 引數無效(缺少或無法解析) | -| 4 | 目的變數名稱無效 | +- **轉換型別**:`c d i o u x X e E f g G a A s`;**旗標**:`- + 0 #` 與空白;寬度/精度支援 `*` +- 浮點數以**字串**傳入:`sprintf2 s '%.2f' '3.14159'` +- 格式字串不展開變數(保持字面值),引數會展開,故 `sprintf2 s '%s,' s` 可累加自身 +- `result`:0 成功、1 缺格式、2 格式無效、3 引數無效、4 目的變數無效 --- -## 範例:SSH 自動登入 + 收 log +## 範例 + +### 自動登入 + 失敗重試(goto / 單行 if) ```ttl -; 等提示字元,逐步登入並收集輸出 timeout = 15 +retry = 0 +:login +sendln '' wait 'login:' sendln 'admin' wait 'Password:' sendln 'secret' -wait '$' +wait 'Login incorrect' '$' +if result = 2 goto ok ; 第 2 個字串($ 提示)命中 → 成功 +retry = retry + 1 +if retry < 3 goto login +messagebox '登入失敗 3 次' 'Login' +end -logopen 'session.log' -sendln 'uname -a' -wait '$' -sendln 'uptime' -wait '$' -logclose - -messagebox 'Done' +:ok +dispstr 'login ok' ``` -## 範例:while 迴圈下命令 +### waitln + strmatch 解析輸出 ```ttl -idx = 0 -while idx < 5 - sendln 'echo loop' - wait '$' - idx = idx + 1 -endwhile -``` - -## 範例:if / elseif / else - -```ttl -sendln 'whoami' -wait '$' -if result == 1 then - logwrite 'prompt matched' -elseif result == 0 then - logwrite 'timed out' -else - logwrite 'unknown' +sendln 'show environment' +timeout = 10 +waitln 'Temperature' ; 例如 "Temperature: 47 C" +if result = 0 goto notfound +strmatch inputstr 'Temperature:\s*(\d+)' +if result > 0 then + str2int temp groupmatchstr1 + if temp > 60 then + messagebox '過溫!' 'ALERT' + endif endif +:notfound +``` + +### for 迴圈 + 檔案輸出 + +```ttl +getdate today '%Y%m%d' +sprintf 'report_%s.txt' today +filecreate fh inputstr + +for i 1 5 + sendln 'cat /proc/loadavg' + recvln ; 回顯 + recvln ; 資料行 + filewriteln fh inputstr + pause 2 +next +fileclose fh +``` + +### call 副程式(迴圈內可用) + +```ttl +for i 1 3 + call powercycle + wait 'login:' +next +end + +:powercycle +pductrl 1 3 0 +pause 5 +pductrl 1 3 1 +return +``` + +### do-loop 等裝置就緒 + +```ttl +; 注意:單字串 wait 逾時會「中止腳本」,輪詢請用 waitln(逾時 result=0 繼續) +timeout = 2 +do + sendln '' + waitln 'SVOS>' +loop until result = 1 ; 每 2 秒敲一次直到提示出現 ``` diff --git a/src/ETTerms/App/AboutView.cs b/src/ETTerms/App/AboutView.cs index abdedd3..de9e67d 100644 --- a/src/ETTerms/App/AboutView.cs +++ b/src/ETTerms/App/AboutView.cs @@ -183,6 +183,15 @@ public sealed class AboutView : UserControl private static readonly ChangelogEntry[] Changelog = [ + new("0.5.0", new DateOnly(2026, 7, 2), "Search, keyword alerts & a much bigger scripting language", + [ + "Press Ctrl+F in any terminal to search everything you've scrolled past — all hits are highlighted, Enter jumps between them.", + "New Settings → Highlight page: add your own keywords (like ERROR or FAIL) and they light up in red wherever they appear.", + "When a keyword shows up in a tab you're not looking at, that tab's dot turns red so you don't miss it.", + "TTL scripting grew from ~15 commands to 90+, matching Tera Term macros: loops (for / do / until), goto and subroutines, waitln / waitregex with regex capture, string and file operations, input dialogs, and serial line control (sendbreak, setbaud).", + "Scripts now show their progress in gray right inside the terminal, so you can watch what they're doing.", + "See the full command table with examples in docs/ttl-script-reference.md.", + ]), new("0.4.0", new DateOnly(2026, 7, 2), "Performance & stability overhaul", [ "The terminal is much smoother during heavy output (long boot logs, big file dumps) — drawing and scroll history were reworked to stay fast no matter how much text has scrolled by.", diff --git a/src/ETTerms/App/SettingsView.cs b/src/ETTerms/App/SettingsView.cs index 9505151..fc434c5 100644 --- a/src/ETTerms/App/SettingsView.cs +++ b/src/ETTerms/App/SettingsView.cs @@ -52,6 +52,7 @@ public sealed class SettingsView : UserControl var termBtn = MakeTab("Terminal", BuildTerminalTab()); tabBar.Controls.Add(termBtn); + tabBar.Controls.Add(MakeTab("Highlight", BuildHighlightTab())); tabBar.Controls.Add(MakeTab("AI MCP", BuildAiMcpTab())); Controls.Add(body); @@ -171,6 +172,115 @@ public sealed class SettingsView : UserControl return page; } + // ═══ Highlight Tab ═══ + private Panel BuildHighlightTab() + { + var page = new Panel { BackColor = Theme.WorkspaceBack, Padding = new Padding(20) }; + var s = AppSettings.Instance; + + var flow = new FlowLayoutPanel + { + Dock = DockStyle.Fill, FlowDirection = FlowDirection.TopDown, + WrapContents = false, BackColor = Theme.WorkspaceBack, AutoScroll = true + }; + + flow.Controls.Add(new Label + { + Text = "Keyword Highlighting", AutoSize = true, + ForeColor = Theme.Accent, Font = Theme.UiFontBold, Margin = new Padding(0, 0, 0, 4) + }); + flow.Controls.Add(new Label + { + Text = "Keywords below are highlighted in red in every terminal (case-insensitive).\n" + + "When a keyword appears in a background tab, that tab's dot turns red until you open it.", + AutoSize = false, Width = 520, Height = 34, + ForeColor = Theme.TextDim, Font = Theme.UiFont, Margin = new Padding(0, 0, 0, 8) + }); + + var enable = new CheckBox + { + Text = "Enable keyword highlighting", Checked = s.KeywordHighlightEnabled, + AutoSize = true, ForeColor = Theme.Text, Font = Theme.UiFont, Margin = new Padding(0, 0, 0, 8) + }; + flow.Controls.Add(enable); + + // 規則清單:每列 = 啟用勾選 + 關鍵字(可直接編輯) + var grid = new DataGridView + { + Width = 420, Height = 240, + BackgroundColor = Theme.WorkspaceBack, ForeColor = Theme.Text, GridColor = Theme.Border, + BorderStyle = BorderStyle.None, CellBorderStyle = DataGridViewCellBorderStyle.SingleHorizontal, + DefaultCellStyle = { BackColor = Theme.TabBack, ForeColor = Theme.Text, SelectionBackColor = Theme.Hover, SelectionForeColor = Theme.Text }, + ColumnHeadersDefaultCellStyle = { BackColor = Theme.RailBack, ForeColor = Theme.Accent, Font = Theme.UiFontBold }, + ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.Single, + EnableHeadersVisualStyles = false, RowHeadersVisible = false, + AllowUserToAddRows = false, AllowUserToDeleteRows = false, + AllowUserToResizeRows = false, SelectionMode = DataGridViewSelectionMode.FullRowSelect, + Font = Theme.UiFont, RowTemplate = { Height = 24 }, Margin = new Padding(0, 0, 0, 8) + }; + grid.Columns.Add(new DataGridViewCheckBoxColumn { Name = "On", HeaderText = "On", Width = 44 }); + grid.Columns.Add(new DataGridViewTextBoxColumn + { + Name = "Keyword", HeaderText = "Keyword", + AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill + }); + foreach (var r in s.KeywordRules) grid.Rows.Add(r.Enabled, r.Text); + flow.Controls.Add(grid); + + // 新增 / 移除 + var newKw = new TextBox { Width = 220, BackColor = Theme.TabBack, ForeColor = Theme.Text, Font = Theme.UiFont, BorderStyle = BorderStyle.FixedSingle }; + var addBtn = MakeButton("Add", Theme.Accent); + var removeBtn = MakeButton("Remove Selected", Color.FromArgb(210, 120, 120)); + + void AddKeyword() + { + var t = newKw.Text.Trim(); + if (t.Length == 0) return; + grid.Rows.Add(true, t); + newKw.Clear(); + newKw.Focus(); + } + addBtn.Click += (_, _) => AddKeyword(); + newKw.KeyDown += (_, e) => { if (e.KeyCode == Keys.Enter) { AddKeyword(); e.Handled = e.SuppressKeyPress = true; } }; + removeBtn.Click += (_, _) => + { + foreach (DataGridViewRow row in grid.SelectedRows) grid.Rows.Remove(row); + }; + + var editRow = new FlowLayoutPanel + { + FlowDirection = FlowDirection.LeftToRight, AutoSize = true, + WrapContents = false, BackColor = Theme.WorkspaceBack, Margin = new Padding(0, 0, 0, 12) + }; + editRow.Controls.Add(newKw); + editRow.Controls.Add(addBtn); + editRow.Controls.Add(removeBtn); + flow.Controls.Add(editRow); + + var save = MakeButton("Save", Theme.Accent); + save.Margin = new Padding(0); + save.Click += (_, _) => + { + grid.EndEdit(); + s.KeywordHighlightEnabled = enable.Checked; + s.KeywordRules = grid.Rows.Cast() + .Select(r => new KeywordRule + { + Enabled = r.Cells["On"].Value is true, + Text = r.Cells["Keyword"].Value?.ToString()?.Trim() ?? "" + }) + .Where(r => r.Text.Length > 0) + .ToList(); + s.Save(); + MessageBox.Show(this, "Highlight settings saved.\nThey apply immediately to all open sessions.", + "Highlight", MessageBoxButtons.OK, MessageBoxIcon.Information); + }; + flow.Controls.Add(save); + + page.Controls.Add(flow); + return page; + } + // ═══ AI MCP Tab ═══ private Panel BuildAiMcpTab() { diff --git a/src/ETTerms/App/Workspace/WorkspaceView.cs b/src/ETTerms/App/Workspace/WorkspaceView.cs index 10101c5..1166503 100644 --- a/src/ETTerms/App/Workspace/WorkspaceView.cs +++ b/src/ETTerms/App/Workspace/WorkspaceView.cs @@ -20,6 +20,7 @@ public sealed class WorkspaceView : UserControl public required SessionPage Page; public Rectangle TabBounds; public Rectangle CloseRect; + public bool Alert; // 背景分頁出現高亮關鍵字 → 標紅點,切到該分頁時清除 } private readonly FlowLayoutPanel _toolbar; @@ -114,6 +115,12 @@ public sealed class WorkspaceView : UserControl var page = BuildPage(conn); var s = new Session { Title = conn.Name, IsSsh = conn.IsSsh, Page = page }; page.ConnectFailed += msg => OnConnectFailed(s, msg); + page.KeywordAlert += _ => + { + if (s == _active || s.Alert) return; + s.Alert = true; + _tabStrip.Invalidate(); + }; _sessions.Add(s); _active = s; Relayout(); @@ -191,6 +198,7 @@ public sealed class WorkspaceView : UserControl } _empty.Visible = false; _active ??= _sessions[0]; + _active.Alert = false; // 使用者正在看這個分頁,警示清除 int cells = _rows * _cols; int activeIdx = _sessions.IndexOf(_active); @@ -360,7 +368,8 @@ public sealed class WorkspaceView : UserControl if (drag) using (var pen = new Pen(Theme.Accent, 1)) g.DrawRectangle(pen, new Rectangle(s.TabBounds.Left, s.TabBounds.Top, s.TabBounds.Width - 1, s.TabBounds.Height - 1)); - using (var dot = new SolidBrush(s.IsSsh ? Theme.SshColor : Theme.SerialColor)) + // 警示中的背景分頁:型別圓點改紅色,切過去看時清除 + using (var dot = new SolidBrush(s.Alert ? Color.FromArgb(235, 85, 85) : s.IsSsh ? Theme.SshColor : Theme.SerialColor)) g.FillEllipse(dot, s.TabBounds.Left + 9, StripH / 2 - 4, 8, 8); var tr = new Rectangle(s.TabBounds.Left + 22, s.TabBounds.Top, s.TabBounds.Width - 22 - CloseSz - 10, StripH); TextRenderer.DrawText(g, s.Title, Theme.UiFont, tr, active ? Theme.Text : Theme.TextDim, diff --git a/src/ETTerms/ETTerms.csproj b/src/ETTerms/ETTerms.csproj index f4101d8..5a37617 100644 --- a/src/ETTerms/ETTerms.csproj +++ b/src/ETTerms/ETTerms.csproj @@ -10,7 +10,7 @@ ETTerms - 0.4.0 + 0.5.0 ETTerms ETTerms Project @@ -51,9 +51,9 @@ <_McpSelfContained Condition="'$(SelfContained)' != ''">$(SelfContained) <_McpSelfContained Condition="'$(SelfContained)' == ''">false - + - + diff --git a/src/ETTerms/Infrastructure/AppSettings.cs b/src/ETTerms/Infrastructure/AppSettings.cs index cb167cf..30ac9d8 100644 --- a/src/ETTerms/Infrastructure/AppSettings.cs +++ b/src/ETTerms/Infrastructure/AppSettings.cs @@ -27,6 +27,10 @@ public sealed class AppSettings public string ShellType { get; set; } = "PowerShell"; // PowerShell, Bash, Cmd public string ShellStartupDir { get; set; } = ""; + // ── Keyword highlight(終端機關鍵字標色 + 分頁警示;Settings → Highlight 分頁設定)── + public bool KeywordHighlightEnabled { get; set; } = true; + public List KeywordRules { get; set; } = new(); + // ── Window ── public int WindowX { get; set; } = -1; public int WindowY { get; set; } = -1; @@ -83,3 +87,10 @@ public sealed class AppSettings return new(); } } + +/// 一條關鍵字高亮規則:關鍵字文字 + 是否啟用(比對不分大小寫)。 +public sealed class KeywordRule +{ + public string Text { get; set; } = ""; + public bool Enabled { get; set; } = true; +} diff --git a/src/ETTerms/Scripting/TTLInterpreter.cs b/src/ETTerms/Scripting/TTLInterpreter.cs index e0373c5..2803f93 100644 --- a/src/ETTerms/Scripting/TTLInterpreter.cs +++ b/src/ETTerms/Scripting/TTLInterpreter.cs @@ -1,6 +1,8 @@ +using System.Diagnostics; using System.Globalization; using System.Text; using System.Text.RegularExpressions; +using System.Windows.Forms; using ETTerms.Infrastructure; using ETTerms.PduCore; using ETTerms.Sessions; @@ -8,10 +10,16 @@ using ETTerms.Sessions; namespace ETTerms.Scripting; /// -/// TTL (Tera Term Language) 直譯器,移植自 MyTeraTerm,改驅動 -/// (取代舊版的 ComPortBridge)。送出走 channel.Write,接收監聽 channel.DataReceived。 -/// 支援:send / sendln / pause / wait / timeout / flushrecv / logopen / logwrite / logclose / -/// messagebox / if-elseif-else-endif / while-endwhile / 變數指派。 +/// TTL (Tera Term Language) 直譯器,移植自 MyTeraTerm,改驅動 。 +/// 送出走 channel.Write,接收監聽 channel.DataReceived。 +/// +/// v0.5.0 起大幅對齊 TeraTerm macro 指令集: +/// 控制流 goto / call / return / for-next / do-loop / until-enduntil / break / continue / +/// end / exit / include / mpause;等待 waitln / waitregex / recvln / wait 多字串 / mtimeout; +/// 字串、檔案、雜項、serial 控制指令。完整清單見 docs/ttl-script-reference.md。 +/// +/// 運算式(if / while / until / for / 指派)由 解析; +/// 解析失敗時退回 v0.4 的 legacy 規則以相容舊腳本。 /// 阻塞執行(wait/pause 用 Thread.Sleep),由 放到背景執行緒驅動。 /// public sealed class TTLInterpreter : IDisposable @@ -19,7 +27,7 @@ public sealed class TTLInterpreter : IDisposable private readonly ISessionChannel _channel; private readonly Encoding _enc = new UTF8Encoding(false); private readonly Decoder _rxDecoder = Encoding.UTF8.GetDecoder(); // stateful:多位元組字元跨 chunk 不會解成亂碼 - private readonly Dictionary _vars = new(); + private readonly Dictionary _vars = new(StringComparer.OrdinalIgnoreCase); private readonly StringBuilder _recv = new(); private readonly CancellationTokenSource _cts = new(); @@ -30,7 +38,8 @@ public sealed class TTLInterpreter : IDisposable private string _groupMemberLabel = ""; private readonly Dictionary _pdus = new(); private StreamWriter? _logWriter; - private int _timeout; // 0 = 無限等待(wait 會一直等到關鍵字出現或被取消) + private int _timeout; // ms;0 = 無限等待 + private int _mtimeout; // ms;與 timeout 相加(TeraTerm mtimeout) private int _result; private string[] _lines = Array.Empty(); private int _line; @@ -38,10 +47,16 @@ public sealed class TTLInterpreter : IDisposable private volatile bool _cancelled; private bool _disposed; + // v0.5.0 新增狀態 + private readonly Dictionary _fileHandles = new(); // fileopen 的 fh → StreamReader/StreamWriter + private int _fileSeq; + private int _includeDepth; + private int _callDepth; + /// (檔名, 行號, 當前指令) 進度更新。 public event Action? StatusChanged; - /// 輸出訊息(log / 提示 / 錯誤),供 UI 顯示。 + /// 輸出訊息(log / 提示 / 錯誤 / dispstr),供 UI 顯示。 public event Action? Output; public TTLInterpreter(ISessionChannel channel, GroupSyncContext? groupSync = null, string memberLabel = "") @@ -74,26 +89,62 @@ public sealed class TTLInterpreter : IDisposable _lines = Preprocess(scriptContent); _line = 0; + try { RunMainLoop(); } + catch (ExitSignal) { } // 主檔的 exit 視同 end + + StatusChanged?.Invoke(_scriptFile, _lines.Length, "Completed"); + LogClose(); + } + + /// 頂層執行迴圈:goto / call / return / end 的訊號都在這層收斂。 + private void RunMainLoop() + { while (_line < _lines.Length) + { + ThrowIfCancelled(); + StatusChanged?.Invoke(_scriptFile, _line + 1, _lines[_line]); + try + { + ExecuteLine(_lines[_line]); + } + catch (GotoSignal g) { _line = g.Target; continue; } + catch (ReturnSignal) { throw new Exception("'return' without matching 'call'"); } + catch (EndSignal) { return; } + _line++; + } + } + + /// 執行 [start, end) 區間(if / while / for / do / until 的區塊本體)。 + /// Break/Continue 由呼叫端迴圈處理;goto/call/return/end 一路往頂層傳。 + private void ExecuteRange(int start, int end) + { + _line = start; + while (_line < end) { ThrowIfCancelled(); StatusChanged?.Invoke(_scriptFile, _line + 1, _lines[_line]); ExecuteLine(_lines[_line]); _line++; } - - StatusChanged?.Invoke(_scriptFile, _lines.Length, "Completed"); - LogClose(); } + /// 前處理:去註解(引號內的 ; 不算註解)、去空白行。 private static string[] Preprocess(string content) { var lines = new List(); foreach (string raw in content.Split('\n')) { string t = raw.Trim(); - int comment = t.IndexOf(';'); - if (comment >= 0) t = t.Substring(0, comment).Trim(); + char quote = '\0'; + int comment = -1; + for (int i = 0; i < t.Length; i++) + { + char c = t[i]; + if (quote != '\0') { if (c == quote) quote = '\0'; continue; } + if (c is '\'' or '"') { quote = c; continue; } + if (c == ';') { comment = i; break; } + } + if (comment >= 0) t = t[..comment].Trim(); if (!string.IsNullOrWhiteSpace(t)) lines.Add(t); } return lines.ToArray(); @@ -108,6 +159,15 @@ public sealed class TTLInterpreter : IDisposable #region Line Execution + /// 這些 legacy 指令維持 v0.4 的「整行變數展開」行為(含引號內),確保舊腳本不變。 + /// 新指令一律自行解析引數(變數展開由運算式解析器處理,目的變數名稱不會被誤展開)。 + private static readonly HashSet LegacyExpand = new(StringComparer.OrdinalIgnoreCase) + { + "send", "sendln", "wait", "pause", "timeout", "flushrecv", + "logopen", "logwrite", "logclose", "messagebox", + "waitall", "sendlnall", "sendlngroup", "pduconnect", "pductrl" + }; + private void ExecuteLine(string line) { string original = line; @@ -116,8 +176,8 @@ public sealed class TTLInterpreter : IDisposable && !original.Contains(">=") && !original.Contains("<=") && !original.StartsWith("if ") && !original.StartsWith("elseif "); - string command = GetCommand(line).ToLower(); - if (!isAssignment && command != "while" && command != "if" && command != "sprintf2") + string command = GetCommand(line).ToLowerInvariant(); + if (!isAssignment && LegacyExpand.Contains(command)) line = ReplaceVariables(line); if (line.StartsWith(":")) return; // label @@ -126,29 +186,129 @@ public sealed class TTLInterpreter : IDisposable switch (command) { + // ── 通訊 ── case "send": Send(args, false); break; case "sendln": Send(args, true); break; - case "pause": Pause(args); break; - case "wait": Wait(args); break; - case "timeout": SetTimeout(args); break; + case "wait": DispatchWait(args); break; + case "waitln": WaitLn(TokenizeArgs(args)); break; + case "waitregex": WaitRegex(TokenizeArgs(args)); break; + case "recvln": RecvLn(); break; case "flushrecv": FlushReceive(); break; + case "dispstr": DispStr(args); break; + case "sendfile": SendFile(args); break; + case "sendbreak": SerialOnly(sc => sc.SendBreak(), "sendbreak"); break; + case "setbaud": SerialOnly(sc => sc.SetBaudRate(ValI(FirstToken(args))), "setbaud"); break; + case "setdtr": SerialOnly(sc => sc.SetDtr(ValI(FirstToken(args)) != 0), "setdtr"); break; + case "setrts": SerialOnly(sc => sc.SetRts(ValI(FirstToken(args)) != 0), "setrts"); break; + + // ── 時間 / 逾時 ── + case "pause": Pause(args); break; + case "mpause": MPause(args); break; + case "timeout": SetTimeout(args); break; + case "mtimeout": SetMTimeout(args); break; + + // ── log ── case "logopen": LogOpen(args); break; case "logwrite": LogWrite(args); break; case "logclose": LogClose(); break; + + // ── 對話框 ── case "messagebox": ShowMessageBox(args); break; - case "sprintf2": ExecuteSprintf2(args); break; - case "waitall": ExecuteWaitAll(args); break; - case "sendlnall": ExecuteSendlnAll(args); break; - case "sendlngroup": ExecuteSendlnGroup(args); break; - case "pduconnect": ExecutePduConnect(args); break; - case "pductrl": ExecutePduCtrl(args); break; + case "inputbox": InputBox(args); break; + case "yesnobox": YesNoBox(args); break; + + // ── 控制流 ── + case "goto": throw new GotoSignal(FindLabel(StripQuotes(args.Trim()))); + case "call": ExecuteCall(FindLabel(StripQuotes(args.Trim()))); break; + case "return": throw new ReturnSignal(); + case "end": throw new EndSignal(); + case "exit": throw new ExitSignal(); + case "break": throw new BreakSignal(); + case "continue": throw new ContinueSignal(); + case "include": ExecuteInclude(args); break; case "while": ExecuteWhile(original); break; + case "until": ExecuteUntil(original); break; + case "for": ExecuteFor(original); break; + case "do": ExecuteDo(original); break; case "if": ExecuteIf(original); break; case "endwhile": + case "enduntil": + case "next": + case "loop": case "elseif": case "else": case "endif": - break; // handled by ExecuteWhile / ExecuteIf + break; // 區塊邊界由對應的 Execute* 處理 + + // ── 字串 ── + case "sprintf2": ExecuteSprintf2(args); break; + case "sprintf": ExecuteSprintf(args); break; + case "strlen": StrLen(args); break; + case "strcompare": StrCompare(args); break; + case "strconcat": StrConcat(args); break; + case "strcopy": StrCopy(args); break; + case "strinsert": StrInsert(args); break; + case "strremove": StrRemove(args); break; + case "strmatch": StrMatch(args); break; + case "strscan": StrScan(args); break; + case "strreplace": StrReplace(args); break; + case "strtrim": StrTrim(args); break; + case "strsplit": StrSplit(args); break; + case "strjoin": StrJoin(args); break; + case "tolower": ToLowerCmd(args); break; + case "toupper": ToUpperCmd(args); break; + case "str2int": Str2Int(args); break; + case "int2str": Int2Str(args); break; + case "code2str": Code2Str(args); break; + case "str2code": Str2Code(args); break; + case "expandenv": ExpandEnv(args); break; + + // ── 檔案 ── + case "fileopen": FileOpenCmd(args); break; + case "fileclose": FileCloseCmd(args); break; + case "filereadln": FileReadLn(args); break; + case "filewrite": FileWriteCmd(args, false); break; + case "filewriteln": FileWriteCmd(args, true); break; + case "filecreate": FileCreateCmd(args); break; + case "filedelete": FileDeleteCmd(args); break; + case "filesearch": FileSearchCmd(args); break; + case "basename": BaseNameCmd(args); break; + case "dirname": DirNameCmd(args); break; + case "makepath": MakePathCmd(args); break; + case "foldercreate": FolderCreateCmd(args); break; + case "folderdelete": FolderDeleteCmd(args); break; + case "foldersearch": FolderSearchCmd(args); break; + case "getdir": GetDirCmd(args); break; + case "setdir": SetDirCmd(args); break; + + // ── 雜項 ── + case "beep": try { System.Media.SystemSounds.Beep.Play(); } catch { } break; + case "getdate": GetDateCmd(args, "%Y-%m-%d"); break; + case "gettime": GetDateCmd(args, "%H:%M:%S"); break; + case "getenv": GetEnvCmd(args); break; + case "setenv": SetEnvCmd(args); break; + case "random": RandomCmd(args); break; + case "exec": ExecCmd(args); break; + case "getver": SetDest(FirstToken(args), AppVersion()); break; + case "getttdir": SetDest(FirstToken(args), AppContext.BaseDirectory.TrimEnd('\\', '/')); break; + case "uptime": SetDest(FirstToken(args), unchecked((int)Environment.TickCount64)); break; + case "ifdefined": IfDefined(args); break; + case "clipb2var": Clipb2Var(args); break; + case "var2clipb": Var2Clipb(args); break; + case "crc32": SetDest(FirstToken(args), unchecked((int)Crc32(ValS(SecondToken(args))))); break; + case "checksum8": Checksum(args, 0xFF); break; + case "checksum16": Checksum(args, 0xFFFF); break; + case "checksum32": Checksum(args, -1); break; + + // ── Group 同步(ETTerms 獨有)── + case "waitall": ExecuteWaitAll(args); break; + case "sendlnall": ExecuteSendlnAll(args); break; + case "sendlngroup": ExecuteSendlnGroup(args); break; + + // ── PDU(ETTerms 獨有)── + case "pduconnect": ExecutePduConnect(args); break; + case "pductrl": ExecutePduCtrl(args); break; + case "": if (isAssignment) ExecuteAssignment(original); break; @@ -161,31 +321,130 @@ public sealed class TTLInterpreter : IDisposable #endregion - #region Control Flow - If + #region Control Flow + + /// call:行內執行子程式(label 起,直到 return / 檔尾),呼叫點的區塊 / 迴圈 + /// 上下文完整保留 —— 在 while / for 裡 call 完會回到原處續跑。 + private void ExecuteCall(int target) + { + if (_callDepth >= 32) throw new Exception("call nested too deep (max 32)"); + int saved = _line; + _callDepth++; + _line = target; + try + { + while (_line < _lines.Length) + { + ThrowIfCancelled(); + StatusChanged?.Invoke(_scriptFile, _line + 1, _lines[_line]); + try { ExecuteLine(_lines[_line]); } + catch (GotoSignal g) { _line = g.Target; continue; } + _line++; + } + // 跑到檔尾沒 return → 視同 return + } + catch (ReturnSignal) { } + finally + { + _callDepth--; + _line = saved; + } + } + + /// 找 label(:name)所在行;大小寫不敏感。 + private int FindLabel(string name) + { + for (int i = 0; i < _lines.Length; i++) + { + var t = _lines[i]; + if (t.Length > 1 && t[0] == ':' && + t[1..].Trim().Equals(name, StringComparison.OrdinalIgnoreCase)) + return i; + } + throw new Exception($"label ':{name}' not found"); + } + + /// 區塊 if(if expr then / if expr)才算巢狀;單行 if 不算。 + private bool IsBlockIf(string line) + { + try + { + int pos = 2; // 跳過 "if" + TtlExpression.Parse(line, ref pos, _ => 0); + string rest = line[pos..].Trim(); + return rest.Length == 0 || rest.Equals("then", StringComparison.OrdinalIgnoreCase); + } + catch { return true; } // 解析不了 → 當區塊(legacy 寬鬆) + } + + /// 找出與 配對的 (支援巢狀,比對行首整個 token)。 + private int FindBlockEnd(int startIndex, string open, string close) + { + int depth = 0; + for (int i = startIndex; i < _lines.Length; i++) + { + string first = GetCommand(_lines[i]).ToLowerInvariant(); + if (first == open) + { + if (open != "if" || IsBlockIf(_lines[i])) depth++; + } + else if (first == close) + { + depth--; + if (depth == 0) return i; + } + } + return -1; + } private void ExecuteIf(string line) { - var match = Regex.Match(line, @"if\s+(.+?)\s+then", RegexOptions.IgnoreCase); - if (!match.Success) match = Regex.Match(line, @"if\s+(.+)", RegexOptions.IgnoreCase); - if (!match.Success) throw new Exception("Invalid if statement"); + bool cond; + string rest; + try + { + int pos = 2; // "if" + cond = TtlExpression.Truthy(TtlExpression.Parse(line, ref pos, ResolveVar)); + rest = line[pos..].Trim(); + } + catch (FormatException) + { + // legacy 條件(整行變數展開 + 舊字串比較),一律視為區塊 if + var m = Regex.Match(line, @"if\s+(.+?)\s+then\s*$", RegexOptions.IgnoreCase); + if (!m.Success) m = Regex.Match(line, @"if\s+(.+)$", RegexOptions.IgnoreCase); + if (!m.Success) throw new Exception("Invalid if statement"); + cond = LegacyCondition(ReplaceVariables(m.Groups[1].Value.Trim())); + rest = ""; + } - string condition = match.Groups[1].Value.Trim(); + // 單行 if:if + if (rest.Length > 0 && !rest.Equals("then", StringComparison.OrdinalIgnoreCase)) + { + if (cond) ExecuteLine(rest); + return; + } + + // 區塊 if int ifStart = _line; - int endif = FindBlockEnd(ifStart, "if ", "endif"); + int endif = FindBlockEnd(ifStart, "if", "endif"); if (endif < 0) throw new Exception("if statement without matching endif"); + // 只認同一層(depth 0)的 elseif / else,巢狀 if 的分支不會被誤抓 var elseifLines = new List(); - int elseLine = -1; + int elseLine = -1, depth = 0; for (int i = ifStart + 1; i < endif; i++) { - string t = _lines[i].Trim().ToLower(); - if (t.StartsWith("elseif")) elseifLines.Add(i); - else if (t.StartsWith("else")) { elseLine = i; break; } + string first = GetCommand(_lines[i]).ToLowerInvariant(); + if (first == "if" && IsBlockIf(_lines[i])) { depth++; continue; } + if (first == "endif") { depth--; continue; } + if (depth != 0) continue; + if (first == "elseif") elseifLines.Add(i); + else if (first == "else") { elseLine = i; break; } } bool met = false; int start = -1, end = -1; - if (EvaluateCondition(ReplaceVariables(condition))) + if (cond) { met = true; start = ifStart + 1; end = elseifLines.Count > 0 ? elseifLines[0] : (elseLine >= 0 ? elseLine : endif); @@ -194,9 +453,7 @@ public sealed class TTLInterpreter : IDisposable { for (int i = 0; i < elseifLines.Count && !met; i++) { - var em = Regex.Match(_lines[elseifLines[i]], @"elseif\s+(.+?)\s+then", RegexOptions.IgnoreCase); - if (!em.Success) em = Regex.Match(_lines[elseifLines[i]], @"elseif\s+(.+)", RegexOptions.IgnoreCase); - if (em.Success && EvaluateCondition(ReplaceVariables(em.Groups[1].Value.Trim()))) + if (EvalElseif(_lines[elseifLines[i]])) { met = true; start = elseifLines[i] + 1; end = (i + 1 < elseifLines.Count) ? elseifLines[i + 1] : (elseLine >= 0 ? elseLine : endif); @@ -206,22 +463,24 @@ public sealed class TTLInterpreter : IDisposable } if (met && start >= 0 && end > start) - { - _line = start; - while (_line < end) - { - ThrowIfCancelled(); - StatusChanged?.Invoke(_scriptFile, _line + 1, _lines[_line]); - ExecuteLine(_lines[_line]); - _line++; - } - } + ExecuteRange(start, end); _line = endif; } - #endregion - - #region Control Flow - While + private bool EvalElseif(string line) + { + try + { + int pos = 6; // "elseif" + return TtlExpression.Truthy(TtlExpression.Parse(line, ref pos, ResolveVar)); + } + catch (FormatException) + { + var em = Regex.Match(line, @"elseif\s+(.+?)\s+then\s*$", RegexOptions.IgnoreCase); + if (!em.Success) em = Regex.Match(line, @"elseif\s+(.+)$", RegexOptions.IgnoreCase); + return em.Success && LegacyCondition(ReplaceVariables(em.Groups[1].Value.Trim())); + } + } private void ExecuteWhile(string line) { @@ -236,31 +495,131 @@ public sealed class TTLInterpreter : IDisposable while (true) { ThrowIfCancelled(); - if (!EvaluateCondition(ReplaceVariables(condition))) break; - - _line = whileStart + 1; - while (_line < endwhile) - { - ThrowIfCancelled(); - StatusChanged?.Invoke(_scriptFile, _line + 1, _lines[_line]); - ExecuteLine(_lines[_line]); - _line++; - } + if (!EvaluateCondition(condition)) break; + try { ExecuteRange(whileStart + 1, endwhile); } + catch (BreakSignal) { break; } + catch (ContinueSignal) { } } _line = endwhile; } - /// 找出與 配對的 (支援巢狀)。 - private int FindBlockEnd(int startIndex, string open, string close) + /// until 區塊:條件為假時重複執行本體(每輪開頭測試)。 + private void ExecuteUntil(string line) { - int depth = 0; - for (int i = startIndex; i < _lines.Length; i++) + var match = Regex.Match(line, @"until\s+(.+)", RegexOptions.IgnoreCase); + if (!match.Success) throw new Exception("Invalid until statement"); + + string condition = match.Groups[1].Value.Trim(); + int untilStart = _line; + int endLine = FindBlockEnd(untilStart, "until", "enduntil"); + if (endLine < 0) throw new Exception("until statement without matching enduntil"); + + while (true) { - string t = _lines[i].Trim().ToLower(); - if (t.StartsWith(open)) depth++; - else if (t.StartsWith(close)) { depth--; if (depth == 0) return i; } + ThrowIfCancelled(); + if (EvaluateCondition(condition)) break; + try { ExecuteRange(untilStart + 1, endLine); } + catch (BreakSignal) { break; } + catch (ContinueSignal) { } + } + _line = endLine; + } + + /// for var first lastnext:var 由 first 走到 last(含),自動 ±1。 + private void ExecuteFor(string line) + { + var m = Regex.Match(line, @"^for\s+([a-zA-Z_]\w*)\s+(.+)$", RegexOptions.IgnoreCase); + if (!m.Success) throw new Exception("Invalid for statement (expected: for )"); + string var = m.Groups[1].Value; + string rest = m.Groups[2].Value; + + int pos = 0; + int first = TtlExpression.ToInt(TtlExpression.Parse(rest, ref pos, ResolveVar)); + int last = TtlExpression.ToInt(TtlExpression.Parse(rest, ref pos, ResolveVar)); + + int forStart = _line; + int next = FindBlockEnd(forStart, "for", "next"); + if (next < 0) throw new Exception("for statement without matching next"); + + int step = first <= last ? 1 : -1; + _vars[var] = first; + while (true) + { + ThrowIfCancelled(); + try { ExecuteRange(forStart + 1, next); } + catch (BreakSignal) { break; } + catch (ContinueSignal) { } + + int cur = TtlExpression.ToInt(_vars.TryGetValue(var, out var v) ? v : first); + if (cur == last) break; + _vars[var] = cur + step; + } + _line = next; + } + + /// do [while|until expr]loop [while|until expr] + private void ExecuteDo(string line) + { + int doStart = _line; + int loopLine = FindBlockEnd(doStart, "do", "loop"); + if (loopLine < 0) throw new Exception("do statement without matching loop"); + + var (headKind, headCond) = ParseLoopCond(line[2..].Trim()); + var (tailKind, tailCond) = ParseLoopCond(GetArgs(_lines[loopLine])); + + while (true) + { + ThrowIfCancelled(); + if (headKind == LoopCond.While && !EvaluateCondition(headCond)) break; + if (headKind == LoopCond.Until && EvaluateCondition(headCond)) break; + + try { ExecuteRange(doStart + 1, loopLine); } + catch (BreakSignal) { break; } + catch (ContinueSignal) { } + + if (tailKind == LoopCond.While && !EvaluateCondition(tailCond)) break; + if (tailKind == LoopCond.Until && EvaluateCondition(tailCond)) break; + } + _line = loopLine; + } + + private enum LoopCond { None, While, Until } + + private static (LoopCond kind, string cond) ParseLoopCond(string text) + { + text = text.Trim(); + if (text.Length == 0) return (LoopCond.None, ""); + if (text.StartsWith("while ", StringComparison.OrdinalIgnoreCase)) return (LoopCond.While, text[6..].Trim()); + if (text.StartsWith("until ", StringComparison.OrdinalIgnoreCase)) return (LoopCond.Until, text[6..].Trim()); + return (LoopCond.None, ""); + } + + /// include '路徑':執行另一個 ttl 檔(絕對路徑,或相對於目前工作目錄)。 + private void ExecuteInclude(string args) + { + if (_includeDepth >= 8) throw new Exception("include nested too deep (max 8)"); + string path = ValS(FirstToken(args)); + if (!File.Exists(path)) throw new Exception($"include file not found: {path}"); + + var savedLines = _lines; + var savedLine = _line; + var savedFile = _scriptFile; + _includeDepth++; + try + { + _lines = Preprocess(File.ReadAllText(path)); + _line = 0; + _scriptFile = Path.GetFileName(path); + try { RunMainLoop(); } + catch (ExitSignal) { } // include 檔內的 exit:只離開該檔 + } + finally + { + _includeDepth--; + _lines = savedLines; + _line = savedLine; + _scriptFile = savedFile; } - return -1; } #endregion @@ -268,6 +627,13 @@ public sealed class TTLInterpreter : IDisposable #region Condition Evaluation private bool EvaluateCondition(string condition) + { + try { return TtlExpression.Truthy(TtlExpression.Evaluate(condition, ResolveVar)); } + catch (FormatException) { return LegacyCondition(ReplaceVariables(condition)); } + } + + /// v0.4 的字串式條件比較(新解析器失敗時的相容路徑)。 + private static bool LegacyCondition(string condition) { condition = condition.Trim(); @@ -275,8 +641,8 @@ public sealed class TTLInterpreter : IDisposable { int at = condition.IndexOf(op, StringComparison.Ordinal); if (at < 0) continue; - string l = condition.Substring(0, at); - string r = condition.Substring(at + op.Length); + string l = condition[..at]; + string r = condition[(at + op.Length)..]; if (isNumeric) { int li = ParseIntDirect(l), ri = ParseIntDirect(r); @@ -286,11 +652,10 @@ public sealed class TTLInterpreter : IDisposable return op == "==" ? ls == rs : ls != rs; } - // single '=' as equality int eq = condition.IndexOf('='); if (eq >= 0) { - string l = condition.Substring(0, eq).Trim(), r = condition.Substring(eq + 1).Trim(); + string l = condition[..eq].Trim(), r = condition[(eq + 1)..].Trim(); if (int.TryParse(l, out int li) && int.TryParse(r, out int ri)) return li == ri; return l.Trim('\'', '"') == r.Trim('\'', '"'); } @@ -307,8 +672,8 @@ public sealed class TTLInterpreter : IDisposable int eq = line.IndexOf('='); if (eq < 0) return; - string name = line.Substring(0, eq).Trim(); - string expr = line.Substring(eq + 1).Trim(); + string name = line[..eq].Trim(); + string expr = line[(eq + 1)..].Trim(); if (!Regex.IsMatch(name, @"^[a-zA-Z_][a-zA-Z0-9_]*$")) { @@ -316,10 +681,30 @@ public sealed class TTLInterpreter : IDisposable return; } - _vars[name] = EvaluateExpression(ReplaceVariables(expr)); + // 相容 v0.4:右側是單一裸字且不是已定義變數 → 存字面字串(例:mode = fast) + if (Regex.IsMatch(expr, @"^[a-zA-Z_][a-zA-Z0-9_]*$") + && !_vars.ContainsKey(expr) + && !expr.Equals("result", StringComparison.OrdinalIgnoreCase)) + { + SetVarOrResult(name, expr); + return; + } + + try { SetVarOrResult(name, TtlExpression.Evaluate(expr, ResolveVar)); } + catch (FormatException) + { + SetVarOrResult(name, EvaluateExpressionLegacy(ReplaceVariables(expr))); + } } - private object EvaluateExpression(string expr) + private void SetVarOrResult(string name, object value) + { + if (name.Equals("result", StringComparison.OrdinalIgnoreCase)) _result = TtlExpression.ToInt(value); + else _vars[name] = value; + } + + /// v0.4 的指派求值(單一二元運算 / 字串字面值),新解析器失敗時的相容路徑。 + private static object EvaluateExpressionLegacy(string expr) { expr = expr.Trim(); @@ -328,13 +713,13 @@ public sealed class TTLInterpreter : IDisposable if (op == '-' && expr.StartsWith("-")) continue; int at = expr.IndexOf(op); if (at <= 0) continue; - int l = ParseIntDirect(expr.Substring(0, at)); - int r = ParseIntDirect(expr.Substring(at + 1)); + int l = ParseIntDirect(expr[..at]); + int r = ParseIntDirect(expr[(at + 1)..]); return op switch { '+' => l + r, '-' => l - r, '*' => l * r, _ => r != 0 ? l / r : 0 }; } if (expr.StartsWith("\"") && expr.EndsWith("\"") && expr.Length >= 2) - return expr.Substring(1, expr.Length - 2); + return expr[1..^1]; if (int.TryParse(expr, out int v)) return v; return expr; } @@ -351,6 +736,15 @@ public sealed class TTLInterpreter : IDisposable Output?.Invoke($">> {text}"); } + private int EffectiveTimeoutMs => _timeout + _mtimeout; // 0 = 無限 + + private void DispatchWait(string args) + { + var tokens = TokenizeArgs(args); + if (tokens.Count <= 1) Wait(args); + else WaitMulti(tokens); + } + private void Wait(string text) { text = ReplaceVariables(text.Trim().Trim('"', '\'')); @@ -375,17 +769,164 @@ public sealed class TTLInterpreter : IDisposable if (found && SettleAndConsume(text)) return; // 只有在明確設定 timeout(>0) 且超時才中止腳本;否則一直等到關鍵字出現或被取消。 - if (_timeout > 0 && elapsed >= _timeout) + if (EffectiveTimeoutMs > 0 && elapsed >= EffectiveTimeoutMs) { _result = 0; _logWriter?.WriteLine($"[Wait] timeout: {text}"); - throw new TimeoutException($"wait timeout ({_timeout}ms): '{text}'"); + throw new TimeoutException($"wait timeout ({EffectiveTimeoutMs}ms): '{text}'"); } Thread.Sleep(100); elapsed += 100; } } + /// wait 多字串(TeraTerm 相容):任一出現即消費,result = 命中的字串序號(1 起算); + /// 逾時 result = 0 且**繼續執行**(與單字串 wait 的逾時中止不同)。無 settle 邏輯。 + private void WaitMulti(List tokens) + { + var keys = tokens.Select(StripQuotes).Where(k => k.Length > 0).ToList(); + if (keys.Count == 0) return; + Output?.Invoke($"[wait] any of: {string.Join(" | ", keys)}"); + + int elapsed = 0, lastLen = -1; + while (true) + { + ThrowIfCancelled(); + string? buf = null; + lock (_recv) + { + if (_recv.Length != lastLen) { lastLen = _recv.Length; buf = _recv.ToString(); } + } + if (buf != null) + { + int bestIdx = -1, bestAt = int.MaxValue; + for (int i = 0; i < keys.Count; i++) + { + int at = buf.IndexOf(keys[i], StringComparison.Ordinal); + if (at >= 0 && at < bestAt) { bestAt = at; bestIdx = i; } + } + if (bestIdx >= 0) + { + lock (_recv) _recv.Remove(0, Math.Min(_recv.Length, bestAt + keys[bestIdx].Length)); + _result = bestIdx + 1; + return; + } + } + if (EffectiveTimeoutMs > 0 && elapsed >= EffectiveTimeoutMs) { _result = 0; return; } + Thread.Sleep(50); + elapsed += 50; + } + } + + /// 取出一行完整的輸入(遇 \n),並自 buffer 消費;沒有完整行回 null。 + private string? TryTakeLine() + { + lock (_recv) + { + for (int i = 0; i < _recv.Length; i++) + { + if (_recv[i] != '\n') continue; + string line = _recv.ToString(0, i); + _recv.Remove(0, i + 1); + return line.TrimEnd('\r'); + } + } + return null; + } + + /// waitln:等到「包含任一字串」的完整一行;該行存入 inputstr,result = 序號;逾時 result=0。 + private void WaitLn(List tokens) + { + var keys = tokens.Select(StripQuotes).Where(k => k.Length > 0).ToList(); + if (keys.Count == 0) return; + Output?.Invoke($"[waitln] any of: {string.Join(" | ", keys)}"); + + int elapsed = 0; + while (true) + { + ThrowIfCancelled(); + string? line = TryTakeLine(); + if (line != null) + { + for (int i = 0; i < keys.Count; i++) + { + if (!line.Contains(keys[i], StringComparison.Ordinal)) continue; + _vars["inputstr"] = line; + _result = i + 1; + return; + } + continue; // 不匹配的行已消費,馬上看下一行 + } + if (EffectiveTimeoutMs > 0 && elapsed >= EffectiveTimeoutMs) { _result = 0; return; } + Thread.Sleep(50); + elapsed += 50; + } + } + + /// recvln:收下一行到 inputstr;result=1 成功、0 逾時。 + private void RecvLn() + { + int elapsed = 0; + while (true) + { + ThrowIfCancelled(); + string? line = TryTakeLine(); + if (line != null) { _vars["inputstr"] = line; _result = 1; return; } + if (EffectiveTimeoutMs > 0 && elapsed >= EffectiveTimeoutMs) { _result = 0; return; } + Thread.Sleep(50); + elapsed += 50; + } + } + + /// waitregex:任一 regex 命中即消費到命中處;matchstr / groupmatchstr1..9 設定, + /// result = 命中的 pattern 序號;逾時 result=0。 + private void WaitRegex(List tokens) + { + var pats = tokens.Select(StripQuotes).Where(p => p.Length > 0).ToList(); + if (pats.Count == 0) return; + Output?.Invoke($"[waitregex] {string.Join(" | ", pats)}"); + + int elapsed = 0, lastLen = -1; + while (true) + { + ThrowIfCancelled(); + string? buf = null; + lock (_recv) + { + if (_recv.Length != lastLen) { lastLen = _recv.Length; buf = _recv.ToString(); } + } + if (buf != null) + { + Match? best = null; + int bestIdx = -1; + for (int i = 0; i < pats.Count; i++) + { + Match m; + try { m = Regex.Match(buf, pats[i]); } + catch (ArgumentException ex) + { + Output?.Invoke($"[waitregex] invalid pattern '{pats[i]}': {ex.Message}"); + _result = 0; + return; + } + if (m.Success && (best == null || m.Index < best.Index)) { best = m; bestIdx = i; } + } + if (best != null) + { + _vars["matchstr"] = best.Value; + for (int g = 1; g <= 9; g++) + _vars[$"groupmatchstr{g}"] = g < best.Groups.Count ? best.Groups[g].Value : ""; + lock (_recv) _recv.Remove(0, Math.Min(_recv.Length, best.Index + best.Length)); + _result = bestIdx + 1; + return; + } + } + if (EffectiveTimeoutMs > 0 && elapsed >= EffectiveTimeoutMs) { _result = 0; return; } + Thread.Sleep(50); + elapsed += 50; + } + } + /// /// 找到關鍵字後,等待裝置「安靜」( 內無新資料進來)才接受, /// 並消費到「最後一次」出現處。若 settle 期間又有資料進來,視為輸出尚未結束 @@ -408,7 +949,7 @@ public sealed class TTLInterpreter : IDisposable if (idx < 0) return false; _result = 1; _recv.Clear(); - _recv.Append(buf.Substring(idx + text.Length)); + _recv.Append(buf[(idx + text.Length)..]); } return true; } @@ -420,11 +961,21 @@ public sealed class TTLInterpreter : IDisposable private void Pause(string args) { - int total = ParseInt(args) * 1000, elapsed = 0; - while (elapsed < total) + SleepCancellable(ParseInt(args) * 1000); + } + + private void MPause(string args) + { + SleepCancellable(ValI(FirstToken(args))); + } + + private void SleepCancellable(int totalMs) + { + int elapsed = 0; + while (elapsed < totalMs) { ThrowIfCancelled(); - int slice = Math.Min(100, total - elapsed); + int slice = Math.Min(100, totalMs - elapsed); Thread.Sleep(slice); elapsed += slice; } @@ -436,6 +987,12 @@ public sealed class TTLInterpreter : IDisposable _timeout = (m.Success ? ParseInt(m.Groups[1].Value) : ParseInt(args)) * 1000; } + private void SetMTimeout(string args) + { + var m = Regex.Match(args, @"=\s*(\d+)"); + _mtimeout = m.Success ? ParseInt(m.Groups[1].Value) : ParseInt(args); + } + private void LogOpen(string args) { var m = Regex.Match(args, @"['""]([^'""]+)['""]"); @@ -463,16 +1020,83 @@ public sealed class TTLInterpreter : IDisposable private void ShowMessageBox(string args) { - string message = ReplaceVariables(args.Trim('\'', '"')); - Output?.Invoke($"[messagebox] {message}"); - var main = System.Windows.Forms.Application.OpenForms.Count > 0 - ? System.Windows.Forms.Application.OpenForms[0] : null; - if (main != null && main.InvokeRequired) - main.Invoke(() => System.Windows.Forms.MessageBox.Show(main, message, "TTL Script", - System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information)); + // messagebox '訊息' ['標題'];單引數維持 v0.4 行為(整段當訊息) + string message, title = "TTL Script"; + var t = TokenizeArgs(args); + if (t.Count >= 2 && (t[0].StartsWith("'") || t[0].StartsWith("\""))) + { + message = ReplaceVariables(StripQuotes(t[0])); + title = StripQuotes(t[1]); + } else - System.Windows.Forms.MessageBox.Show(main, message, "TTL Script", - System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information); + { + message = ReplaceVariables(args.Trim('\'', '"')); + } + Output?.Invoke($"[messagebox] {message}"); + UiInvoke(owner => + { + MessageBox.Show(owner, message, title, MessageBoxButtons.OK, MessageBoxIcon.Information); + return null; + }); + } + + private void InputBox(string args) + { + var t = TokenizeArgs(args); + string msg = t.Count > 0 ? ValS(t[0]) : ""; + string title = t.Count > 1 ? ValS(t[1]) : "TTL Script"; + string init = t.Count > 2 ? ValS(t[2]) : ""; + string? val = UiInvoke(owner => App.Dialogs.TextPromptDialog.Ask(owner!, title, msg, init)); + _vars["inputstr"] = val ?? ""; + _result = val != null ? 1 : 0; + } + + private void YesNoBox(string args) + { + var t = TokenizeArgs(args); + string msg = t.Count > 0 ? ValS(t[0]) : ""; + string title = t.Count > 1 ? ValS(t[1]) : "TTL Script"; + var r = UiInvoke(owner => MessageBox.Show(owner, msg, title, MessageBoxButtons.YesNo, MessageBoxIcon.Question)); + _result = r == DialogResult.Yes ? 1 : 0; + } + + private void DispStr(string args) + { + var t = TokenizeArgs(args); + var sb = new StringBuilder(); + foreach (var tok in t) sb.Append(ValS(tok)); + Output?.Invoke(sb.ToString()); + } + + private void SendFile(string args) + { + var t = TokenizeArgs(args); + if (t.Count < 1) { Output?.Invoke("[sendfile] syntax: sendfile ''"); return; } + string path = ValS(t[0]); + try + { + var bytes = File.ReadAllBytes(path); + _channel.Write(bytes); + Output?.Invoke($"[sendfile] {path} ({bytes.Length} bytes)"); + _result = 1; + } + catch (Exception ex) + { + Output?.Invoke($"[sendfile] failed: {ex.Message}"); + _result = 0; + } + } + + private void SerialOnly(Action action, string cmd) + { + if (_channel is not SerialChannel sc) + { + Output?.Invoke($"[{cmd}] only available on Serial sessions"); + _result = 0; + return; + } + try { action(sc); _result = 1; } + catch (Exception ex) { Output?.Invoke($"[{cmd}] failed: {ex.Message}"); _result = 0; } } private void ExecuteWaitAll(string args) @@ -560,6 +1184,509 @@ public sealed class TTLInterpreter : IDisposable #endregion + #region String Commands + + private void StrLen(string args) + { + var t = TokenizeArgs(args); + _result = t.Count > 0 ? ValS(t[0]).Length : 0; + } + + private void StrCompare(string args) + { + var t = TokenizeArgs(args); + if (t.Count < 2) { Output?.Invoke("[strcompare] syntax: strcompare "); return; } + _result = Math.Sign(string.CompareOrdinal(ValS(t[0]), ValS(t[1]))); + } + + private void StrConcat(string args) + { + var t = TokenizeArgs(args); + if (t.Count < 2 || !IsIdent(t[0])) { Output?.Invoke("[strconcat] syntax: strconcat "); return; } + _vars[t[0]] = TtlExpression.ToStr(ResolveVar(t[0])) + ValS(t[1]); + } + + private void StrCopy(string args) + { + // strcopy + var t = TokenizeArgs(args); + if (t.Count < 4 || !IsIdent(t[3])) { Output?.Invoke("[strcopy] syntax: strcopy "); return; } + string s = ValS(t[0]); + int pos = Math.Max(1, ValI(t[1])) - 1; + int len = Math.Max(0, ValI(t[2])); + if (pos >= s.Length) { _vars[t[3]] = ""; return; } + _vars[t[3]] = s.Substring(pos, Math.Min(len, s.Length - pos)); + } + + private void StrInsert(string args) + { + var t = TokenizeArgs(args); + if (t.Count < 3 || !IsIdent(t[0])) { Output?.Invoke("[strinsert] syntax: strinsert "); return; } + string s = TtlExpression.ToStr(ResolveVar(t[0])); + int pos = Math.Clamp(ValI(t[1]) - 1, 0, s.Length); + _vars[t[0]] = s.Insert(pos, ValS(t[2])); + } + + private void StrRemove(string args) + { + var t = TokenizeArgs(args); + if (t.Count < 3 || !IsIdent(t[0])) { Output?.Invoke("[strremove] syntax: strremove "); return; } + string s = TtlExpression.ToStr(ResolveVar(t[0])); + int pos = Math.Clamp(ValI(t[1]) - 1, 0, s.Length); + int len = Math.Clamp(ValI(t[2]), 0, s.Length - pos); + _vars[t[0]] = s.Remove(pos, len); + } + + private void StrMatch(string args) + { + // strmatch → result = 命中位置(1-based)/0;matchstr / groupmatchstr1..9 + var t = TokenizeArgs(args); + if (t.Count < 2) { Output?.Invoke("[strmatch] syntax: strmatch "); return; } + try + { + var m = Regex.Match(ValS(t[0]), StripQuotes(t[1])); + if (m.Success) + { + _vars["matchstr"] = m.Value; + for (int g = 1; g <= 9; g++) + _vars[$"groupmatchstr{g}"] = g < m.Groups.Count ? m.Groups[g].Value : ""; + _result = m.Index + 1; + } + else _result = 0; + } + catch (ArgumentException ex) { Output?.Invoke($"[strmatch] invalid regex: {ex.Message}"); _result = 0; } + } + + private void StrScan(string args) + { + var t = TokenizeArgs(args); + if (t.Count < 2) { Output?.Invoke("[strscan] syntax: strscan "); return; } + _result = ValS(t[0]).IndexOf(ValS(t[1]), StringComparison.Ordinal) + 1; // 0 = 沒找到 + } + + private void StrReplace(string args) + { + // strreplace → 自 pos 起全部取代;result 1/0 + var t = TokenizeArgs(args); + if (t.Count < 4 || !IsIdent(t[0])) { Output?.Invoke("[strreplace] syntax: strreplace "); return; } + string s = TtlExpression.ToStr(ResolveVar(t[0])); + int pos = Math.Clamp(ValI(t[1]) - 1, 0, s.Length); + try + { + string head = s[..pos], tail = s[pos..]; + string replaced = Regex.Replace(tail, StripQuotes(t[2]), ValS(t[3])); + _vars[t[0]] = head + replaced; + _result = replaced != tail ? 1 : 0; + } + catch (ArgumentException ex) { Output?.Invoke($"[strreplace] invalid regex: {ex.Message}"); _result = 0; } + } + + private void StrTrim(string args) + { + var t = TokenizeArgs(args); + if (t.Count < 1 || !IsIdent(t[0])) { Output?.Invoke("[strtrim] syntax: strtrim []"); return; } + string s = TtlExpression.ToStr(ResolveVar(t[0])); + _vars[t[0]] = t.Count > 1 ? s.Trim(ValS(t[1]).ToCharArray()) : s.Trim(); + } + + private void StrSplit(string args) + { + // strsplit [maxcount≤9] → groupmatchstr1..9,result = 個數 + var t = TokenizeArgs(args); + if (t.Count < 2) { Output?.Invoke("[strsplit] syntax: strsplit [count]"); return; } + int max = t.Count > 2 ? Math.Clamp(ValI(t[2]), 1, 9) : 9; + var parts = ValS(t[0]).Split(ValS(t[1]), max, StringSplitOptions.None); + for (int g = 1; g <= 9; g++) + _vars[$"groupmatchstr{g}"] = g <= parts.Length ? parts[g - 1] : ""; + _result = parts.Length; + } + + private void StrJoin(string args) + { + // strjoin [count] → 把 groupmatchstr1..count 以 sep 接起來 + var t = TokenizeArgs(args); + if (t.Count < 2 || !IsIdent(t[0])) { Output?.Invoke("[strjoin] syntax: strjoin [count]"); return; } + int count = t.Count > 2 ? Math.Clamp(ValI(t[2]), 1, 9) : 9; + var parts = new List(); + for (int g = 1; g <= count; g++) + parts.Add(TtlExpression.ToStr(ResolveVar($"groupmatchstr{g}"))); + while (parts.Count > 0 && parts[^1].Length == 0) parts.RemoveAt(parts.Count - 1); // 去尾端空 token + _vars[t[0]] = string.Join(ValS(t[1]), parts); + } + + private void ToLowerCmd(string args) + { + var t = TokenizeArgs(args); + if (t.Count < 2 || !IsIdent(t[0])) { Output?.Invoke("[tolower] syntax: tolower "); return; } + _vars[t[0]] = ValS(t[1]).ToLowerInvariant(); + } + + private void ToUpperCmd(string args) + { + var t = TokenizeArgs(args); + if (t.Count < 2 || !IsIdent(t[0])) { Output?.Invoke("[toupper] syntax: toupper "); return; } + _vars[t[0]] = ValS(t[1]).ToUpperInvariant(); + } + + private void Str2Int(string args) + { + var t = TokenizeArgs(args); + if (t.Count < 2 || !IsIdent(t[0])) { Output?.Invoke("[str2int] syntax: str2int "); return; } + if (int.TryParse(ValS(t[1]).Trim(), out int v)) { _vars[t[0]] = v; _result = 1; } + else { _vars[t[0]] = 0; _result = 0; } + } + + private void Int2Str(string args) + { + var t = TokenizeArgs(args); + if (t.Count < 2 || !IsIdent(t[0])) { Output?.Invoke("[int2str] syntax: int2str "); return; } + _vars[t[0]] = ValI(t[1]).ToString(CultureInfo.InvariantCulture); + } + + private void Code2Str(string args) + { + var t = TokenizeArgs(args); + if (t.Count < 2 || !IsIdent(t[0])) { Output?.Invoke("[code2str] syntax: code2str "); return; } + _vars[t[0]] = ((char)ValI(t[1])).ToString(); + } + + private void Str2Code(string args) + { + var t = TokenizeArgs(args); + if (t.Count < 2 || !IsIdent(t[0])) { Output?.Invoke("[str2code] syntax: str2code "); return; } + string s = ValS(t[1]); + _vars[t[0]] = s.Length > 0 ? s[0] : 0; + } + + private void ExpandEnv(string args) + { + var t = TokenizeArgs(args); + if (t.Count < 2 || !IsIdent(t[0])) { Output?.Invoke("[expandenv] syntax: expandenv "); return; } + _vars[t[0]] = Environment.ExpandEnvironmentVariables(ValS(t[1])); + } + + /// sprintf 格式 [引數 ...]:與 sprintf2 相同引擎,結果存入 inputstr(TeraTerm 相容)。 + private void ExecuteSprintf(string args) + { + var tokens = TokenizeArgs(args); + if (tokens.Count < 1) { _result = 1; Output?.Invoke("[sprintf] no format string"); return; } + + string format = StripQuotes(tokens[0]); + var fmtArgs = new List(); + for (int k = 1; k < tokens.Count; k++) fmtArgs.Add(ReplaceVariables(StripQuotes(tokens[k]))); + + try + { + _vars["inputstr"] = CFormat(format, fmtArgs); + _result = 0; + } + catch (FormatException) { _result = 2; Output?.Invoke("[sprintf] invalid format"); } + catch (ArgumentException) { _result = 3; Output?.Invoke("[sprintf] invalid argument"); } + } + + #endregion + + #region File Commands + + private void FileOpenCmd(string args) + { + // fileopen [readonly] + var t = TokenizeArgs(args); + if (t.Count < 3 || !IsIdent(t[0])) { Output?.Invoke("[fileopen] syntax: fileopen [readonly 0|1]"); return; } + string path = ValS(t[1]); + bool append = ValI(t[2]) != 0; + bool readOnly = t.Count > 3 && ValI(t[3]) != 0; + try + { + object handle = readOnly + ? new StreamReader(path, Encoding.UTF8) + : new StreamWriter(path, append, new UTF8Encoding(false)); + int fh = ++_fileSeq; + _fileHandles[fh] = handle; + _vars[t[0]] = fh; + } + catch (Exception ex) + { + Output?.Invoke($"[fileopen] failed: {ex.Message}"); + _vars[t[0]] = -1; + } + } + + private void FileCreateCmd(string args) + { + var t = TokenizeArgs(args); + if (t.Count < 2 || !IsIdent(t[0])) { Output?.Invoke("[filecreate] syntax: filecreate "); return; } + try + { + var w = new StreamWriter(ValS(t[1]), false, new UTF8Encoding(false)); + int fh = ++_fileSeq; + _fileHandles[fh] = w; + _vars[t[0]] = fh; + } + catch (Exception ex) + { + Output?.Invoke($"[filecreate] failed: {ex.Message}"); + _vars[t[0]] = -1; + } + } + + private void FileCloseCmd(string args) + { + int fh = ValI(FirstToken(args)); + if (!_fileHandles.TryGetValue(fh, out var h)) return; + _fileHandles.Remove(fh); + try { (h as IDisposable)?.Dispose(); } catch { } + } + + private void FileReadLn(string args) + { + // filereadln → result = 1 表示 EOF(TeraTerm 相容) + var t = TokenizeArgs(args); + if (t.Count < 2 || !IsIdent(t[1])) { Output?.Invoke("[filereadln] syntax: filereadln "); return; } + if (_fileHandles.TryGetValue(ValI(t[0]), out var h) && h is StreamReader r) + { + string? line = r.ReadLine(); + _vars[t[1]] = line ?? ""; + _result = line == null ? 1 : 0; + } + else + { + Output?.Invoke("[filereadln] invalid file handle (opened for writing?)"); + _vars[t[1]] = ""; + _result = 1; + } + } + + private void FileWriteCmd(string args, bool newline) + { + var t = TokenizeArgs(args); + string cmd = newline ? "filewriteln" : "filewrite"; + if (t.Count < 2) { Output?.Invoke($"[{cmd}] syntax: {cmd} "); return; } + if (_fileHandles.TryGetValue(ValI(t[0]), out var h) && h is StreamWriter w) + { + if (newline) w.WriteLine(ValS(t[1])); + else w.Write(ValS(t[1])); + w.Flush(); + } + else Output?.Invoke($"[{cmd}] invalid file handle (opened read-only?)"); + } + + private void FileDeleteCmd(string args) + { + string path = ValS(FirstToken(args)); + try { File.Delete(path); _result = 1; } + catch (Exception ex) { Output?.Invoke($"[filedelete] failed: {ex.Message}"); _result = 0; } + } + + private void FileSearchCmd(string args) => _result = File.Exists(ValS(FirstToken(args))) ? 1 : 0; + + private void BaseNameCmd(string args) + { + var t = TokenizeArgs(args); + if (t.Count < 2 || !IsIdent(t[0])) { Output?.Invoke("[basename] syntax: basename "); return; } + _vars[t[0]] = Path.GetFileName(ValS(t[1])); + } + + private void DirNameCmd(string args) + { + var t = TokenizeArgs(args); + if (t.Count < 2 || !IsIdent(t[0])) { Output?.Invoke("[dirname] syntax: dirname "); return; } + _vars[t[0]] = Path.GetDirectoryName(ValS(t[1])) ?? ""; + } + + private void MakePathCmd(string args) + { + var t = TokenizeArgs(args); + if (t.Count < 3 || !IsIdent(t[0])) { Output?.Invoke("[makepath] syntax: makepath "); return; } + _vars[t[0]] = Path.Combine(ValS(t[1]), ValS(t[2])); + } + + private void FolderCreateCmd(string args) + { + try { Directory.CreateDirectory(ValS(FirstToken(args))); _result = 1; } + catch (Exception ex) { Output?.Invoke($"[foldercreate] failed: {ex.Message}"); _result = 0; } + } + + private void FolderDeleteCmd(string args) + { + try { Directory.Delete(ValS(FirstToken(args)), false); _result = 1; } + catch (Exception ex) { Output?.Invoke($"[folderdelete] failed: {ex.Message}"); _result = 0; } + } + + private void FolderSearchCmd(string args) => _result = Directory.Exists(ValS(FirstToken(args))) ? 1 : 0; + + private void GetDirCmd(string args) + { + string dest = FirstToken(args); + if (!IsIdent(dest)) { Output?.Invoke("[getdir] syntax: getdir "); return; } + _vars[dest] = Environment.CurrentDirectory; + } + + private void SetDirCmd(string args) + { + try { Directory.SetCurrentDirectory(ValS(FirstToken(args))); _result = 1; } + catch (Exception ex) { Output?.Invoke($"[setdir] failed: {ex.Message}"); _result = 0; } + } + + #endregion + + #region Misc Commands + + private void GetDateCmd(string args, string defaultFmt) + { + var t = TokenizeArgs(args); + if (t.Count < 1 || !IsIdent(t[0])) { Output?.Invoke("[getdate] syntax: getdate ['format']"); return; } + string fmt = t.Count > 1 ? ValS(t[1]) : defaultFmt; + _vars[t[0]] = Strftime(fmt, DateTime.Now); + } + + private void GetEnvCmd(string args) + { + var t = TokenizeArgs(args); + if (t.Count < 2 || !IsIdent(t[1])) { Output?.Invoke("[getenv] syntax: getenv '' "); return; } + _vars[t[1]] = Environment.GetEnvironmentVariable(ValS(t[0])) ?? ""; + } + + private void SetEnvCmd(string args) + { + var t = TokenizeArgs(args); + if (t.Count < 2) { Output?.Invoke("[setenv] syntax: setenv '' ''"); return; } + Environment.SetEnvironmentVariable(ValS(t[0]), ValS(t[1])); + } + + private void RandomCmd(string args) + { + var t = TokenizeArgs(args); + if (t.Count < 2 || !IsIdent(t[0])) { Output?.Invoke("[random] syntax: random "); return; } + int max = ValI(t[1]); + _vars[t[0]] = max <= 0 ? 0 : Random.Shared.Next(max + 1); // 0..max(含) + } + + private void ExecCmd(string args) + { + // exec '' ['show'|'hide'|'minimize'] [] + var t = TokenizeArgs(args); + if (t.Count < 1) { Output?.Invoke("[exec] syntax: exec '' ['show'] []"); return; } + string cmd = ValS(t[0]); + string show = t.Count > 1 ? ValS(t[1]).ToLowerInvariant() : "show"; + bool waitExit = t.Count > 2 && ValI(t[2]) != 0; + try + { + var (exe, arguments) = SplitCommandLine(cmd); + var psi = new ProcessStartInfo(exe, arguments) + { + UseShellExecute = true, + WindowStyle = show switch + { + "hide" => ProcessWindowStyle.Hidden, + "minimize" => ProcessWindowStyle.Minimized, + "maximize" => ProcessWindowStyle.Maximized, + _ => ProcessWindowStyle.Normal + } + }; + using var proc = Process.Start(psi); + if (waitExit && proc != null) + { + proc.WaitForExit(); + _result = proc.ExitCode; + } + else _result = 0; + } + catch (Exception ex) { Output?.Invoke($"[exec] failed: {ex.Message}"); _result = -1; } + } + + private void IfDefined(string args) + { + // result: 0 = 未定義, 1 = 整數, 2 = 字串 + string name = FirstToken(args).Trim(); + var v = ResolveVar(name); + _result = v switch { int => 1, string => 2, _ => 0 }; + } + + private void Clipb2Var(string args) + { + string dest = FirstToken(args); + if (!IsIdent(dest)) { Output?.Invoke("[clipb2var] syntax: clipb2var "); return; } + string text = UiInvoke(_ => { try { return Clipboard.ContainsText() ? Clipboard.GetText() : ""; } catch { return ""; } }); + _vars[dest] = text; + _result = text.Length > 0 ? 1 : 0; + } + + private void Var2Clipb(string args) + { + string text = ValS(FirstToken(args)); + UiInvoke(_ => { try { Clipboard.SetText(text.Length > 0 ? text : " "); } catch { } return null; }); + } + + private void Checksum(string args, int mask) + { + var t = TokenizeArgs(args); + if (t.Count < 2 || !IsIdent(t[0])) { Output?.Invoke("[checksum] syntax: checksum8/16/32 "); return; } + int sum = 0; + foreach (byte b in Encoding.UTF8.GetBytes(ValS(t[1]))) sum = unchecked(sum + b); + _vars[t[0]] = mask == -1 ? sum : sum & mask; + } + + private static uint Crc32(string s) + { + uint crc = 0xFFFFFFFF; + foreach (byte b in Encoding.UTF8.GetBytes(s)) + { + crc ^= b; + for (int i = 0; i < 8; i++) + crc = (crc >> 1) ^ (0xEDB88320u & (uint)(-(int)(crc & 1))); + } + return ~crc; + } + + private static string AppVersion() + { + var v = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version; + return v == null ? "0.0.0" : $"{v.Major}.{v.Minor}.{v.Build}"; + } + + /// strftime 子集(%Y %y %m %d %H %M %S %j %a %A %b %%)。 + private static string Strftime(string fmt, DateTime now) + { + var sb = new StringBuilder(); + for (int i = 0; i < fmt.Length; i++) + { + if (fmt[i] != '%' || i + 1 >= fmt.Length) { sb.Append(fmt[i]); continue; } + i++; + sb.Append(fmt[i] switch + { + 'Y' => now.Year.ToString("D4"), + 'y' => (now.Year % 100).ToString("D2"), + 'm' => now.Month.ToString("D2"), + 'd' => now.Day.ToString("D2"), + 'H' => now.Hour.ToString("D2"), + 'M' => now.Minute.ToString("D2"), + 'S' => now.Second.ToString("D2"), + 'j' => now.DayOfYear.ToString("D3"), + 'a' => now.ToString("ddd", CultureInfo.InvariantCulture), + 'A' => now.ToString("dddd", CultureInfo.InvariantCulture), + 'b' => now.ToString("MMM", CultureInfo.InvariantCulture), + '%' => "%", + _ => "%" + fmt[i] + }); + } + return sb.ToString(); + } + + private static (string exe, string args) SplitCommandLine(string cmd) + { + cmd = cmd.Trim(); + if (cmd.StartsWith("\"")) + { + int end = cmd.IndexOf('"', 1); + if (end > 0) return (cmd[1..end], cmd[(end + 1)..].Trim()); + } + int sp = cmd.IndexOf(' '); + return sp < 0 ? (cmd, "") : (cmd[..sp], cmd[(sp + 1)..].Trim()); + } + + #endregion + #region sprintf2 /// @@ -695,7 +1822,7 @@ public sealed class TTLInterpreter : IDisposable ? ((char)code).ToString() : (arg.Length > 0 ? arg[0].ToString() : ""); case 's': - return (prec >= 0 && arg.Length > prec) ? arg.Substring(0, prec) : arg; + return (prec >= 0 && arg.Length > prec) ? arg[..prec] : arg; case 'f': case 'F': { double d = ParseDouble(arg); @@ -713,7 +1840,7 @@ public sealed class TTLInterpreter : IDisposable if (alt && p == 0 && !s.Contains('.')) { int ei = s.IndexOfAny(new[] { 'e', 'E' }); - s = s.Substring(0, ei) + "." + s.Substring(ei); + s = s[..ei] + "." + s[ei..]; } prefix = Sign(d, plus, space); allowZero = true; return s; @@ -724,7 +1851,7 @@ public sealed class TTLInterpreter : IDisposable int p = prec < 0 ? 6 : (prec == 0 ? 1 : prec); double ad = Math.Abs(d); string etmp = ad.ToString("E" + (p - 1), CultureInfo.InvariantCulture); - int x = ad == 0 ? 0 : int.Parse(etmp.Substring(etmp.IndexOf('E') + 1), CultureInfo.InvariantCulture); + int x = ad == 0 ? 0 : int.Parse(etmp[(etmp.IndexOf('E') + 1)..], CultureInfo.InvariantCulture); string s; if (x < -4 || x >= p) { @@ -770,22 +1897,22 @@ public sealed class TTLInterpreter : IDisposable { int ei = s.IndexOfAny(new[] { 'e', 'E' }); if (ei < 0 || ei + 2 >= s.Length) return s; - string exp = s.Substring(ei + 2).TrimStart('0'); + string exp = s[(ei + 2)..].TrimStart('0'); if (exp.Length < 2) exp = exp.PadLeft(2, '0'); - return s.Substring(0, ei + 2) + exp; + return s[..(ei + 2)] + exp; } private static string TrimTrailingZeros(string s) { if (!s.Contains('.')) return s; s = s.TrimEnd('0'); - return s.EndsWith(".") ? s.Substring(0, s.Length - 1) : s; + return s.EndsWith(".") ? s[..^1] : s; } private static string TrimGExp(string s) { int ei = s.IndexOfAny(new[] { 'e', 'E' }); - return TrimTrailingZeros(s.Substring(0, ei)) + s.Substring(ei); + return TrimTrailingZeros(s[..ei]) + s[ei..]; } private static string HexFloat(double d, bool upper, int prec) @@ -797,7 +1924,7 @@ public sealed class TTLInterpreter : IDisposable if (rawExp == 0) { lead = "0"; e2 = mant == 0 ? 0 : -1022; } else { lead = "1"; e2 = rawExp - 1023; } string frac = mant.ToString("x13", CultureInfo.InvariantCulture); - if (prec >= 0) frac = prec < frac.Length ? frac.Substring(0, prec) : frac.PadRight(prec, '0'); + if (prec >= 0) frac = prec < frac.Length ? frac[..prec] : frac.PadRight(prec, '0'); else frac = frac.TrimEnd('0'); string body = "0x" + lead + (frac.Length > 0 ? "." + frac : "") + "p" + (e2 >= 0 ? "+" : "-") + Math.Abs(e2); return upper ? body.ToUpperInvariant() : body; @@ -832,7 +1959,7 @@ public sealed class TTLInterpreter : IDisposable private static string StripQuotes(string s) => s.Length >= 2 && (s[0] == '\'' || s[0] == '"') && s[^1] == s[0] - ? s.Substring(1, s.Length - 2) : s; + ? s[1..^1] : s; private static string NextArg(IReadOnlyList args, ref int ai) { @@ -845,7 +1972,7 @@ public sealed class TTLInterpreter : IDisposable s = s.Trim(); if (long.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out long v)) return v; if ((s.StartsWith("0x") || s.StartsWith("0X")) && - long.TryParse(s.Substring(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out long h)) return h; + long.TryParse(s[2..], NumberStyles.HexNumber, CultureInfo.InvariantCulture, out long h)) return h; if (double.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out double d)) return (long)d; throw new ArgumentException("invalid integer argument"); } @@ -869,13 +1996,13 @@ public sealed class TTLInterpreter : IDisposable private static string GetCommand(string line) { int sp = line.IndexOf(' '); - return sp > 0 ? line.Substring(0, sp).Trim() : line.Trim(); + return sp > 0 ? line[..sp].Trim() : line.Trim(); } private static string GetArgs(string line) { int sp = line.IndexOf(' '); - return sp > 0 ? line.Substring(sp + 1).Trim() : ""; + return sp > 0 ? line[(sp + 1)..].Trim() : ""; } private string ReplaceVariables(string text) @@ -890,6 +2017,56 @@ public sealed class TTLInterpreter : IDisposable private static int ParseIntDirect(string value) => int.TryParse(value.Trim(), out int r) ? r : 0; + // ── v0.5.0 引數求值 / 變數存取 ── + + private object? ResolveVar(string name) + { + if (name.Equals("result", StringComparison.OrdinalIgnoreCase)) return _result; + if (name.Equals("timeout", StringComparison.OrdinalIgnoreCase)) return _timeout / 1000; + if (name.Equals("mtimeout", StringComparison.OrdinalIgnoreCase)) return _mtimeout; + return _vars.TryGetValue(name, out var v) ? v : null; + } + + /// token 求值:帶引號 → 字串常值;否則交給運算式解析器(變數 / 數字 / 簡單運算式,不可含空白)。 + private object Val(string token) + { + if (token.Length >= 2 && (token[0] == '\'' || token[0] == '"') && token[^1] == token[0]) + return token[1..^1]; + try { return TtlExpression.Evaluate(token, ResolveVar); } + catch (FormatException) { return token; } // 解析不了就當字面字串(寬鬆) + } + + private string ValS(string token) => TtlExpression.ToStr(Val(token)); + private int ValI(string token) => TtlExpression.ToInt(Val(token)); + + private static bool IsIdent(string s) => Regex.IsMatch(s, @"^[a-zA-Z_][a-zA-Z0-9_]*$"); + + private void SetDest(string name, object value) + { + if (!IsIdent(name)) { Output?.Invoke($"[ttl] invalid destination variable '{name}'"); return; } + _vars[name] = value; + } + + private static string FirstToken(string args) + { + var t = TokenizeArgs(args); + return t.Count > 0 ? t[0] : ""; + } + + private static string SecondToken(string args) + { + var t = TokenizeArgs(args); + return t.Count > 1 ? t[1] : ""; + } + + /// 在 UI thread 上執行(messagebox / inputbox / 剪貼簿等 WinForms 操作)。 + private static T UiInvoke(Func fn) + { + var main = Application.OpenForms.Count > 0 ? Application.OpenForms[0] : null; + if (main is { InvokeRequired: true }) return (T)main.Invoke(() => fn(main))!; + return fn(main); + } + #endregion public void Cancel() { _cancelled = true; _cts.Cancel(); } @@ -902,8 +2079,19 @@ public sealed class TTLInterpreter : IDisposable _cts.Cancel(); _cts.Dispose(); LogClose(); + foreach (var h in _fileHandles.Values) { try { (h as IDisposable)?.Dispose(); } catch { } } + _fileHandles.Clear(); foreach (var pdu in _pdus.Values) pdu.Dispose(); _pdus.Clear(); _channel.DataReceived -= OnData; } + + // ── 控制流訊號(goto / return / end / exit / break / continue)── + // 用例外把訊號從巢狀區塊一路帶回 RunMainLoop / 迴圈執行器 / ExecuteCall。 + private sealed class GotoSignal : Exception { public int Target; public GotoSignal(int t) : base("goto") => Target = t; } + private sealed class ReturnSignal : Exception { public ReturnSignal() : base("'return' outside of a subroutine") { } } + private sealed class EndSignal : Exception { public EndSignal() : base("end") { } } + private sealed class ExitSignal : Exception { public ExitSignal() : base("exit") { } } + private sealed class BreakSignal : Exception { public BreakSignal() : base("'break' outside of a loop") { } } + private sealed class ContinueSignal : Exception { public ContinueSignal() : base("'continue' outside of a loop") { } } } diff --git a/src/ETTerms/Scripting/TtlExpression.cs b/src/ETTerms/Scripting/TtlExpression.cs new file mode 100644 index 0000000..080d696 --- /dev/null +++ b/src/ETTerms/Scripting/TtlExpression.cs @@ -0,0 +1,253 @@ +using System.Globalization; + +namespace ETTerms.Scripting; + +/// +/// TTL 運算式解析 / 求值器(v0.5.0,供 if / elseif / while / until / for / 變數指派使用)。 +/// +/// 支援: +/// - 整數:十進位、0x1F$1F(TeraTerm 十六進位) +/// - 字串常值:'...'"..." +/// - 變數(由呼叫端 resolver 解析;未定義視為 0) +/// - 括號、一元 - / not / ! / ~ +/// - 算術 * / % + - +/// - 比較 = == <> != > < >= <=(兩邊皆可為整數時用數值比較,否則字串比較) +/// - 邏輯 and or xor(同義:&& ||) +/// +/// 值為 :int 或 string;比較 / 邏輯運算結果為 int 1/0。 +/// +public static class TtlExpression +{ + /// 求值整段文字;結尾若有多餘內容視為錯誤(FormatException)。 + public static object Evaluate(string text, Func resolve) + { + int pos = 0; + var v = ParseOr(text, ref pos, resolve); + SkipWs(text, ref pos); + if (pos < text.Length) throw new FormatException($"unexpected '{text[pos..]}'"); + return v; + } + + /// 起解析一個運算式,pos 停在運算式之後(供單行 if 判斷剩餘 statement)。 + public static object Parse(string text, ref int pos, Func resolve) + => ParseOr(text, ref pos, resolve); + + public static bool Truthy(object? v) => ToInt(v) != 0; + + public static int ToInt(object? v) => v switch + { + int i => i, + string s when TryParseInt(s.Trim(), out int r) => r, + _ => 0 + }; + + public static string ToStr(object? v) => v switch + { + null => "", + string s => s, + _ => v.ToString() ?? "" + }; + + // ── 文法(優先序低 → 高)───────────────────────────────── + private static object ParseOr(string s, ref int p, Func r) + { + var v = ParseAnd(s, ref p, r); + while (true) + { + SkipWs(s, ref p); + if (MatchWord(s, ref p, "or") || MatchOp(s, ref p, "||")) + v = (Truthy(v) | Truthy(ParseAnd(s, ref p, r))) ? 1 : 0; + else if (MatchWord(s, ref p, "xor")) + v = (Truthy(v) ^ Truthy(ParseAnd(s, ref p, r))) ? 1 : 0; + else return v; + } + } + + private static object ParseAnd(string s, ref int p, Func r) + { + var v = ParseCompare(s, ref p, r); + while (true) + { + SkipWs(s, ref p); + if (MatchWord(s, ref p, "and") || MatchOp(s, ref p, "&&")) + v = (Truthy(v) & Truthy(ParseCompare(s, ref p, r))) ? 1 : 0; + else return v; + } + } + + private static object ParseCompare(string s, ref int p, Func r) + { + var l = ParseAdd(s, ref p, r); + SkipWs(s, ref p); + string? op = + MatchOp(s, ref p, ">=") ? ">=" : + MatchOp(s, ref p, "<=") ? "<=" : + MatchOp(s, ref p, "<>") ? "!=" : + MatchOp(s, ref p, "==") ? "==" : + MatchOp(s, ref p, "!=") ? "!=" : + MatchOp(s, ref p, "=") ? "==" : + MatchOp(s, ref p, ">") ? ">" : + MatchOp(s, ref p, "<") ? "<" : null; + if (op == null) return l; + + var rt = ParseAdd(s, ref p, r); + + // 兩邊皆可為整數 → 數值比較;否則字串比較(僅 == / !=;大小比較退回數值 0) + bool numeric = l is int || rt is int + || (TryParseInt(ToStr(l).Trim(), out _) && TryParseInt(ToStr(rt).Trim(), out _)); + if (numeric) + { + int a = ToInt(l), b = ToInt(rt); + return op switch + { + "==" => a == b ? 1 : 0, + "!=" => a != b ? 1 : 0, + ">=" => a >= b ? 1 : 0, + "<=" => a <= b ? 1 : 0, + ">" => a > b ? 1 : 0, + _ => a < b ? 1 : 0 + }; + } + int cmp = string.CompareOrdinal(ToStr(l), ToStr(rt)); + return op switch + { + "==" => cmp == 0 ? 1 : 0, + "!=" => cmp != 0 ? 1 : 0, + ">=" => cmp >= 0 ? 1 : 0, + "<=" => cmp <= 0 ? 1 : 0, + ">" => cmp > 0 ? 1 : 0, + _ => cmp < 0 ? 1 : 0 + }; + } + + private static object ParseAdd(string s, ref int p, Func r) + { + var v = ParseMul(s, ref p, r); + while (true) + { + SkipWs(s, ref p); + if (MatchOp(s, ref p, "+")) v = ToInt(v) + ToInt(ParseMul(s, ref p, r)); + else if (MatchOp(s, ref p, "-")) v = ToInt(v) - ToInt(ParseMul(s, ref p, r)); + else return v; + } + } + + private static object ParseMul(string s, ref int p, Func r) + { + var v = ParseUnary(s, ref p, r); + while (true) + { + SkipWs(s, ref p); + if (MatchOp(s, ref p, "*")) v = ToInt(v) * ToInt(ParseUnary(s, ref p, r)); + else if (MatchOp(s, ref p, "/")) + { + int d = ToInt(ParseUnary(s, ref p, r)); + v = d != 0 ? ToInt(v) / d : 0; + } + else if (MatchOp(s, ref p, "%")) + { + int d = ToInt(ParseUnary(s, ref p, r)); + v = d != 0 ? ToInt(v) % d : 0; + } + else return v; + } + } + + private static object ParseUnary(string s, ref int p, Func r) + { + SkipWs(s, ref p); + if (MatchOp(s, ref p, "-")) return -ToInt(ParseUnary(s, ref p, r)); + if (MatchOp(s, ref p, "~")) return ~ToInt(ParseUnary(s, ref p, r)); + if (MatchOp(s, ref p, "!")) return Truthy(ParseUnary(s, ref p, r)) ? 0 : 1; + if (MatchWord(s, ref p, "not")) return Truthy(ParseUnary(s, ref p, r)) ? 0 : 1; + return ParsePrimary(s, ref p, r); + } + + private static object ParsePrimary(string s, ref int p, Func r) + { + SkipWs(s, ref p); + if (p >= s.Length) throw new FormatException("unexpected end of expression"); + + char c = s[p]; + if (c == '(') + { + p++; + var v = ParseOr(s, ref p, r); + SkipWs(s, ref p); + if (p >= s.Length || s[p] != ')') throw new FormatException("missing ')'"); + p++; + return v; + } + if (c is '\'' or '"') + { + char q = c; + int start = ++p; + while (p < s.Length && s[p] != q) p++; + if (p >= s.Length) throw new FormatException("unterminated string"); + var str = s[start..p]; + p++; + return str; + } + if (c == '$') // TeraTerm 十六進位 $1F + { + int start = ++p; + while (p < s.Length && Uri.IsHexDigit(s[p])) p++; + if (p == start) throw new FormatException("invalid hex literal"); + return int.Parse(s[start..p], NumberStyles.HexNumber, CultureInfo.InvariantCulture); + } + if (char.IsDigit(c)) + { + if (c == '0' && p + 1 < s.Length && (s[p + 1] is 'x' or 'X')) + { + int hs = p + 2, hp = hs; + while (hp < s.Length && Uri.IsHexDigit(s[hp])) hp++; + if (hp == hs) throw new FormatException("invalid hex literal"); + p = hp; + return int.Parse(s[hs..hp], NumberStyles.HexNumber, CultureInfo.InvariantCulture); + } + int ds = p; + while (p < s.Length && char.IsDigit(s[p])) p++; + return int.Parse(s[ds..p], CultureInfo.InvariantCulture); + } + if (char.IsLetter(c) || c == '_') + { + int ws = p; + while (p < s.Length && (char.IsLetterOrDigit(s[p]) || s[p] == '_')) p++; + return r(s[ws..p]) ?? 0; // 未定義變數 → 0 + } + throw new FormatException($"unexpected character '{c}'"); + } + + // ── 小工具 ─────────────────────────────────────────────── + private static void SkipWs(string s, ref int p) { while (p < s.Length && char.IsWhiteSpace(s[p])) p++; } + + private static bool MatchOp(string s, ref int p, string op) + { + if (p + op.Length > s.Length || !s.AsSpan(p, op.Length).SequenceEqual(op)) return false; + // "=" 不可吃掉 "=="、"<" 不可吃掉 "<=" / "<>"(呼叫端已按長度優先排序,這裡防呆單字元誤判) + if (op == "=" && p + 1 < s.Length && s[p + 1] == '=') return false; + if (op == ">" && p + 1 < s.Length && s[p + 1] == '=') return false; + if (op == "<" && p + 1 < s.Length && (s[p + 1] == '=' || s[p + 1] == '>')) return false; + p += op.Length; + return true; + } + + private static bool MatchWord(string s, ref int p, string word) + { + if (p + word.Length > s.Length) return false; + if (!s.AsSpan(p, word.Length).Equals(word, StringComparison.OrdinalIgnoreCase)) return false; + int after = p + word.Length; + if (after < s.Length && (char.IsLetterOrDigit(s[after]) || s[after] == '_')) return false; // 是識別字的一部分 + p = after; + return true; + } + + private static bool TryParseInt(string s, out int v) + { + if (s.StartsWith("0x") || s.StartsWith("0X")) + return int.TryParse(s[2..], NumberStyles.HexNumber, CultureInfo.InvariantCulture, out v); + if (s.StartsWith("$")) + return int.TryParse(s[1..], NumberStyles.HexNumber, CultureInfo.InvariantCulture, out v); + return int.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out v); + } +} diff --git a/src/ETTerms/Sessions/SerialChannel.cs b/src/ETTerms/Sessions/SerialChannel.cs index a020c5d..ebb9b23 100644 --- a/src/ETTerms/Sessions/SerialChannel.cs +++ b/src/ETTerms/Sessions/SerialChannel.cs @@ -72,6 +72,22 @@ public sealed class SerialChannel : ISessionChannel if (_port.IsOpen) _port.Write(data, 0, data.Length); } + // ── TTL serial 控制指令用(sendbreak / setbaud / setdtr / setrts)── + + /// 送出 serial break(拉 break 狀態約 300ms)。 + public void SendBreak() + { + if (!_port.IsOpen) return; + try { _port.BreakState = true; Thread.Sleep(300); } + finally { try { _port.BreakState = false; } catch { } } + } + + /// 執行中變更 baud rate(TTL setbaud)。 + public void SetBaudRate(int baud) => _port.BaudRate = baud; + + public void SetDtr(bool on) => _port.DtrEnable = on; + public void SetRts(bool on) => _port.RtsEnable = on; + public void Resize(int cols, int rows) { /* serial 無 PTY size */ } public void Close() diff --git a/src/ETTerms/Sessions/SessionPage.cs b/src/ETTerms/Sessions/SessionPage.cs index f67622a..7339397 100644 --- a/src/ETTerms/Sessions/SessionPage.cs +++ b/src/ETTerms/Sessions/SessionPage.cs @@ -63,6 +63,9 @@ public sealed class SessionPage : UserControl /// 同步開啟失敗(主要是 Serial 連不上 / 被占用)時觸發,附帶訊息。 public event Action? ConnectFailed; + /// 輸出中出現啟用的高亮關鍵字(UI thread),供 WorkspaceView 標分頁警示。 + public event Action? KeywordAlert; + public SessionPage(ISessionChannel channel, string title) { _channel = channel; @@ -90,12 +93,16 @@ public sealed class SessionPage : UserControl _term = new TerminalView(new TerminalProfile()) { Dock = DockStyle.Fill }; _term.SendData += data => _channel.Write(data); _term.Resized += (cols, rows) => _channel.Resize(cols, rows); + _term.KeywordAlert += k => KeywordAlert?.Invoke(k); Controls.Add(_term); // Fill 先加 Controls.Add(bar); // Top _runner.StatusChanged += (_, line, cmd) => Ui(() => _status.Text = $"line {line}: {Trunc(cmd)}"); _runner.Finished += (_, msg) => Ui(() => { _status.Text = msg; SetRunning(false); }); + // 腳本輸出(dispstr / [wait] 進度 / 錯誤)以灰色 echo 到終端機,執行過程看得見 + _runner.Output += m => Ui(() => + _term.Feed(System.Text.Encoding.UTF8.GetBytes($"\x1b[90m{m}\x1b[0m\r\n"))); } private async void OnRunScript(object? sender, EventArgs e) diff --git a/src/ETTerms/Terminal/ScreenBuffer.cs b/src/ETTerms/Terminal/ScreenBuffer.cs index 7b34bf4..5db0b4b 100644 --- a/src/ETTerms/Terminal/ScreenBuffer.cs +++ b/src/ETTerms/Terminal/ScreenBuffer.cs @@ -62,6 +62,10 @@ public sealed class ScreenBuffer public int TotalRows => _sbCount + Rows; public Cell[] LineAt(int abs) => abs < _sbCount ? _sb[(_sbHead + abs) % _sb.Length]! : _screen[abs - _sbCount]; + /// scrollback 滿後被丟棄的總行數。搜尋以「絕對行號 = DroppedLines + abs」錨定命中, + /// 舊行被丟棄時命中位置不會漂移。 + public long DroppedLines { get; private set; } + // ── 內部建構工具 ───────────────────────────────────────── private Cell BlankPen() => new() { Ch = ' ', Fg = PenFg, Bg = PenBg, Attr = CellAttr.None }; private Cell BlankDefault() => new() { Ch = ' ', Fg = DefaultFg, Bg = DefaultBg, Attr = CellAttr.None }; @@ -78,7 +82,7 @@ public sealed class ScreenBuffer { if (_sb.Length == 0) return; if (_sbCount < _sb.Length) _sb[(_sbHead + _sbCount++) % _sb.Length] = line; - else { _sb[_sbHead] = line; _sbHead = (_sbHead + 1) % _sb.Length; } // 滿了:覆蓋最舊一行 + else { _sb[_sbHead] = line; _sbHead = (_sbHead + 1) % _sb.Length; DroppedLines++; } // 滿了:覆蓋最舊一行 } // ── 輸出字元 ───────────────────────────────────────────── @@ -233,7 +237,7 @@ public sealed class ScreenBuffer public void EraseInDisplay(int mode) { - if (mode == 3) { Array.Clear(_sb); _sbHead = 0; _sbCount = 0; return; } + if (mode == 3) { DroppedLines += _sbCount; Array.Clear(_sb); _sbHead = 0; _sbCount = 0; return; } if (mode == 2) { for (int r = 0; r < Rows; r++) _screen[r] = BlankLine(); return; } if (mode == 0) { diff --git a/src/ETTerms/Terminal/TerminalView.cs b/src/ETTerms/Terminal/TerminalView.cs index 4447629..f38ac7b 100644 --- a/src/ETTerms/Terminal/TerminalView.cs +++ b/src/ETTerms/Terminal/TerminalView.cs @@ -1,7 +1,9 @@ using System.Drawing; using System.Runtime.InteropServices; using System.Text; +using System.Text.RegularExpressions; using System.Windows.Forms; +using ETTerms.Infrastructure; namespace ETTerms.Terminal; @@ -33,6 +35,31 @@ public sealed class TerminalView : UserControl private (int row, int col) _selStart, _selEnd; private bool _hasSel; + // ── 搜尋(Ctrl+F)── + private Panel? _searchPanel; + private TextBox _searchBox = null!; + private Label _searchCount = null!; + private readonly List<(long line, int col, int len)> _matches = new(); // line = DroppedLines + abs + private int _matchIdx = -1; + + // ── 高亮標記(搜尋命中 + 關鍵字),每次 OnPaint 對可見行重建 ── + private enum MarkKind { Keyword, Search, SearchCurrent } + private readonly Dictionary> _rowMarks = new(); + private readonly StringBuilder _lineSb = new(); + private readonly List _lineColMap = new(); + + // ── 關鍵字警示(Feed 偵測,分頁標紅點用)── + private static readonly Regex AnsiStrip = new( + @"\x1B\][^\x07\x1B]*(\x07|\x1B\\)|\x1B[@-Z\\-_]|\x1B\[[0-?]*[ -/]*[@-~]", + RegexOptions.Compiled); + private readonly Decoder _alertDec = Encoding.UTF8.GetDecoder(); + private string _alertCarry = ""; + private readonly Dictionary _alertLastFired = new(StringComparer.OrdinalIgnoreCase); + private const int AlertCooldownMs = 2000; + + /// 啟用的關鍵字在輸出中出現(UI thread 觸發),供分頁標警示。 + public event Action? KeywordAlert; + public TerminalView(TerminalProfile profile) { SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint @@ -63,6 +90,7 @@ public sealed class TerminalView : UserControl /// 餵入遠端資料(須在 UI thread 呼叫)。 public void Feed(byte[] data) { + DetectKeywords(data); int before = _buf.ScrollbackCount; _parser.Feed(data); // 已貼底才跟隨新輸出;使用者往回看歷史時,補償 scrollback 增量讓畫面停在原處, @@ -88,6 +116,8 @@ public sealed class TerminalView : UserControl if (ClientSize.Width < _cellW || ClientSize.Height < _cellH) return; if (FindForm() is { WindowState: FormWindowState.Minimized }) return; + PositionSearchPanel(); + int cols = VisibleCols, rows = VisibleRows; if (cols == _lastCols && rows == _lastRows) return; _lastCols = cols; _lastRows = rows; @@ -106,6 +136,8 @@ public sealed class TerminalView : UserControl int top = _buf.ScrollbackCount - _scrollOffset; // 視窗第一列的絕對 index if (top < 0) top = 0; + CollectMarks(top, rows); + for (int vr = 0; vr < rows; vr++) { int abs = top + vr; @@ -179,6 +211,27 @@ public sealed class TerminalView : UserControl fg = cell.Fg.A == 0 ? _buf.DefaultFg : cell.Fg; bg = cell.Bg.A == 0 ? _buf.DefaultBg : cell.Bg; if ((cell.Attr & CellAttr.Inverse) != 0) (fg, bg) = (bg, fg); + + // 標記優先序:目前搜尋命中 > 其他搜尋命中 > 關鍵字(選取反白最後蓋上) + if (_rowMarks.TryGetValue(abs, out var marks)) + { + var best = MarkKind.Keyword; bool hit = false; + foreach (var (c0, len, kind) in marks) + { + if (col < c0 || col >= c0 + len) continue; + if (!hit || kind > best) { best = kind; hit = true; } + } + if (hit) + { + switch (best) + { + case MarkKind.SearchCurrent: bg = Color.FromArgb(215, 160, 40); fg = Color.Black; break; + case MarkKind.Search: bg = Color.FromArgb(120, 100, 25); break; + case MarkKind.Keyword: bg = Color.FromArgb(150, 45, 45); break; + } + } + } + if (_hasSel && InSelection(abs, col)) (fg, bg) = (bg, Color.FromArgb(70, 90, 140)); } @@ -199,6 +252,9 @@ public sealed class TerminalView : UserControl { if (e.Control && e.KeyCode == Keys.C && _hasSel) { CopySelection(); e.Handled = e.SuppressKeyPress = true; return; } if ((e.Control && e.KeyCode == Keys.V) || (e.Shift && e.KeyCode == Keys.Insert)) { Paste(); e.Handled = e.SuppressKeyPress = true; return; } + if (e.Control && e.KeyCode == Keys.F) { OpenSearch(); e.Handled = e.SuppressKeyPress = true; return; } + if (e.KeyCode == Keys.F3 && _searchPanel is { Visible: true }) { StepMatch(e.Shift ? +1 : -1); e.Handled = e.SuppressKeyPress = true; return; } + if (e.KeyCode == Keys.Escape && _searchPanel is { Visible: true }) { CloseSearch(); e.Handled = e.SuppressKeyPress = true; return; } var bytes = TerminalInput.Map(e, _parser.AppCursorKeys); if (bytes != null) { SendData?.Invoke(bytes); e.Handled = e.SuppressKeyPress = true; } @@ -358,6 +414,243 @@ public sealed class TerminalView : UserControl catch { } } + // ── 搜尋(Ctrl+F)───────────────────────────────────────── + private void OpenSearch() + { + EnsureSearchUi(); + _searchPanel!.Visible = true; + PositionSearchPanel(); + _searchBox.SelectAll(); + _searchBox.Focus(); + if (_searchBox.Text.Length > 0) RunSearch(); + } + + private void CloseSearch() + { + if (_searchPanel == null) return; + _searchPanel.Visible = false; + _matches.Clear(); + _matchIdx = -1; + Focus(); + Invalidate(); + } + + private void EnsureSearchUi() + { + if (_searchPanel != null) return; + + var back = Color.FromArgb(32, 32, 38); + _searchPanel = new Panel { Size = new Size(268, 30), BackColor = back, Visible = false }; + _searchPanel.Paint += (_, pe) => + { + using var pen = new Pen(Color.FromArgb(58, 58, 66)); + pe.Graphics.DrawRectangle(pen, 0, 0, _searchPanel.Width - 1, _searchPanel.Height - 1); + }; + + _searchBox = new TextBox + { + Bounds = new Rectangle(6, 5, 130, 20), BorderStyle = BorderStyle.None, + BackColor = back, ForeColor = Color.FromArgb(222, 222, 226), Font = new Font("Segoe UI", 9.5f) + }; + _searchBox.TextChanged += (_, _) => RunSearch(); + _searchBox.KeyDown += (_, e) => + { + if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.F3) + { StepMatch(e.Shift ? +1 : -1); e.Handled = e.SuppressKeyPress = true; } // Enter 往上找(較舊),Shift 往下 + else if (e.KeyCode == Keys.Escape) + { CloseSearch(); e.Handled = e.SuppressKeyPress = true; } + }; + + _searchCount = new Label + { + Bounds = new Rectangle(138, 7, 56, 16), Text = "", + ForeColor = Color.FromArgb(150, 150, 158), BackColor = back, + Font = new Font("Segoe UI", 8.5f), TextAlign = ContentAlignment.MiddleRight + }; + + Button MakeBtn(string text, int x, Action onClick) + { + var b = new Button + { + Bounds = new Rectangle(x, 4, 22, 22), Text = text, FlatStyle = FlatStyle.Flat, + ForeColor = Color.FromArgb(180, 180, 188), BackColor = back, + Font = new Font("Segoe UI", 8.5f), TabStop = false, Cursor = Cursors.Hand + }; + b.FlatAppearance.BorderSize = 0; + b.FlatAppearance.MouseOverBackColor = Color.FromArgb(60, 60, 70); + b.Click += (_, _) => { onClick(); _searchBox.Focus(); }; + return b; + } + var up = MakeBtn("▲", 196, () => StepMatch(-1)); // 往上(較舊) + var down = MakeBtn("▼", 218, () => StepMatch(+1)); // 往下(較新) + var close = MakeBtn("✕", 240, CloseSearch); + + _searchPanel.Controls.AddRange(new Control[] { _searchBox, _searchCount, up, down, close }); + Controls.Add(_searchPanel); + _searchPanel.BringToFront(); + } + + private void PositionSearchPanel() + { + if (_searchPanel == null) return; + _searchPanel.Location = new Point(Math.Max(0, ContentWidth - _searchPanel.Width - 8), 6); + } + + /// 重掃整個 buffer(scrollback + 畫面)建立命中清單,並跳到最靠近底部的命中。 + private void RunSearch() + { + _matches.Clear(); + _matchIdx = -1; + string q = _searchBox.Text; + if (q.Length > 0) + { + long dropped = _buf.DroppedLines; + for (int abs = 0; abs < _buf.TotalRows; abs++) + { + BuildLineText(_buf.LineAt(abs), _lineSb, _lineColMap); + string s = _lineSb.ToString(); + int at = 0; + while (s.Length >= q.Length && (at = s.IndexOf(q, at, StringComparison.OrdinalIgnoreCase)) >= 0) + { + int colStart = _lineColMap[at]; + int colEnd = at + q.Length < _lineColMap.Count + ? _lineColMap[at + q.Length] + : _buf.LineAt(abs).Length; + _matches.Add((dropped + abs, colStart, Math.Max(1, colEnd - colStart))); + at++; + } + } + if (_matches.Count > 0) { _matchIdx = _matches.Count - 1; ScrollToMatch(); } + } + UpdateSearchCount(); + Invalidate(); + } + + /// dir = -1 往上(較舊)、+1 往下(較新),循環。 + private void StepMatch(int dir) + { + if (_matches.Count == 0) { RunSearch(); if (_matches.Count == 0) return; } + else + { + _matchIdx = (_matchIdx + dir + _matches.Count) % _matches.Count; + ScrollToMatch(); + } + UpdateSearchCount(); + Invalidate(); + } + + private void ScrollToMatch() + { + if (_matchIdx < 0 || _matchIdx >= _matches.Count) return; + int abs = (int)(_matches[_matchIdx].line - _buf.DroppedLines); + if (abs < 0) return; // 該行已被 scrollback 丟棄 + int top = Math.Max(0, abs - VisibleRows / 2); + _scrollOffset = Math.Clamp(_buf.ScrollbackCount - top, 0, _buf.ScrollbackCount); + UpdateScrollBar(); + } + + private void UpdateSearchCount() => + _searchCount.Text = _matches.Count == 0 + ? (_searchBox.Text.Length > 0 ? "0" : "") + : $"{_matchIdx + 1}/{_matches.Count}"; + + // ── 高亮標記收集(每次重繪對可見行執行)────────────────── + private void CollectMarks(int top, int rows) + { + _rowMarks.Clear(); + + // 關鍵字(Settings → Highlight):只掃可見行,成本固定 + var settings = AppSettings.Instance; + bool kwOn = settings.KeywordHighlightEnabled && settings.KeywordRules.Count > 0; + + if (kwOn) + { + for (int vr = 0; vr < rows; vr++) + { + int abs = top + vr; + if (abs >= _buf.TotalRows) break; + BuildLineText(_buf.LineAt(abs), _lineSb, _lineColMap); + string s = _lineSb.ToString(); + foreach (var rule in settings.KeywordRules) + { + if (!rule.Enabled || rule.Text.Length == 0) continue; + int at = 0; + while (s.Length >= rule.Text.Length && + (at = s.IndexOf(rule.Text, at, StringComparison.OrdinalIgnoreCase)) >= 0) + { + int colStart = _lineColMap[at]; + int colEnd = at + rule.Text.Length < _lineColMap.Count + ? _lineColMap[at + rule.Text.Length] + : _buf.LineAt(abs).Length; + AddMark(abs, colStart, Math.Max(1, colEnd - colStart), MarkKind.Keyword); + at++; + } + } + } + } + + // 搜尋命中(RunSearch 已算好,換算回目前 abs) + if (_matches.Count > 0) + { + long dropped = _buf.DroppedLines; + for (int i = 0; i < _matches.Count; i++) + { + int abs = (int)(_matches[i].line - dropped); + if (abs < top || abs >= top + rows) continue; + AddMark(abs, _matches[i].col, _matches[i].len, + i == _matchIdx ? MarkKind.SearchCurrent : MarkKind.Search); + } + } + } + + private void AddMark(int abs, int col, int len, MarkKind kind) + { + if (!_rowMarks.TryGetValue(abs, out var list)) _rowMarks[abs] = list = new(); + list.Add((col, len, kind)); + } + + /// 把一行 cell 轉成緊湊字串(略過 WideTrail),並記錄字元 index → 欄位 col 的對應。 + private static void BuildLineText(Cell[] line, StringBuilder sb, List colMap) + { + sb.Clear(); + colMap.Clear(); + for (int c = 0; c < line.Length; c++) + { + var cell = line[c]; + if ((cell.Attr & CellAttr.WideTrail) != 0) continue; + sb.Append(cell.Ch == '\0' ? ' ' : cell.Ch); + colMap.Add(c); + } + } + + // ── 關鍵字警示(Feed 路徑偵測,供分頁標紅點)────────────── + private void DetectKeywords(byte[] data) + { + var settings = AppSettings.Instance; + if (!settings.KeywordHighlightEnabled || settings.KeywordRules.Count == 0 || KeywordAlert == null) + { _alertCarry = ""; return; } + + var chars = new char[data.Length]; + int n = _alertDec.GetChars(data, 0, data.Length, chars, 0); + if (n == 0) return; + + string text = _alertCarry + AnsiStrip.Replace(new string(chars, 0, n), ""); + int maxKw = 1; + foreach (var rule in settings.KeywordRules) + { + if (!rule.Enabled || rule.Text.Length == 0) continue; + maxKw = Math.Max(maxKw, rule.Text.Length); + if (text.IndexOf(rule.Text, StringComparison.OrdinalIgnoreCase) < 0) continue; + long now = Environment.TickCount64; + if (_alertLastFired.TryGetValue(rule.Text, out var last) && now - last < AlertCooldownMs) continue; + _alertLastFired[rule.Text] = now; + KeywordAlert.Invoke(rule.Text); + } + // 保留尾巴(最長關鍵字 - 1),跨 chunk 的關鍵字下一輪才接得上 + int keep = maxKw - 1; + _alertCarry = text.Length <= keep ? text : text[^keep..]; + } + // ── IME(中文 / 日文 / 韓文輸入)───────────────────────── // 自繪控制項預設不處理 IME 組字,故攔截 WM_IME_COMPOSITION 取「結果字串」直接送出 UTF-8。 private const int WM_IME_STARTCOMPOSITION = 0x010D;