diff --git a/docs/engineering/a11y-safety.md b/docs/engineering/a11y-safety.md index 93d0b3ad..8e1e5946 100644 --- a/docs/engineering/a11y-safety.md +++ b/docs/engineering/a11y-safety.md @@ -22,22 +22,25 @@ - 鍵盤焦點:強烈靜態視覺回饋 (反轉、字體加粗)。 - 按壓狀態:獨立於焦點的第三層級。深色模式使用飽和暖色 (琥珀色 `255,200,120`),亮度差 **ΔL*≥13**。 - **Tritanopia 調整亮度公式**:$L_{tritan} = (R_{lin} \times 0.2126 + G_{lin} \times 0.7152) / 0.9278$。 - - **Dwell 與 Latest 交接**:共用眼動儀回饋按鈕使用 "FeedbackButton";回饋結束先還原 Color.Empty,再清除該按鈕的原生背景動畫快取,讓背景、文字與提示框於同一幀還原。不得為此切換 VisualStylesMode、重建 HWND 或改變版面。 - - 視窗未啟用時仍須保持懸停文字與背景成對,不以略過自訂回饋後交回原生懸停取代;這不應啟用視窗或移動焦點。 - - Dwell 更新在 UI 寫入前再次檢查動畫識別碼,避免過期更新重啟已結束的視覺。測試須涵蓋三種主題、啟用/未啟用視窗、預設/一般按鈕的整段過渡取樣,不能只檢查最後一幀。 + - **Standard/Latest 與必要疊層**:共用回饋使用 `FeedbackButton`,一般、懸停及停用沿用原生 Standard 表面;不得將系統強調色假設為藍色,不以固定黑/白文字取代原生選色。 + - 焦點反轉、粗體、按壓及提示框使用必要疊層,不寫入按鈕 BackColor/ForeColor,不切換 VisualStylesMode、不重建 HWND。保留 System 色彩模式、Deferred 顯示與必要重啟提示。 + - 高對比焦點使用 Highlight/HighlightText;按壓交換此系統色對並加入固定位置的內框。兩狀態的文字與內框都須通過實際相鄰像素對比,不只依賴色相區分。 + - 視窗未啟用時仍提供成對原生懸停與提示,不啟用視窗或移動焦點。滑鼠與 Space 按壓獨立管理;MouseLeave/Capture 取消只清除滑鼠來源,失焦或停用清除所有按壓。 + - Dwell 使用控制項自己的 UI Timer。更新字型、DPI、語系或系統色只更新設定與繪圖,不重建互動狀態/重啟進度;取消、表單權杖結束、HandleDestroyed 與 Dispose 終止計時。進度不作為懸停狀態的替代旗標。權杖取消必須有獨立 UI 通知,滿格停止 Timer 或停用 UI 特效時也須清除提示;更換權杖及 Dispose 時解除舊註冊,已排程的舊通知不可影響新生命週期。 + - 點擊後接合不得覆蓋更新的互動或明確取消,也不得自動產生點擊。測試涵蓋三主題、啟用/未啟用視窗、預設/一般按鈕、完整過渡與滑鼠/鍵盤交錯。 - **預設動作引導**:當焦點在輸入框時,`AcceptButton` 必須顯示與焦點框一致的情境感知邊框色;強視覺反轉情境使用 **Cyan / MediumBlue**,中性情境使用 **LightBlue / MediumBlue**。 - 輸入框與預設動作提示須共用情境選色,並在輸入框底色/焦點變更時重繪。Latest 的強調色按鈕不得使提示對比下降;可在提示邊框緊鄰處繪製對比襯底,保留按鈕本體與原生主題外觀,不得改變尺寸、Margin 或 Padding。 - 測試須量測實際渲染的邊框與相鄰背景,不得只比對顏色名稱;同時覆蓋反轉及中性情境、三種主題與進度條主填色的對比。文件中對比數值為四捨五入顯示,不取代未取整的最低門檻。 - **眼動儀優化與視覺穩定性**: - **視覺凍結 (Zero-Jitter)**:狀態變更嚴禁變動物理尺寸、Margin 或 Padding。 - - **抗抖動鎖定 (Anti-Jitter Lock)**:初始化時預先計算 **Bold** 狀態最大寬度並鎖定為 `MinimumSize`。 - - **懸停進度條對比 (WCAG 1.4.11)**:填色須以按鈕「**實際**底色」為基準,使用 `btn.BackColor.GetBrightness() > 0.5f`(`Color.Empty` 時退回至 `!isDark`)動態選色,**禁止**直接使用 `isDark` 旗標(懸停時 `ApplyStrongVisual` 會反轉底色,`isDark` 與實際底色脫節): - - 底色為淺色(亮度 > 0.5,含懸停反轉後的 White)→ **Green** + CVD 紋理 PaleGreen。 - - 底色為深色(亮度 ≤ 0.5,含懸停反轉後的 Black)→ **LimeGreen** + CVD 紋理 DarkGreen。 - - 自然狀態對比:淺色模式 Green vs `#DCDCDC` = 3.75:1 ✅;深色模式 LimeGreen vs `#3C3C3C` = 5.21:1 ✅。 - - 懸停反轉對比:深色模式 bg→White,Green vs White = 5.14:1 ✅;淺色模式 bg→Black,LimeGreen vs Black = 9.91:1 ✅。 + - **抗抖動鎖定 (Anti-Jitter Lock)**:初始化時預先計算 **Bold** 狀態最大寬度並鎖定為 `MinimumSize`。AutoSize 的偏好高度須依 Bold 文字及 DPI 預留原生置中文字上下的固定空間,確保完整 Dwell 襯底與字形不重疊;不得等懸停才擴高或改 Padding。 + - **懸停進度條對比 (WCAG 1.4.11)**:以實際相鄰的可見襯底為基準,不以原生按鈕 BackColor 屬性推測已渲染的強調色。填滿至 100% 時襯底仍須在四邊可見(至少 1 個實體像素,依 DPI 縮放)。 + - 淺色使用 #DCDCDC 襯底、Green 主填色、PaleGreen 色覺紋理,主填色對比約 3.75:1。 + - 深色使用 #3C3C3C 襯底、LimeGreen 主填色、DarkGreen 色覺紋理,主填色對比約 5.21:1。 + - 高對比使用 Highlight 襯底與 HighlightText 填色,不硬編碼替代系統色。 + - 主填色對襯底須 ≥3:1;紋理不能取代主填色門檻,亦不把裝飾混色像素誤當成主填色。襯底與進度皆在固定範圍內繪製,不變動控制項尺寸、Margin 或 Padding。 - **色覺友善 (CVD) 與亮度計算**: - - **情境感知焦點邊框色**:依 `BackColor` 實際值與主題動態選取(完整 4 情境): + - **情境感知焦點邊框色**:依目前視覺表面/輸入情境與主題動態選取(完整 4 情境): - `BackColor == Black`(淺色反轉,強視覺)→ `Cyan` (16.75:1 AAA) - `BackColor == White`(深色反轉,強視覺)→ `MediumBlue` (11.16:1 AAA) - 深色中性(未反轉,深色主題)→ `LightBlue` (≥7.2:1 AAA) diff --git a/src/InputBox/Core/Controls/FeedbackButton.cs b/src/InputBox/Core/Controls/FeedbackButton.cs index 64333378..d92841be 100644 --- a/src/InputBox/Core/Controls/FeedbackButton.cs +++ b/src/InputBox/Core/Controls/FeedbackButton.cs @@ -1,8 +1,406 @@ -namespace InputBox.Core.Controls; +using InputBox.Core.Configuration; +using InputBox.Core.Extensions; +using InputBox.Resources; +using System.Drawing.Drawing2D; -/// 保留原生 Latest 外觀,並提供自訂回饋結束時的原生色彩快取重設。 +namespace InputBox.Core.Controls; + +/// 原生 Standard/Latest 表面與專案必要的焦點、按壓及凝視提示。 public class FeedbackButton : Button { - /// 透過 WinForms 既有主題刷新路徑終止舊色動畫,不改變樣式、HWND 或版面。 - internal void ResetNativeColorTransition() => base.OnSystemColorsChanged(EventArgs.Empty); -} \ No newline at end of file + private readonly System.Windows.Forms.Timer _timer = new() { Interval = (int)Math.Round(AppSettings.TargetFrameTimeMs) }; + private bool _hovered; + private bool _pointerPressed; + private bool _keyboardPressed; + private long _started; + private float _progress; + private Font? _regular; + private Font? _bold; + private bool _configured; + private string _description = string.Empty; + private Action? _onFocusStateChanged; + private CancellationToken _formToken; + private CancellationTokenRegistration _formRegistration; + private int _lifetimeVersion; + private int _interactionVersion; + + public FeedbackButton() + { + FlatStyle = FlatStyle.Standard; + SetStyle(ControlStyles.OptimizedDoubleBuffer, true); + _timer.Tick += (_, _) => + { + if (!_hovered || Pressed || !Enabled || IsDisposed || !IsHandleCreated || _formToken.IsCancellationRequested) + { + StopDwell(); + return; + } + _progress = Math.Min(1, (Environment.TickCount64 - _started) / 1000f); + Invalidate(); + if (_progress >= 1) + { + _timer.Stop(); + } + }; + } + + /// 目前的按壓視覺,滑鼠與鍵盤來源分開清理。 + internal bool Pressed => _pointerPressed || _keyboardPressed; + /// 供畫面回歸驗證讀取,不以進度推導互動狀態。 + internal float Progress => _progress; + + /// 初始化或更新字型/在地化設定,不重新建立互動狀態或動畫。 + internal void ConfigureFeedback(string description, Font? regular, Font? bold, + Action? onFocusStateChanged, CancellationToken formToken) + { + _regular = regular ?? Font; + _bold = bold; + _description = description; + _onFocusStateChanged = onFocusStateChanged; + FlatStyle = FlatStyle.Standard; + bool replaceLifetime = !_configured || _formToken != formToken; + _configured = true; + if (replaceLifetime) + { + int version = ++_lifetimeVersion; + _formRegistration.Dispose(); + _formToken = formToken; + _formRegistration = formToken.Register(() => + { + if (IsDisposed || Disposing || !IsHandleCreated) { return; } + this.SafeBeginInvoke(() => + { + if (_configured && version == _lifetimeVersion && _formToken.IsCancellationRequested) + { + CancelDwell(); + } + }); + }); + } + Reconcile(); + } + + /// 初始化版面時在置中文字上下保留固定空間,讓底部 Dwell 不遮住字形。 + public override Size GetPreferredSize(Size proposedSize) + { + Size preferred = base.GetPreferredSize(proposedSize); + Font measuringFont = _bold ?? _regular ?? Font; + Size text = TextRenderer.MeasureText(Text, measuringFont); + float scale = DeviceDpi / AppSettings.BaseDpi; + int dwellSpace = (int)Math.Ceiling(7 * scale) + (int)Math.Ceiling(6 * scale) + + 2 * (int)Math.Max(1, Math.Ceiling(scale)) + (int)Math.Ceiling(2 * scale); + return new Size(Math.Max(preferred.Width, text.Width + Padding.Horizontal + (int)Math.Ceiling(8 * scale)), + Math.Max(preferred.Height, text.Height + Padding.Vertical + 2 * dwellSpace)); + } + /// 更新呼叫端提供的共享字型,保留描述、回呼與正在進行的互動。 + internal void UpdateFeedbackFonts(Font regular, Font? bold) + { + _regular = regular; + _bold = bold; + Reconcile(); + } + internal void CancelDwell() + { + ++_interactionVersion; + StopDwell(); + Reconcile(); + } + + /// 點擊結束後依實際游標重接視線;新的互動會使舊接合失效。 + internal async Task ReGazeAfterClickAsync() + { + int version = ++_interactionVersion; + StopDwell(); + Invalidate(); + await Task.Yield(); + if (IsDisposed || !Enabled || _formToken.IsCancellationRequested || version != _interactionVersion) + { + return; + } + _hovered = ClientRectangle.Contains(PointToClient(Cursor.Position)); + RestartDwell(); + Reconcile(); + } + private void RestartDwell() + { + StopDwell(); + if (!_configured || !_hovered || Pressed || !Enabled || _formToken.IsCancellationRequested) + { + return; + } + _started = Environment.TickCount64; + if (SystemInformation.UIEffectsEnabled) + { + _timer.Start(); + } + else + { + _progress = 1; + } + } + + private void StopDwell() + { + _timer.Stop(); + bool visibleProgress = _progress > 0; + _progress = 0; + if (visibleProgress && IsHandleCreated && !IsDisposed && !Disposing) { Invalidate(); } + } + + private void Reconcile() + { + if (!_configured || IsDisposed || Disposing) { return; } + Font? desired = Pressed || (Focused && !_hovered) ? _bold : _regular; + if (desired is not null && !ReferenceEquals(Font, desired)) + { + Font = desired; + } + AccessibleDescription = !Enabled ? _description : Pressed ? + $"{_description} ({Strings.A11y_State_Pressed})" : _hovered ? + $"{_description} ({Strings.A11y_State_Hover})" : Focused ? + $"{_description} ({Strings.A11y_State_Focused})" : _description; + Invalidate(); + } + + protected override void OnMouseEnter(EventArgs e) + { + ++_interactionVersion; + _hovered = true; + RestartDwell(); + Reconcile(); + _onFocusStateChanged?.Invoke(true); + base.OnMouseEnter(e); + } + + protected override void OnMouseLeave(EventArgs e) + { + ++_interactionVersion; + _hovered = false; + _pointerPressed = false; + StopDwell(); + Reconcile(); + _onFocusStateChanged?.Invoke(Focused); + base.OnMouseLeave(e); + } + + protected override void OnMouseDown(MouseEventArgs e) + { + ++_interactionVersion; + if (Enabled && e.Button == MouseButtons.Left) + { + _pointerPressed = true; + StopDwell(); + Reconcile(); + } + base.OnMouseDown(e); + } + + protected override void OnMouseUp(MouseEventArgs e) + { + ++_interactionVersion; + if (e.Button == MouseButtons.Left) + { + _pointerPressed = false; + RestartDwell(); + Reconcile(); + } + base.OnMouseUp(e); + } + + protected override void OnKeyDown(KeyEventArgs e) + { + ++_interactionVersion; + if (Enabled && Focused && e.KeyCode == Keys.Space) + { + _keyboardPressed = true; + StopDwell(); + Reconcile(); + } + base.OnKeyDown(e); + } + + protected override void OnKeyUp(KeyEventArgs e) + { + ++_interactionVersion; + if (e.KeyCode == Keys.Space) + { + _keyboardPressed = false; + RestartDwell(); + Reconcile(); + } + base.OnKeyUp(e); + } + + protected override void OnGotFocus(EventArgs e) + { + ++_interactionVersion; + Reconcile(); + _onFocusStateChanged?.Invoke(true); + base.OnGotFocus(e); + } + + protected override void OnLostFocus(EventArgs e) + { + ++_interactionVersion; + _pointerPressed = false; + _keyboardPressed = false; + RestartDwell(); + Reconcile(); + _onFocusStateChanged?.Invoke(_hovered); + base.OnLostFocus(e); + } + + protected override void OnMouseCaptureChanged(EventArgs e) + { + if (!Capture && _pointerPressed) + { + ++_interactionVersion; + _pointerPressed = false; + RestartDwell(); + Reconcile(); + } + base.OnMouseCaptureChanged(e); + } + + protected override void OnEnabledChanged(EventArgs e) + { + ++_interactionVersion; + if (!Enabled) + { + _hovered = false; + _pointerPressed = false; + _keyboardPressed = false; + StopDwell(); + } + Reconcile(); + base.OnEnabledChanged(e); + } + + protected override void OnSystemColorsChanged(EventArgs e) + { + base.OnSystemColorsChanged(e); + Invalidate(); + } + + protected override void OnHandleDestroyed(EventArgs e) + { + ++_interactionVersion; + StopDwell(); + _hovered = false; + _pointerPressed = false; + _keyboardPressed = false; + base.OnHandleDestroyed(e); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + _configured = false; + ++_lifetimeVersion; + _formRegistration.Dispose(); + StopDwell(); + _regular = null; + _bold = null; + _onFocusStateChanged = null; + } + try + { + base.Dispose(disposing); + } + finally + { + if (disposing) { _timer.Dispose(); } + } + } + protected override void OnPaint(PaintEventArgs e) + { + if (Width <= 0 || Height <= 0) + { + return; + } + base.OnPaint(e); + if (!_configured) { return; } + Graphics graphics = e.Graphics; + bool dark = this.IsDarkModeActive(); + bool highContrast = SystemInformation.HighContrast; + bool strong = Enabled && (Pressed || (Focused && !_hovered)); + bool isDefault = Enabled && FindForm() is Form form && + ReferenceEquals(form.AcceptButton, this) && form.ActiveControl is not Button; + float scale = DeviceDpi / AppSettings.BaseDpi; + Color back = Color.Empty; + Color fore = ForeColor; + if (strong) + { + (back, fore) = highContrast + ? Pressed ? (SystemColors.HighlightText, SystemColors.Highlight) : (SystemColors.Highlight, SystemColors.HighlightText) + : Pressed ? (dark ? Color.FromArgb(255, 200, 120) : Color.FromArgb(28, 28, 28), dark ? Color.Black : Color.White) + : dark ? (Color.White, Color.Black) : (Color.Black, Color.White); + using Brush surface = new SolidBrush(back); + graphics.FillRectangle(surface, ClientRectangle); + int inset = (int)Math.Ceiling(4 * scale); + TextFormatFlags flags = TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | + TextFormatFlags.WordBreak | TextFormatFlags.PreserveGraphicsClipping; + if (!UseMnemonic) + { + flags |= TextFormatFlags.NoPrefix; + } + if (RightToLeft == RightToLeft.Yes) + { + flags |= TextFormatFlags.RightToLeft; + } + if (!ShowKeyboardCues) { flags |= TextFormatFlags.HidePrefix; } + Rectangle textBounds = Rectangle.FromLTRB(inset + Padding.Left, inset + Padding.Top, + Width - inset - Padding.Right, Height - inset - Padding.Bottom); + TextRenderer.DrawText(graphics, Text, Font, textBounds, fore, flags); + } + + if (Enabled && (strong || _hovered || isDefault)) + { + (Color border, Color backing) = strong + ? highContrast ? (fore, back) : (dark ? Color.MediumBlue : Color.Cyan, back) + : ControlExtensions.GetContextualFocusColors(isDefault ? GetInputContext()?.BackColor ?? Color.Empty : Color.Empty, dark); + this.DrawButtonInteractiveBorder(graphics, border, scale, out int inset, out int thickness, backing); + if (Pressed) + { + // 高對比也保留固定位置的內框,提供不只依賴色彩的按壓線索。 + int inner = inset + thickness + (int)Math.Ceiling(scale); + using Pen line = new(fore, Math.Max(1, 2 * scale)); + graphics.DrawRectangle(line, inner, inner, Width - 2 * inner - 1, Height - 2 * inner - 1); + } + } + + if (Enabled && _hovered && !Pressed && _progress > 0) + { + int inset = (int)Math.Ceiling(7 * scale); + int backing = (int)Math.Max(1, Math.Ceiling(scale)); + int height = (int)Math.Ceiling(6 * scale) + 2 * backing; + Rectangle track = new(inset, Height - inset - height, Width - 2 * inset, height); + Color trackColor = highContrast ? SystemColors.Highlight : dark ? Color.FromArgb(60, 60, 60) : Color.FromArgb(220, 220, 220); + Color fillColor = highContrast ? SystemColors.HighlightText : dark ? Color.LimeGreen : Color.Green; + using Brush trackBrush = new SolidBrush(trackColor); + using Brush fillBrush = new SolidBrush(fillColor); + graphics.FillRectangle(trackBrush, track); + Rectangle fill = Rectangle.Inflate(track, -backing, -backing); + fill.Width = (int)(fill.Width * _progress); + graphics.FillRectangle(fillBrush, fill); + if (!highContrast) + { + using HatchBrush texture = new(HatchStyle.BackwardDiagonal, dark ? Color.DarkGreen : Color.PaleGreen, Color.Transparent); + graphics.FillRectangle(texture, fill); + } + } + + } + + /// 沿巢狀容器尋找實際輸入焦點,與輸入框提示共用情境選色。 + private Control? GetInputContext() + { + Control? context = FindForm()?.ActiveControl; + while (context is ContainerControl { ActiveControl: not null } container) + { + context = container.ActiveControl; + } + return context; + } +} diff --git a/src/InputBox/Core/Controls/GamepadCalibrationDialog.Layout.cs b/src/InputBox/Core/Controls/GamepadCalibrationDialog.Layout.cs index c9068990..de46acfd 100644 --- a/src/InputBox/Core/Controls/GamepadCalibrationDialog.Layout.cs +++ b/src/InputBox/Core/Controls/GamepadCalibrationDialog.Layout.cs @@ -70,9 +70,9 @@ protected override void OnDpiChanged(DpiChangedEventArgs e) _lblStatus?.Font = _a11yFont; - _btnReset?.Font = _a11yFont; + _btnReset?.UpdateEyeTrackerFonts(_a11yFont, MainForm.GetSharedA11yFont(DeviceDpi, FontStyle.Bold, _a11yFont.FontFamily)); - _btnClose?.Font = _a11yFont; + _btnClose?.UpdateEyeTrackerFonts(_a11yFont, MainForm.GetSharedA11yFont(DeviceDpi, FontStyle.Bold, _a11yFont.FontFamily)); } UpdateMinimumSize(forceRecalculate: true); diff --git a/src/InputBox/Core/Controls/GamepadCalibrationDialog.cs b/src/InputBox/Core/Controls/GamepadCalibrationDialog.cs index 20fb41c6..cd7112fa 100644 --- a/src/InputBox/Core/Controls/GamepadCalibrationDialog.cs +++ b/src/InputBox/Core/Controls/GamepadCalibrationDialog.cs @@ -393,7 +393,7 @@ private Button CreateEyeTrackerButton(string text, string accessibleName, string AutoSize = true, MinimumSize = new Size(Math.Max((int)(120 * scale), boldTextSize.Width + (int)(32 * scale)), Math.Max((int)(56 * scale), boldTextSize.Height + (int)(20 * scale))), Margin = new Padding((int)(8 * scale), (int)(6 * scale), (int)(8 * scale), (int)(4 * scale)), - FlatStyle = FlatStyle.Flat, + FlatStyle = FlatStyle.Standard, BackColor = Color.Empty, ForeColor = Color.Empty }; diff --git a/src/InputBox/Core/Controls/GamepadMessageBox.cs b/src/InputBox/Core/Controls/GamepadMessageBox.cs index 01ab3a01..1827c42c 100644 --- a/src/InputBox/Core/Controls/GamepadMessageBox.cs +++ b/src/InputBox/Core/Controls/GamepadMessageBox.cs @@ -429,7 +429,7 @@ private Button CreateEyeTrackerButton(string label) AccessibleRole = AccessibleRole.PushButton, Font = font, AutoSize = true, - FlatStyle = FlatStyle.Flat, + FlatStyle = FlatStyle.Standard, BackColor = Color.Empty, ForeColor = Color.Empty, }; @@ -785,7 +785,7 @@ private void ApplyFont() continue; } - btn.Font = shared; + btn.UpdateEyeTrackerFonts(shared, boldFont); DialogLayoutHelper.UpdateButtonMinimumSize(btn, boldFont, scale, 88, 0, 24, 8); } diff --git a/src/InputBox/Core/Controls/HelpDialog.cs b/src/InputBox/Core/Controls/HelpDialog.cs index da85c6ff..c97ccdc2 100644 --- a/src/InputBox/Core/Controls/HelpDialog.cs +++ b/src/InputBox/Core/Controls/HelpDialog.cs @@ -175,7 +175,7 @@ public HelpDialog() AutoSize = true, Anchor = AnchorStyles.Right, Margin = Padding.Empty, // 移除預設外距避免被底部面板裁切 - FlatStyle = FlatStyle.Flat, + FlatStyle = FlatStyle.Standard, AccessibleName = Strings.Help_Btn_Close, AccessibleRole = AccessibleRole.PushButton, DialogResult = DialogResult.Cancel, diff --git a/src/InputBox/Core/Controls/NumericInputDialog.Layout.cs b/src/InputBox/Core/Controls/NumericInputDialog.Layout.cs index 546e57fd..64c0f946 100644 --- a/src/InputBox/Core/Controls/NumericInputDialog.Layout.cs +++ b/src/InputBox/Core/Controls/NumericInputDialog.Layout.cs @@ -89,11 +89,11 @@ protected override void OnDpiChanged(DpiChangedEventArgs e) // 同步更新所有按鈕的基礎字體。 if (_a11yFont != null) { - _btnOk!.Font = _a11yFont; - _btnCancel!.Font = _a11yFont; - _btnPlus!.Font = _a11yFont; - _btnMinus!.Font = _a11yFont; - _btnReset!.Font = _a11yFont; + _btnOk!.UpdateEyeTrackerFonts(_a11yFont, MainForm.GetSharedA11yFont(DeviceDpi, FontStyle.Bold, _a11yFont.FontFamily)); + _btnCancel!.UpdateEyeTrackerFonts(_a11yFont, MainForm.GetSharedA11yFont(DeviceDpi, FontStyle.Bold, _a11yFont.FontFamily)); + _btnPlus!.UpdateEyeTrackerFonts(_a11yFont, MainForm.GetSharedA11yFont(DeviceDpi, FontStyle.Bold, _a11yFont.FontFamily)); + _btnMinus!.UpdateEyeTrackerFonts(_a11yFont, MainForm.GetSharedA11yFont(DeviceDpi, FontStyle.Bold, _a11yFont.FontFamily)); + _btnReset!.UpdateEyeTrackerFonts(_a11yFont, MainForm.GetSharedA11yFont(DeviceDpi, FontStyle.Bold, _a11yFont.FontFamily)); } // 數值顯示區字體需重新依據新縮放比例建立。 diff --git a/src/InputBox/Core/Controls/NumericInputDialog.cs b/src/InputBox/Core/Controls/NumericInputDialog.cs index 166dd77f..28921328 100644 --- a/src/InputBox/Core/Controls/NumericInputDialog.cs +++ b/src/InputBox/Core/Controls/NumericInputDialog.cs @@ -916,7 +916,7 @@ private Button CreateEyeTrackerButton( AutoSize = true, MinimumSize = new Size(baseMinWidth, baseMinHeight), Margin = new Padding((int)(12 * scale)), - FlatStyle = FlatStyle.Flat, + FlatStyle = FlatStyle.Standard, BackColor = Color.Empty, ForeColor = Color.Empty }; diff --git a/src/InputBox/Core/Controls/PhraseEditDialog.cs b/src/InputBox/Core/Controls/PhraseEditDialog.cs index 4b6ba881..1d724d27 100644 --- a/src/InputBox/Core/Controls/PhraseEditDialog.cs +++ b/src/InputBox/Core/Controls/PhraseEditDialog.cs @@ -338,7 +338,7 @@ public PhraseEditDialog(string name, string content, Font? a11yFont) { Text = profile.FormatCancelButtonText(Strings.Phrase_Btn_Cancel), AutoSize = true, - FlatStyle = FlatStyle.Flat, + FlatStyle = FlatStyle.Standard, DialogResult = DialogResult.Cancel, BackColor = Color.Empty, ForeColor = Color.Empty, @@ -354,7 +354,7 @@ public PhraseEditDialog(string name, string content, Font? a11yFont) { Text = profile.FormatConfirmButtonText(Strings.Phrase_Btn_Confirm), AutoSize = true, - FlatStyle = FlatStyle.Flat, + FlatStyle = FlatStyle.Standard, // 重要:確認按鈕不可直接回傳 OK,必須先經過 HandleConfirm 驗證。 DialogResult = DialogResult.None, BackColor = Color.Empty, diff --git a/src/InputBox/Core/Controls/PhraseManagerDialog.Layout.cs b/src/InputBox/Core/Controls/PhraseManagerDialog.Layout.cs index fb4bde54..2df74e61 100644 --- a/src/InputBox/Core/Controls/PhraseManagerDialog.Layout.cs +++ b/src/InputBox/Core/Controls/PhraseManagerDialog.Layout.cs @@ -127,7 +127,7 @@ private static Button CreateActionButton( { Text = ControlExtensions.GetMnemonicText(text, mnemonic), AutoSize = true, - FlatStyle = FlatStyle.Flat, + FlatStyle = FlatStyle.Standard, AccessibleName = text, AccessibleDescription = a11yDesc, AccessibleRole = AccessibleRole.PushButton, diff --git a/src/InputBox/Core/Controls/PhraseManagerDialog.cs b/src/InputBox/Core/Controls/PhraseManagerDialog.cs index 5126f728..ba0fe58f 100644 --- a/src/InputBox/Core/Controls/PhraseManagerDialog.cs +++ b/src/InputBox/Core/Controls/PhraseManagerDialog.cs @@ -361,7 +361,7 @@ public PhraseManagerDialog(PhraseService phraseService) Text = profile.FormatCancelButtonText(Strings.Phrase_Btn_Close), AutoSize = true, Anchor = AnchorStyles.Right, - FlatStyle = FlatStyle.Flat, + FlatStyle = FlatStyle.Standard, AccessibleName = Strings.Phrase_Btn_Close, AccessibleDescription = Strings.Phrase_A11y_Btn_Close_Desc, AccessibleRole = AccessibleRole.PushButton, diff --git a/src/InputBox/Core/Extensions/ButtonEyeTrackerExtensions.cs b/src/InputBox/Core/Extensions/ButtonEyeTrackerExtensions.cs index 8d7470b4..a2e33e98 100644 --- a/src/InputBox/Core/Extensions/ButtonEyeTrackerExtensions.cs +++ b/src/InputBox/Core/Extensions/ButtonEyeTrackerExtensions.cs @@ -1,749 +1,27 @@ -using InputBox.Core.Configuration; -using InputBox.Core.Controls; -using InputBox.Resources; -using System.Diagnostics; -using System.Drawing.Drawing2D; -using System.Runtime.CompilerServices; +using InputBox.Core.Controls; namespace InputBox.Core.Extensions; -/// -/// 按鈕眼動儀回饋擴充方法, -/// 統一收斂對話框的 A11y Boilerplate -/// +/// 將現有表單的回饋設定與點擊接合呼叫導向共用按鈕,不維護第二份狀態。 public static class ButtonEyeTrackerExtensions { - /// - /// 按鈕視覺狀態封裝類別, - /// 包含當前是否懸停、按壓、凝視進度,以及相關的字型與描述資訊 - /// - private sealed class ButtonVisualState + /// 更新共用按鈕的描述、共享字型與表單生命週期;不重建正在進行的互動。 + public static void AttachEyeTrackerFeedback(this Button btn, string baseDescription, + Font? regularFont, Font? boldFont, CancellationToken formCt, Action? onFocusStateChanged = null) { - /// - /// 是否懸停在按鈕上 - /// - public bool IsHovered { get; set; } - - /// - /// 是否按壓按鈕(包含實際的鼠標按壓或鍵盤焦點狀態下的強視覺反饋) - /// - public bool IsPressed => IsPointerPressed || IsKeyboardPressed; - - /// 滑鼠按壓狀態,與鍵盤狀態獨立清理。 - public bool IsPointerPressed { get; set; } - - /// Space 按壓狀態,失焦時必須清理。 - public bool IsKeyboardPressed { get; set; } - - /// - /// 凝視進度(Dwell Progress),表示使用者注視按鈕的時間比例 - /// - public float DwellProgress { get; set; } - - /// - /// 動畫識別碼,用於取消過時的動畫回饋,確保視覺狀態與當前互動一致 - /// - public long AnimId; - - /// 重設原生色彩快取期間避免系統色事件重入。 - public bool IsResettingNativeColors { get; set; } - - /// - /// 基礎無障礙描述,供不同互動狀態下的 AccessibleDescription 組合使用 - /// - public string BaseDescription { get; set; } = string.Empty; - - /// - /// 按鈕預設狀態下的字型(傳入 null 則 fallback 為按鈕現有字型) - /// - public Font? RegularFont { get; set; } - - /// - /// 粗體字型,用於按鈕取得焦點或按壓時的強調視覺(傳入 null 則維持 RegularFont),建議外部預先建立好 Font 實例以避免頻繁產生造成效能問題 - /// - public Font? BoldFont { get; set; } - - /// - /// 當按鈕焦點狀態或懸停狀態改變時觸發的回呼,供外部連動處理(例如提示標籤顯示) - /// - public Action? OnFocusStateChanged { get; set; } - - /// - /// 綁定 UI 表單生命週期的 CancellationToken,用於安全終止按鈕內部非同步動畫 - /// - public CancellationToken FormCt { get; set; } - - /// - /// 按鈕的原始內邊距,用於在視覺狀態改變時恢復原始佈局 - /// - public Padding OriginalPadding { get; set; } - } - - /// - /// 按鈕與其視覺狀態的映射表, - /// 用於管理按鈕的眼動儀回饋與無障礙狀態 - /// - private static readonly ConditionalWeakTable _buttonStates = []; - - /// - /// 為按鈕綁定眼動儀與無障礙完整事件(包含 Paint、Focus、Hover、Pressed 與 Dwell 凝視回饋) - /// - /// 要擴充的按鈕目標。 - /// 按鈕的基礎無障礙輔助描述(AccessibleDescription)。 - /// 按鈕預設狀態下的字型(傳入 null 則 fallback 為按鈕現有字型)。 - /// 按鈕取得焦點或按壓時的強調粗體字型。 - /// 綁定 UI 表單生命週期的 CancellationToken,用於安全終止按鈕內部非同步動畫。 - /// 當按鈕焦點狀態或懸停狀態改變時觸發的回呼,供外部連動處理(例如提示標籤顯示)。 - public static void AttachEyeTrackerFeedback( - this Button btn, - string baseDescription, - Font? regularFont, - Font? boldFont, - CancellationToken formCt, - Action? onFocusStateChanged = null) - { - ButtonVisualState state = new() - { - BaseDescription = baseDescription, - // 若未提供字型,則沿用按鈕目前的字型設定。 - RegularFont = regularFont ?? btn.Font, - BoldFont = boldFont, - FormCt = formCt, - OnFocusStateChanged = onFocusStateChanged, - OriginalPadding = btn.Padding - }; - _buttonStates.AddOrUpdate(btn, state); - - // 避免重複綁定。 - btn.Paint -= HandleButtonPaint; - btn.Paint += HandleButtonPaint; - - btn.GotFocus -= HandleButtonGotFocus; - btn.GotFocus += HandleButtonGotFocus; - - btn.LostFocus -= HandleButtonLostFocus; - btn.LostFocus += HandleButtonLostFocus; - - btn.MouseEnter -= HandleButtonMouseEnter; - btn.MouseEnter += HandleButtonMouseEnter; - - btn.MouseLeave -= HandleButtonMouseLeave; - btn.MouseLeave += HandleButtonMouseLeave; - - btn.MouseDown -= HandleButtonMouseDown; - btn.MouseDown += HandleButtonMouseDown; - - btn.MouseUp -= HandleButtonMouseUp; - btn.MouseUp += HandleButtonMouseUp; - - btn.KeyDown -= HandleButtonKeyDown; - btn.KeyDown += HandleButtonKeyDown; - btn.KeyUp -= HandleButtonKeyUp; - btn.KeyUp += HandleButtonKeyUp; - - btn.SystemColorsChanged -= HandleButtonSystemColorsChanged; - btn.SystemColorsChanged += HandleButtonSystemColorsChanged; - } - - /// Space 按住時套用獨立按下視覺,不攔截原生鍵盤點擊。 - private static void HandleButtonKeyDown(object? sender, KeyEventArgs eventArgs) - { - if (eventArgs.KeyCode == Keys.Space && sender is Button { Enabled: true, Focused: true } button && - _buttonStates.TryGetValue(button, out ButtonVisualState? state) && !state.IsKeyboardPressed) - { - state.IsKeyboardPressed = true; - StartAnimationFeedback(button); - } - } - - /// Space 放開後還原目前焦點或懸停狀態。 - private static void HandleButtonKeyUp(object? sender, KeyEventArgs eventArgs) - { - if (eventArgs.KeyCode == Keys.Space && sender is Button button && - _buttonStates.TryGetValue(button, out ButtonVisualState? state)) - { - state.IsKeyboardPressed = false; - StopFeedback(button); - } - } - /// - /// 系統色或高對比改變時重新套用目前互動狀態,避免保留上一個配色。 - /// 深淺色模式仍由框架的啟動設定決定,不取代既有重啟提示。 - /// - private static void HandleButtonSystemColorsChanged(object? sender, EventArgs eventArgs) - { - if (sender is Button { IsDisposed: false } button && - _buttonStates.TryGetValue(button, out ButtonVisualState? state) && !state.IsResettingNativeColors) - { - StopFeedback(button); - } - } - /// - /// 點擊後重置進度, - /// 並執行視線重新接合(Gaze Re-engagement), - /// 用於取代按鈕 Click 內部的手動清理 - /// - /// 發生點擊的按鈕目標。 - /// 表示非同步重置與接合操作的工作任務。 - public static async Task CompleteClickAndReGazeAsync(this Button btn) - { - if (!_buttonStates.TryGetValue(btn, out ButtonVisualState? state)) - { - return; - } - - Interlocked.Increment(ref state.AnimId); - - state.DwellProgress = 0f; - - btn.Invalidate(); - - await Task.Yield(); - - if (btn.IsDisposed || - !btn.Enabled) - { - return; - } - - Point cursorPos = btn.PointToClient(Cursor.Position); - - if (btn.ClientRectangle.Contains(cursorPos)) - { - state.IsHovered = true; - - StartAnimationFeedback(btn); - } - else - { - state.IsHovered = false; - - StopFeedback(btn); - } - } - - /// - /// 取消目前進行中的 Dwell 動畫且不啟動新動畫, - /// 用於在程式主動移焦時阻斷因 LostFocus 意外觸發的寄生動畫 - /// - /// 目標按鈕 - public static void CancelDwellAnimation(this Button btn) - { - if (!_buttonStates.TryGetValue(btn, out ButtonVisualState? state)) - { - return; - } - - Interlocked.Increment(ref state.AnimId); - - state.DwellProgress = 0f; - - btn.Invalidate(); - } - - /// - /// 取得鍵盤焦點時套用強視覺狀態, - /// 並觸發焦點狀態改變回呼以連動提示標籤等 UI 元件的更新 - /// - /// 事件觸發的按鈕。 - /// 事件參數。 - private static void HandleButtonGotFocus(object? sender, EventArgs eventArgs) - { - if (sender is Button btn) - { - if (_buttonStates.TryGetValue(btn, out ButtonVisualState? buttonState)) - { - buttonState.OnFocusStateChanged?.Invoke(true); - } - - // 如果同時處於懸停狀態,應維持懸停溫和視覺,不強制套用強烈視覺。 - if (_buttonStates.TryGetValue(btn, out ButtonVisualState? hoverState) && - hoverState.IsHovered) - { - StartAnimationFeedback(btn); - } - else - { - ApplyStrongVisual(btn); - } - } - } - - /// - /// 失去鍵盤焦點時重置強視覺狀態, - /// 並觸發焦點狀態改變回呼以連動提示標籤等 UI 元件的更新 - /// - /// 事件觸發的按鈕。 - /// 事件參數。 - private static void HandleButtonLostFocus(object? sender, EventArgs eventArgs) - { - if (sender is Button btn) - { - if (_buttonStates.TryGetValue(btn, out ButtonVisualState? state)) - { - state.IsPointerPressed = false; - state.IsKeyboardPressed = false; - state.OnFocusStateChanged?.Invoke(state.IsHovered); - } - - StopFeedback(btn); - } - } - - /// - /// 滑鼠進入按鈕區域時啟動懸停回饋, - /// 並透過焦點狀態回呼讓外部 UI 可同步更新提示或邊框狀態, - /// 提升眼動儀使用者的互動體驗。 - /// - /// 事件觸發的按鈕。 - /// 事件參數。 - private static void HandleButtonMouseEnter(object? sender, EventArgs eventArgs) - { - if (sender is Button btn) - { - if (_buttonStates.TryGetValue(btn, out ButtonVisualState? state)) - { - state.IsHovered = true; - state.OnFocusStateChanged?.Invoke(true); - } - - StartAnimationFeedback(btn); - } - } - - /// - /// 滑鼠離開按鈕區域時停止懸停回饋, - /// 並透過焦點狀態回呼讓外部 UI 邏輯可依目前焦點狀態還原提示, - /// 確保視覺反饋與使用者互動保持一致, - /// 避免誤導眼動儀使用者的視線追蹤與互動判斷。 - /// - /// 事件觸發的按鈕。 - /// 事件參數。 - private static void HandleButtonMouseLeave(object? sender, EventArgs eventArgs) - { - if (sender is Button btn) - { - if (_buttonStates.TryGetValue(btn, out ButtonVisualState? state)) - { - state.IsHovered = false; - state.IsPointerPressed = false; - state.IsKeyboardPressed = false; - state.OnFocusStateChanged?.Invoke(btn.Focused); - } - - StopFeedback(btn); - } - } - - /// - /// 滑鼠左鍵按下時套用按壓狀態。 - /// - /// 事件觸發的按鈕。 - /// 滑鼠事件參數。 - private static void HandleButtonMouseDown(object? sender, MouseEventArgs eventArgs) - { - if (sender is Button btn && - eventArgs.Button == MouseButtons.Left) - { - if (_buttonStates.TryGetValue(btn, out ButtonVisualState? state)) - { - state.IsPointerPressed = true; - } - - StartAnimationFeedback(btn); - } - } - - /// - /// 滑鼠左鍵放開時重置按壓狀態。 - /// - /// 事件觸發的按鈕。 - /// 滑鼠事件參數。 - private static void HandleButtonMouseUp(object? sender, MouseEventArgs eventArgs) - { - if (sender is Button btn && - eventArgs.Button == MouseButtons.Left) - { - if (_buttonStates.TryGetValue(btn, out ButtonVisualState? state)) - { - state.IsPointerPressed = false; - } - - StartAnimationFeedback(btn); - } - } - - /// - /// 套用按壓或取得鍵盤焦點時的強視覺狀態(包含背景色彩切換與強調字型) - /// - /// 目標按鈕 - private static void ApplyStrongVisual(Button btn) - { - if (!_buttonStates.TryGetValue(btn, out ButtonVisualState? st)) - { - return; - } - - Interlocked.Increment(ref st.AnimId); - - st.DwellProgress = 0f; - - if (SystemInformation.HighContrast) - { - btn.BackColor = SystemColors.Highlight; - btn.ForeColor = SystemColors.HighlightText; - } - else - { - bool isDark = btn.IsDarkModeActive(); - - if (st.IsPressed) - { - btn.BackColor = isDark ? - Color.FromArgb(255, 200, 120) : - Color.FromArgb(28, 28, 28); - btn.ForeColor = isDark ? - Color.Black : - Color.White; - } - else - { - btn.BackColor = isDark ? - Color.White : - Color.Black; - btn.ForeColor = isDark ? - Color.Black : - Color.White; - } - } - - Font? bold = st.BoldFont; - - if (bold != null && - !ReferenceEquals(btn.Font, bold)) - { - btn.Font = bold; - } - - btn.AccessibleDescription = st.IsPressed ? - $"{st.BaseDescription} ({Strings.A11y_State_Pressed})" : - $"{st.BaseDescription} ({Strings.A11y_State_Focused})"; - - btn.Invalidate(); - } - - /// - /// 啟動眼動儀特化的懸停或注視進度條(Dwell Animation)回饋機制 - /// - /// 目標按鈕 - private static void StartAnimationFeedback(Button btn) - { - if (btn.IsDisposed || - !btn.Enabled) - { - return; - } - - if (!_buttonStates.TryGetValue(btn, out ButtonVisualState? st)) - { - return; - } - - if (st.IsPressed || - (btn.Focused && !st.IsHovered)) - { - ApplyStrongVisual(btn); - - return; - } - - long currentId = Interlocked.Increment(ref st.AnimId); - - st.DwellProgress = 0f; - - if (SystemInformation.HighContrast) - { - btn.BackColor = SystemColors.Highlight; - btn.ForeColor = SystemColors.HighlightText; - } - else - { - bool isDark = btn.IsDarkModeActive(); - - btn.BackColor = isDark ? - Color.FromArgb(60, 60, 60) : - Color.FromArgb(220, 220, 220); - btn.ForeColor = isDark ? - Color.White : - Color.Black; - } - - Font? regular = st.RegularFont; - - if (regular != null && - !ReferenceEquals(btn.Font, regular)) - { - btn.Font = regular; - } - - btn.AccessibleDescription = $"{st.BaseDescription} ({Strings.A11y_State_Hover})"; - - btn.Invalidate(); - - btn.RunDwellAnimationAsync( - id: currentId, - animationIdGetter: () => Interlocked.Read(ref st.AnimId), - progressSetter: p => - { - if (Interlocked.Read(ref st.AnimId) == currentId) - { - st.DwellProgress = p; - } - }, - durationMs: 1000, - ct: st.FormCt - ).SafeFireAndForget(); - } - - /// - /// 停止進度條回饋並恢復原本按鈕預設外觀或焦點狀態的外觀 - /// - /// 目標按鈕 - private static void StopFeedback(Button btn) - { - if (!_buttonStates.TryGetValue(btn, out ButtonVisualState? st)) - { - return; - } - - Interlocked.Increment(ref st.AnimId); - - st.DwellProgress = 0f; - - if (st.IsHovered || st.IsPressed) - { - StartAnimationFeedback(btn); - - return; - } - - if (btn.Focused) - { - ApplyStrongVisual(btn); - - return; - } - - btn.BackColor = Color.Empty; - btn.ForeColor = Color.Empty; - - Font? regular = st.RegularFont; - - if (regular != null && - !ReferenceEquals(btn.Font, regular)) - { - btn.Font = regular; - } - - btn.AccessibleDescription = st.BaseDescription; - - btn.Padding = st.OriginalPadding; - ResetNativeColors(btn, st); - btn.Invalidate(); - } - - /// - /// 使用自家按鈕的框架主題刷新路徑清除原生動畫快取;不改主題、尺寸或焦點。 - /// Color.Empty 已先還原,因此下一幀直接以 Latest 的目前原生配色繪製。 - /// - private static void ResetNativeColors(Button button, ButtonVisualState state) - { - if (button is not FeedbackButton feedbackButton || button.IsDisposed || state.IsResettingNativeColors) - { - return; - } - - state.IsResettingNativeColors = true; - try - { - feedbackButton.ResetNativeColorTransition(); - } - finally - { - state.IsResettingNativeColors = false; - } + GetFeedbackButton(btn).ConfigureFeedback(baseDescription, regularFont, boldFont, onFocusStateChanged, formCt); } - /// - /// 為現有文字按鈕繪製一致的互動配色,不受 Net11 預設動作強調色覆蓋。 - /// - /// 目前處於自訂回饋狀態的按鈕。 - /// 按鈕繪圖內容。 - private static void DrawFeedbackSurface(Button button, Graphics graphics) - { - using Brush background = new SolidBrush(button.BackColor); - graphics.FillRectangle(background, button.ClientRectangle); - - int inset = (int)Math.Ceiling(4 * button.DeviceDpi / AppSettings.BaseDpi); - Rectangle textBounds = Rectangle.FromLTRB( - inset + button.Padding.Left, inset + button.Padding.Top, - button.Width - inset - button.Padding.Right, button.Height - inset - button.Padding.Bottom); - TextFormatFlags flags = TextFormatFlags.HorizontalCenter | - TextFormatFlags.VerticalCenter | TextFormatFlags.WordBreak | - TextFormatFlags.PreserveGraphicsClipping; - if (!button.UseMnemonic) - { - flags |= TextFormatFlags.NoPrefix; - } - - if (button.RightToLeft == RightToLeft.Yes) - { - flags |= TextFormatFlags.RightToLeft; - } - - TextRenderer.DrawText(graphics, button.Text, button.Font, textBounds, button.ForeColor, flags); - } - - /// - /// 負責接管原生的 Paint 事件以繪製包含基礎邊框、 - /// 互動邊框、對比色、與 Dwell 進度條的所有按鈕客製化視覺 - /// - /// 事件的發送者,通常是按鈕 - /// 包含繪圖資訊的事件參數 - private static void HandleButtonPaint(object? sender, PaintEventArgs e) - { - if (sender is not Button btn) - { - return; - } - - try - { - _buttonStates.TryGetValue(btn, out ButtonVisualState? st); - Graphics g = e.Graphics; + /// 點擊完成後重新接合實際視線;不執行自動點擊或剪貼簿輸出。 + public static Task CompleteClickAndReGazeAsync(this Button btn) => GetFeedbackButton(btn).ReGazeAfterClickAsync(); - float scale = btn.DeviceDpi / AppSettings.BaseDpi; + /// 停止目前 Dwell,不影響焦點、按壓或原生色彩。 + public static void CancelDwellAnimation(this Button btn) => GetFeedbackButton(btn).CancelDwell(); - bool isDark = btn.IsDarkModeActive(), - isFocused = btn.Focused, - isHoveredOrDwell = (st?.IsHovered ?? false) || - (st?.DwellProgress ?? 0f) > 0f; + /// 同步 DPI/主題更新取得的共享字型,不重設回饋生命週期。 + public static void UpdateEyeTrackerFonts(this Button btn, Font regularFont, Font? boldFont) => + GetFeedbackButton(btn).UpdateFeedbackFonts(regularFont, boldFont); - if (btn.TryDrawDisabledButtonCue(g, isDark, scale)) - { - return; - } - - // Net11 的預設按鈕強制使用強調色背景,但仍接受自訂文字色。 - // 自訂回饋期間成對繪製背景與文字,避免背景被覆寫而失去對比; - // 高對比的一般狀態也保留系統色配對;其他一般與停用狀態沿用原生渲染。 - if (st != null && (SystemInformation.HighContrast || st.IsPressed || isFocused || isHoveredOrDwell)) - { - DrawFeedbackSurface(btn, g); - } - - Form? parentForm = btn.FindForm(); - - bool isDefault = parentForm != null && - ReferenceEquals(parentForm.AcceptButton, btn) && - parentForm.ActiveControl is not Button && - btn.Enabled; - - if (!isFocused && - !isHoveredOrDwell && - !isDefault) - { - btn.DrawButtonBaseBorder(g, isDark, scale); - } - - bool isStrongVisual = (st?.IsPressed ?? false) || - (isFocused && !(st?.IsHovered ?? false)); - - if (isFocused || - isHoveredOrDwell || - isDefault) - { - Color borderColor = btn.GetButtonInteractiveBorderColor(isStrongVisual, isDark); - Color? backingColor = null; - if (isDefault && !isFocused && !isHoveredOrDwell && !(st?.IsPressed ?? false)) - { - Control? context = parentForm?.ActiveControl; - while (context is ContainerControl { ActiveControl: not null } container) - { - context = container.ActiveControl; - } - - (Color Border, Color Backing) = ControlExtensions.GetContextualFocusColors( - context?.BackColor ?? Color.Empty, isDark); - borderColor = Border; - backingColor = Backing; - } - - btn.DrawButtonInteractiveBorder( - g, - borderColor, - scale, - out int inset, - out int borderThickness, - backingColor); - - if (!SystemInformation.HighContrast && - (st?.IsPressed ?? false)) - { - btn.DrawPressedInnerCue(g, scale, inset, borderThickness); - } - } - - float progress = st?.DwellProgress ?? 0f; - - if (progress > 0f && - !(st?.IsPressed ?? false)) - { - int barH = (int)(6 * scale), - barW = (int)(btn.Width * progress); - - if (barW > 0) - { - Rectangle barRect = new(0, btn.Height - barH, barW, barH); - - if (SystemInformation.HighContrast) - { - using Brush barBrush = new SolidBrush(SystemColors.HighlightText); - - g.FillRectangle(barBrush, barRect); - } - else - { - // 依據按鈕實際背景亮度(而非主題)決定進度條顏色。 - // 眼動儀懸停時背景反轉(深色主題→White, 淺色主題→Black), - // 若繼續用 isDark 判斷,深色主題懸停 LimeGreen vs White - // 對比僅 2.12:1,低於 WCAG 1.4.11 Non-text Contrast 3:1 要求。 - bool bgIsLight = btn.BackColor != Color.Empty - ? btn.BackColor.GetBrightness() > 0.5f - : !isDark; - - Color baseColor = bgIsLight ? - Color.Green : - Color.LimeGreen, - hatchColor = bgIsLight ? - Color.PaleGreen : - Color.DarkGreen; - - using Brush bgBrush = new SolidBrush(baseColor); - using Brush hatchBrush = new HatchBrush( - HatchStyle.BackwardDiagonal, - hatchColor, - Color.Transparent); - - g.FillRectangle(bgBrush, barRect); - g.FillRectangle(hatchBrush, barRect); - } - } - } - } - catch (Exception ex) - { - Debug.WriteLine($"[EyeTrackerButton] Paint 失敗:{ex.Message}"); - } - } + private static FeedbackButton GetFeedbackButton(Button button) => button as FeedbackButton ?? + throw new ArgumentException("Eye tracker feedback requires FeedbackButton.", nameof(button)); } \ No newline at end of file diff --git a/src/InputBox/Core/Extensions/ControlExtensions.cs b/src/InputBox/Core/Extensions/ControlExtensions.cs index f157acc3..5eb77f20 100644 --- a/src/InputBox/Core/Extensions/ControlExtensions.cs +++ b/src/InputBox/Core/Extensions/ControlExtensions.cs @@ -435,82 +435,9 @@ public static bool IsDarkModeActive(this Control control) return Application.IsDarkModeEnabled; } - /// - /// 繪製按鈕停用態提示(虛線邊框 + 斜線),並回傳是否已處理停用態。 - /// - /// 目標按鈕 - /// 繪圖物件 - /// 是否深色模式 - /// DPI 縮放 - /// 若按鈕為停用且已繪製提示則回傳 true - public static bool TryDrawDisabledButtonCue( - this Button button, - Graphics graphics, - bool isDark, - float scale) - { - if (button.Enabled) - { - return false; - } - - int thickness = (int)Math.Max(1, scale); - - Color disabledColor = SystemInformation.HighContrast ? - SystemColors.GrayText : - (isDark ? Color.FromArgb(140, 140, 140) : Color.FromArgb(120, 120, 120)); - - using Pen disabledPen = new(disabledColor, thickness) - { - DashStyle = DashStyle.Dot - }; - - graphics.DrawRectangle(disabledPen, 0, 0, button.Width - 1, button.Height - 1); - // 美觀 + A11y:在一般模式加入低透明度斜線紋理,避免僅靠單一線段提示停用。 - if (!SystemInformation.HighContrast && - button.Width > 4 && - button.Height > 4) - { - Rectangle innerRect = new(2, 2, Math.Max(1, button.Width - 4), Math.Max(1, button.Height - 4)); - - using Brush hatchBrush = new HatchBrush( - HatchStyle.ForwardDiagonal, - Color.FromArgb(isDark ? 60 : 45, disabledColor), - Color.Transparent); - - graphics.FillRectangle(hatchBrush, innerRect); - } - - using Pen cuePen = new(disabledColor, Math.Max(1f, scale)); - graphics.DrawLine(cuePen, 2, button.Height - 3, button.Width - 3, 2); - - return true; - } - - /// - /// 繪製按鈕基礎邊框(非焦點、非懸停狀態)。 - /// - /// 目標按鈕。 - /// 繪圖物件。 - /// 是否為深色模式。 - /// 目前 DPI 縮放比例。 - public static void DrawButtonBaseBorder( - this Button button, - Graphics graphics, - bool isDark, - float scale) - { - int thickness = (int)Math.Max(1, scale); - using Pen basePen = new( - SystemInformation.HighContrast ? - SystemColors.WindowFrame : - (isDark ? Color.DimGray : Color.DarkGray), - thickness); - graphics.DrawRectangle(basePen, 0, 0, button.Width - 1, button.Height - 1); - } /// /// 取得輸入焦點與預設動作共用的提示色及對比襯底,保留專案四種情境配色。 @@ -539,42 +466,7 @@ internal static (Color Border, Color Backing) GetContextualFocusColors(Color bac (Color.LightBlue, Color.FromArgb(60, 60, 60)) : (Color.MediumBlue, Color.FromArgb(220, 220, 220)); } - /// - /// 依互動情境取得焦點/懸停邊框色。 - /// - /// 目標按鈕。 - /// 是否為強視覺場景(按下或眼動儀目視狀態)。 - /// 是否為深色模式。 - /// 對應情境的邊框顏色。 - public static Color GetButtonInteractiveBorderColor(this Button button, bool isStrongVisual, bool isDark) - { - if (SystemInformation.HighContrast) - { - return button.BackColor.ToArgb() == SystemColors.Highlight.ToArgb() ? - SystemColors.HighlightText : SystemColors.ControlText; - } - static bool IsSameColor(Color left, Color right) => left.ToArgb() == right.ToArgb(); - - // 強視覺場景依實際背景色決策,避免僅依主題旗標造成對比不足。 - if (isStrongVisual) - { - if (IsSameColor(button.BackColor, Color.Black)) - { - return Color.Cyan; - } - - if (IsSameColor(button.BackColor, Color.White)) - { - return Color.MediumBlue; - } - - return isDark ? Color.MediumBlue : Color.Cyan; - } - - // 中性場景保持主題感知對比(深色 LightBlue、淺色 MediumBlue)。 - return isDark ? Color.LightBlue : Color.MediumBlue; - } /// /// 繪製按鈕焦點/懸停邊框。 @@ -614,116 +506,9 @@ public static void DrawButtonInteractiveBorder( button.Height - (inset * 2) - 1); } - /// - /// 繪製 Pressed 內緣提示(非顏色線索)。 - /// - /// 目標按鈕。 - /// 繪圖物件。 - /// 目前 DPI 縮放比例。 - /// 焦點邊框內縮量(由 DrawButtonInteractiveBorder 取得)。 - /// 焦點邊框厚度(由 DrawButtonInteractiveBorder 取得)。 - public static void DrawPressedInnerCue( - this Button button, - Graphics graphics, - float scale, - int inset, - int borderThickness) - { - int pressedInset = inset + borderThickness; - if (button.Width - (pressedInset * 2) - 1 <= 0 || - button.Height - (pressedInset * 2) - 1 <= 0) - { - return; - } - using Pen pressedCuePen = new(button.ForeColor, Math.Max(1f, scale)); - - graphics.DrawRectangle( - pressedCuePen, - pressedInset, - pressedInset, - button.Width - (pressedInset * 2) - 1, - button.Height - (pressedInset * 2) - 1); - } - /// - /// 執行通用的眼動儀注視填滿動畫 - /// - /// 要執行動畫的控制項。 - /// 本次動畫的目標序號;與 回傳值比對,序號失效時立即停止。 - /// 讀取目前最新動畫序號的委派(通常讀取以 Interlocked 維護的欄位)。 - /// 設定進度值(0.0 ~ 1.0)的回呼委派。 - /// 動畫總時長(毫秒),預設 1000ms。 - /// 取消權杖。 - /// 代表眼動儀注視動畫非同步執行的工作任務。 - public static async Task RunDwellAnimationAsync( - this Control control, - long id, - Func animationIdGetter, - Action progressSetter, - int durationMs = 1000, - CancellationToken ct = default) - { - if (control == null || - control.IsDisposed) - { - return; - } - - // 系統動畫服從性:若使用者關閉了 UI 特效,直接跳至完成狀態。 - if (!SystemInformation.UIEffectsEnabled) - { - // 確保在 UI 執行緒執行。 - control.SafeInvoke(() => - { - progressSetter(1.0f); - - control.Invalidate(); - }); - - return; - } - - // 防禦性寫法:避免除以零。 - int safeDuration = Math.Max(1, durationMs); - - Stopwatch stopwatch = Stopwatch.StartNew(); - - // 根據規範:統一使用 60 FPS(16.6ms)物理頻率。 - using PeriodicTimer timer = new(TimeSpan.FromMilliseconds(AppSettings.TargetFrameTimeMs)); - - try - { - while (await timer.WaitForNextTickAsync(ct) && - animationIdGetter() == id && - !control.IsDisposed && - control.IsHandleCreated) - { - double elapsed = stopwatch.Elapsed.TotalMilliseconds; - - float progress = (float)Math.Min(1.0, elapsed / safeDuration); - - // 由於 PeriodicTimer 可能在 ThreadPool 執行緒恢復, - // 雖然 WinForms 有 SynchronizationContext,但此處顯式使用 SafeInvokeAsync 以策萬全。 - await control.SafeInvokeAsync(() => - { - progressSetter(progress); - - control.Invalidate(); - }); - - if (progress >= 1.0f) - { - break; - } - } - } - catch (OperationCanceledException) - { - // 正常取消。 - } - } /// /// 遞歸更新控制項及其所有子控制項的背景色與前景色。 diff --git a/tests/InputBox.Tests/ButtonFeedbackRenderingTests.cs b/tests/InputBox.Tests/ButtonFeedbackRenderingTests.cs index 49a22d93..514c3605 100644 --- a/tests/InputBox.Tests/ButtonFeedbackRenderingTests.cs +++ b/tests/InputBox.Tests/ButtonFeedbackRenderingTests.cs @@ -1,618 +1,507 @@ using InputBox.Core.Extensions; using InputBox.Core.Interop; -using System.Reflection; +using InputBox.Core.Services; +using InputBox.Resources; +using System.ComponentModel; +using System.Globalization; using System.Runtime.ExceptionServices; using Xunit; namespace InputBox.Tests; -/// -/// 驗證 Latest 預設按鈕的實際像素與自訂互動配色一致,避免強調色覆寫背景。 -/// +/// Standard/Latest 的原生表面、必要提示及完整互動交接像素驗證。 [Collection(UiSmokeTestRequirements.CollectionName)] [Trait("Category", "UI")] public sealed class ButtonFeedbackRenderingTests { - /// - /// 在獨立測試程序中選擇淺色或深色,讓同一組像素檢查覆蓋兩種渲染路徑。 - /// static ButtonFeedbackRenderingTests() { - Application.SetHighDpiMode(HighDpiMode.PerMonitorV2); - Application.SetColorMode(Environment.GetEnvironmentVariable("INPUTBOX_BUTTON_TEST_DARK") == "1" ? - SystemColorMode.Dark : SystemColorMode.Classic); + Application.SetHighDpiMode(Environment.GetEnvironmentVariable("INPUTBOX_BUTTON_TEST_96DPI") == "1" ? HighDpiMode.DpiUnaware : HighDpiMode.PerMonitorV2); + Application.EnableVisualStyles(); + Application.SetColorMode(Environment.GetEnvironmentVariable("INPUTBOX_BUTTON_TEST_DARK") == "1" ? SystemColorMode.Dark : SystemColorMode.Classic); + Application.SetDefaultVisualStylesMode(VisualStylesMode.Latest); } - /// - /// 預設與一般按鈕的焦點、懸停、按下背景及文字應成對呈現,且互動不改變尺寸或內距。 - /// - [Theory(Skip = "Requires explicit UI test opt-in.", - SkipUnless = nameof(UiSmokeTestRequirements.IsEnabled), SkipType = typeof(UiSmokeTestRequirements))] - [InlineData(true, "focus")] - [InlineData(true, "hover")] - [InlineData(true, "pressed")] - [InlineData(false, "focus")] - [InlineData(false, "hover")] - [InlineData(false, "pressed")] - [InlineData(true, "focus-hover")] - [InlineData(false, "focus-hover")] - [InlineData(true, "keyboard-pressed")] - [InlineData(false, "keyboard-pressed")] - [InlineData(true, "keyboard-release")] - [InlineData(false, "keyboard-release")] - [InlineData(true, "keyboard-cancel")] - [InlineData(false, "keyboard-cancel")] - public void Render_InteractiveState_PreservesCustomContrast(bool isDefault, string state) + /// 驗證預設與一般按鈕各互動狀態的實際文字、提示及按壓對比。 + [Theory(Skip = "Requires explicit UI test opt-in.", SkipUnless = nameof(UiSmokeTestRequirements.IsEnabled), SkipType = typeof(UiSmokeTestRequirements))] + [InlineData(true, "focus")][InlineData(false, "focus")] + [InlineData(true, "hover")][InlineData(false, "hover")] + [InlineData(true, "pressed")][InlineData(false, "pressed")] + [InlineData(true, "focus-hover")][InlineData(false, "focus-hover")] + [InlineData(true, "keyboard-pressed")][InlineData(false, "keyboard-pressed")] + [InlineData(true, "keyboard-release")][InlineData(false, "keyboard-release")] + [InlineData(true, "keyboard-cancel")][InlineData(false, "keyboard-cancel")] + public void Render_InteractiveState_PreservesContrast(bool isDefault, string state) => RunUi(isDefault, async scene => { - RunSta(() => + ProbeButton button = scene.Button; + bool hover = state is "hover" or "focus-hover"; + bool pressed = state is "pressed" or "keyboard-pressed"; + if (state != "hover") { Assert.True(button.Focus()); } + if (hover) { button.EnterHover(); } + if (state == "pressed") { button.PressMouse(); } + if (state.StartsWith("keyboard", StringComparison.Ordinal)) { - using var form = new Form(); - using var input = new TextBox(); - using var bold = new Font(form.Font, FontStyle.Bold); - using var button = new FeedbackButton - { - Text = "Button text", - Bounds = new Rectangle(10, 50, 240, 90), - FlatStyle = FlatStyle.Flat, - VisualStylesMode = VisualStylesMode.Latest, - Padding = new Padding(7) - }; - using var lifetime = new CancellationTokenSource(); - form.Controls.AddRange([input, button]); - button.AttachEyeTrackerFeedback("Button", button.Font, bold, lifetime.Token); - if (isDefault) + button.PressSpace(); + if (state == "keyboard-release") { button.ReleaseSpace(); } + if (state == "keyboard-cancel") { scene.Input.Focus(); button.Focus(); } + } + button.RefreshSystemColors(); + await Task.Delay(50); + using Bitmap image = Render(button); + Color actualBack = image.GetPixel(25, 20); + AssertText(button, 4.5); + AssertAmbient(button); + Assert.Equal(!hover, button.Font.Bold); + if (!hover) + { + bool dark = button.IsDarkModeActive(); + Color expectedBack = SystemInformation.HighContrast ? (pressed ? SystemColors.HighlightText : SystemColors.Highlight) : + pressed ? (dark ? Color.FromArgb(255, 200, 120) : Color.FromArgb(28, 28, 28)) : dark ? Color.White : Color.Black; + Assert.Equal(expectedBack.ToArgb(), actualBack.ToArgb()); + double cue = Contrast(image.GetPixel(2, 20), image.GetPixel(0, 20)); + double minimum = SystemInformation.HighContrast || pressed ? 3 : dark ? 11.16 : 16.75; + Assert.True(cue >= 3 && cue + .005 >= minimum); + if (pressed) { - form.AcceptButton = button; + double inner = Enumerable.Range(5, 6).Max(x => Contrast(actualBack, image.GetPixel(x, 20))); + Assert.True(inner >= 3, "按壓缺少可見內框,包括高對比。"); + if (dark && !SystemInformation.HighContrast) { Assert.True(100 - TritanLightness(actualBack) >= 13); } } + } + else + { + double cue = Contrast(image.GetPixel(2, 20), image.GetPixel(0, 20)); + double minimum = SystemInformation.HighContrast ? 3 : button.IsDarkModeActive() ? 7.2 : 8.14; + Assert.True(cue >= 3 && cue + .005 >= minimum); + } + Save(image, $"{isDefault}-{state}"); + }); + + /// 驗證中性與停用狀態保留原生表面和可辨識文字。 + [Theory(Skip = "Requires explicit UI test opt-in.", SkipUnless = nameof(UiSmokeTestRequirements.IsEnabled), SkipType = typeof(UiSmokeTestRequirements))] + [InlineData(true, true)][InlineData(false, true)][InlineData(true, false)][InlineData(false, false)] + public void Render_NeutralAndDisabled_KeepNativeSurface(bool isDefault, bool enabled) => RunUi(isDefault, async scene => + { + scene.Button.Enabled = enabled; + await Task.Delay(450); + AssertAmbient(scene.Button); + AssertText(scene.Button, enabled ? 4.5 : 1.5); + }); + + /// 驗證預設動作提示與實際輸入焦點的情境色一致。 + [Theory(Skip = "Requires explicit UI test opt-in.", SkipUnless = nameof(UiSmokeTestRequirements.IsEnabled), SkipType = typeof(UiSmokeTestRequirements))] + [InlineData(true)][InlineData(false)] + public void Render_DefaultAction_FollowsInputContext(bool strong) => RunUi(true, async scene => + { + bool dark = scene.Button.IsDarkModeActive(); + scene.Input.BackColor = strong ? (dark ? Color.White : Color.Black) : Color.Empty; + scene.Button.Invalidate(); + await Task.Delay(30); + using Bitmap image = Render(scene.Button); + (Color border, Color backing) = ControlExtensions.GetContextualFocusColors(scene.Input.BackColor, dark); + Assert.Equal(border.ToArgb(), image.GetPixel(2, 20).ToArgb()); + Assert.Equal(backing.ToArgb(), image.GetPixel(0, 20).ToArgb()); + Assert.True(Contrast(image.GetPixel(2, 20), image.GetPixel(0, 20)) >= 3); + AssertAmbient(scene.Button); + }); - form.Show(); - form.Activate(); - Application.DoEvents(); - input.Focus(); - if (state == "focus") + /// 驗證部分與完整 Dwell 皆保留可見襯底及足夠相鄰對比。 + [Theory(Skip = "Requires explicit UI test opt-in.", SkipUnless = nameof(UiSmokeTestRequirements.IsEnabled), SkipType = typeof(UiSmokeTestRequirements))] + [InlineData(true, false)][InlineData(false, false)][InlineData(true, true)][InlineData(false, true)] + public void Render_Dwell_HasVisibleBackingAtPartialAndFullProgress(bool isDefault, bool complete) => RunUi(isDefault, async scene => + { + ProbeButton button = scene.Button; + int clicks = 0; + button.Click += (_, _) => clicks++; + button.EnterHover(); + await WaitProgress(button, complete ? 1 : .4f); + using Bitmap image = Render(button); + float scale = button.DeviceDpi / 96f; + int inset = (int)Math.Ceiling(7 * scale); + int backing = (int)Math.Max(1, Math.Ceiling(scale)); + int height = (int)Math.Ceiling(6 * scale) + 2 * backing; + int top = button.Height - inset - height; + Color track = image.GetPixel(inset, top); + bool dark = button.IsDarkModeActive(); + Color fill = SystemInformation.HighContrast ? SystemColors.HighlightText : dark ? Color.LimeGreen : Color.Green; + Color expectedTrack = SystemInformation.HighContrast ? SystemColors.Highlight : dark ? Color.FromArgb(60, 60, 60) : Color.FromArgb(220, 220, 220); + Assert.Equal(expectedTrack.ToArgb(), track.ToArgb()); + Assert.Equal(track.ToArgb(), image.GetPixel(inset, top + height - 1).ToArgb()); + Assert.Equal(track.ToArgb(), image.GetPixel(button.Width - inset - 1, top + height / 2).ToArgb()); + Assert.Equal(track.ToArgb(), image.GetPixel(inset, top + height / 2).ToArgb()); + int ink = 0; + for (int y = top + backing; y < top + height - backing; y++) + { + for (int x = inset + backing; x < inset + backing + 40; x++) { - Assert.True(button.Focus()); + if (image.GetPixel(x, y).ToArgb() == fill.ToArgb()) { ink++; } } - else if (state == "hover") + } + Assert.True(ink > 20); + double ratio = Contrast(fill, track); + double minimum = SystemInformation.HighContrast ? 3 : dark ? 5.21 : 3.75; + Assert.True(ratio >= 3 && ratio + .005 >= minimum); + Assert.Equal(0, clicks); + AssertAmbient(button); + AssertText(button, 4.5); + Save(image, $"dwell-{isDefault}-{complete}"); + }); + + /// 驗證鍵盤與滑鼠交錯、Capture 取消及生命週期清理不殘留回饋。 + [Theory(Skip = "Requires explicit UI test opt-in.", SkipUnless = nameof(UiSmokeTestRequirements.IsEnabled), SkipType = typeof(UiSmokeTestRequirements))] + [InlineData(true, "space-leave")][InlineData(false, "space-leave")] + [InlineData(true, "pointer-space-release")][InlineData(false, "pointer-space-release")] + [InlineData(true, "capture")][InlineData(false, "capture")] + [InlineData(true, "disable")][InlineData(false, "disable")] + [InlineData(true, "cancel")][InlineData(false, "cancel")] + [InlineData(true, "reconfigure")][InlineData(false, "reconfigure")] + [InlineData(true, "lifetime")][InlineData(false, "lifetime")] + public void Interaction_InterleavingAndLifecycle_DoNotLeaveFeedback(bool isDefault, string action) => RunUi(isDefault, async scene => + { + ProbeButton button = scene.Button; + if (action is "space-leave" or "pointer-space-release") + { + button.Focus(); button.PressSpace(); button.EnterHover(); + if (action == "space-leave") { button.ExitHover(); } + else { button.Capture = true; button.PressMouse(); button.ReleaseMouse(); } + Assert.True(button.Pressed, "滑鼠狀態不應清除仍按住的 Space。"); + button.ReleaseSpace(); + Assert.False(button.Pressed); + } + else if (action == "capture") + { + button.EnterHover(); button.Capture = true; + Assert.True(button.Capture); + button.PressMouse(); Assert.True(button.Pressed); + button.Capture = false; + Assert.False(button.Pressed); + button.ReleaseMouse(); + } + else + { + button.EnterHover(); await WaitProgress(button, .2f); + if (action == "disable") { - button.Hover(); - Assert.NotEqual(form.BackColor, button.BackColor); + button.Enabled = false; Assert.Equal(0, button.Progress); Assert.False(button.Pressed); + button.Enabled = true; Assert.Equal(0, button.Progress); } - else + else if (action == "cancel") { - Assert.True(button.Focus()); - if (state == "focus-hover") - { - button.Hover(); - } - else if (state.StartsWith("keyboard", StringComparison.Ordinal)) - { - button.PressSpace(); - if (state == "keyboard-release") - { - button.ReleaseSpace(); - } - else if (state == "keyboard-cancel") - { - Assert.True(input.Focus()); - Assert.True(button.Focus()); - } - } - else - { - button.Press(); - } + Task pending = button.CompleteClickAndReGazeAsync(); + button.CancelDwellAnimation(); await pending; await Task.Delay(60); + Assert.Equal(0, button.Progress); } - bool hovered = state is "hover" or "focus-hover"; - bool pressed = state is "pressed" or "keyboard-pressed"; - - button.BackColor = Color.Magenta; - button.ForeColor = Color.Magenta; - button.RefreshSystemColors(); - Assert.NotEqual(Color.Magenta, button.BackColor); - if (!SystemInformation.HighContrast) + else if (action == "lifetime") { - bool dark = button.IsDarkModeActive(); - Color expectedBackground = pressed ? (dark ? Color.FromArgb(255, 200, 120) : Color.FromArgb(28, 28, 28)) : - hovered ? (dark ? Color.FromArgb(60, 60, 60) : Color.FromArgb(220, 220, 220)) : - (dark ? Color.White : Color.Black); - Assert.Equal(expectedBackground, button.BackColor); + scene.Lifetime.Cancel(); await Task.Delay(60); + Assert.Equal(0, button.Progress); } - - using var bitmap = new Bitmap(button.Width, button.Height); - button.DrawToBitmap(bitmap, button.ClientRectangle); - string? artifacts = Environment.GetEnvironmentVariable("INPUTBOX_BUTTON_ARTIFACTS"); - if (artifacts != null) + else { - Directory.CreateDirectory(artifacts); - bitmap.Save(Path.Combine(artifacts, $"{isDefault}-{state}.png")); + float progress = button.Progress; + button.AttachEyeTrackerFeedback("Updated", scene.Regular, scene.Bold, scene.Lifetime.Token); + button.UpdateEyeTrackerFonts(scene.Regular, scene.Bold); + button.RefreshSystemColors(); await Task.Delay(25); + Assert.True(button.Progress >= progress, "更新字型或系統色不應重新開始凝視。"); + Assert.Contains("Updated", button.AccessibleDescription); } - Assert.Equal(button.BackColor.ToArgb(), bitmap.GetPixel(25, 20).ToArgb()); - int textPixels = 0; - for (int y = 25; y < 65; y++) + } + AssertAmbient(button); + AssertText(button, 4.5); + }); + + /// 逐幀驗證視窗有無焦點時懸停過渡的對比與版面不變。 + [Theory(Skip = "Requires explicit UI test opt-in.", SkipUnless = nameof(UiSmokeTestRequirements.IsEnabled), SkipType = typeof(UiSmokeTestRequirements))] + [InlineData(true, true)][InlineData(true, false)][InlineData(false, true)][InlineData(false, false)] + public void Render_Transition_EverySamplePreservesContrastAndGeometry(bool isDefault, bool active) => RunUi(isDefault, async scene => + { + ProbeButton button = scene.Button; + using Form other = new() { StartPosition = FormStartPosition.Manual, Location = new Point(850, 550), Size = new Size(100, 80) }; + if (!active) { other.Show(); other.Activate(); } + Form target = active ? scene.Form : other; + _ = await WindowFocusService.RestoreWindowAsync(target.Handle, TestContext.Current.CancellationToken); + for (int attempt = 0; attempt < 8; attempt++) + { + _ = User32.ShowWindow(target.Handle, User32.ShowWindowCommand.Restore); + _ = User32.SetForegroundWindow(target.Handle); + target.Activate(); + await Task.Delay(60); + if ((Form.ActiveForm == scene.Form) == active) { break; } + } + Assert.Equal(active, Form.ActiveForm == scene.Form); + Size size = button.Size; Padding padding = button.Padding; Padding margin = button.Margin; nint handle = button.Handle; + for (int phase = 0; phase < 4; phase++) + { + if (phase is 0 or 2) { button.EnterHover(); } else { button.ExitHover(); } + for (int i = 0; i < 25; i++) { - for (int x = 35; x < 205; x++) + AssertText(button, 4.5); + AssertAmbient(button); + Assert.Equal(size, button.Size); Assert.Equal(padding, button.Padding); + Assert.Equal(margin, button.Margin); Assert.Equal(handle, button.Handle); + if (isDefault || phase is 0 or 2) { - if (bitmap.GetPixel(x, y).ToArgb() == button.ForeColor.ToArgb()) - { - textPixels++; - } + using Bitmap image = Render(button); + Assert.True(Contrast(image.GetPixel(2, 20), image.GetPixel(0, 20)) >= 3); } + await Task.Delay(16); } + } + other.Close(); + }); - Color border = button.GetButtonInteractiveBorderColor(!hovered, button.IsDarkModeActive()); - Assert.Equal(border.ToArgb(), bitmap.GetPixel(2, 20).ToArgb()); - double borderMinimum = SystemInformation.HighContrast || pressed ? 3 : - !hovered ? (button.IsDarkModeActive() ? 11.16 : 16.75) : - (button.IsDarkModeActive() ? 7.2 : 8.14); - double borderContrast = Contrast(bitmap.GetPixel(2, 20), bitmap.GetPixel(0, 20)); - Assert.True(borderContrast >= 3 && borderContrast + 0.005 >= borderMinimum); - Assert.Equal(!hovered, button.Font.Bold); - if (pressed && button.IsDarkModeActive() && !SystemInformation.HighContrast) - { - double red = LinearComponent(button.BackColor.R); - double green = LinearComponent(button.BackColor.G); - double tritanLuminance = (red * 0.2126 + green * 0.7152) / 0.9278; - double lightness = 116 * Math.Cbrt(tritanLuminance) - 16; - Assert.True(100 - lightness >= 13); - } - Assert.True(Contrast(button.BackColor, button.ForeColor) >= 4.5); - Assert.True(textPixels > 10, "自訂文字色沒有實際繪製到按鈕。"); - Assert.Equal(new Padding(7), button.Padding); - Assert.Equal(new Size(240, 90), button.Size); - Assert.Equal(SystemInformation.HighContrast ? VisualStylesMode.Classic : VisualStylesMode.Latest, button.ResolvedMode); - lifetime.Cancel(); - }); - } + /// 驗證文字量測會拒絕空標題,避免僅量到裝飾的假陽性。 + [Fact(Skip = "Requires explicit UI test opt-in.", SkipUnless = nameof(UiSmokeTestRequirements.IsEnabled), SkipType = typeof(UiSmokeTestRequirements))] + public void Render_EmptyCaption_DoesNotPassTextCheck() => RunUi(false, scene => + { + scene.Button.Enabled = false; scene.Button.Text = string.Empty; + Assert.Throws(() => AssertText(scene.Button, 1.5)); + return Task.CompletedTask; + }); - /// - /// 回饋結束後必須還原環境配色,不得留下硬編碼顏色或破壞主題渲染。 - /// - [Theory(Skip = "Requires explicit UI test opt-in.", - SkipUnless = nameof(UiSmokeTestRequirements.IsEnabled), SkipType = typeof(UiSmokeTestRequirements))] - [InlineData(true)] - [InlineData(false)] - public void Render_AfterMouseLeave_RestoresAmbientColors(bool isDefault) + /// 驗證七語系及左右文字方向下的實際文字對比與內距。 + [Theory(Skip = "Requires explicit UI test opt-in.", SkipUnless = nameof(UiSmokeTestRequirements.IsEnabled), SkipType = typeof(UiSmokeTestRequirements))] + [InlineData("zh-Hant")][InlineData("en")][InlineData("de")][InlineData("fr")][InlineData("ja")][InlineData("ko")][InlineData("zh-Hans")] + public void Render_LocalizedAndRtlCaption_PreservesTextAndPadding(string culture) => RunUi(true, async scene => { - RunSta(() => + scene.Button.Text = Strings.ResourceManager.GetString("Btn_CopyDefault", new CultureInfo(culture))!; + Assert.False(string.IsNullOrWhiteSpace(scene.Button.Text)); + Padding original = scene.Button.Padding; + foreach (RightToLeft rtl in new[] { RightToLeft.No, RightToLeft.Yes }) { - using var form = new Form(); - using var input = new TextBox(); - using var button = new FeedbackButton - { - Text = "Button text", Bounds = new Rectangle(10, 50, 240, 90), - FlatStyle = FlatStyle.Flat, VisualStylesMode = VisualStylesMode.Latest - }; - using var lifetime = new CancellationTokenSource(); - form.Controls.AddRange([input, button]); - button.AttachEyeTrackerFeedback("Button", null, null, lifetime.Token); - if (isDefault) - { - form.AcceptButton = button; - } + scene.Button.RightToLeft = rtl; scene.Button.Focus(); + await Task.Delay(30); AssertText(scene.Button, 4.5); + Assert.Equal(original, scene.Button.Padding); AssertAmbient(scene.Button); + scene.Input.Focus(); + } + }); - form.Show(); - form.Activate(); - Application.DoEvents(); - input.Focus(); - button.Press(); - button.ExitHover(); - Assert.Equal(form.BackColor, button.BackColor); - Assert.Equal(form.ForeColor, button.ForeColor); - CheckNeutralRendering(button, isDefault); - button.Enabled = false; - CheckNeutralRendering(button, isDefault); - lifetime.Cancel(); - }); - } + /// 驗證舊點擊的非同步重新接合不能覆寫新懸停狀態。 + [Theory(Skip = "Requires explicit UI test opt-in.", SkipUnless = nameof(UiSmokeTestRequirements.IsEnabled), SkipType = typeof(UiSmokeTestRequirements))] + [InlineData(true)][InlineData(false)] + public void Interaction_StaleClickRegaze_DoesNotReplaceNewHover(bool isDefault) => RunUi(isDefault, async scene => + { + List notifications = []; + scene.Button.AttachEyeTrackerFeedback("Button", scene.Regular, scene.Bold, scene.Lifetime.Token, notifications.Add); + Task oldClick = scene.Button.CompleteClickAndReGazeAsync(); + scene.Button.EnterHover(); + await oldClick; + await WaitProgress(scene.Button, .1f); + Assert.True(notifications[^1]); + scene.Button.ExitHover(); + Assert.False(notifications[^1]); + Assert.Equal(0, scene.Button.Progress); + AssertAmbient(scene.Button); + }); + /// 滿格或停用 UI 特效後,取消仍須清除提示,換權杖及處置也不得殘留註冊。 + [Theory(Skip = "Requires explicit UI test opt-in.", SkipUnless = nameof(UiSmokeTestRequirements.IsEnabled), SkipType = typeof(UiSmokeTestRequirements))] + [InlineData(true, "cancel")][InlineData(false, "cancel")] + [InlineData(true, "rebind")][InlineData(false, "rebind")] + [InlineData(true, "dispose")][InlineData(false, "dispose")] + public void Interaction_CompletedDwellLifetime_ClearsWithoutTimer(bool isDefault, string action) => RunUi(isDefault, async scene => + { + ProbeButton button = scene.Button; + button.EnterHover(); + await WaitProgress(button, 1); + using CancellationTokenSource replacement = new(); + CancellationTokenSource cancellation = scene.Lifetime; + if (action == "rebind") + { + button.AttachEyeTrackerFeedback("Replacement", scene.Regular, scene.Bold, replacement.Token); + await Task.Run(scene.Lifetime.Cancel, TestContext.Current.CancellationToken); + await Task.Delay(60); + Assert.Equal(1, button.Progress); + cancellation = replacement; + } + if (action == "dispose") { button.Dispose(); } + await Task.Run(cancellation.Cancel, TestContext.Current.CancellationToken); + for (int i = 0; i < 100 && button.Progress > 0; i++) { await Task.Delay(16); } + Assert.Equal(0, button.Progress); + if (!button.IsDisposed) { AssertAmbient(button); AssertText(button, 4.5); } + }); - /// - /// 預設動作邊框須跟隨輸入框反轉/中性背景,並在實際相鄰襯底達到專案對比目標。 - /// - [Theory(Skip = "Requires explicit UI test opt-in.", - SkipUnless = nameof(UiSmokeTestRequirements.IsEnabled), SkipType = typeof(UiSmokeTestRequirements))] - [InlineData(true)] - [InlineData(false)] - public void Render_DefaultAction_MatchesInputContextWithContrast(bool strong) + /// 以訊息框的 AutoSize 與最小尺寸規則驗證七語系較矮按鈕,完整 Dwell 不得遮字或抖動。 + [Theory(Skip = "Requires explicit UI test opt-in.", SkipUnless = nameof(UiSmokeTestRequirements.IsEnabled), SkipType = typeof(UiSmokeTestRequirements))] + [InlineData(true, "zh-Hant")][InlineData(false, "zh-Hant")] + [InlineData(true, "en")][InlineData(false, "en")] + [InlineData(true, "de")][InlineData(false, "de")] + [InlineData(true, "fr")][InlineData(false, "fr")] + [InlineData(true, "ja")][InlineData(false, "ja")] + [InlineData(true, "ko")][InlineData(false, "ko")] + [InlineData(true, "zh-Hans")][InlineData(false, "zh-Hans")] + public void Render_MessageBoxSizedDwell_PreservesEveryCaptionPixel(bool isDefault, string culture) => RunUi(isDefault, async scene => { - RunSta(() => + ProbeButton button = scene.Button; + button.Text = Strings.ResourceManager.GetString("Btn_CopyDefault", new CultureInfo(culture))!; + button.Padding = Padding.Empty; + button.AutoSize = true; + float scale = button.DeviceDpi / 96f; + InputBox.Core.Utilities.DialogLayoutHelper.UpdateButtonMinimumSize(button, scene.Bold, scale, 88, 0, 24, 8); + button.Size = button.GetPreferredSize(Size.Empty); + button.AutoSize = false; + Size size = button.Size; Padding padding = button.Padding; Padding margin = button.Margin; nint handle = button.Handle; + button.EnterHover(); + HashSet caption = GetCaptionPixels(button); + Assert.True(caption.Count > 10); + int trackTop = button.Height - (int)Math.Ceiling(7 * scale) - (int)Math.Ceiling(6 * scale) - 2 * (int)Math.Max(1, Math.Ceiling(scale)); + Assert.True(caption.Max(point => point.Y) < trackTop, "原生標題與 Dwell 區域重疊。"); + for (int phase = 0; phase < 2; phase++) { - bool dark = Application.IsDarkModeEnabled; - Color contextColor = strong ? (dark ? Color.White : Color.Black) : - (dark ? Color.FromArgb(60, 60, 60) : Color.FromArgb(220, 220, 220)); - using var form = new Form(); - using var input = new TextBox { BackColor = contextColor }; - using var button = new FeedbackButton - { - Text = "Button text", Bounds = new Rectangle(10, 50, 240, 90), - FlatStyle = FlatStyle.Flat, VisualStylesMode = VisualStylesMode.Latest - }; - using var lifetime = new CancellationTokenSource(); - form.Controls.AddRange([input, button]); - form.AcceptButton = button; - button.AttachEyeTrackerFeedback("Button", null, null, lifetime.Token); - form.Show(); - Assert.True(input.Focus()); - Assert.Same(input, form.ActiveControl); - Color expected = SystemInformation.HighContrast ? SystemColors.Highlight : - strong ? (dark ? Color.MediumBlue : Color.Cyan) : - (dark ? Color.LightBlue : Color.MediumBlue); - using var bitmap = new Bitmap(button.Width, button.Height); - button.DrawToBitmap(bitmap, button.ClientRectangle); - Assert.Equal(expected.ToArgb(), bitmap.GetPixel(2, 20).ToArgb()); - double minimum = SystemInformation.HighContrast ? 3 : - strong ? (dark ? 11.16 : 16.75) : (dark ? 7.2 : 8.14); - double contrast = Contrast(bitmap.GetPixel(2, 20), bitmap.GetPixel(0, 20)); - Assert.True(contrast >= 3 && contrast + 0.005 >= minimum, $"預設動作邊框對比不足:{contrast:F3} < {minimum}"); - Assert.Equal(new Size(240, 90), button.Size); - string? artifacts = Environment.GetEnvironmentVariable("INPUTBOX_BUTTON_ARTIFACTS"); - if (artifacts != null) - { - Directory.CreateDirectory(artifacts); - bitmap.Save(Path.Combine(artifacts, $"default-context-{strong}.png")); - File.AppendAllText(Path.Combine(artifacts, "contrast.txt"), $"default strong={strong}, dpi={button.DeviceDpi}: {contrast:F3}:1{Environment.NewLine}"); - } - lifetime.Cancel(); - }); - } + float progress = phase == 0 ? .4f : 1f; + await WaitProgress(button, progress); + Assert.True(caption.IsSubsetOf(GetCaptionPixels(button)), "Dwell 遮住部分標題像素。"); + AssertText(button, 4.5); AssertAmbient(button); + Assert.Equal(size, button.Size); Assert.Equal(padding, button.Padding); + Assert.Equal(margin, button.Margin); Assert.Equal(handle, button.Handle); + } + using Bitmap image = Render(button); + Save(image, $"compact-{isDefault}-{culture}"); + }); - /// - /// 凝視進度條須依實際底色選用 Green/LimeGreen,保留色覺紋理並達至少 3:1。 - /// - [Theory(Skip = "Requires explicit UI test opt-in.", - SkipUnless = nameof(UiSmokeTestRequirements.IsEnabled), SkipType = typeof(UiSmokeTestRequirements))] - [InlineData(0)] - [InlineData(1)] - [InlineData(2)] - [InlineData(3)] - public void Render_Dwell_UsesActualBackgroundWithNonTextContrast(int palette) + private static HashSet GetCaptionPixels(Button button) { - RunSta(() => + string caption = button.Text; + button.Text = string.Empty; using Bitmap before = Render(button); + button.Text = caption; using Bitmap image = Render(button); + button.Text = string.Empty; using Bitmap after = Render(button); + button.Text = caption; + HashSet pixels = []; + for (int y = 0; y < button.Height; y++) { - Color[] backgrounds = [Color.White, Color.Black, Color.FromArgb(220, 220, 220), Color.FromArgb(60, 60, 60)]; - using var form = new Form(); - using var input = new TextBox(); - using var button = new FeedbackButton + for (int x = 0; x < button.Width; x++) { - Text = "Button text", Bounds = new Rectangle(10, 50, 240, 90), - FlatStyle = FlatStyle.Flat, VisualStylesMode = VisualStylesMode.Latest - }; - using var lifetime = new CancellationTokenSource(); - form.Controls.AddRange([input, button]); - button.AttachEyeTrackerFeedback("Button", null, null, lifetime.Token); - form.Show(); - input.Focus(); - button.Hover(); - button.CancelDwellAnimation(); - button.BackColor = SystemInformation.HighContrast ? SystemColors.Highlight : backgrounds[palette]; - button.SetProgress(0.5f); - using var bitmap = new Bitmap(button.Width, button.Height); - button.DrawToBitmap(bitmap, button.ClientRectangle); - Color fill = SystemInformation.HighContrast ? SystemColors.HighlightText : - palette is 0 or 2 ? Color.Green : Color.LimeGreen; - Color texture = palette is 0 or 2 ? Color.PaleGreen : Color.DarkGreen; - int fillPixels = 0; - int texturePixels = 0; - for (int y = button.Height - 5; y < button.Height; y++) - { - for (int x = 10; x < 110; x++) + int background = before.GetPixel(x, y).ToArgb(); + if (background == after.GetPixel(x, y).ToArgb() && background != image.GetPixel(x, y).ToArgb()) { - Color actual = bitmap.GetPixel(x, y); - int pixel = actual.ToArgb(); - if (pixel == fill.ToArgb()) - { - fillPixels++; - } - if (pixel != fill.ToArgb() && IsTextureBlend(actual, fill, texture)) - { - texturePixels++; - } + pixels.Add(new Point(x, y)); } } - string? debugArtifacts = Environment.GetEnvironmentVariable("INPUTBOX_BUTTON_ARTIFACTS"); - if (debugArtifacts != null) - { - Directory.CreateDirectory(debugArtifacts); - bitmap.Save(Path.Combine(debugArtifacts, $"dwell-{palette}.png")); - } - Assert.True(fillPixels > 100); - Assert.True(SystemInformation.HighContrast || texturePixels > 20); - double contrast = Contrast(fill, bitmap.GetPixel(25, 20)); - double[] targets = [5.14, 9.91, 3.75, 5.21]; - Assert.True(contrast >= 3 && contrast + 0.005 >= (SystemInformation.HighContrast ? 3 : targets[palette]), $"進度條對比不足:{contrast:F3}"); - string? artifacts = Environment.GetEnvironmentVariable("INPUTBOX_BUTTON_ARTIFACTS"); - if (artifacts != null) - { - Directory.CreateDirectory(artifacts); - bitmap.Save(Path.Combine(artifacts, $"dwell-{palette}.png")); - File.AppendAllText(Path.Combine(artifacts, "contrast.txt"), $"dwell palette={palette}: {contrast:F3}:1{Environment.NewLine}"); - } - lifetime.Cancel(); - }); + } + return pixels; } - /// - /// 沒有文字的停用按鈕即使保有斜線裝飾,也必須被文字檢查拒絕。 - /// - [Fact(Skip = "Requires explicit UI test opt-in.", - SkipUnless = nameof(UiSmokeTestRequirements.IsEnabled), SkipType = typeof(UiSmokeTestRequirements))] - public void Render_DisabledWithoutText_DoesNotPassTextCheck() + + private static void AssertAmbient(ProbeButton button) { - RunSta(() => - { - using var form = new Form(); - using var button = new FeedbackButton - { - Text = string.Empty, Bounds = new Rectangle(10, 50, 240, 90), - Enabled = false, FlatStyle = FlatStyle.Flat, VisualStylesMode = VisualStylesMode.Latest - }; - using var lifetime = new CancellationTokenSource(); - form.Controls.Add(button); - button.AttachEyeTrackerFeedback("Button", null, null, lifetime.Token); - form.Show(); - Assert.Throws(() => CheckNeutralRendering(button, false)); - lifetime.Cancel(); - }); + Assert.Equal(FlatStyle.Standard, button.FlatStyle); + Assert.False(TypeDescriptor.GetProperties(button)[nameof(button.BackColor)]!.ShouldSerializeValue(button)); + Assert.False(TypeDescriptor.GetProperties(button)[nameof(button.ForeColor)]!.ShouldSerializeValue(button)); + Assert.Equal(SystemInformation.HighContrast ? VisualStylesMode.Classic : VisualStylesMode.Latest, button.ResolvedMode); } - /// - /// 確認一般及停用狀態仍由 Latest 繪製可辨識文字,並保留實際像素供人工檢視。 - /// - private static void CheckNeutralRendering(Button button, bool isDefault) + + private static Bitmap Render(Button button) + { + Bitmap image = new(button.Width, button.Height); + button.DrawToBitmap(image, button.ClientRectangle); + return image; + } + + private static void AssertText(Button button, double minimum) { string caption = button.Text; - button.Text = string.Empty; - using var baseline = new Bitmap(button.Width, button.Height); - button.DrawToBitmap(baseline, button.ClientRectangle); + button.Text = string.Empty; using Bitmap before = Render(button); + button.Text = caption; using Bitmap image = Render(button); + button.Text = string.Empty; using Bitmap after = Render(button); button.Text = caption; - using var bitmap = new Bitmap(button.Width, button.Height); - button.DrawToBitmap(bitmap, button.ClientRectangle); - button.Text = string.Empty; - using var after = new Bitmap(button.Width, button.Height); - button.DrawToBitmap(after, button.ClientRectangle); - button.Text = caption; - int textPixels = 0; - Color background = bitmap.GetPixel(25, 20); - double contrast = 1; - for (int y = 30; y < 60; y++) + Dictionary colors = []; + for (int y = button.Height / 4; y < button.Height * 3 / 4; y++) { - for (int x = 35; x < 205; x++) + for (int x = 25; x < button.Width - 25; x++) { - Color pixel = bitmap.GetPixel(x, y); - if (baseline.GetPixel(x, y).ToArgb() == after.GetPixel(x, y).ToArgb() && - pixel.ToArgb() != baseline.GetPixel(x, y).ToArgb()) - { - textPixels++; - contrast = Math.Max(contrast, Contrast(background, pixel)); - } + int pixel = image.GetPixel(x, y).ToArgb(); + if (before.GetPixel(x, y).ToArgb() != after.GetPixel(x, y).ToArgb() || pixel == before.GetPixel(x, y).ToArgb()) { continue; } + colors.TryGetValue(pixel, out int count); colors[pixel] = count + 1; } } + Assert.True(colors.Values.Sum() > 10, "沒有找到實際文字墨色。"); + Color ink = Color.FromArgb(colors.MaxBy(pair => pair.Value).Key); + double ratio = Contrast(image.GetPixel(25, 20), ink); + Assert.True(ratio >= minimum, $"文字對比 {ratio:F3} < {minimum}"); + } - Assert.True(textPixels > 10, "排除裝飾後未找到文字像素。"); - Assert.True(contrast >= (button.Enabled ? 4.5 : 1.5), $"按鈕文字無法辨識:contrast={contrast}"); - string? artifacts = Environment.GetEnvironmentVariable("INPUTBOX_BUTTON_ARTIFACTS"); - if (artifacts != null) - { - Directory.CreateDirectory(artifacts); - bitmap.Save(Path.Combine(artifacts, $"{isDefault}-enabled-{button.Enabled}.png")); - } + private static async Task WaitProgress(ProbeButton button, float minimum) + { + for (int i = 0; i < 200 && button.Progress < minimum; i++) { await Task.Delay(16); } + Assert.True(button.Progress >= minimum, "Dwell 未到達驗證進度。"); } - /// - /// HatchBrush 在 DPI 縮放時會混合紋理與填色,檢查實際像素仍落於指定色對的範圍。 - /// - private static bool IsTextureBlend(Color pixel, Color fill, Color texture) + + private static double Contrast(Color a, Color b) + { + static double Linear(byte value) { double s = value / 255.0; return s <= .04045 ? s / 12.92 : Math.Pow((s + .055) / 1.055, 2.4); } + static double Lum(Color c) => .2126 * Linear(c.R) + .7152 * Linear(c.G) + .0722 * Linear(c.B); + double first = Lum(a); double second = Lum(b); + return (Math.Max(first, second) + .05) / (Math.Min(first, second) + .05); + } + + private static double TritanLightness(Color c) { - static bool Between(byte value, byte first, byte second) => - value >= Math.Min(first, second) && value <= Math.Max(first, second); - return Between(pixel.R, fill.R, texture.R) && - Between(pixel.G, fill.G, texture.G) && Between(pixel.B, fill.B, texture.B); + static double Linear(byte v) { double s = v / 255.0; return s <= .04045 ? s / 12.92 : Math.Pow((s + .055) / 1.055, 2.4); } + return 116 * Math.Cbrt((.2126 * Linear(c.R) + .7152 * Linear(c.G)) / .9278) - 16; } - /// - /// 取得 sRGB 分量的線性值,供色覺友善的按下亮度差驗證使用。 - /// - private static double LinearComponent(byte component) + + private static void Save(Bitmap image, string name) { - double value = component / 255.0; - return value <= 0.04045 ? value / 12.92 : Math.Pow((value + 0.055) / 1.055, 2.4); + string? path = Environment.GetEnvironmentVariable("INPUTBOX_BUTTON_ARTIFACTS"); + if (path is null) { return; } + Directory.CreateDirectory(path); image.Save(Path.Combine(path, name + ".png")); } - /// 逐幀檢查 Dwell 進出與未啟用視窗的配色,不能只等原生動畫完成再驗證。 - [Theory(Skip = "Requires explicit UI test opt-in.", - SkipUnless = nameof(UiSmokeTestRequirements.IsEnabled), SkipType = typeof(UiSmokeTestRequirements))] - [InlineData(true, true)] - [InlineData(true, false)] - [InlineData(false, true)] - [InlineData(false, false)] - public void Render_DwellHandoff_PreservesEveryFrame(bool isDefault, bool active) + + private static void RunUi(bool isDefault, Func action) { - RunSta(() => + Exception? failure = null; + Thread thread = new(() => { - using var form = new Form { ClientSize = new Size(300, 200), TopMost = true }; - using var input = new TextBox { Top = 150 }; - using var button = new FeedbackButton - { - Text = "Button text", Bounds = new Rectangle(10, 30, 240, 90), - FlatStyle = FlatStyle.Flat, VisualStylesMode = VisualStylesMode.Latest - }; - using var lifetime = new CancellationTokenSource(); - form.Controls.AddRange([input, button]); - button.AttachEyeTrackerFeedback("Button", button.Font, null, lifetime.Token); - if (isDefault) - { - form.AcceptButton = button; - } - Exception? frameFailure = null; - form.Shown += (_, _) => - { - try - { - form.Activate(); - input.Focus(); - using var other = new Form { Location = new Point(850, 500), Size = new Size(100, 80) }; - if (!active) - { - other.Show(); - other.Activate(); - } - Form target = active ? form : other; - _ = User32.ShowWindow(target.Handle, User32.ShowWindowCommand.Restore); - _ = User32.SetForegroundWindow(target.Handle); - target.Activate(); - Settle(500); - if (active) - { - Assert.Same(form, Form.ActiveForm); - } - else - { - Assert.NotSame(form, Form.ActiveForm); - } - using var expected = new Bitmap(button.Width, button.Height); - button.DrawToBitmap(expected, button.ClientRectangle); - Color neutralBack = expected.GetPixel(25, 20); - Color neutralBorder = expected.GetPixel(2, 20); - Size size = button.Size; - Padding padding = button.Padding; - nint handle = button.Handle; - button.EnterHover(); - for (int i = 0; i < 25; i++) + try { - Settle(16); - using var hover = new Bitmap(button.Width, button.Height); - button.DrawToBitmap(hover, button.ClientRectangle); - Assert.Equal(button.BackColor.ToArgb(), hover.GetPixel(25, 20).ToArgb()); - Assert.True(Contrast(hover.GetPixel(25, 20), button.ForeColor) >= 4.5); - int ink = 0; - for (int y = 25; y < 65; y++) + using Scene scene = new(isDefault); + scene.Form.Shown += async (_, _) => { - for (int x = 35; x < 205; x++) + try { - if (hover.GetPixel(x, y).ToArgb() == button.ForeColor.ToArgb()) - { - ink++; - } + _ = User32.ShowWindow(scene.Form.Handle, User32.ShowWindowCommand.Restore); + _ = User32.SetForegroundWindow(scene.Form.Handle); + _ = await WindowFocusService.RestoreWindowAsync(scene.Form.Handle, TestContext.Current.CancellationToken); + scene.Form.Activate(); scene.Input.Focus(); await Task.Delay(40); + await action(scene); } - } - Assert.True(ink > 10, "懸停文字未以配對前景色繪製。"); - Assert.True(Contrast(hover.GetPixel(2, 20), hover.GetPixel(0, 20)) >= 3); - } - button.ExitHover(); - for (int i = 0; i < 40; i++) - { - Application.DoEvents(); - using var frame = new Bitmap(button.Width, button.Height); - button.DrawToBitmap(frame, button.ClientRectangle); - Assert.True(neutralBack.ToArgb() == frame.GetPixel(25, 20).ToArgb(), $"frame={i}; expected={neutralBack}; actual={frame.GetPixel(25, 20)}; back={button.BackColor}; fore={button.ForeColor}; active={form.ActiveControl?.GetType().Name}; default={button.NativeDefault}"); - Assert.Equal(neutralBorder.ToArgb(), frame.GetPixel(2, 20).ToArgb()); - CheckNeutralRendering(button, isDefault); - if (isDefault) - { - Assert.True(Contrast(frame.GetPixel(2, 20), frame.GetPixel(0, 20)) >= 3); - } - Assert.Equal(size, button.Size); - Assert.Equal(padding, button.Padding); - Assert.Equal(handle, button.Handle); - Assert.False(button.Focused); - Settle(16); - } - lifetime.Cancel(); - other.Close(); - } - catch (Exception ex) - { - frameFailure = ex; - } - finally - { - form.Close(); - } - }; - Application.Run(form); - if (frameFailure != null) - { - ExceptionDispatchInfo.Capture(frameFailure).Throw(); + catch (Exception ex) { failure = ex; } + finally { scene.Form.Close(); } + }; + Application.Run(scene.Form); } + catch (Exception ex) { failure = ex; } }); - - static void Settle(int milliseconds) - { - long start = Environment.TickCount64; - do - { - Application.DoEvents(); - Thread.Sleep(1); - } while (Environment.TickCount64 - start < milliseconds); - } + thread.SetApartmentState(ApartmentState.STA); thread.Start(); thread.Join(); + if (failure is not null) { ExceptionDispatchInfo.Capture(failure).Throw(); } } - /// - /// 以 WCAG 相對亮度檢查實際文字與背景的對比,不以色彩名稱推測可讀性。 - /// - private static double Contrast(Color background, Color foreground) - { - static double Linear(byte component) - { - double value = component / 255.0; - return value <= 0.04045 ? value / 12.92 : Math.Pow((value + 0.055) / 1.055, 2.4); - } - static double Luminance(Color color) => - 0.2126 * Linear(color.R) + 0.7152 * Linear(color.G) + 0.0722 * Linear(color.B); - double back = Luminance(background); - double fore = Luminance(foreground); - return (Math.Max(back, fore) + 0.05) / (Math.Min(back, fore) + 0.05); - } - /// - /// 將 WinForms 驗證隔離於 STA,並將背景執行緒的實際失敗傳回測試執行緒。 - /// - private static void RunSta(Action action) + private sealed class Scene : IDisposable { - Exception? failure = null; - var thread = new Thread(() => + internal Form Form { get; } = new() { ClientSize = new Size(410, 250), StartPosition = FormStartPosition.Manual, Location = new Point(10, 10), TopMost = true }; + internal TextBox Input { get; } = new() { Bounds = new Rectangle(10, 195, 280, 30) }; + internal ProbeButton Button { get; } = new() { Text = "Button text", Bounds = new Rectangle(10, 50, 370, 120), Padding = new Padding(7) }; + internal Font Regular { get; } = new("Segoe UI", 18); + internal Font Bold { get; } = new("Segoe UI", 18, FontStyle.Bold); + internal CancellationTokenSource Lifetime { get; } = new(); + internal Scene(bool isDefault) { - try - { - action(); - } - catch (Exception ex) - { - failure = ex; - } - }); - thread.SetApartmentState(ApartmentState.STA); - thread.Start(); - thread.Join(); - if (failure != null) - { - ExceptionDispatchInfo.Capture(failure).Throw(); + Button.Font = Regular; Form.Controls.AddRange([Input, Button]); + if (Environment.GetEnvironmentVariable("INPUTBOX_BUTTON_TEST_96DPI") == "1") { Assert.Equal(96, Button.DeviceDpi); } + Button.AttachEyeTrackerFeedback("Button", Regular, Bold, Lifetime.Token); + if (isDefault) { Form.AcceptButton = Button; } + if (Form.Bounds.Contains(Cursor.Position)) { Form.Location = new Point(30, 450); } } + public void Dispose() { Lifetime.Cancel(); Form.Dispose(); Lifetime.Dispose(); Regular.Dispose(); Bold.Dispose(); } } - /// - /// 僅在測試控制項本身觸發事件,不向任何其他視窗模擬輸入。 - /// - private sealed class FeedbackButton : InputBox.Core.Controls.FeedbackButton + private sealed class ProbeButton : InputBox.Core.Controls.FeedbackButton { - public VisualStylesMode ResolvedMode => EffectiveVisualStylesMode; - public bool NativeDefault => IsDefault; - public void Hover() - { - // 僅驗證繪製:不依賴 Windows 是否允許測試主機搶到前景。 - object table = typeof(ButtonEyeTrackerExtensions).GetField("_buttonStates", BindingFlags.Static | BindingFlags.NonPublic)!.GetValue(null)!; - object?[] args = [this, null]; - table.GetType().GetMethod("TryGetValue")!.Invoke(table, args); - object state = args[1]!; - state.GetType().GetProperty("IsHovered")!.SetValue(state, true); - typeof(ButtonEyeTrackerExtensions).GetMethod("StartAnimationFeedback", BindingFlags.Static | BindingFlags.NonPublic)!.Invoke(null, [this]); - } - public void SetProgress(float progress) - { - object table = typeof(ButtonEyeTrackerExtensions).GetField("_buttonStates", BindingFlags.Static | BindingFlags.NonPublic)!.GetValue(null)!; - object?[] args = [this, null]; - table.GetType().GetMethod("TryGetValue")!.Invoke(table, args); - args[1]!.GetType().GetProperty("DwellProgress")!.SetValue(args[1], progress); - } - public void PressSpace() => OnKeyDown(new KeyEventArgs(Keys.Space)); - public void ReleaseSpace() => OnKeyUp(new KeyEventArgs(Keys.Space)); - public void RefreshSystemColors() => OnSystemColorsChanged(EventArgs.Empty); - public void Press() => OnMouseDown(new MouseEventArgs(MouseButtons.Left, 1, 0, 0, 0)); - public void EnterHover() => OnMouseEnter(EventArgs.Empty); - public void ExitHover() => OnMouseLeave(EventArgs.Empty); + internal VisualStylesMode ResolvedMode => EffectiveVisualStylesMode; + internal void EnterHover() => OnMouseEnter(EventArgs.Empty); + internal void ExitHover() => OnMouseLeave(EventArgs.Empty); + internal void PressMouse() => OnMouseDown(new MouseEventArgs(MouseButtons.Left, 1, 30, 30, 0)); + internal void ReleaseMouse() => OnMouseUp(new MouseEventArgs(MouseButtons.Left, 1, 30, 30, 0)); + internal void PressSpace() => OnKeyDown(new KeyEventArgs(Keys.Space)); + internal void ReleaseSpace() => OnKeyUp(new KeyEventArgs(Keys.Space)); + internal void RefreshSystemColors() => OnSystemColorsChanged(EventArgs.Empty); } -} \ No newline at end of file +} diff --git a/tests/InputBox.Tests/README.md b/tests/InputBox.Tests/README.md index b6112f03..eb9df0b9 100644 --- a/tests/InputBox.Tests/README.md +++ b/tests/InputBox.Tests/README.md @@ -50,9 +50,9 @@ | `TextBoxSelectionExtensionsTests` | 右搖桿延伸選取共用的 `ResolveSelectionAnchor` 錨點解析(無選取、正向、反向、錨點失效)與 `GetWordJumpTarget` 單字跳轉目標(不改變目前選取、方向與邊界);原本三處複本集中後的一致性保護 | 6 | | `VibrationPatternsTests` | `VibrationPatterns` 與方向性震動設定、語意情境解析、能力感知的多段式微震動序列,以及歷程滾輪阻尼感、字數上限硬牆、震動強度預覽、右搖桿選取粒度、組合鍵進入提示與喚起握手回饋的回歸保護 | 37 | | `VibrationSafetyLimiterTests` | `VibrationSafetyLimiter` 熱保護、Duty Cycle 限制器與極端邊界保護;馬達數量熱成本倍率正規化,以及所有內建震動模式在冷啟動下不得被拒絕、單次超出預算改為降強度,以及Critical 自動連發(含不同模式交錯)降級、熱負載不失控,以及冷啟動短序列仍完整送出的回歸保護 | 20 | -| `ButtonFeedbackRenderingTests` | Latest 預設/一般按鈕實際文字與背景、焦點/預設動作同步及對比襯底、四種底色進度條與色覺紋理、粗體、按下亮度差、零抖動與配色還原、焦點懸停組合、Space 按放/失焦、空文字反例與 Dwell 交接逐幀對比 | 27 | +| `ButtonFeedbackRenderingTests` | Standard/Latest 原生色彩、焦點與高對比按壓、Dwell 可見襯底與全進度、Space/滑鼠交錯、Capture 取消、生命週期、字型更新、過期點擊接合、三主題過渡、七語系/RTL | 72 | | `BlinkFrameRenderingTests` | 實際螢幕非客戶區像素:Blink 完成/取消、有/無焦點還原;HWND、選取範圍及尺寸不變 | 4 | -| **合計** | | **498** | +| **合計** | | **543** | ## 二、執行方式 🚀 @@ -179,7 +179,7 @@ UI 測試宿主在啟動 UIA 前使用 Application.SetHighDpiMode(PerMonitorV2) 合規查核(2026-11-14):以可執行 JavaScript 的官方頁面確認 FFXIV 使用者合約、USERJOY 使用條款與隱私政策,並讀取第三方授權及免責聲明。此次輸入相關來源僅清理多餘初值、索引與必要回呼參數名稱,保持既有剪貼簿輸出邊界與控制器行為。 -## .NET 11 Latest 按鈕配色回歸(2026-11-14) +## 歷史:.NET 11 Latest 按鈕配色回歸(2026-11-14,Standard 整合前) `ButtonFeedbackRenderingTests` 是需 `INPUTBOX_RUN_UI_TESTS=1` 才執行的 27 項 UI 測試。它以實際點陣圖檢查預設/一般按鈕的焦點、懸停、按下背景、文字及焦點邊框,並檢查文字對比至少 4.5:1、尺寸/內距不變,以及回饋結束後的一般/停用外觀。停用狀態只檢查文字仍可辨識,不套用一般可操作文字的 4.5:1 門檻。 @@ -215,3 +215,29 @@ Dwell/Latest 交接:所有共用回饋按鈕改用 FeedbackButton,在還 新增四組逐幀測試:預設/一般 Flat 按鈕 × 啟用/未啟用視窗。每組檢查 25 個懸停樣本及還原後 40 個樣本(約每 16ms),以實際渲染文字、背景及提示邊框驗證文字至少 4.5:1、互動提示至少 3:1;還原首幀即須符合原生穩定底色與提示邊框,並保留尺寸、Padding、HWND 與按鈕焦點狀態。測試明確驗證視窗啟用狀態,因此需在可顯示視窗的測試程序執行;不能以未取得前景的執行結果宣稱啟用情境通過。 最終驗證:完整非 UI 456/456、UI 42/42;淺色、深色及實際 Windows 高對比各 27/27;暫時略過原生快取重設時,新增四組逐幀測試均失敗,恢復修正後通過。高對比設定已還原。Release -warnaserror 建置 0 警告/0 錯誤;所有修改 C# 的 severity info style/analyzers 報告均為空。 + +## Standard/Latest 正式整合(2026-11-15) + +`ButtonFeedbackRenderingTests` 現有 72 項需 `INPUTBOX_RUN_UI_TESTS=1` 的 UI 測試。一般/懸停/停用沿用原生 Standard,焦點、按壓、情境預設動作與 Dwell 使用必要疊層,不將系統強調色假設成藍色,不寫入 BackColor/ForeColor。按鈕沿用全域 Latest;高對比自動解析為 Classic。既有 Blink 還原及主題重啟提示保留。 + +Dwell 在 100% 時保留四邊可見襯底;測試直接量測實際填色像素與相鄰襯底,至少 3:1。淺色 Green/#DCDCDC 約 3.746:1,深色 LimeGreen/#3C3C3C 約 5.208:1;高對比配對 HighlightText/Highlight。文字採空/有/空三次繪圖排除裝飾,以主要墨色驗證一般文字 ≥4.5:1。停用不使用可操作文字的門檻,但需可辨識;空文字必須被檢查拒絕。 + +高對比焦點與按壓交換系統色對,並在按壓增加固定內框。深色琥珀色按壓保留 Tritanopia ΔL*≥13。進度、提示及字體切換不改變尺寸、Margin、Padding 或 HWND。 + +回歸另外覆蓋視窗啟用/未啟用、預設/一般、逐幀懸停進出、Space 與滑鼠交錯、真正先取得 Capture 再取消、取消與表單權杖、設定/系統色更新保留進度,以及舊點擊接合不得覆蓋新互動。DPI 字型更新透過保留狀態的設定入口同步 Regular/Bold;七語系與 RTL 檢查渲染文字及 Padding。 + +UI 程序必須可顯示自家視窗;測試以有界重試確認實際前景狀態,未取得前景不能宣稱啟用情境通過。測試只對 InputBox 自家控制項觸發鉤點,不向第三方視窗送出輸入。 + +即時安全邊界查核:已讀取工程規範列出的五個官方網址;FFXIV 合約及 USERJOY 使用條款/隱私頁面只回傳框架,未取得完整條款本文。本次限定自家視覺回饋與原生按鈕事件傳遞,不改變核心剪貼簿輸出、控制器映射、第三方輸入或前景恢復;不宣稱完成完整條款合規審查。 + +本輪正式整合驗證(實際 125%/120 DPI):淺色、深色與 Windows 高對比各 52/52;完整 UI 67/67,非 UI 重跑 456/456,皆無略過。Release -warnaserror 建置為 0 警告/0 錯誤,修改 C# 的 severity info style/analyzers 報告皆為空;git diff --check 及 UTF-8 BOM/CRLF 檢查通過。高對比設定已讀回確認還原為原值 126。原生強調色由渲染器決定,本輪未切換其他系統強調色或其他實際 DPI,不將目前色彩宣稱為 Latest 固定配色。 + +非 UI 首輪 455/456:既有 WriteConfigToFile_ConcurrentWrites_LeavesValidJsonAndNoTempFiles 偶發看到暫存檔。測試使用每行程新的隔離目錄,不能歸因於舊工作區產物;未修改設定持久化程式碼。完整重跑 456/456,該案例另以三個獨立程序連續重驗皆通過,首次原因尚未確定。保留首輪與重驗日誌於 TestResults/StandardIntegration,後續若重現須調查檔案刪除或並行寫入時序,不以重試掩蓋持續失敗。 + +PR #95 的 GitHub Runner 為 100%/96 DPI,Dwell 襯底只有 1px;舊測試從 (inset+1, top+1) 取樣時已進入填色,導致四項假失敗。正式繪圖無需修改,測試改從實際四邊襯底取樣;另可用 INPUTBOX_BUTTON_TEST_96DPI=1 啟動 DPI-unaware 的隔離按鈕測試程序,明確驗證 DeviceDpi=96 並重現 Runner 幾何條件。此為 96 DPI 渲染驗證,不代表已切換實際顯示器縮放。 + +修正驗證:96 DPI 隔離按鈕完整 52/52;淺色 120 DPI、深色 96/120 DPI、高對比 96/120 DPI 的 Dwell 各 4/4。搭配完整 96 DPI 淺色測試,共覆蓋三主題與兩種渲染 DPI。建置 0 警告/0 錯誤,資訊層級診斷皆為空,高對比還原原值。 + +PR #95 審查補強:新增 20 項(總數 543,UI 87、非 UI 456)。其中 6 項覆蓋滿格/停用 UI 特效後的生命週期取消、換權杖及 Dispose;14 項依訊息框 AutoSize 與最小尺寸規則量測七語系、預設/一般按鈕,逐像素確認部分與完整 Dwell 不遮住任何標題字形,且尺寸、Padding、Margin 與 HWND 不變。偏好尺寸在初始化量測時固定預留 Dwell 區域,保留原生 Latest 標題置中與動態強調色。 + +審查修正本機驗證:淺色、深色及實際 Windows 高對比各 72/72;96 DPI 隔離渲染 72/72;實際關閉 Windows UI 特效後,滿格取消/換權杖/Dispose 共 6/6,高對比與 UI 特效皆已還原。完整本機 UI 82/87:5 項 FlaUI 選單/對話框操作失敗,失敗截圖顯示本機另有 pinentry 與觸控鍵盤,鍵盤遮住選單下方項目;保留失敗日誌,未略過或改寫這些測試,需以最新提交在乾淨 GitHub Runner 的完整 87 項結果確認。非 UI 另行完整重跑;Release 建置零警告零錯誤,資訊層級診斷報告皆為空。