Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions docs/engineering/a11y-safety.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# A11y 無障礙與視覺安全 (A11y & Visual Safety)

- **數值編輯區尺寸**:保留 Latest 原生樣式,依 `NumericUpDown.PreferredHeight` 在字型、Handle、DPI 與系統色更新後同步高度;不得假設原生渲染器會隨大字型自動增高。寬度依有效範圍的完整格式化數字與原生微調按鈕預留,不在數值或焦點變更時改變尺寸。驗證內部編輯區能容納完整數字字形(非字型行距留白),涵蓋負數、小數、三主題及多 DPI。
- **回饋生命週期**:直接 `Dispose` 與正常關閉都必須解除控制器及系統事件、取消表單權杖;取消關閉則保留資源。已處置的控制項不得再註冊外部權杖、事件或保留呼叫端回呼;共享字型與借用控制器不得由對話框處置。
- **數值框重新啟用**:DPI/主題更新期間若清除焦點配色,對話框重新啟用後須依原生還原完成的實際焦點,同步套用數值框反轉、游標與預設動作提示;不得強制改變焦點或重設輸入內容。

- **廣播與避讓 (Announce)**:
- 廣播前保留 200ms 延遲 (於非 UI 執行緒執行),避開 Audio Ducking。
- 重複訊息末尾交替附加 `\u200B` (ZWSP) 或 `\u200C` (ZWNJ)。
Expand Down
4 changes: 4 additions & 0 deletions src/InputBox/Core/Controls/FeedbackButton.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ public FeedbackButton()
internal void ConfigureFeedback(string description, Font? regular, Font? bold,
Action<bool>? onFocusStateChanged, CancellationToken formToken)
{
if (IsDisposed || Disposing) { return; }
_regular = regular ?? Font;
_bold = bold;
_description = description;
Expand Down Expand Up @@ -95,12 +96,14 @@ public override Size GetPreferredSize(Size proposedSize)
/// <summary>更新呼叫端提供的共享字型,保留描述、回呼與正在進行的互動。</summary>
internal void UpdateFeedbackFonts(Font regular, Font? bold)
{
if (IsDisposed || Disposing) { return; }
_regular = regular;
_bold = bold;
Reconcile();
}
internal void CancelDwell()
{
if (IsDisposed || Disposing) { return; }
++_interactionVersion;
StopDwell();
Reconcile();
Expand All @@ -109,6 +112,7 @@ internal void CancelDwell()
/// <summary>點擊結束後依實際游標重接視線;新的互動會使舊接合失效。</summary>
internal async Task ReGazeAfterClickAsync()
{
if (IsDisposed || Disposing) { return; }
int version = ++_interactionVersion;
StopDwell();
Invalidate();
Expand Down
28 changes: 26 additions & 2 deletions src/InputBox/Core/Controls/GamepadMessageBox.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public IGamepadController? GamepadController
get => _gamepadController;
set
{
if (ReferenceEquals(_gamepadController, value))
if (IsDisposed || Disposing || _cts == null || ReferenceEquals(_gamepadController, value))
{
return;
}
Expand Down Expand Up @@ -722,7 +722,15 @@ protected override void OnFormClosing(FormClosingEventArgs e)
return;
}

ReleaseRuntimeResources();
}

/// <summary>正常關閉及直接處置共用清理;控制器與共享字型不屬於此視窗。</summary>
private void ReleaseRuntimeResources()
{
UnsubscribeGamepadEvents();
_gamepadController = null;
SystemEvents.UserPreferenceChanged -= SystemEvents_UserPreferenceChanged;

Interlocked.Exchange(ref _announcer, null)?.Dispose();

Expand All @@ -740,6 +748,22 @@ protected override void OnFormClosing(FormClosingEventArgs e)
_buttonFlow = null;
}

/// <summary>未顯示或未經 FormClosing 的對話框也必須解除外部訂閱。</summary>
protected override void Dispose(bool disposing)
{
try
{
if (disposing)
{
ReleaseRuntimeResources();
}
}
finally
{
base.Dispose(disposing);
}
}

/// <summary>
/// Handle 銷毀時確保靜態系統事件訂閱被絕對釋放。
/// </summary>
Expand Down Expand Up @@ -1175,4 +1199,4 @@ public static DialogResult Show(
MessageBoxDefaultButton defaultButton = MessageBoxDefaultButton.Button1,
IGamepadController? gamepad = null)
=> Show(null, text, caption, buttons, icon, defaultButton, gamepad);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,47 @@ private sealed class AccessibleNumericUpDown(NumericInputDialog parent) : Numeri
/// </summary>
private readonly NumericInputDialog _parent = parent;

/// <summary>依原生行高及有效範圍預留完整字形,僅在字型、DPI 或系統樣式更新時調整。</summary>
protected override void OnFontChanged(EventArgs e)
{
base.OnFontChanged(e);
UpdateEditorSize();
}

protected override void OnHandleCreated(EventArgs e)
{
base.OnHandleCreated(e);
UpdateEditorSize();
}

protected override void OnDpiChangedAfterParent(EventArgs e)
{
base.OnDpiChangedAfterParent(e);
UpdateEditorSize();
}

protected override void OnSystemColorsChanged(EventArgs e)
{
base.OnSystemColorsChanged(e);
UpdateEditorSize();
}

private void UpdateEditorSize()
{
if (!IsDisposed && !Disposing)
{
string format = $"{(ThousandsSeparator ? 'N' : 'F')}{DecimalPlaces}";
int textWidth = Math.Max(TextRenderer.MeasureText(Minimum.ToString(format), Font).Width,
TextRenderer.MeasureText(Maximum.ToString(format), Font).Width);
int buttonsWidth = Controls.Cast<Control>().Where(control => control is not TextBox)
.Select(control => control.Width).DefaultIfEmpty().Max();
int inset = (int)Math.Ceiling(12 * (DeviceDpi / 96.0f));
MinimumSize = new Size(textWidth + buttonsWidth + inset, 0);
Width = Math.Max((int)Math.Ceiling(220 * (DeviceDpi / 96.0f)), MinimumSize.Width);
Height = PreferredHeight;
}
}

/// <summary>
/// 遞增數值,若已達上限則通知父對話框播放邊界回饋。
/// </summary>
Expand Down
2 changes: 1 addition & 1 deletion src/InputBox/Core/Controls/NumericInputDialog.Gamepad.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public IGamepadController? GamepadController
set
{
// 如果控制器相同,不執行任何操作。
if (ReferenceEquals(_gamepadController, value))
if (IsDisposed || Disposing || _cts == null || ReferenceEquals(_gamepadController, value))
{
return;
}
Expand Down
14 changes: 14 additions & 0 deletions src/InputBox/Core/Controls/NumericInputDialog.Layout.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,19 @@ partial class DesignerBlocker { };
/// </summary>
internal sealed partial class NumericInputDialog
{
protected override void OnActivated(EventArgs e)
{
base.OnActivated(e);
// 等原生焦點還原完成,再重接 DPI/主題更新期間清除的焦點反轉。
this.SafeBeginInvoke(() =>
{
if (ContainsFocus)
{
UpdateFocusVisuals(_nud?.Focused == true || _nud?.ContainsFocus == true);
}
});
}

protected override void OnResizeEnd(EventArgs e)
{
try
Expand Down Expand Up @@ -221,6 +234,7 @@ private void UpdateFocusVisuals(bool isFocused)
{
UpdateCaretWidth();
}
_btnOk?.Invalidate();
}
catch (Exception ex)
{
Expand Down
3 changes: 2 additions & 1 deletion src/InputBox/Core/Controls/NumericInputDialog.cs
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,7 @@ protected override void Dispose(bool disposing)
// 優先解除控制器事件訂閱,確保事件解除先於控制項處置,
// 防止控制器輪詢在 UI 控制項釋放後仍觸發事件。
UnsubscribeGamepadEvents();
_gamepadController = null;

// 處置取消權杖來源(主要任務與 Flash Alert 各自獨立處置)。
Interlocked.Exchange(ref _cts, null)?.CancelAndDispose();
Expand Down Expand Up @@ -420,7 +421,7 @@ public NumericInputDialog(
// 使用 Math.Clamp 確保數值在有效範圍內,防止異常。
Value = Math.Clamp(currentValue, minimum, maximum),
TextAlign = HorizontalAlignment.Center,
// 動態縮放寬度,高度則由 Font 自動決定。
// 動態縮放寬度;AccessibleNumericUpDown 依原生偏好高度同步字型與 DPI。
Width = (int)(220 * scale),
Font = _nudFont,
BackColor = Color.Empty,
Expand Down
63 changes: 53 additions & 10 deletions tests/InputBox.Tests/BlinkFrameRenderingTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,17 @@
using InputBox.Core.Extensions;
using InputBox.Core.Feedback;
using InputBox.Core.Interop;
using InputBox.Core.Services;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using Xunit;

namespace InputBox.Tests;

/// <summary>以實際畫面驗證 Blink 完成/取消後的非客戶區框架,不以重新繪圖的截圖 API 掩蓋殘影。</summary>
[Collection(UiSmokeTestRequirements.CollectionName)]
[Trait("Category", "UI")]
public sealed class BlinkFrameRenderingTests
public sealed partial class BlinkFrameRenderingTests
{
/// <summary>以明確色彩模式建立獨立驗證程序,保留實際 Windows 高對比判斷。</summary>
static BlinkFrameRenderingTests()
Expand Down Expand Up @@ -51,6 +53,10 @@ public void Blink_Finally_RestoresFrameWithoutChangingInputState(bool focused, b
{
try
{
_ = User32.ShowWindow(form.Handle, User32.ShowWindowCommand.Restore);
_ = await WindowFocusService.RestoreWindowAsync(form.Handle, TestContext.Current.CancellationToken);
form.Activate();
Assert.Equal(form.Handle, User32.GetForegroundWindow());
if (focused)
{
Assert.True(input.Focus());
Expand Down Expand Up @@ -102,6 +108,8 @@ await FlashAlertAnimator.RunAsync(form, intensity =>
}
await Task.Delay(500, TestContext.Current.CancellationToken);
using Bitmap after = Capture(input);
SaveCapture(before, $"blink-{focused}-{cancel}-before");
SaveCapture(after, $"blink-{focused}-{cancel}-after");
Assert.True(framePaintedDuringAlert);
Assert.Equal(expectedBack, input.BackColor);
Assert.Equal(expectedFore, input.ForeColor);
Expand Down Expand Up @@ -146,9 +154,16 @@ await FlashAlertAnimator.RunAsync(form, intensity =>
/// <summary>容許螢幕合成的兩階 RGB 量化差;警示殘色仍會產生遠大於此值的差異。</summary>
private static void AssertFramePixel(Color expected, Color actual)
{
Assert.InRange(Math.Abs(expected.R - actual.R), 0, 2);
Assert.InRange(Math.Abs(expected.G - actual.G), 0, 2);
Assert.InRange(Math.Abs(expected.B - actual.B), 0, 2);
Assert.True(Math.Abs(expected.R - actual.R) <= 2 && Math.Abs(expected.G - actual.G) <= 2 &&
Math.Abs(expected.B - actual.B) <= 2, $"Frame pixel expected {expected}, actual {actual}.");
}

private static void SaveCapture(Bitmap image, string name)
{
string? path = Environment.GetEnvironmentVariable("INPUTBOX_BUTTON_ARTIFACTS");
if (path is null) { return; }
Directory.CreateDirectory(path);
image.Save(Path.Combine(path, name + ".png"));
}
/// <summary>依與主視窗相同的還原順序先重設主題,再套用焦點背景與外框。</summary>
private static void Restore(Panel host, TextBox input)
Expand All @@ -167,10 +182,38 @@ private static void Restore(Panel host, TextBox input)
/// <summary>只讀取自家控制項所在的螢幕像素,不透過 DrawToBitmap 觸發額外框架重繪。</summary>
private static Bitmap Capture(Control control)
{
Point origin = control.Parent!.PointToScreen(control.Location);
var bitmap = new Bitmap(control.Width, control.Height);
using Graphics graphics = Graphics.FromImage(bitmap);
graphics.CopyFromScreen(origin, Point.Empty, control.Size);
return bitmap;
Assert.Equal(control.FindForm()!.Handle, User32.GetForegroundWindow());
// Classic/高對比的游標會碰到首列像素;只在擷取期間隱藏並成對還原,
// 避免把游標閃爍的相位差誤當成框架殘色,不重繪或修改框架像素。
bool caretHidden = control.Focused && HideCaret(control.Handle);
try
{
Assert.Equal(0, DwmFlush());
Point origin = control.Parent!.PointToScreen(control.Location);
var bitmap = new Bitmap(control.Width, control.Height);
try
{
using Graphics graphics = Graphics.FromImage(bitmap);
graphics.CopyFromScreen(origin, Point.Empty, control.Size);
AssertFramePixel(control.BackColor, bitmap.GetPixel(bitmap.Width / 2, bitmap.Height / 2));
return bitmap;
}
catch
{
bitmap.Dispose();
throw;
}
}
finally
{
if (caretHidden) { _ = User32.ShowCaret(control.Handle); }
}
}
}

[LibraryImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static partial bool HideCaret(nint window);

[LibraryImport("dwmapi.dll")]
private static partial int DwmFlush();
}
30 changes: 30 additions & 0 deletions tests/InputBox.Tests/FeedbackButtonLifetimeTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
using InputBox.Core.Controls;
using InputBox.Core.Extensions;
using System.Runtime.CompilerServices;
using Xunit;

namespace InputBox.Tests;

public sealed class FeedbackButtonLifetimeTests
{
[Fact]
public void AttachAfterDispose_DoesNotRetainButtonThroughLiveToken()
{
using CancellationTokenSource lifetime = new();
WeakReference reference = CreateDisposedButton(lifetime.Token);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
Assert.False(reference.IsAlive);
GC.KeepAlive(lifetime);
}

[MethodImpl(MethodImplOptions.NoInlining)]
private static WeakReference CreateDisposedButton(CancellationToken token)
{
FeedbackButton button = new();
button.Dispose();
button.AttachEyeTrackerFeedback("disposed", null, null, token);
return new WeakReference(button);
}
}
38 changes: 37 additions & 1 deletion tests/InputBox.Tests/GamepadMessageBoxTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,42 @@ namespace InputBox.Tests;
/// </summary>
public sealed class GamepadMessageBoxTests
{
[Fact]
public void NumericDialog_Dispose_DetachesControllerAndRejectsRebinding()
{
StubGamepadController controller = new();
using NumericInputDialog dialog = new("number", 100, 100, 0, 1, 1, 10000);
dialog.GamepadController = controller;
FieldInfo[] events = [.. typeof(StubGamepadController).GetFields(BindingFlags.Instance | BindingFlags.NonPublic).Where(field => typeof(Delegate).IsAssignableFrom(field.FieldType))];
Assert.Contains(events, field => field.GetValue(controller) != null);

dialog.Dispose();
dialog.GamepadController = controller;

Assert.Null(dialog.GamepadController);
Assert.All(events, field => Assert.Null(field.GetValue(controller)));
}

[Fact]
public void Dispose_WithoutClosing_DetachesControllerAndRejectsRebinding()
{
StubGamepadController controller = new();
using GamepadMessageBox dialog = new("message", "caption", MessageBoxButtons.OK, MessageBoxIcon.None);
dialog.GamepadController = controller;
FieldInfo[] events = [.. typeof(StubGamepadController).GetFields(BindingFlags.Instance | BindingFlags.NonPublic).Where(field => typeof(Delegate).IsAssignableFrom(field.FieldType))];
Assert.Contains(events, field => field.GetValue(controller) != null);
CancellationToken token = ((CancellationTokenSource)typeof(GamepadMessageBox)
.GetField("_cts", BindingFlags.Instance | BindingFlags.NonPublic)!.GetValue(dialog)!).Token;

dialog.Dispose();
dialog.GamepadController = controller;
dialog.Dispose();

Assert.True(token.IsCancellationRequested);
Assert.Null(dialog.GamepadController);
Assert.All(events, field => Assert.Null(field.GetValue(controller)));
}

/// <summary>
/// 測試替身控制器:可指定連線狀態,供對話框初始化提示列與事件綁定驗證使用。
/// </summary>
Expand Down Expand Up @@ -334,4 +370,4 @@ public void GamepadButtons_NintendoMode_SwapsPhysicalConfirmAndCancelBehavior()
AppSettings.Current.GamepadFaceButtonModeType = previousMode;
}
}
}
}
Loading
Loading