From 12635145862e05171d93afc692e1dae658910d74 Mon Sep 17 00:00:00 2001 From: ETWen Date: Thu, 11 Jun 2026 09:03:32 +0800 Subject: [PATCH] feat(status): add Status page with PDU outlet on/off buttons (v0.3.2) - New left-rail Status view (StatusView.cs) hosting the PDU tab; PDU panel moved out of SettingsView and auto-polls all 12 outlets every 3s on a background thread (no manual Refresh). - Each outlet row gets a Control button (DataGridViewButtonColumn) that toggles the port via SNMP off the UI thread, re-reads after ~400ms, and resets the grid on disconnect. - fix(shell): ShellChannel falls back to the user home folder when StartupDirectory no longer exists (avoids CreateProcess 267). - docs: update ARCHITECTURE / CLAUDE / README / README.zh-TW and About changelog; bump version to 0.3.2. --- ARCHITECTURE.md | 7 +- CLAUDE.md | 2 + README.md | 8 +- README.zh-TW.md | 8 +- src/ETTerms/App/AboutView.cs | 7 + src/ETTerms/App/ActivityRail.cs | 3 +- src/ETTerms/App/MainForm.cs | 4 + src/ETTerms/App/SettingsView.cs | 104 +--------- src/ETTerms/App/StatusView.cs | 288 +++++++++++++++++++++++++++ src/ETTerms/ETTerms.csproj | 2 +- src/ETTerms/Sessions/ShellChannel.cs | 9 +- 11 files changed, 330 insertions(+), 112 deletions(-) create mode 100644 src/ETTerms/App/StatusView.cs diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index f2adc82..958bfe1 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -118,8 +118,11 @@ ETTerms/ │ ├── MainForm.cs # 主視窗:Rail + Sidebar + Workspace(含深色標題列 DWM) │ ├── MainForm.Designer.cs │ ├── Theme.cs # 全域深色配色 (KKTerm 風格) - │ ├── ActivityRail.cs # 左側圖示列 (Terminal/Scripts/Settings) + │ ├── ActivityRail.cs # 左側圖示列 (Terminal/Status/Settings/About) │ ├── ConnectionSidebar.cs# 仿 KKTerm 可編輯資料夾樹(搜尋/CRUD/拖曳分類) + │ ├── StatusView.cs # Status 檢視:分頁式(PDU…),PDU 連線後每 3 秒背景輪詢插座狀態,並可用表格內 Control 鈕直接開關各 Port + │ ├── SettingsView.cs # Settings 檢視:分頁式(Terminal / AI MCP) + │ ├── AboutView.cs # About 檢視(版本 / 連結) │ ├── Dialogs/ # ── 深色對話框 ── │ │ ├── DarkDialog.cs # 對話框基底(深色 + DWM 標題列) │ │ ├── TextPromptDialog.cs # 單行輸入(資料夾命名 / 改名) @@ -140,7 +143,7 @@ ETTerms/ │ ├── ISessionChannel.cs # Write(byte[]) + event DataReceived │ ├── SshChannel.cs # SSH.NET 實作 (ShellStream) │ ├── SerialChannel.cs # System.IO.Ports 實作 - │ ├── ShellChannel.cs # Windows ConPTY 本機 Shell + │ ├── ShellChannel.cs # Windows ConPTY 本機 Shell(StartupDirectory 不存在時 fallback 使用者家目錄) │ ├── SessionPage.cs # 一個分頁 = TerminalView + Channel + 狀態 │ ├── SessionManager.cs # 開 / 關 / 列舉所有 active session │ ├── SerialBridgeServer.cs# ✅ 本機 named pipe server:把 serial session 的讀寫橋接給 MCP(Phase 9) diff --git a/CLAUDE.md b/CLAUDE.md index bfb83bb..13786e4 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.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 行為一致。 + **v0.3.1:** 終端機體驗修正(皆在 `src/ETTerms/Terminal/`)。**(1) 深色垂直捲軸** — 新增自繪 `DarkScrollBar`(細長、無箭頭、圓角滑塊,配合 KKTerm 深色主題),`TerminalView` 右側 `Dock=Right` 掛上,`ContentWidth` 扣掉捲軸寬避免文字被蓋,`UpdateScrollBar()` 在 `Feed` / 滾輪 / resize 時同步滑塊範圍與位置,滾輪與拖曳互通。**(2) 多行貼上修正** — `AnsiParser` 新增 `BracketedPaste`(DEC mode 2004);`TerminalView.Paste()` 在對方啟用 bracketed paste(PSReadLine / Kiro CLI 等)時以 `ESC[200~ … ESC[201~` 包夾整段,視為「單次貼上」而非逐行 Enter 立即送出;未啟用時退回原本逐字送出。**(3) 右鍵複製清反白** — 右鍵複製後清掉 `_hasSel` 並重繪,讓使用者知道已複製。 **v0.3.0:** 新增 **`ETTerms.PduMcp`**(stdio MCP server):讓 AI agent 直接控制 SNMP PDU 插座。與 serial 不同,PDU 走 SNMP(UDP) **非獨佔**,故 PduMcp **直接打 SNMP、不經 GUI 橋接**(內含精簡版 `PduController`,OID 邏輯複製自 GUI 版,log 走 stderr),GUI 不開著也能用。工具:`pdu_connect` / `pdu_list` / `pdu_set_port` / `pdu_get_port` / `pdu_status` / `pdu_power_cycle` / `pdu_disconnect`,回傳統一 `{ok, result/error}` JSON;連線狀態以行程內單例 `PduRegistry`(IP→controller)保存。`McpRegistrar` 改為多 server,**Settings → AI MCP 一鍵同時註冊 `etterms-serial` 與 `etterms-pdu`**;`ETTerms.csproj` 的 publish target 更名 `PublishMcpServers`,GUI publish 會把兩個 MCP 各自帶到 `\ETTerms.SerialMcp\`、`\ETTerms.PduMcp\` 子資料夾。 diff --git a/README.md b/README.md index cad95b7..ccddc49 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ > A native Windows terminal workspace (C# .NET 8 WinForms) — **SSH**, **Serial Port**, and **local Shell (ConPTY)** in one window, with a **TTL scripting engine** ported from MyTeraTerm for automation, plus an optional **Serial MCP server** that lets AI agents (Kiro CLI / Claude CLI) drive the serial port directly. Standalone, no cloud, no login. -![version](https://img.shields.io/badge/version-0.3.1-blue.svg) ![platform](https://img.shields.io/badge/platform-Windows-0078D6.svg?logo=windows&logoColor=white) ![.NET](https://img.shields.io/badge/.NET-8.0-512BD4.svg?logo=dotnet&logoColor=white) ![UI](https://img.shields.io/badge/UI-WinForms-5C2D91.svg) ![SSH](https://img.shields.io/badge/SSH-SSH.NET-success.svg) ![Serial](https://img.shields.io/badge/Serial-System.IO.Ports-success.svg) ![status](https://img.shields.io/badge/status-beta-yellow.svg) ![license](https://img.shields.io/badge/license-MIT-green.svg) +![version](https://img.shields.io/badge/version-0.3.2-blue.svg) ![platform](https://img.shields.io/badge/platform-Windows-0078D6.svg?logo=windows&logoColor=white) ![.NET](https://img.shields.io/badge/.NET-8.0-512BD4.svg?logo=dotnet&logoColor=white) ![UI](https://img.shields.io/badge/UI-WinForms-5C2D91.svg) ![SSH](https://img.shields.io/badge/SSH-SSH.NET-success.svg) ![Serial](https://img.shields.io/badge/Serial-System.IO.Ports-success.svg) ![status](https://img.shields.io/badge/status-beta-yellow.svg) ![license](https://img.shields.io/badge/license-MIT-green.svg) --- @@ -63,6 +63,7 @@ - ⚡ **PDU power control (optional)** - Control PDU outlets over SNMP (`SnmpSharpNet`) to power-cycle devices during tests + - **Status → PDU** tab: connect to a PDU, auto-poll outlet state every 3 s, and toggle any port on/off with per-row **Control** buttons - Script commands: `pduconnect` / `pductrl` - 🤖 **AI / MCP integration (optional)** @@ -403,6 +404,11 @@ ETTerms/ ## 📜 Version History +### v0.3.2 + +- **Status → PDU tab** — a dedicated `Status` rail view hosts the PDU panel: connect by IP, auto-poll all 12 outlets every 3 s (background thread, no manual Refresh), with live current / power readouts +- **Manual outlet control buttons** — each row has a **Control** button that toggles that port on/off over SNMP; the label tracks state (ON → "Turn OFF", OFF → "Turn ON"), the SNMP set runs off the UI thread, and the grid refreshes after the command + ### v0.3.1 - **Terminal usability fixes** — added a **dark vertical scrollbar** (drag or click-to-page through long output instead of long mouse-wheel scrolling) diff --git a/README.zh-TW.md b/README.zh-TW.md index 160982a..96d0aea 100644 --- a/README.zh-TW.md +++ b/README.zh-TW.md @@ -4,7 +4,7 @@ > 原生 Windows 終端機工作台(C# .NET 8 WinForms)—— 一個視窗整合 **SSH**、**Serial Port**、**本機 Shell (ConPTY)** 連線,內建從 MyTeraTerm 移植的 **TTL 腳本引擎**做自動化,並提供選用的 **Serial MCP server**,讓 AI agent(Kiro CLI / Claude CLI)直接操作 serial port。單機、無雲、無登入系統。 -![version](https://img.shields.io/badge/version-0.3.1-blue.svg) ![platform](https://img.shields.io/badge/platform-Windows-0078D6.svg?logo=windows&logoColor=white) ![.NET](https://img.shields.io/badge/.NET-8.0-512BD4.svg?logo=dotnet&logoColor=white) ![UI](https://img.shields.io/badge/UI-WinForms-5C2D91.svg) ![SSH](https://img.shields.io/badge/SSH-SSH.NET-success.svg) ![Serial](https://img.shields.io/badge/Serial-System.IO.Ports-success.svg) ![status](https://img.shields.io/badge/status-beta-yellow.svg) ![license](https://img.shields.io/badge/license-MIT-green.svg) +![version](https://img.shields.io/badge/version-0.3.2-blue.svg) ![platform](https://img.shields.io/badge/platform-Windows-0078D6.svg?logo=windows&logoColor=white) ![.NET](https://img.shields.io/badge/.NET-8.0-512BD4.svg?logo=dotnet&logoColor=white) ![UI](https://img.shields.io/badge/UI-WinForms-5C2D91.svg) ![SSH](https://img.shields.io/badge/SSH-SSH.NET-success.svg) ![Serial](https://img.shields.io/badge/Serial-System.IO.Ports-success.svg) ![status](https://img.shields.io/badge/status-beta-yellow.svg) ![license](https://img.shields.io/badge/license-MIT-green.svg) --- @@ -63,6 +63,7 @@ - ⚡ **PDU 電源控制(選用)** - 透過 SNMP(`SnmpSharpNet`)控制 PDU 插座,測試中遠端電源循環 + - **Status → PDU** 分頁:連線 PDU 後每 3 秒自動輪詢插座狀態,並可用各列的 **Control** 鈕直接開 / 關該 Port - 腳本指令:`pduconnect` / `pductrl` - 🤖 **AI / MCP 整合(選用)** @@ -403,6 +404,11 @@ ETTerms/ ## 📜 版本紀錄 +### v0.3.2 + +- **Status → PDU 分頁** —— 新增 `Status` rail 檢視,PDU 面板移到此處:輸入 IP 連線後每 3 秒自動輪詢全部 12 個插座(背景執行緒,免手動 Refresh),即時顯示電流 / 功率 +- **手動插座開關鈕** —— 每列新增 **Control** 鈕,按一下即透過 SNMP 切換該 Port 開 / 關;按鈕文字隨狀態變動(ON →「Turn OFF」、OFF →「Turn ON」),SNMP 設定在 UI 執行緒外執行,下命令後自動回讀刷新表格 + ### v0.3.1 - **終端機體驗修正** —— 新增**深色垂直捲軸**(拖曳滑塊或點軌道翻頁,不必狂滾滑鼠看長輸出) diff --git a/src/ETTerms/App/AboutView.cs b/src/ETTerms/App/AboutView.cs index 7548355..5ee9ef5 100644 --- a/src/ETTerms/App/AboutView.cs +++ b/src/ETTerms/App/AboutView.cs @@ -183,6 +183,13 @@ public sealed class AboutView : UserControl private static readonly ChangelogEntry[] Changelog = [ + new("0.3.2", new DateOnly(2026, 6, 11), "New Status page — control PDU outlets with buttons", + [ + "New Status page (the ⚡ icon on the left) with a PDU tab — connect to your PDU by IP and see every outlet at a glance.", + "Each outlet now has its own on/off button: the button shows \"Turn ON\" or \"Turn OFF\" depending on the current state, so one click flips it.", + "Outlet status, current and power refresh automatically every 3 seconds — no need to hit Refresh anymore.", + "Fixed: the local Shell no longer fails to start when its saved folder is gone (e.g. an unplugged USB drive); it now falls back to your home folder.", + ]), new("0.3.1", new DateOnly(2026, 6, 8), "Bugfix — terminal usability", [ "Added a scrollbar on the right of the terminal — just drag it to look back through long output, instead of spinning the mouse wheel for ages.", diff --git a/src/ETTerms/App/ActivityRail.cs b/src/ETTerms/App/ActivityRail.cs index 44d659f..97a9c52 100644 --- a/src/ETTerms/App/ActivityRail.cs +++ b/src/ETTerms/App/ActivityRail.cs @@ -10,7 +10,7 @@ namespace ETTerms.App; /// public sealed class ActivityRail : UserControl { - public enum RailView { Terminal, Settings, About } + public enum RailView { Terminal, Status, Settings, About } public event EventHandler? ViewSelected; @@ -23,6 +23,7 @@ public sealed class ActivityRail : UserControl private static readonly (RailView view, string glyph, string tip)[] Items = { (RailView.Terminal, "▤", "Terminal"), + (RailView.Status, "⚡", "Status"), (RailView.Settings, "⚙", "Settings"), (RailView.About, "ℹ", "About"), }; diff --git a/src/ETTerms/App/MainForm.cs b/src/ETTerms/App/MainForm.cs index ea13e27..7f35966 100644 --- a/src/ETTerms/App/MainForm.cs +++ b/src/ETTerms/App/MainForm.cs @@ -14,6 +14,7 @@ public partial class MainForm : Form private readonly ActivityRail _rail = new(); private readonly ConnectionSidebar _sidebar = new(); private readonly WorkspaceView _workspace = new(); + private readonly StatusView _statusView = new(); private readonly SettingsView _settings = new(); private readonly AboutView _about = new(); private readonly StatusStrip _status = new(); @@ -45,11 +46,13 @@ public partial class MainForm : Form private void BuildLayout() { Controls.Add(_workspace); // Fill + Controls.Add(_statusView); // Fill (hidden) Controls.Add(_settings); // Fill (hidden) Controls.Add(_about); // Fill (hidden) Controls.Add(_sidebar); // Left (內側) Controls.Add(_rail); // Left (最外側) + _statusView.Visible = false; _settings.Visible = false; _about.Visible = false; @@ -68,6 +71,7 @@ public partial class MainForm : Form _statusLabel.Text = $"View: {view}"; _sidebar.Visible = view == ActivityRail.RailView.Terminal; _workspace.Visible = view == ActivityRail.RailView.Terminal; + _statusView.Visible = view == ActivityRail.RailView.Status; _settings.Visible = view == ActivityRail.RailView.Settings; _about.Visible = view == ActivityRail.RailView.About; AppLogger.LogInfo($"View selected: {view}"); diff --git a/src/ETTerms/App/SettingsView.cs b/src/ETTerms/App/SettingsView.cs index 1732d03..9505151 100644 --- a/src/ETTerms/App/SettingsView.cs +++ b/src/ETTerms/App/SettingsView.cs @@ -1,11 +1,10 @@ using System.Drawing; using System.Windows.Forms; using ETTerms.Infrastructure; -using ETTerms.Scripting.Pdu; namespace ETTerms.App; -/// Settings page with tabs: Terminal / PDU / AI MCP. +/// Settings page with tabs: Terminal / AI MCP. public sealed class SettingsView : UserControl { public SettingsView() @@ -53,7 +52,6 @@ public sealed class SettingsView : UserControl var termBtn = MakeTab("Terminal", BuildTerminalTab()); tabBar.Controls.Add(termBtn); - tabBar.Controls.Add(MakeTab("PDU", BuildPduTab())); tabBar.Controls.Add(MakeTab("AI MCP", BuildAiMcpTab())); Controls.Add(body); @@ -173,106 +171,6 @@ public sealed class SettingsView : UserControl return page; } - // ═══ PDU Tab ═══ - private Panel BuildPduTab() - { - var page = new Panel { BackColor = Theme.WorkspaceBack, Padding = new Padding(20) }; - - var flow = new FlowLayoutPanel - { - Dock = DockStyle.Fill, FlowDirection = FlowDirection.TopDown, - WrapContents = false, BackColor = Theme.WorkspaceBack, AutoScroll = true - }; - - // Connection row - var ipBox = new TextBox { Width = 160, Text = "192.168.1.21", BackColor = Theme.TabBack, ForeColor = Theme.Text, Font = Theme.UiFont }; - var connectBtn = MakeButton("Connect", Theme.SerialColor); - var statusLabel = new Label { AutoSize = true, Text = "Disconnected", ForeColor = Theme.TextDim, Font = Theme.UiFont, Margin = new Padding(8, 8, 0, 0) }; - - var connRow = new FlowLayoutPanel { FlowDirection = FlowDirection.LeftToRight, Width = 500, Height = 36, WrapContents = false, Margin = new Padding(0, 0, 0, 8) }; - connRow.Controls.Add(new Label { Text = "PDU IP:", AutoSize = true, ForeColor = Theme.Text, Font = Theme.UiFont, Margin = new Padding(0, 6, 8, 0) }); - connRow.Controls.Add(ipBox); - connRow.Controls.Add(connectBtn); - connRow.Controls.Add(statusLabel); - flow.Controls.Add(connRow); - - // Port status grid - var grid = new DataGridView - { - Width = 480, Height = 310, AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill, - 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, ReadOnly = true, - AllowUserToResizeRows = false, SelectionMode = DataGridViewSelectionMode.FullRowSelect, - ScrollBars = ScrollBars.None, Font = Theme.UiFont, - RowTemplate = { Height = 24 }, - Margin = new Padding(0, 8, 0, 8) - }; - grid.Columns.Add("Port", "Port"); - grid.Columns.Add("Status", "Status"); - grid.Columns.Add("Current", "Current (mA)"); - grid.Columns.Add("Power", "Power (W)"); - for (int i = 1; i <= 12; i++) - grid.Rows.Add($"Port {i}", "—", "—", "—"); - flow.Controls.Add(grid); - - // Refresh button - var refreshBtn = MakeButton("Refresh", Theme.Accent); - flow.Controls.Add(refreshBtn); - - // Logic - PduController? pdu = null; - - connectBtn.Click += (_, _) => - { - if (pdu != null) { pdu.Dispose(); pdu = null; statusLabel.Text = "Disconnected"; statusLabel.ForeColor = Theme.TextDim; connectBtn.Text = "Connect"; return; } - var ip = ipBox.Text.Trim(); - var p = new PduController(ip); - if (p.CheckConnection()) - { - pdu = p; - statusLabel.Text = $"Connected to {ip}"; - statusLabel.ForeColor = Theme.SerialColor; - connectBtn.Text = "Disconnect"; - RefreshPduGrid(pdu, grid); - } - else - { - p.Dispose(); - MessageBox.Show(this, $"Failed to connect to PDU at {ip}", "PDU", MessageBoxButtons.OK, MessageBoxIcon.Warning); - } - }; - - refreshBtn.Click += (_, _) => - { - if (pdu == null) { MessageBox.Show(this, "Connect to PDU first.", "PDU", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } - RefreshPduGrid(pdu, grid); - }; - - page.Controls.Add(flow); - return page; - } - - private static void RefreshPduGrid(PduController pdu, DataGridView grid) - { - for (int i = 0; i < 12; i++) - { - int port = i + 1; - var state = pdu.GetPortState(port); - var current = pdu.GetPortCurrent(port); - var power = pdu.GetPortPowerWatts(port); - var row = grid.Rows[i]; - row.Cells["Status"].Value = state == true ? "ON" : state == false ? "OFF" : "—"; - row.Cells["Current"].Value = current.HasValue ? $"{current.Value}" : "—"; - row.Cells["Power"].Value = power.HasValue ? $"{power.Value:F1}" : "—"; - row.DefaultCellStyle.BackColor = state == true ? Color.FromArgb(40, 80, 40) : state == false ? Color.FromArgb(60, 40, 40) : Theme.TabBack; - } - } - // ═══ AI MCP Tab ═══ private Panel BuildAiMcpTab() { diff --git a/src/ETTerms/App/StatusView.cs b/src/ETTerms/App/StatusView.cs new file mode 100644 index 0000000..f894884 --- /dev/null +++ b/src/ETTerms/App/StatusView.cs @@ -0,0 +1,288 @@ +using System.Drawing; +using System.Windows.Forms; +using ETTerms.Scripting.Pdu; + +namespace ETTerms.App; + +/// +/// Status page with tabs: PDU (more views to come). +/// 風格參考 :自繪 tab strip + panel 切換,避免 TabControl 白邊。 +/// PDU 分頁連線後每 3 秒於背景自動輪詢插座狀態(不需手動 Refresh)。 +/// +public sealed class StatusView : UserControl +{ + public StatusView() + { + Dock = DockStyle.Fill; + BackColor = Theme.WorkspaceBack; + + var tabBar = new FlowLayoutPanel + { + Dock = DockStyle.Top, Height = 32, BackColor = Theme.RailBack, + Padding = new Padding(4, 4, 4, 0), WrapContents = false + }; + + var body = new Panel { Dock = DockStyle.Fill, BackColor = Theme.WorkspaceBack }; + var pages = new List(); + + Button? activeBtn = null; + Button MakeTab(string text, Panel page) + { + page.Dock = DockStyle.Fill; + page.Visible = false; + body.Controls.Add(page); + pages.Add(page); + + var b = new Button + { + Text = text, AutoSize = true, AutoSizeMode = AutoSizeMode.GrowAndShrink, + MinimumSize = new Size(70, 26), Padding = new Padding(10, 2, 10, 2), + FlatStyle = FlatStyle.Flat, + ForeColor = Theme.Text, BackColor = Theme.TabBack, Font = Theme.UiFont, + Margin = new Padding(0, 0, 4, 0), Cursor = Cursors.Hand + }; + b.FlatAppearance.BorderColor = Theme.Border; + b.FlatAppearance.MouseOverBackColor = Theme.Hover; + b.Click += (_, _) => + { + foreach (var p in pages) p.Visible = p == page; + if (activeBtn != null) activeBtn.BackColor = Theme.TabBack; + b.BackColor = Theme.TabActiveBack; + activeBtn = b; + }; + return b; + } + + var pduBtn = MakeTab("PDU", BuildPduTab()); + tabBar.Controls.Add(pduBtn); + + Controls.Add(body); + Controls.Add(tabBar); + + pduBtn.PerformClick(); + } + + // ═══ PDU Tab ═══ + private Panel BuildPduTab() + { + var page = new Panel { BackColor = Theme.WorkspaceBack, Padding = new Padding(20) }; + + var flow = new FlowLayoutPanel + { + Dock = DockStyle.Fill, FlowDirection = FlowDirection.TopDown, + WrapContents = false, BackColor = Theme.WorkspaceBack, AutoScroll = true + }; + + // Connection row + var ipBox = new TextBox { Width = 160, Text = "192.168.1.21", BackColor = Theme.TabBack, ForeColor = Theme.Text, Font = Theme.UiFont }; + var connectBtn = MakeButton("Connect", Theme.SerialColor); + var statusLabel = new Label { AutoSize = true, Text = "Disconnected", ForeColor = Theme.TextDim, Font = Theme.UiFont, Margin = new Padding(8, 8, 0, 0) }; + + var connRow = new FlowLayoutPanel { FlowDirection = FlowDirection.LeftToRight, Width = 500, Height = 36, WrapContents = false, Margin = new Padding(0, 0, 0, 8) }; + connRow.Controls.Add(new Label { Text = "PDU IP:", AutoSize = true, ForeColor = Theme.Text, Font = Theme.UiFont, Margin = new Padding(0, 6, 8, 0) }); + connRow.Controls.Add(ipBox); + connRow.Controls.Add(connectBtn); + connRow.Controls.Add(statusLabel); + flow.Controls.Add(connRow); + + // Port status grid + var grid = new DataGridView + { + Width = 480, Height = 310, AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill, + 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, ReadOnly = true, + AllowUserToResizeRows = false, SelectionMode = DataGridViewSelectionMode.FullRowSelect, + ScrollBars = ScrollBars.None, Font = Theme.UiFont, + RowTemplate = { Height = 24 }, + Margin = new Padding(0, 8, 0, 8) + }; + grid.Columns.Add("Port", "Port"); + grid.Columns.Add("Status", "Status"); + grid.Columns.Add("Current", "Current (mA)"); + grid.Columns.Add("Power", "Power (W)"); + + // 控制按鈕欄:按一下切換該 Port 的 ON/OFF + var actionCol = new DataGridViewButtonColumn + { + Name = "Action", HeaderText = "Control", + UseColumnTextForButtonValue = false, FlatStyle = FlatStyle.Flat, + FillWeight = 80, + DefaultCellStyle = + { + BackColor = Theme.TabBack, ForeColor = Theme.Text, + SelectionBackColor = Theme.Hover, SelectionForeColor = Theme.Text, + Alignment = DataGridViewContentAlignment.MiddleCenter + } + }; + grid.Columns.Add(actionCol); + + for (int i = 1; i <= 12; i++) + grid.Rows.Add($"Port {i}", "—", "—", "—", "—"); + flow.Controls.Add(grid); + + // 連線後每 3 秒自動輪詢(背景執行緒讀 SNMP,Invoke 回 UI 更新) + var pollLabel = new Label { AutoSize = true, Text = "", ForeColor = Theme.TextDim, Font = Theme.UiFont, Margin = new Padding(0, 4, 0, 0) }; + flow.Controls.Add(pollLabel); + + // Logic + PduController? pdu = null; + System.Threading.Timer? timer = null; + int polling = 0; // 0=idle, 1=in-flight(避免上一次未讀完又疊一次) + + void StopPolling() + { + timer?.Dispose(); + timer = null; + } + + void PollOnce() + { + // 已在輪詢中就跳過這一輪 + if (System.Threading.Interlocked.Exchange(ref polling, 1) == 1) return; + var current = pdu; + if (current == null) { System.Threading.Volatile.Write(ref polling, 0); return; } + + try + { + var rows = new (bool? state, int? current, double? power)[12]; + for (int i = 0; i < 12; i++) + { + int port = i + 1; + rows[i] = (current.GetPortState(port), current.GetPortCurrent(port), current.GetPortPowerWatts(port)); + } + + if (!IsDisposed && IsHandleCreated) + { + BeginInvoke(new Action(() => + { + if (pdu != current) return; // 期間已斷線 + ApplyPduRows(grid, rows); + pollLabel.Text = $"Auto-refresh every 3s · last update {DateTime.Now:HH:mm:ss}"; + })); + } + } + catch { /* 輪詢失敗忽略,下一輪再試 */ } + finally { System.Threading.Volatile.Write(ref polling, 0); } + } + + connectBtn.Click += (_, _) => + { + if (pdu != null) + { + StopPolling(); + pdu.Dispose(); pdu = null; + statusLabel.Text = "Disconnected"; statusLabel.ForeColor = Theme.TextDim; + connectBtn.Text = "Connect"; + pollLabel.Text = ""; + // 斷線後清空表格,避免顯示過時的狀態 + foreach (DataGridViewRow row in grid.Rows) + { + row.Cells["Status"].Value = "—"; + row.Cells["Current"].Value = "—"; + row.Cells["Power"].Value = "—"; + row.Cells["Action"].Value = "—"; + row.DefaultCellStyle.BackColor = Theme.TabBack; + } + return; + } + + var ip = ipBox.Text.Trim(); + var p = new PduController(ip); + if (p.CheckConnection()) + { + pdu = p; + statusLabel.Text = $"Connected to {ip}"; + statusLabel.ForeColor = Theme.SerialColor; + connectBtn.Text = "Disconnect"; + // 立即讀一次,之後每 3 秒一次 + timer = new System.Threading.Timer(_ => PollOnce(), null, + dueTime: 0, period: 3000); + } + else + { + p.Dispose(); + MessageBox.Show(this, $"Failed to connect to PDU at {ip}", "PDU", MessageBoxButtons.OK, MessageBoxIcon.Warning); + } + }; + + // 控制項銷毀時收掉計時器與連線 + Disposed += (_, _) => { StopPolling(); pdu?.Dispose(); }; + + // 按下 Control 欄按鈕:切換該 Port 的 ON/OFF(SNMP Set 在背景執行,避免卡 UI) + grid.CellContentClick += (_, e) => + { + if (e.RowIndex < 0 || e.ColumnIndex < 0) return; + if (grid.Columns[e.ColumnIndex].Name != "Action") return; + + var current = pdu; + if (current == null) + { + MessageBox.Show(this, "PDU is not connected. Please connect first.", + "PDU", MessageBoxButtons.OK, MessageBoxIcon.Warning); + return; + } + + int port = e.RowIndex + 1; + var statusVal = grid.Rows[e.RowIndex].Cells["Status"].Value?.ToString(); + if (statusVal != "ON" && statusVal != "OFF") return; // 狀態未知時不動作 + bool turnOn = statusVal != "ON"; // 目前 ON → 關;其餘 → 開 + + var actionCell = grid.Rows[e.RowIndex].Cells["Action"]; + actionCell.Value = "…"; + + System.Threading.Tasks.Task.Run(() => + { + bool ok = turnOn ? current.SetPortOn(port) : current.SetPortOff(port); + System.Threading.Thread.Sleep(400); // 等 PDU 套用後再讀回確認 + PollOnce(); // 背景讀 SNMP 後 Invoke 回 UI 更新整張表 + + if (!ok && !IsDisposed && IsHandleCreated) + { + BeginInvoke(new Action(() => + MessageBox.Show(this, + $"Failed to turn {(turnOn ? "ON" : "OFF")} Port {port}", + "PDU", MessageBoxButtons.OK, MessageBoxIcon.Error))); + } + }); + }; + + page.Controls.Add(flow); + return page; + } + + private static void ApplyPduRows(DataGridView grid, (bool? state, int? current, double? power)[] rows) + { + for (int i = 0; i < rows.Length && i < grid.Rows.Count; i++) + { + var (state, current, power) = rows[i]; + var row = grid.Rows[i]; + row.Cells["Status"].Value = state == true ? "ON" : state == false ? "OFF" : "—"; + row.Cells["Current"].Value = current.HasValue ? $"{current.Value}" : "—"; + row.Cells["Power"].Value = power.HasValue ? $"{power.Value:F1}" : "—"; + // 按鈕文字代表「按下後會做的動作」:ON 時顯示 Turn OFF,反之亦然 + row.Cells["Action"].Value = state == true ? "Turn OFF" : state == false ? "Turn ON" : "—"; + row.DefaultCellStyle.BackColor = state == true ? Color.FromArgb(40, 80, 40) : state == false ? Color.FromArgb(60, 40, 40) : Theme.TabBack; + } + } + + // ── Helpers ── + private static Button MakeButton(string text, Color borderColor) + { + var b = new Button + { + Text = text, AutoSize = true, AutoSizeMode = AutoSizeMode.GrowAndShrink, + MinimumSize = new Size(90, 28), Padding = new Padding(10, 2, 10, 2), + FlatStyle = FlatStyle.Flat, + ForeColor = Theme.Text, BackColor = Theme.TabBack, Font = Theme.UiFont, + Cursor = Cursors.Hand, Margin = new Padding(8, 0, 0, 0) + }; + b.FlatAppearance.BorderColor = borderColor; + b.FlatAppearance.MouseOverBackColor = Theme.Hover; + return b; + } +} diff --git a/src/ETTerms/ETTerms.csproj b/src/ETTerms/ETTerms.csproj index 78ac192..104b812 100644 --- a/src/ETTerms/ETTerms.csproj +++ b/src/ETTerms/ETTerms.csproj @@ -10,7 +10,7 @@ ETTerms - 0.3.1 + 0.3.2 ETTerms ETTerms Project diff --git a/src/ETTerms/Sessions/ShellChannel.cs b/src/ETTerms/Sessions/ShellChannel.cs index 90c4f58..5cc13fe 100644 --- a/src/ETTerms/Sessions/ShellChannel.cs +++ b/src/ETTerms/Sessions/ShellChannel.cs @@ -66,9 +66,12 @@ public sealed class ShellChannel : ISessionChannel UpdateProcThreadAttribute(si.lpAttributeList, 0, (IntPtr)0x00020016 /* PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE */, _ptyHandle, IntPtr.Size, IntPtr.Zero, IntPtr.Zero); - string workDir = string.IsNullOrWhiteSpace(_settings.StartupDirectory) - ? Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) - : _settings.StartupDirectory; + // 啟動目錄:若未設定或該目錄已不存在(例如外接碟拔除、資料夾被刪), + // 一律退回目前使用者的家目錄(C:\Users\),避免 CreateProcess 失敗 267 (ERROR_DIRECTORY)。 + string configured = _settings.StartupDirectory; + string workDir = (!string.IsNullOrWhiteSpace(configured) && Directory.Exists(configured)) + ? configured + : Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); bool ok = CreateProcess(null, $"{exe} {args}".TrimEnd(), IntPtr.Zero, IntPtr.Zero, false, 0x00080000 /* EXTENDED_STARTUPINFO_PRESENT */, IntPtr.Zero, workDir, ref si, out var pi);