diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ba5dfefe..a6621130 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -46,12 +46,18 @@ jobs: - '**/*.props' - '**/*.targets' ui: + - 'global.json' + - 'src/InputBox/InputBox.csproj' + - 'src/InputBox/Program.cs' + - 'tests/InputBox.Tests/InputBox.Tests.csproj' - 'src/InputBox/MainForm*.cs' - 'src/InputBox/MainForm.resx' - 'src/InputBox/Core/Controls/**' - 'src/InputBox/Resources/**' - 'tests/InputBox.Tests/MainFormUiSmokeTests.cs' - 'tests/InputBox.Tests/UiSmokeTestRequirements.cs' + - 'tests/InputBox.Tests/UiVisualSnapshot.cs' + - 'tests/InputBox.Tests/UiWindowDiscovery.cs' build-check: if: needs.changes.outputs.code == 'true' @@ -64,7 +70,7 @@ jobs: # 定義環境變數,方便統一管理。 env: - DOTNET_MAJOR_VERSION: '10' + DOTNET_MAJOR_VERSION: '11' DOTNET_CLI_TELEMETRY_OPTOUT: '1' DOTNET_SKIP_FIRST_TIME_EXPERIENCE: '1' # xUnit v3 MTP 的 coverage 輸出在 bin 輸出目錄的 TestResults 子目錄下。 @@ -140,7 +146,7 @@ jobs: - name: 建置應用程式與測試專案(Build App + Tests) working-directory: ./tests/InputBox.Tests # 測試專案會連同主專案相依一起建置,避免重複編譯浪費資源。 - run: dotnet build InputBox.Tests.csproj -c Release --no-incremental + run: dotnet build InputBox.Tests.csproj -c Release --no-incremental -warnaserror - name: 上傳建置產出(供 ui-smoke 重用) if: needs.changes.outputs.ui == 'true' @@ -215,7 +221,7 @@ jobs: contents: read env: - DOTNET_MAJOR_VERSION: '10' + DOTNET_MAJOR_VERSION: '11' DOTNET_CLI_TELEMETRY_OPTOUT: '1' DOTNET_SKIP_FIRST_TIME_EXPERIENCE: '1' INPUTBOX_RUN_UI_TESTS: '1' diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index fd3f1e3e..05f1e172 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -24,7 +24,7 @@ jobs: # 定義環境變數,方便統一管理。 env: - DOTNET_MAJOR_VERSION: '10' + DOTNET_MAJOR_VERSION: '11' DOTNET_CLI_TELEMETRY_OPTOUT: '1' DOTNET_SKIP_FIRST_TIME_EXPERIENCE: '1' DOTNET_NOLOGO: '1' @@ -582,7 +582,7 @@ jobs: ## 📦 輸入框發佈摘要 - **版本號碼**:`${{ github.ref_name }}` - **目標平台**:Windows x64 - - **執行環境**:.NET 10(已隨附 Runtime,無需額外安裝) + - **執行環境**:.NET 11(已隨附 Runtime,無需額外安裝) - **執行檔案的雜湊值(SHA256)**:`${{ env.SHA256_HASH }}` - **GameInput Redist(選用手動安裝)SHA256**:`${{ env.GAMEINPUT_REDIST_SHA256 }}` diff --git a/README.md b/README.md index 68317edf..bad69ecd 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # 輸入框(InputBox)⌨️ [![Windows 11 22H2 (Build 22621+)](https://img.shields.io/badge/作業系統-Windows%2011%2022H2%20(22621%2B)-003A6D?style=for-the-badge)](https://www.microsoft.com/zh-tw/windows) -[![.NET Runtime](https://img.shields.io/badge/Runtime-.NET%2010-512BD4?logo=dotnet&logoColor=white&style=for-the-badge)](https://dotnet.microsoft.com/zh-tw/download/dotnet/10.0) +[![.NET Runtime](https://img.shields.io/badge/Runtime-.NET%2011-512BD4?logo=dotnet&logoColor=white&style=for-the-badge)](https://dotnet.microsoft.com/zh-tw/download/dotnet/11.0) [![程式語言](https://img.shields.io/badge/程式語言-C%23-1B5E20?style=for-the-badge)](https://learn.microsoft.com/zh-tw/dotnet/csharp/) [![XInput](https://img.shields.io/badge/遊戲控制器輸入%20API-XInput-107C10?style=for-the-badge)](https://learn.microsoft.com/zh-tw/windows/win32/xinput/getting-started-with-xinput) [![GameInput](https://img.shields.io/badge/遊戲控制器輸入%20API-GameInput-A84300?style=for-the-badge)](https://learn.microsoft.com/zh-tw/gaming/gdk/docs/features/common/input/overviews/input-overview) @@ -521,7 +521,7 @@ dotnet publish -c Release -r win-x64 --self-contained true -p:PublishSingleFile= 發佈完成後,編譯好的單一執行檔會生成在以下路徑: ``` -bin\Release\net10.0-windows\publish\win-x64\InputBox.exe +bin\Release\net11.0-windows\publish\win-x64\InputBox.exe ``` ### 2. 使用 Visual Studio 發佈 🚀 diff --git a/docs/engineering/core-engineering.md b/docs/engineering/core-engineering.md index bc1d0345..eeb2db56 100644 --- a/docs/engineering/core-engineering.md +++ b/docs/engineering/core-engineering.md @@ -1,7 +1,7 @@ # 核心工程與架構標準 (Core Engineering) -- **目標框架**:`.NET 10 (net10.0-windows)`。 -- **C# 13 特性**: +- **目標框架**:`.NET 11 (net11.0-windows)`。 +- **C# 15 語言版本(LangVersion=15.0)與既有鎖定規範**: - **執行緒鎖定**:必須使用宣告為 `private readonly Lock _lock = new();` 的專用物件。 - **非同步與 UI 安全 (Threading)**: - **同步與非同步調度**: @@ -22,7 +22,7 @@ - **計算標記**:計算縮放時除數/被除數必須包含 `96.0f` 或 `(float)` 強制轉型,杜絕整數截斷誤差。 - **智慧重定位 (Smart Positioning)**:視窗初始顯示或版面配置擴張時,須執行 `ApplySmartPosition` 螢幕邊界檢查。 - **系統偏好同步**: - - **主題還原**:還原預設配色時應將屬性設為 `Color.Empty`,由 .NET 10 主題引擎自動判斷 (禁:硬式編碼 `SystemColors.Control`)。 + - **主題還原**:還原預設配色時應將屬性設為 `Color.Empty`,由 .NET 11 主題引擎自動判斷 (禁:硬式編碼 `SystemColors.Control`)。 - **程式內重啟與前景恢復**: - **單次啟用標記**:若為本程式主動要求重新啟動,舊執行個體必須先寫入具短時效的一次性啟用標記,供新執行個體在首次顯示時消費;標記必須於讀取後立即清除,避免重複生效。 - **前景授權交接**:由 `RestartProcessLauncher` 自行啟動新執行個體(取代 `Application.Restart()`),並在舊視窗關閉前以 `AllowSetForegroundWindow(新程序 PID)` 只授權該程序搶回前景;不得使用 `ASFW_ANY` 開放給所有程序,僅在無法啟動新程序而退回 `Application.Restart()` 時例外。授權必須在舊視窗仍位於前景時完成,因為控制器操作不會產生 Windows 輸入事件。 @@ -36,3 +36,28 @@ - **`var` 使用原則**:依 [Microsoft C# 編碼慣例](https://learn.microsoft.com/dotnet/csharp/fundamentals/coding-style/coding-conventions#implicitly-typed-local-variables) 與 [.NET Runtime 程式碼風格](https://github.com/dotnet/runtime/blob/main/docs/coding-guidelines/coding-style.md),僅在型別可由右側直接看出(`new`、明確轉型)時使用 `var`,此時亦可使用 target-typed `new()`;內建型別、方法回傳值與 `foreach` 迴圈變數一律使用明確型別,不以方法或變數名稱推測型別;LINQ 匿名型別等必須使用 `var` 的情況除外。對應設定見 `.editorconfig`(IDE0007/IDE0008)。 - **Release 日誌門檻**:正式版預設只寫入 `Warning` 以上;`Info` 僅供 Debug、測試主機或 `INPUTBOX_LOG_LEVEL=Info` 臨時診斷使用。 - **可行動診斷原則**:正常 lifecycle、成功 probe、成功或略過震動、一般輪詢健康資料應維持 `Info`;會影響使用者操作、裝置可用性、API 呼叫失敗或資料修復失敗的訊號才可升級為 `Warning` 或 `Error`。 + +## .NET 11 遷移與主題 + +- SDK 基線由根目錄 global.json 固定為 11.0.100,僅允許同 feature band 的修補更新;主程式、測試與 CI/release 均使用 .NET 11。 +- C# 15 使用正式語言版本;集合需要預設容量時可使用 `[with(capacity: count)]`,保留原有容量與元素語意,不為採用新語法改變輸入/輸出行為。 +- 保留 `Application.SetColorMode(SystemColorMode.System)`、既有高對比與 Color.Empty 配色還原,並在建立視窗前呼叫 `Application.SetDefaultFormRevealMode(FormRevealMode.Deferred)`,避免初次套用深色主題時閃白。 +- 依維護者偏好啟用 `Application.SetDefaultVisualStylesMode(VisualStylesMode.Latest)`,子控制項沿用繼承值。Latest 隨 runtime 解析為最新渲染器,因此 runtime 升級時必須重跑深/淺色、高對比及原生多 DPI UI 矩陣。 +- 發行狀態以 [Microsoft 正式下載頁](https://dotnet.microsoft.com/en-us/download/dotnet/11.0) 與 [支援政策](https://dotnet.microsoft.com/en-us/platform/support/policy) 為準:.NET 11.0.0 已於 2026-11-10 正式發布(GA),正式 SDK 為 11.0.100。[WinForms 功能文件](https://learn.microsoft.com/en-us/dotnet/desktop/winforms/whats-new/net110) 的 RC 1 標題描述該階段的功能資訊,不代表 .NET 11 目前仍為 RC。[C# 15 官方文件](https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-15) 確認 net11.0 預設採用 C# 15,集合建構參數與 union 等正式功能不需 preview。 + +## C# 15 適用性審查(2026-11-14) + +依上述官方版本說明及語言參考,採用能改善現有語意的功能,保留適合的值型別與控制流程。 + +| 新功能 | 目前實作與判斷 | +|---|---| +| 集合建構參數 | SingleInstanceHandoff 容量配置改用 `[with(capacity: commandLineArgs.Count)]`,保留容量及元素行為。其餘集合多已使用 `[]` 或展開語法,沒有需要批次改寫的等價比較器/容量建構式。 | +| union | PhraseService.ImportOutcome/ExportOutcome 的成功旗標、錯誤碼及計數是可重新建模的候選。語言升級本身不要求改變公開回傳型別、預設值、相等性及解構契約;目前保留既有 record 與測試。未來調整 API 時可拆成成功/失敗 case,避免矛盾狀態。 | +| union 的成本與安全 | 生成的 union 使用 object? 儲存,值型別 case 會裝箱,default 內容為 null。採用時應明確處理 null,避免以 `_` 掩蓋未來新增 case。控制器輪詢、NavigationResult、VibrationProfile 及設定快照維持 record struct/enum,不引入額外配置。 | +| closed 階層 | 沒有僅用於 case 分組且需要窮盡比對的 abstract class/record 階層。WinForms 類別及控制器介面具實際共用行為,維持現有契約。 | +| 具標籤 break/continue | 未發現 goto 或布林旗標跨多層迴圈退出的待簡化模式;既有提前 return/continue 已清楚。 | +| 擴充索引子 | 現有 API 使用 List、IReadOnlyList 或陣列,不為一般 IEnumerable 加入隱藏列舉成本的索引子。 | +| 舊 runtime 的非虛擬 static 介面成員 | 只以 net11.0-windows 為目標,沒有此相容性需求。 | +| 記憶體安全 preview | 不啟用 preview 或 updated-memory-safety-rules,保留原生互通既有 unsafe 審查範圍。 | + +取捨依據:[官方 union 參考](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/union)、[官方跳躍語句參考](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/jump-statements)。以上是對目前程式碼的工程評估,並非官方要求所有專案採用新語法。 diff --git a/docs/engineering/gamepad-api.md b/docs/engineering/gamepad-api.md index be519a0c..0e344765 100644 --- a/docs/engineering/gamepad-api.md +++ b/docs/engineering/gamepad-api.md @@ -32,7 +32,7 @@ - **GameInput 同步**:InputBox 仍必須在背景 MTA polling thread 建立、存取與釋放 InputWeave `GameInputClient` / `GameInputDevice` / callback registration;callback 只能設定喚醒或重新整理訊號,不得直接觸發 managed UI 命令。 - **GameInput 診斷 metadata 邊界**:runtime probe、timestamp stale counters、missing reading counters、device unavailable refresh counters 只能進入 log、測試或未來診斷快照,不可直接改變 edge detection、Pause/Resume neutral gate 或任何 UI 命令。 - **GameInput subset 範圍**:目前只實作 InputBox 需要的 Gamepad subset:裝置資訊、VID/PID、timestamp、gamepad button state、rumble、device/reading callbacks,以及 gamepad capabilities / extra control metadata。不得在未重新評估安全與產品需求前擴張到 keyboard、mouse、sensors、raw report、force feedback、aggregate device 或 1:1 GameInput wrapper。 -- **InputWeave callback 互通性**:repo-local `InputWeave.GameInput` 套件的 `IGameInput.Register*Callback` callback 參數必須使用原生 function pointer 路徑;`net10.0-windows` 可透過 `IntPtr`/unmanaged function pointer vtable wrapper 傳遞 callback,`net48` 則必須以 `MarshalAs(UnmanagedType.FunctionPtr)` 宣告。不得以 InputBox 端 aggregate polling fallback 遮蔽 callback marshaling 錯誤;若列舉或 callback 仍失敗,應走既有 GameInput 初始化失敗與 XInput 退避路徑。 +- **InputWeave callback 互通性**:repo-local `InputWeave.GameInput` 套件的 `IGameInput.Register*Callback` callback 參數必須使用原生 function pointer 路徑;`net11.0-windows` 可透過 `IntPtr`/unmanaged function pointer vtable wrapper 傳遞 callback,`net48` 則必須以 `MarshalAs(UnmanagedType.FunctionPtr)` 宣告。不得以 InputBox 端 aggregate polling fallback 遮蔽 callback marshaling 錯誤;若列舉或 callback 仍失敗,應走既有 GameInput 初始化失敗與 XInput 退避路徑。 - **Callback 使用邊界**:GameInput 的 `RegisterDeviceCallback` / `RegisterReadingCallback` 僅可用於要求背景 MTA polling thread 重新整理或喚醒診斷路徑;正式輸入命令仍必須由 60 FPS polling 消費,callback 不得直接觸發 UI、剪貼簿、返回前景或任何輸入動作。 - **GameInput runtime/redist 政策**:`Microsoft.GameInput` NuGet 僅作為官方 SDK、header 與 redist 來源。發佈 ZIP 可隨附 `redist/GameInputRedist.msi` 供使用者手動安裝,但應用程式不得自動執行安裝程式,也不得要求一般啟動流程取得系統管理員權限。 - **Auto 模式解析優先序**:當使用者選擇 Face 鍵 `Auto` 模式且目前提供者為 **GameInput** 時,必須先使用較穩定的硬體識別資訊(例如 VID/PID、產品家族名稱)判斷裝置類型,再退回裝置名稱關鍵字比對;像 `Wireless`、`Bluetooth`、`Adapter`、`Receiver` 等連線詞應視為雜訊而忽略。 diff --git a/docs/engineering/localization.md b/docs/engineering/localization.md index 3f9cbc2f..9c0909f9 100644 --- a/docs/engineering/localization.md +++ b/docs/engineering/localization.md @@ -14,3 +14,5 @@ - 允許在 Designer 中硬式編碼正體中文以供預覽。 - 執行階段必須透過 `ApplyLocalization` 再次賦值以確保多語系正確性。 - 嚴禁手動修改 `MainForm.Designer.cs` 中自動生成的版面配置結構。 + +- **Xbox 模式術語**:Windows 的 Xbox 使用模式統一為「Xbox 模式」(zh-Hant/zh-Hans)、Xbox mode(en)、Xbox-Modus(de)、mode Xbox(fr)、Xbox モード(ja)、Xbox 모드(ko)。此術語適用於應用程式、文件與網站;控制器主按鍵配置中的 Xbox 名稱維持不變。 diff --git a/docs/engineering/testing.md b/docs/engineering/testing.md index 268b2024..de158e37 100644 --- a/docs/engineering/testing.md +++ b/docs/engineering/testing.md @@ -4,7 +4,7 @@ - **框架**:[xUnit v3](https://xunit.net/)(選用理由:每個 `[Fact]` 獨立實例化、`IDisposable` 自動呼叫、語法精簡)。 - **測試專案路徑**:`tests/InputBox.Tests/InputBox.Tests.csproj` -- **目標框架**:`net10.0-windows`(與主專案一致,僅支援 Windows)。 +- **目標框架**:`net11.0-windows`(與主專案一致,僅支援 Windows)。 - **InternalsVisibleTo**:主專案透過 `` 授予測試專案存取 `internal` 類別的權限,無需建立手動的 `AssemblyInfo.cs`。 ## 2. 執行測試 diff --git a/global.json b/global.json index 3140116d..1890855c 100644 --- a/global.json +++ b/global.json @@ -1,4 +1,9 @@ { + "sdk": { + "version": "11.0.100", + "rollForward": "latestPatch", + "allowPrerelease": false + }, "test": { "runner": "Microsoft.Testing.Platform" } diff --git a/src/InputBox/Core/Input/GameInputGamepadController.cs b/src/InputBox/Core/Input/GameInputGamepadController.cs index 410c1e0a..4e5c964e 100644 --- a/src/InputBox/Core/Input/GameInputGamepadController.cs +++ b/src/InputBox/Core/Input/GameInputGamepadController.cs @@ -2097,8 +2097,8 @@ private void StartDeviceDiscovery(int pollingGeneration = 0) /// 目前輪詢迴圈的世代編號。 private void CheckAndApplyDiscoveryResults(int pollingGeneration = 0) { - Task>? task = null; - long capturedVersion = 0; + Task>? task; + long capturedVersion; lock (_discoveryLock) { diff --git a/src/InputBox/Core/Interop/DllResolver.cs b/src/InputBox/Core/Interop/DllResolver.cs index b2ef0925..5024c1d4 100644 --- a/src/InputBox/Core/Interop/DllResolver.cs +++ b/src/InputBox/Core/Interop/DllResolver.cs @@ -22,13 +22,13 @@ internal class DllResolver /// 自訂的 native 載入解析器,用於覆寫 XInput 的載入邏輯。 /// /// 開啟端要求載入的 DLL 名稱 - /// 觸發載入的組件。 - /// DllImportSearchPath 設定。 + /// 觸發載入的組件。 + /// DllImportSearchPath 設定。 /// 成功載入時回傳 DLL handle;若無法載入或名稱不符則回傳 IntPtr.Zero。 public static nint ResolveNativeLibrary( string libraryName, - Assembly assembly, - DllImportSearchPath? searchPath) + Assembly _1, + DllImportSearchPath? _2) { // 僅攔截 xinput1_4.dll,其餘 DLL 交由系統處理。 if (!libraryName.Equals("xinput1_4.dll", StringComparison.OrdinalIgnoreCase)) diff --git a/src/InputBox/Core/Services/SingleInstanceHandoff.cs b/src/InputBox/Core/Services/SingleInstanceHandoff.cs index b967f1d6..74f912c5 100644 --- a/src/InputBox/Core/Services/SingleInstanceHandoff.cs +++ b/src/InputBox/Core/Services/SingleInstanceHandoff.cs @@ -116,7 +116,7 @@ public static IReadOnlyList RemoveHandoffArguments(IReadOnlyList { ArgumentNullException.ThrowIfNull(commandLineArgs); - List result = new(commandLineArgs.Count); + List result = [with(capacity: commandLineArgs.Count)]; for (int i = 0; i < commandLineArgs.Count; i++) { diff --git a/src/InputBox/InputBox.csproj b/src/InputBox/InputBox.csproj index 8d95b176..80d47cf0 100644 --- a/src/InputBox/InputBox.csproj +++ b/src/InputBox/InputBox.csproj @@ -2,7 +2,8 @@ WinExe - net10.0-windows + net11.0-windows + 15.0 true enable true diff --git a/src/InputBox/MainForm.Gamepad.cs b/src/InputBox/MainForm.Gamepad.cs index 7fdfaa6f..fb85f304 100644 --- a/src/InputBox/MainForm.Gamepad.cs +++ b/src/InputBox/MainForm.Gamepad.cs @@ -2141,7 +2141,7 @@ private void PushUndoSnapshot() // 與上一份快照相同,不重複儲存。 if (_undoStack.Count > 0 && - _undoStack[_undoStack.Count - 1] == current) + _undoStack[^1] == current) { return; } @@ -2166,7 +2166,7 @@ private void HandleUndoAction() // 優先使用快照堆疊(覆蓋 B 清空、歷程導覽等程式賦值後的還原)。 if (_undoStack.Count > 0) { - string previous = _undoStack[_undoStack.Count - 1]; + string previous = _undoStack[^1]; _undoStack.RemoveAt(_undoStack.Count - 1); diff --git a/src/InputBox/Program.cs b/src/InputBox/Program.cs index b48b373f..7bfba0b1 100644 --- a/src/InputBox/Program.cs +++ b/src/InputBox/Program.cs @@ -200,7 +200,10 @@ static void Main() // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); + Application.SetDefaultVisualStylesMode(VisualStylesMode.Latest); Application.SetColorMode(SystemColorMode.System); + // 等待初次版面與主題套用完成,避免深色模式啟動時閃白。 + Application.SetDefaultFormRevealMode(FormRevealMode.Deferred); // 載入設定檔(若無檔案會自動建立)。 AppSettings.Load(); diff --git a/tests/InputBox.Tests/AnnouncementServiceTests.cs b/tests/InputBox.Tests/AnnouncementServiceTests.cs index 9f0190e0..a31606ba 100644 --- a/tests/InputBox.Tests/AnnouncementServiceTests.cs +++ b/tests/InputBox.Tests/AnnouncementServiceTests.cs @@ -102,7 +102,7 @@ public void Dispose_CalledMultipleTimes_DoesNotThrow() { _svc = new AnnouncementService(async (_, _, _) => await Task.CompletedTask); - var capturedException = Record.Exception(() => + Exception? capturedException = Record.Exception(() => { _svc.Dispose(); _svc.Dispose(); diff --git a/tests/InputBox.Tests/DialogLayoutHelperTests.cs b/tests/InputBox.Tests/DialogLayoutHelperTests.cs index 3080ed96..0d28be76 100644 --- a/tests/InputBox.Tests/DialogLayoutHelperTests.cs +++ b/tests/InputBox.Tests/DialogLayoutHelperTests.cs @@ -83,7 +83,7 @@ public void TryBeginDpiLayout_DpiDecreased_ReturnsTrueAndUpdatesCache() public void GetMaxFitSize_NormalWorkArea_ReturnsWidthAndHeightMinusMargin() { Rectangle workArea = new(0, 0, 1920, 1080); - var (w, h) = DialogLayoutHelper.GetMaxFitSize(workArea, margin: 40); + (int w, int h) = DialogLayoutHelper.GetMaxFitSize(workArea, margin: 40); Assert.Equal(1880, w); Assert.Equal(1040, h); @@ -96,7 +96,7 @@ public void GetMaxFitSize_NormalWorkArea_ReturnsWidthAndHeightMinusMargin() public void GetMaxFitSize_DefaultMargin_Is40() { Rectangle workArea = new(0, 0, 800, 600); - var (w, h) = DialogLayoutHelper.GetMaxFitSize(workArea); + (int w, int h) = DialogLayoutHelper.GetMaxFitSize(workArea); Assert.Equal(760, w); Assert.Equal(560, h); @@ -109,7 +109,7 @@ public void GetMaxFitSize_DefaultMargin_Is40() public void GetMaxFitSize_WorkAreaSmallerThanMargin_ReturnsAtLeastOne() { Rectangle workArea = new(0, 0, 30, 30); - var (w, h) = DialogLayoutHelper.GetMaxFitSize(workArea, margin: 40); + (int w, int h) = DialogLayoutHelper.GetMaxFitSize(workArea, margin: 40); Assert.Equal(1, w); Assert.Equal(1, h); @@ -122,7 +122,7 @@ public void GetMaxFitSize_WorkAreaSmallerThanMargin_ReturnsAtLeastOne() public void GetMaxFitSize_ZeroMargin_ReturnsExactWorkAreaSize() { Rectangle workArea = new(0, 0, 1280, 720); - var (w, h) = DialogLayoutHelper.GetMaxFitSize(workArea, margin: 0); + (int w, int h) = DialogLayoutHelper.GetMaxFitSize(workArea, margin: 0); Assert.Equal(1280, w); Assert.Equal(720, h); diff --git a/tests/InputBox.Tests/GamepadControllerFactoryTests.cs b/tests/InputBox.Tests/GamepadControllerFactoryTests.cs index 57643206..dcecf1d8 100644 --- a/tests/InputBox.Tests/GamepadControllerFactoryTests.cs +++ b/tests/InputBox.Tests/GamepadControllerFactoryTests.cs @@ -97,14 +97,9 @@ public void Dispose() /// /// 測試用控制器替身。 /// - private sealed class StubGamepadController : IGamepadController + private sealed class StubGamepadController(string deviceName) : IGamepadController { - public StubGamepadController(string deviceName) - { - DeviceName = deviceName; - } - - public string DeviceName { get; } + public string DeviceName { get; } = deviceName; public string DeviceIdentity => DeviceName; diff --git a/tests/InputBox.Tests/GamepadRepeatSettingsTests.cs b/tests/InputBox.Tests/GamepadRepeatSettingsTests.cs index 1630ec63..22d079c7 100644 --- a/tests/InputBox.Tests/GamepadRepeatSettingsTests.cs +++ b/tests/InputBox.Tests/GamepadRepeatSettingsTests.cs @@ -30,7 +30,7 @@ public void Validate_DefaultSettings_DoesNotThrow() { var settings = new GamepadRepeatSettings(); - var capturedException = Record.Exception(settings.Validate); + Exception? capturedException = Record.Exception(settings.Validate); Assert.Null(capturedException); } @@ -93,7 +93,7 @@ public void Validate_BothPositive_DoesNotThrow() IntervalFrames = 1 }; - var capturedException = Record.Exception(settings.Validate); + Exception? capturedException = Record.Exception(settings.Validate); Assert.Null(capturedException); } diff --git a/tests/InputBox.Tests/InputBox.Tests.csproj b/tests/InputBox.Tests/InputBox.Tests.csproj index 1595c826..0e793eb4 100644 --- a/tests/InputBox.Tests/InputBox.Tests.csproj +++ b/tests/InputBox.Tests/InputBox.Tests.csproj @@ -1,7 +1,8 @@ - net10.0-windows + net11.0-windows + 15.0 true enable enable diff --git a/tests/InputBox.Tests/InputHistoryServiceTests.cs b/tests/InputBox.Tests/InputHistoryServiceTests.cs index aab124aa..d39df9fd 100644 --- a/tests/InputBox.Tests/InputHistoryServiceTests.cs +++ b/tests/InputBox.Tests/InputHistoryServiceTests.cs @@ -19,7 +19,7 @@ public void Add_EmptyString_DoesNotAdd() var svc = new InputHistoryService(); svc.Add(string.Empty); - var result = svc.Navigate(-1); + InputHistoryService.NavigationResult result = svc.Navigate(-1); Assert.False(result.Success); Assert.Equal(0, result.TotalCount); @@ -37,7 +37,7 @@ public void Add_PrivacyMode_DoesNotAdd() }; svc.Add("secret"); - var result = svc.Navigate(-1); + InputHistoryService.NavigationResult result = svc.Navigate(-1); Assert.Equal(0, result.TotalCount); } @@ -84,7 +84,7 @@ public void Add_ExceedsMaxHistory_TrimsOldest() // 一路向上導覽,追蹤最後一個成功結果(撞牆時 Text 為 null) InputHistoryService.NavigationResult last = default; - var result = svc.Navigate(-1); + InputHistoryService.NavigationResult result = svc.Navigate(-1); while (!result.IsBoundaryHit) { last = result; @@ -109,7 +109,7 @@ public void NavigatePage_Up_JumpsSpecifiedCount() svc.Add($"item-{i}"); } - var result = svc.NavigatePage(-1, 5); + InputHistoryService.NavigationResult result = svc.NavigatePage(-1, 5); Assert.True(result.Success); Assert.Equal("item-4", result.Text); @@ -132,7 +132,7 @@ public void NavigatePage_Down_PastNewest_ClearsInput() _ = svc.NavigatePage(-1, 5); - var result = svc.NavigatePage(1, 5); + InputHistoryService.NavigationResult result = svc.NavigatePage(1, 5); Assert.True(result.Success); Assert.True(result.IsCleared); @@ -149,7 +149,7 @@ public void NavigatePage_Down_PastNewest_ClearsInput() public void Navigate_EmptyHistory_ReturnsBoundaryHit() { var svc = new InputHistoryService(); - var result = svc.Navigate(-1); + InputHistoryService.NavigationResult result = svc.Navigate(-1); Assert.False(result.Success); Assert.True(result.IsBoundaryHit); @@ -168,7 +168,7 @@ public void Navigate_Up_FirstMove_ReturnsNewest() svc.Add("older"); svc.Add("newer"); - var result = svc.Navigate(-1); + InputHistoryService.NavigationResult result = svc.Navigate(-1); Assert.True(result.Success); Assert.Equal("newer", result.Text); @@ -187,7 +187,7 @@ public void Navigate_Up_PastOldest_StaysAtOldest() svc.Navigate(-1); // b (index 0) svc.Navigate(-1); // a (index 1) - var result = svc.Navigate(-1); // 已在最舊,撞牆 + InputHistoryService.NavigationResult result = svc.Navigate(-1); // 已在最舊,撞牆 Assert.False(result.Success); Assert.True(result.IsBoundaryHit); @@ -207,7 +207,7 @@ public void Navigate_Down_FromOldest_ReturnsNewer() svc.Navigate(-1); // b svc.Navigate(-1); // a(最舊) - var result = svc.Navigate(1); // 回到 b + InputHistoryService.NavigationResult result = svc.Navigate(1); // 回到 b Assert.True(result.Success); Assert.Equal("b", result.Text); @@ -223,7 +223,7 @@ public void Navigate_Down_FromNewest_ReturnsIsCleared() svc.Add("hello"); svc.Navigate(-1); // hello - var result = svc.Navigate(1); // 回到空白 + InputHistoryService.NavigationResult result = svc.Navigate(1); // 回到空白 Assert.True(result.Success); Assert.True(result.IsCleared); @@ -241,7 +241,7 @@ public void Navigate_Down_AtBottom_ReturnsBoundaryHit() svc.Add("hello"); // 不先向上,直接向下(已在底部) - var result = svc.Navigate(1); + InputHistoryService.NavigationResult result = svc.Navigate(1); Assert.False(result.Success); Assert.True(result.IsBoundaryHit); @@ -262,7 +262,7 @@ public void Clear_ResetsHistoryAndIndex() svc.Clear(); - var result = svc.Navigate(-1); + InputHistoryService.NavigationResult result = svc.Navigate(-1); Assert.Equal(0, result.TotalCount); } @@ -280,7 +280,7 @@ public void ResetIndex_AllowsNavigationFromStart() svc.Navigate(-1); // a svc.ResetIndex(); // 重置 - var result = svc.Navigate(-1); // 應再次從 b 開始 + InputHistoryService.NavigationResult result = svc.Navigate(-1); // 應再次從 b 開始 Assert.True(result.Success); Assert.Equal("b", result.Text); diff --git a/tests/InputBox.Tests/MainFormUiSmokeTests.cs b/tests/InputBox.Tests/MainFormUiSmokeTests.cs index 8a004bdc..f13a4618 100644 --- a/tests/InputBox.Tests/MainFormUiSmokeTests.cs +++ b/tests/InputBox.Tests/MainFormUiSmokeTests.cs @@ -43,6 +43,17 @@ public sealed class MainFormUiSmokeTests : IDisposable /// private string _lastUiStep = "UI smoke test initialized."; + /// + /// UIA 與螢幕擷取必須使用實體座標,避免非 100% 縮放時滑鼠位置與圖片裁切失準。 + /// + static MainFormUiSmokeTests() + { + if (UiSmokeTestRequirements.IsEnabled) + { + Application.SetHighDpiMode(HighDpiMode.PerMonitorV2); + } + } + /// /// 建構子:在符合前置條件時啟動受測 WinForms 應用程式。 /// @@ -59,7 +70,16 @@ public MainFormUiSmokeTests() _application = FlaUiApplication.Launch(applicationPath); _automation = new UIA3Automation(); - _mainWindow = WaitForMainWindow(_application, _automation); + try + { + _mainWindow = WaitForMainWindow(_application, _automation); + } + catch + { + _application.Kill(); + _automation.Dispose(); + throw; + } } /// @@ -73,7 +93,7 @@ public MainFormUiSmokeTests() [Trait("Category", "UI")] public void Launch_ShowsPrimaryControls() { - RunWithFailureArtifacts(nameof(Launch_ShowsPrimaryControls), TestContext.Current.CancellationToken, () => + RunWithFailureArtifacts(nameof(Launch_ShowsPrimaryControls), cancellationToken: TestContext.Current.CancellationToken, testAction: () => { Assert.NotNull(_mainWindow); @@ -84,6 +104,7 @@ public void Launch_ShowsPrimaryControls() Assert.False(string.IsNullOrWhiteSpace(_mainWindow.Title)); Assert.True(inputTextBox.IsEnabled); Assert.True(copyButton.IsEnabled); + UiVisualSnapshot.Capture(_mainWindow, nameof(Launch_ShowsPrimaryControls)); }); } @@ -98,7 +119,7 @@ public void Launch_ShowsPrimaryControls() [Trait("Category", "UI")] public void ContextMenu_Open_ShowsCoreCommands() { - RunWithFailureArtifacts(nameof(ContextMenu_Open_ShowsCoreCommands), TestContext.Current.CancellationToken, () => + RunWithFailureArtifacts(nameof(ContextMenu_Open_ShowsCoreCommands), cancellationToken: TestContext.Current.CancellationToken, testAction: () => { AutomationElement contextMenu = OpenContextMenu(); AutomationElement privacyModeMenuItem = FindMenuItemByLabel(contextMenu, Strings.Menu_PrivacyMode); @@ -123,7 +144,7 @@ public void ContextMenu_Open_ShowsCoreCommands() [Trait("Category", "UI")] public void HelpDialog_Open_And_CloseSuccessfully() { - RunWithFailureArtifacts(nameof(HelpDialog_Open_And_CloseSuccessfully), TestContext.Current.CancellationToken, () => + RunWithFailureArtifacts(nameof(HelpDialog_Open_And_CloseSuccessfully), cancellationToken: TestContext.Current.CancellationToken, testAction: () => { AutomationElement contextMenu = OpenContextMenu(); AutomationElement helpMenuItem = FindMenuItemByLabel(contextMenu, Strings.Menu_Help); @@ -159,7 +180,7 @@ public void HelpDialog_Open_And_CloseSuccessfully() [Trait("Category", "UI")] public void MinimizeOnReturn_ConfirmDialog_Open_And_CancelSuccessfully() { - RunWithFailureArtifacts(nameof(MinimizeOnReturn_ConfirmDialog_Open_And_CancelSuccessfully), TestContext.Current.CancellationToken, () => + RunWithFailureArtifacts(nameof(MinimizeOnReturn_ConfirmDialog_Open_And_CancelSuccessfully), cancellationToken: TestContext.Current.CancellationToken, testAction: () => { AutomationElement contextMenu = OpenContextMenu(); AutomationElement minimizeOnReturnMenuItem = FindMenuItemByLabel(contextMenu, Strings.Menu_MinimizeOnReturn); @@ -193,7 +214,7 @@ public void MinimizeOnReturn_ConfirmDialog_Open_And_CancelSuccessfully() [Trait("Category", "UI")] public void SettingsGamepadSubMenu_Open_ShowsCoreCommands() { - RunWithFailureArtifacts(nameof(SettingsGamepadSubMenu_Open_ShowsCoreCommands), TestContext.Current.CancellationToken, () => + RunWithFailureArtifacts(nameof(SettingsGamepadSubMenu_Open_ShowsCoreCommands), cancellationToken: TestContext.Current.CancellationToken, testAction: () => { AutomationElement contextMenu = OpenContextMenu(); AutomationElement settingsMenuItem = FindMenuItemByLabel(contextMenu, Strings.Menu_Settings); @@ -225,7 +246,7 @@ public void SettingsGamepadSubMenu_Open_ShowsCoreCommands() [Trait("Category", "UI")] public void GamepadCalibrationDialog_Open_And_CloseSuccessfully() { - RunWithFailureArtifacts(nameof(GamepadCalibrationDialog_Open_And_CloseSuccessfully), TestContext.Current.CancellationToken, () => + RunWithFailureArtifacts(nameof(GamepadCalibrationDialog_Open_And_CloseSuccessfully), cancellationToken: TestContext.Current.CancellationToken, testAction: () => { AutomationElement contextMenu = OpenContextMenu(); AutomationElement settingsMenuItem = FindMenuItemByLabel(contextMenu, Strings.Menu_Settings); @@ -266,7 +287,7 @@ public void GamepadCalibrationDialog_Open_And_CloseSuccessfully() [Trait("Category", "UI")] public void PhraseSubMenu_Open_ShowsManagementCommands() { - RunWithFailureArtifacts(nameof(PhraseSubMenu_Open_ShowsManagementCommands), TestContext.Current.CancellationToken, () => + RunWithFailureArtifacts(nameof(PhraseSubMenu_Open_ShowsManagementCommands), cancellationToken: TestContext.Current.CancellationToken, testAction: () => { AutomationElement contextMenu = OpenContextMenu(); AutomationElement phrasesMenuItem = FindMenuItemByLabel(contextMenu, Strings.Menu_Phrases); @@ -294,7 +315,7 @@ public void PhraseSubMenu_Open_ShowsManagementCommands() [Trait("Category", "UI")] public void PhraseManagerDialog_Open_And_CloseSuccessfully() { - RunWithFailureArtifacts(nameof(PhraseManagerDialog_Open_And_CloseSuccessfully), TestContext.Current.CancellationToken, () => + RunWithFailureArtifacts(nameof(PhraseManagerDialog_Open_And_CloseSuccessfully), cancellationToken: TestContext.Current.CancellationToken, testAction: () => { AutomationElement contextMenu = OpenContextMenu(); AutomationElement phrasesMenuItem = FindMenuItemByLabel(contextMenu, Strings.Menu_Phrases); @@ -333,7 +354,7 @@ public void PhraseManagerDialog_Open_And_CloseSuccessfully() [Trait("Category", "UI")] public void PhraseEditDialog_Open_And_CancelSuccessfully() { - RunWithFailureArtifacts(nameof(PhraseEditDialog_Open_And_CancelSuccessfully), TestContext.Current.CancellationToken, () => + RunWithFailureArtifacts(nameof(PhraseEditDialog_Open_And_CancelSuccessfully), cancellationToken: TestContext.Current.CancellationToken, testAction: () => { AutomationElement contextMenu = OpenContextMenu(); AutomationElement phrasesMenuItem = FindMenuItemByLabel(contextMenu, Strings.Menu_Phrases); @@ -386,7 +407,7 @@ public void PhraseEditDialog_Open_And_CancelSuccessfully() [Trait("Category", "UI")] public void CopyButton_Click_ClearsInput() { - RunWithFailureArtifacts(nameof(CopyButton_Click_ClearsInput), TestContext.Current.CancellationToken, () => + RunWithFailureArtifacts(nameof(CopyButton_Click_ClearsInput), cancellationToken: TestContext.Current.CancellationToken, testAction: () => { FlaUiTextBox inputTextBox = FindInputBox(); FlaUiButton copyButton = FindCopyButton(); @@ -417,13 +438,13 @@ public void CopyButton_Click_ClearsInput() [Trait("Category", "UI")] public void RestartPrompt_ConfirmYes_RelaunchedWindowStaysForeground() { - RunWithFailureArtifacts(nameof(RestartPrompt_ConfirmYes_RelaunchedWindowStaysForeground), TestContext.Current.CancellationToken, () => + RunWithFailureArtifacts(nameof(RestartPrompt_ConfirmYes_RelaunchedWindowStaysForeground), cancellationToken: TestContext.Current.CancellationToken, testAction: () => { Assert.NotNull(_application); Assert.NotNull(_mainWindow); string applicationPath = GetApplicationPath(); - int originalProcessId = _application!.ProcessId; + int originalProcessId = _application.ProcessId; AppSettings.GamepadProvider originalProvider = AppSettings.Current.GamepadProviderType; string targetProvider = originalProvider == AppSettings.GamepadProvider.XInput ? AppSettings.GamepadProvider.GameInput.ToString() : @@ -505,8 +526,6 @@ public void Dispose() { RestartActivationCoordinator.Shared.ClearPendingActivationRequest(); - _automation?.Dispose(); - if (_application == null) { return; @@ -534,6 +553,7 @@ public void Dispose() catch { } + _automation?.Dispose(); } /// @@ -617,6 +637,7 @@ private Window FindDialogWindowByTitle(string dialogTitle, string failureMessage failureMessage); MarkStep($"Dialog ready: {dialogTitle}"); + UiVisualSnapshot.Capture(dialogWindow, dialogTitle); return dialogWindow; } @@ -663,7 +684,7 @@ private Window FindDialogWindowByTitle(string dialogTitle, string failureMessage /// 來自資源檔的目前語系標籤文字。 /// 等待逾時後要拋出的錯誤訊息。 /// 成功找到的控制項元素。 - private AutomationElement FindDescendantByLabel(AutomationElement rootElement, ControlType controlType, string labelText, string failureMessage) + private static AutomationElement FindDescendantByLabel(AutomationElement rootElement, ControlType controlType, string labelText, string failureMessage) { return WaitForElement( () => FindFirstDescendantContainingText(rootElement, controlType, labelText), @@ -760,7 +781,7 @@ private AutomationElement FindContextMenu() return null; } - foreach (AutomationElement menuElement in _automation.GetDesktop().FindAllDescendants(cf => cf.ByControlType(ControlType.Menu))) + foreach (AutomationElement menuElement in EnumerateApplicationMenus()) { if (!BelongsToApplication(menuElement)) { @@ -784,7 +805,7 @@ private AutomationElement FindContextMenu() /// 已開啟的右鍵選單元素。 /// 來自資源檔的目前語系標籤文字。 /// 成功找到的選單項目元素。 - private AutomationElement FindMenuItemByLabel(AutomationElement menuElement, string labelText) + private static AutomationElement FindMenuItemByLabel(AutomationElement menuElement, string labelText) { return WaitForElement( () => FindFirstMenuItemContainingText(menuElement, labelText), @@ -904,7 +925,7 @@ private static string NormalizeMenuLabel(string? text) return null; } - foreach (AutomationElement menuElement in _automation.GetDesktop().FindAllDescendants(cf => cf.ByControlType(ControlType.Menu))) + foreach (AutomationElement menuElement in EnumerateApplicationMenus()) { if (!BelongsToApplication(menuElement)) { @@ -921,18 +942,43 @@ private static string NormalizeMenuLabel(string? text) return null; } + /// + /// 先以 Win32 HWND 篩選受測行程,再搜尋視窗內的選單,避免存取無關程式的 UIA provider。 + /// + /// 目前屬於受測應用程式的選單。 + private IEnumerable EnumerateApplicationMenus() + { + if (_automation == null || _application == null) + { + yield break; + } + + foreach (AutomationElement root in UiWindowDiscovery.FindRoots(_automation, _application.ProcessId)) + { + if (root.ControlType == ControlType.Menu) + { + yield return root; + } + + foreach (AutomationElement menu in root.FindAllDescendants(cf => cf.ByControlType(ControlType.Menu))) + { + yield return menu; + } + } + } + /// /// 列舉目前屬於受測 InputBox 行程的頂層視窗。 /// /// 所有屬於 InputBox.exe 的頂層視窗元素。 private IEnumerable EnumerateApplicationWindows() { - if (_automation == null) + if (_automation == null || _application == null) { yield break; } - foreach (AutomationElement windowElement in _automation.GetDesktop().FindAllChildren(cf => cf.ByControlType(ControlType.Window))) + foreach (AutomationElement windowElement in UiWindowDiscovery.FindRoots(_automation, _application.ProcessId).Where(root => root.ControlType == ControlType.Window)) { if (BelongsToApplication(windowElement)) { @@ -1004,7 +1050,9 @@ private static Window WaitForMainWindow(FlaUiApplication application, UIA3Automa while (stopwatch.Elapsed < TimeSpan.FromSeconds(15)) { - Window? window = application.GetMainWindow(automation); + using Process process = Process.GetProcessById(application.ProcessId); + nint handle = process.MainWindowHandle; + Window? window = handle == 0 ? null : automation.FromHandle(handle).AsWindow(); if (window != null) { return window; @@ -1176,7 +1224,7 @@ private static void WaitUntil( /// 目前執行中的測試名稱。 /// xUnit 測試逾時所提供的取消權杖。 /// 實際要執行的測試邏輯。 - private void RunWithFailureArtifacts(string testName, CancellationToken cancellationToken, Action testAction) + private void RunWithFailureArtifacts(string testName, Action testAction, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); @@ -1307,7 +1355,7 @@ private IEnumerable GetOpenMenuDiagnostics() bool hasMenu = false; - foreach (AutomationElement menuElement in _automation.GetDesktop().FindAllDescendants(cf => cf.ByControlType(ControlType.Menu))) + foreach (AutomationElement menuElement in EnumerateApplicationMenus()) { if (!BelongsToApplication(menuElement)) { @@ -1485,4 +1533,4 @@ private static void CleanupStaleProcesses(string applicationPath) } } } -} \ No newline at end of file +} diff --git a/tests/InputBox.Tests/PhraseServiceTests.cs b/tests/InputBox.Tests/PhraseServiceTests.cs index c621770e..16a27bf9 100644 --- a/tests/InputBox.Tests/PhraseServiceTests.cs +++ b/tests/InputBox.Tests/PhraseServiceTests.cs @@ -108,7 +108,7 @@ public void Add_ValidEntry_PhrasesContainsEntry() var svc = new PhraseService(); svc.Add("TestName", "TestContent"); - var entry = svc.Phrases[0]; + PhraseService.PhraseEntry entry = svc.Phrases[0]; Assert.Equal("TestName", entry.Name); Assert.Equal("TestContent", entry.Content); @@ -623,8 +623,8 @@ public void ImportFromFile_ValidJson_ReplacesPhrasesAndReturnsSuccess() Assert.Equal(PhraseService.ImportError.None, result.Error); Assert.Equal(1, result.Imported); Assert.Equal(1, result.Total); - Assert.Single(svc.Phrases); - Assert.Equal("新片語", svc.Phrases[0].Name); + PhraseService.PhraseEntry item = Assert.Single(svc.Phrases); + Assert.Equal("新片語", item.Name); Assert.Equal("新內容", svc.Phrases[0].Content); } finally diff --git a/tests/InputBox.Tests/README.md b/tests/InputBox.Tests/README.md index 3c8d9786..5bc07029 100644 --- a/tests/InputBox.Tests/README.md +++ b/tests/InputBox.Tests/README.md @@ -1,7 +1,7 @@ # InputBox.Tests 🧪 [![作業系統](https://img.shields.io/badge/作業系統-Windows-003A6D?style=for-the-badge)](https://www.microsoft.com/windows) -[![.NET](https://img.shields.io/badge/Runtime-.NET%2010-512BD4?logo=dotnet&logoColor=white&style=for-the-badge)](https://dotnet.microsoft.com/) +[![.NET](https://img.shields.io/badge/Runtime-.NET%2011-512BD4?logo=dotnet&logoColor=white&style=for-the-badge)](https://dotnet.microsoft.com/) [![測試框架](https://img.shields.io/badge/Test%20Framework-xUnit%20v3-5C2D91?style=for-the-badge)](https://xunit.net/) [![UI%20Smoke](https://img.shields.io/badge/Desktop%20UI-FlaUI-2E8B57?style=for-the-badge)](https://github.com/FlaUI/FlaUI) @@ -153,4 +153,26 @@ xUnit v3 為每個 `[Fact]` 建立獨立的測試類別實例,`IDisposable.Dis ### 6. 目標框架 -測試專案使用 `net10.0-windows`(需要 WinForms 執行環境),**僅支援 Windows**。 +測試專案使用 `net11.0-windows`(需要 WinForms 執行環境),**僅支援 Windows**。 + +### UIA 搜尋範圍回歸保護 + +既有 11 項 UI 冒煙測試維持真實點擊與對話框生命週期檢查;先以 Win32 HWND/ProcessId 篩選可見頂層視窗,再搜尋 InputBox 視窗內與浮動選單,避免遍歷瀏覽器等無關 UIA 子樹造成延遲、選單失效與測試逾時。測試數量不變。 + +UI 測試宿主在啟動 UIA 前使用 Application.SetHighDpiMode(PerMonitorV2),關閉受測視窗後才處置 UIA;初始視窗直接由受測程序 HWND 綁定,啟動失敗時清理該受測程序。設定 INPUTBOX_CAPTURE_UI=1 時,UiVisualSnapshot 會擷取主視窗及對話框,記錄 HWND 的原生 DPI、高對比旗標與視窗邊界,並檢查可見按鈕未超出視窗。可用 INPUTBOX_EXPECTED_DPI=144 等值要求實際 DPI 必須符合預期;圖片不做 DPI 模擬。 + +### .NET 11/Latest 原生 UI 矩陣(2026-11-14) + +| Windows 縮放/實際 HWND DPI | 淺色 Classic | 深色 Dark | Windows 高對比 | +|---|---|---|---| +| 100%/96 | 11/11 | 11/11 | 11/11 | +| 125%/120 | 11/11 | 11/11 | 11/11 | +| 150%/144 | 11/11 | 11/11 | 11/11 | + +矩陣使用同一實體顯示器的 Windows 原生縮放;隔離副本只覆寫啟動色彩模式以強制 Classic/Dark,保留 Latest 與 Deferred、所有 UI 與測試來源。appearance.txt 記錄 Application.IsDarkModeEnabled、SystemInformation.HighContrast 與 Application.DefaultVisualStylesMode,三者均符合預期;每一組保留主視窗、說明、片語管理/編輯、確認與校正視窗擷圖。原縮放 125% 與主題/高對比設定於結束後還原。 + +原始 .NET 10 測試亦可重現 NoClickablePointException(10/11);限制搜尋範圍後,.NET 10、.NET 11 未啟用 Deferred、.NET 11 啟用 Deferred 的對照均為 11/11。後續納入 Win32 HWND 探索、PerMonitorV2 測試宿主與 UIA 處置順序修正,避免其他無回應 provider、座標虛擬化及殘留測試程序干擾驗證。 + +最終 dev 正式 System + Latest + Deferred 路徑於 125%/120 DPI 為 11/11,非 UI 回歸為 456/456,行覆蓋率 32.58%。Release 建置使用 -warnaserror 為 0 警告/0 錯誤;完整 style 與 analyzers 的 severity info 檢查報告皆為空清單。七語系資源的鍵名與格式預留位置一致;Xbox 使用模式術語已對齊文件與網站,應用程式資源未發現舊稱,控制器 Xbox 配置名稱維持既有語意。 + +合規查核(2026-11-14):以可執行 JavaScript 的官方頁面確認 FFXIV 使用者合約、USERJOY 使用條款與隱私政策,並讀取第三方授權及免責聲明。此次輸入相關來源僅清理多餘初值、索引與必要回呼參數名稱,保持既有剪貼簿輸出邊界與控制器行為。 diff --git a/tests/InputBox.Tests/TaskExtensionsTests.cs b/tests/InputBox.Tests/TaskExtensionsTests.cs index 85350eb1..e517ec3e 100644 --- a/tests/InputBox.Tests/TaskExtensionsTests.cs +++ b/tests/InputBox.Tests/TaskExtensionsTests.cs @@ -17,7 +17,7 @@ public class TaskExtensionsTests public void CancelAndDispose_Null_DoesNotThrow() { CancellationTokenSource? cts = null; - var capturedException = Record.Exception(() => cts.CancelAndDispose()); + Exception? capturedException = Record.Exception(() => cts.CancelAndDispose()); Assert.Null(capturedException); } @@ -30,7 +30,7 @@ public void CancelAndDispose_ActiveCts_CancelsSuccessfully() var cts = new CancellationTokenSource(); Assert.False(cts.IsCancellationRequested); - var capturedException = Record.Exception(() => cts.CancelAndDispose()); + Exception? capturedException = Record.Exception(() => cts.CancelAndDispose()); Assert.Null(capturedException); // 呼叫後 cts 已被 Dispose,無法再讀取 IsCancellationRequested,不驗證此屬性 @@ -45,7 +45,7 @@ public void CancelAndDispose_AlreadyCancelled_DoesNotThrow() var cts = new CancellationTokenSource(); cts.Cancel(); - var capturedException = Record.Exception(() => cts.CancelAndDispose()); + Exception? capturedException = Record.Exception(() => cts.CancelAndDispose()); Assert.Null(capturedException); } @@ -59,7 +59,7 @@ public void CancelAndDispose_AlreadyDisposed_DoesNotThrow() var cts = new CancellationTokenSource(); cts.Dispose(); - var capturedException = Record.Exception(() => cts.CancelAndDispose()); + Exception? capturedException = Record.Exception(() => cts.CancelAndDispose()); Assert.Null(capturedException); } diff --git a/tests/InputBox.Tests/UiVisualSnapshot.cs b/tests/InputBox.Tests/UiVisualSnapshot.cs new file mode 100644 index 00000000..ef23c904 --- /dev/null +++ b/tests/InputBox.Tests/UiVisualSnapshot.cs @@ -0,0 +1,72 @@ +using FlaUI.Core.AutomationElements; +using FlaUI.Core.Capturing; +using FlaUI.Core.Definitions; +using System.Globalization; +using System.Runtime.InteropServices; +using Xunit; + +namespace InputBox.Tests; + +/// +/// 顯式啟用時記錄實際 Win32 DPI、視窗尺寸與畫面,供主題及原生縮放驗證。 +/// +internal static partial class UiVisualSnapshot +{ + /// + /// 擷取主視窗或對話框,並檢查可見按鈕是否位於視窗內;不以縮放圖片模擬 DPI。 + /// + /// 已顯示的受測視窗。 + /// 產物標籤。 + public static void Capture(Window? window, string label) + { + if (Environment.GetEnvironmentVariable("INPUTBOX_CAPTURE_UI") != "1") + { + return; + } + + Assert.NotNull(window); + uint dpi = GetDpiForWindow(window.Properties.NativeWindowHandle.Value); + Assert.True(dpi > 0); + string? expectedDpi = Environment.GetEnvironmentVariable("INPUTBOX_EXPECTED_DPI"); + if (!string.IsNullOrEmpty(expectedDpi)) + { + Assert.Equal(uint.Parse(expectedDpi, CultureInfo.InvariantCulture), dpi); + } + + Rectangle bounds = window.BoundingRectangle; + Assert.True(bounds.Width > 0 && bounds.Height > 0); + foreach (AutomationElement button in window.FindAllDescendants(cf => cf.ByControlType(ControlType.Button))) + { + if (!button.IsOffscreen) + { + Assert.True(bounds.Contains(button.BoundingRectangle), + $"按鈕超出視窗:{button.Name}, button={button.BoundingRectangle}, window={bounds}"); + } + } + + string directory = Environment.GetEnvironmentVariable("INPUTBOX_UI_ARTIFACT_DIR") + ?? Path.Combine(AppContext.BaseDirectory, "TestResults", "UiArtifacts"); + Directory.CreateDirectory(directory); + string safeLabel = string.Concat(label.Split(Path.GetInvalidFileNameChars(), StringSplitOptions.RemoveEmptyEntries)); + string prefix = Path.Combine(directory, $"{safeLabel}-{dpi}dpi"); + using CaptureImage capture = FlaUI.Core.Capturing.Capture.Element(window); + capture.ToFile(prefix + ".png"); + File.WriteAllLines(prefix + ".txt", + [ + $"label={label}", + $"dpi={dpi}", + $"bounds={bounds}", + $"highContrast={SystemInformation.HighContrast}", + $"utc={DateTime.UtcNow:O}" + ]); + Console.WriteLine($"[UI Visual] {label}: dpi={dpi}, bounds={bounds}, highContrast={SystemInformation.HighContrast}"); + } + + /// + /// 取得目標 HWND 的實際 DPI。 + /// + /// 受測視窗控制代碼。 + /// 視窗目前使用的 DPI。 + [LibraryImport("user32.dll")] + private static partial uint GetDpiForWindow(nint window); +} \ No newline at end of file diff --git a/tests/InputBox.Tests/UiWindowDiscovery.cs b/tests/InputBox.Tests/UiWindowDiscovery.cs new file mode 100644 index 00000000..62d8c9d2 --- /dev/null +++ b/tests/InputBox.Tests/UiWindowDiscovery.cs @@ -0,0 +1,68 @@ +using FlaUI.Core; +using FlaUI.Core.AutomationElements; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +namespace InputBox.Tests; + +/// +/// 先由 Win32 取得受測行程的可見頂層 HWND,再交給 UIA,避免其他程式無回應的 provider 阻塞桌面搜尋。 +/// +internal static partial class UiWindowDiscovery +{ + /// + /// 列舉指定行程的可見頂層視窗與浮動選單。 + /// + /// 目前測試的 UIA 連線。 + /// 受測 InputBox 行程識別碼。 + /// 可供 UIA 搜尋的受測視窗。 + public static unsafe IEnumerable FindRoots(AutomationBase automation, int processId) + { + WindowSearch search = new(processId); + GCHandle state = GCHandle.Alloc(search); + try + { + _ = EnumWindows(&CollectWindow, GCHandle.ToIntPtr(state)); + } + finally + { + state.Free(); + } + + return search.Handles.Select(automation.FromHandle); + } + + /// + /// 僅收集指定行程的可見 HWND,不向其他應用程式的 UIA provider 查詢。 + /// + [UnmanagedCallersOnly(CallConvs = [typeof(CallConvStdcall)])] + private static int CollectWindow(nint window, nint state) + { + WindowSearch search = (WindowSearch)GCHandle.FromIntPtr(state).Target!; + _ = GetWindowThreadProcessId(window, out uint processId); + if (processId == search.ProcessId && IsWindowVisible(window) != 0) + { + search.Handles.Add(window); + } + + return 1; + } + + /// + /// 單次同步列舉使用的狀態,生命週期由 GCHandle 保護。 + /// + private sealed class WindowSearch(int processId) + { + public uint ProcessId { get; } = checked((uint)processId); + public List Handles { get; } = []; + } + + [LibraryImport("user32.dll")] + private static unsafe partial int EnumWindows(delegate* unmanaged[Stdcall] callback, nint state); + + [LibraryImport("user32.dll")] + private static partial uint GetWindowThreadProcessId(nint window, out uint processId); + + [LibraryImport("user32.dll")] + private static partial int IsWindowVisible(nint window); +} \ No newline at end of file diff --git a/tests/InputBox.Tests/VibrationPatternsTests.cs b/tests/InputBox.Tests/VibrationPatternsTests.cs index 53cff90d..694a0a8f 100644 --- a/tests/InputBox.Tests/VibrationPatternsTests.cs +++ b/tests/InputBox.Tests/VibrationPatternsTests.cs @@ -243,8 +243,8 @@ public void VibrationPatterns_GetNavigationSequence_WithoutTriggerSupport_FallsB context: VibrationContext.PrivacyMode, motorSupport: VibrationMotorSupport.DualMain); - Assert.Single(sequence); - Assert.Equal(VibrationPatterns.PrivacyModeToggle, sequence[0].Profile); + VibrationSequenceStep item = Assert.Single(sequence); + Assert.Equal(VibrationPatterns.PrivacyModeToggle, item.Profile); } ///