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.
This commit is contained in:
2026-06-11 09:03:32 +08:00
parent 9addc5f2d9
commit 1263514586
11 changed files with 330 additions and 112 deletions
+7
View File
@@ -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.",
+2 -1
View File
@@ -10,7 +10,7 @@ namespace ETTerms.App;
/// </summary>
public sealed class ActivityRail : UserControl
{
public enum RailView { Terminal, Settings, About }
public enum RailView { Terminal, Status, Settings, About }
public event EventHandler<RailView>? 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"),
};
+4
View File
@@ -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}");
+1 -103
View File
@@ -1,11 +1,10 @@
using System.Drawing;
using System.Windows.Forms;
using ETTerms.Infrastructure;
using ETTerms.Scripting.Pdu;
namespace ETTerms.App;
/// <summary>Settings page with tabs: Terminal / PDU / AI MCP.</summary>
/// <summary>Settings page with tabs: Terminal / AI MCP.</summary>
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()
{
+288
View File
@@ -0,0 +1,288 @@
using System.Drawing;
using System.Windows.Forms;
using ETTerms.Scripting.Pdu;
namespace ETTerms.App;
/// <summary>
/// Status page with tabs: PDU (more views to come).
/// 風格參考 <see cref="SettingsView"/>:自繪 tab strip + panel 切換,避免 TabControl 白邊。
/// PDU 分頁連線後每 3 秒於背景自動輪詢插座狀態(不需手動 Refresh)。
/// </summary>
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<Panel>();
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;
}
}
+1 -1
View File
@@ -10,7 +10,7 @@
<AssemblyName>ETTerms</AssemblyName>
<!-- 版本資訊 -->
<Version>0.3.1</Version>
<Version>0.3.2</Version>
<Product>ETTerms</Product>
<Company>ETTerms Project</Company>
+6 -3
View File
@@ -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\<user>),避免 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);