From 6e68912836a7852d15b2f281b48f155fb5823d9e Mon Sep 17 00:00:00 2001 From: perditavojo <117562794+perditavojo@users.noreply.github.com> Date: Sat, 31 Oct 2026 07:33:41 +0800 Subject: [PATCH 1/6] =?UTF-8?q?fix(gameinput):=20=E6=94=B9=E7=94=A8?= =?UTF-8?q?=E9=9D=9E=E5=90=8C=E6=AD=A5=E5=88=86=E9=9A=8E=E6=AE=B5=E8=A3=9D?= =?UTF-8?q?=E7=BD=AE=E6=8E=A2=E7=B4=A2=E9=81=BF=E5=85=8D=E6=8C=81=E9=8E=96?= =?UTF-8?q?=E9=98=BB=E5=A1=9E=E8=BC=AA=E8=A9=A2=E8=88=87=E8=BC=B8=E5=85=A5?= =?UTF-8?q?=E9=81=BA=E5=A4=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 因 InputWeave 0.0.1 (API 4) 之 EnumerateDevices 會呼叫 CollectFor(TimeSpan.FromSeconds(1.25)) 並在內部執行 Thread.Sleep,原先在輪詢迴圈中持 _deviceLock 同步列舉會導致現有手把停頓 1.25 秒並遺失按鍵輸入。 本次修正包含: - 將同步裝置列舉改為背景分階段非同步探索(StartDeviceDiscovery 與 CheckAndApplyDiscoveryResults),保留 MTA 執行緒與裝置生命週期約束。 - 在 1.25 秒探索期間不再持有 _deviceLock,讓 60 FPS 輪詢迴圈能持續順暢讀取現有手把輸入。 - 探索結果由輪詢執行緒透過 ApplyDiscoveredDevices 於微秒級持鎖時段內套用至裝置快取,並在目前裝置斷線時優先無縫接手快取中的可用控制器。 - PollingLoopAsync 初始化改以非同步列舉 await _gameInput.EnumerateDevicesAsync 啟動,停止與處置時確保未完成探索工作之裝置代理被妥善釋放。 - 同步補充單元測試覆蓋非同步探索 API 介面、空清單套用與斷線通知,並更新測試說明文件。 --- .../Core/Input/GameInputGamepadController.cs | 318 ++++++++++++++++-- .../GameInputDirectUsageTests.cs | 1 + .../GamepadControllerPauseTests.cs | 53 +++ tests/InputBox.Tests/README.md | 4 +- 4 files changed, 344 insertions(+), 32 deletions(-) diff --git a/src/InputBox/Core/Input/GameInputGamepadController.cs b/src/InputBox/Core/Input/GameInputGamepadController.cs index 17a93812..596e892b 100644 --- a/src/InputBox/Core/Input/GameInputGamepadController.cs +++ b/src/InputBox/Core/Input/GameInputGamepadController.cs @@ -114,6 +114,16 @@ internal sealed partial class GameInputGamepadController : IGamepadController /// private int _missingReadingFrameCounter; + /// + /// 目前進行中的背景裝置探索工作 + /// + private Task>? _deviceDiscoveryTask; + + /// + /// 背景裝置探索工作的取消權杖來源 + /// + private CancellationTokenSource? _discoveryCts; + /// /// 輪詢任務的 CancellationTokenSource /// @@ -736,6 +746,34 @@ private void StopPolling() LogGameInputDiagnosticsSnapshot("stop-polling"); cts.CancelAndDispose(); + + Interlocked.Exchange(ref _discoveryCts, null)?.CancelAndDispose(); + + Task>? pendingDiscovery = _deviceDiscoveryTask; + _deviceDiscoveryTask = null; + + if (pendingDiscovery != null) + { + _ = pendingDiscovery.ContinueWith(t => + { + if (t.IsCompletedSuccessfully) + { + IReadOnlyList devices = t.Result; + + for (int i = 0; i < devices.Count; i++) + { + try + { + devices[i].Dispose(); + } + catch (Exception ex) + { + Debug.WriteLine($"[GameInput] 取消後清理探索裝置失敗(已忽略):{ex.Message}"); + } + } + } + }, TaskScheduler.Default); + } } /// @@ -853,18 +891,7 @@ private async Task PollingLoopAsync(CancellationToken cancellationToken, TaskCom LoggerService.LogInfo($"GameInputRuntime/InputWeave loader={runtimeInfo.LoaderPolicy} available={runtimeInfo.IsAvailable} moduleKind={runtimeInfo.LoadedModuleKind} modulePath={runtimeInfo.LoadedModulePath} version={runtimeInfo.FileVersion}"); LogGameInputDiagnosticsSnapshot("init"); - // 初始化時先直接列舉一次,再註冊非阻塞裝置回呼。 - // 這樣可避免為了拿到既有裝置名單而付出兩次同步枚舉成本。 - if (_needsRefresh && - !cancellationToken.IsCancellationRequested && - _disposed == 0) - { - TryFindDevice(); - } - - // 註冊裝置變更事件。 - // 使用 None 避免在註冊當下再次為現有裝置執行同步枚舉, - // 讓啟動成本只落在一次直接列舉上。 + // 註冊裝置變更回呼。 _deviceCallbackReg = _gameInput.RegisterDeviceCallback( null!, GameInputKind.GameInputKindGamepad, @@ -878,6 +905,30 @@ private async Task PollingLoopAsync(CancellationToken cancellationToken, TaskCom Interlocked.Exchange(ref _refreshRequestedTicks, Stopwatch.GetTimestamp()); } }); + + // 初始化時先非同步列舉一次以取得既有連線裝置。 + if (_needsRefresh && + !cancellationToken.IsCancellationRequested && + _disposed == 0) + { + try + { + IReadOnlyList initialDevices = await _gameInput.EnumerateDevicesAsync( + GameInputKind.GameInputKindGamepad, + cancellationToken).ConfigureAwait(false); + + ApplyDiscoveredDevices(initialDevices); + } + catch (OperationCanceledException) + { + // 取消時正常退出。 + } + catch (Exception ex) + { + LoggerService.LogException(ex, "GameInput 初次裝置列舉失敗"); + Debug.WriteLine($"[GameInput] 初次裝置列舉失敗:{ex.Message}"); + } + } } // 成功完成初始化,通知 CreateAsync 解除等待 @@ -1189,20 +1240,21 @@ private void Poll() Interlocked.Exchange(ref _refreshRequestedTicks, Stopwatch.GetTimestamp()); } + // 先檢查並套用已完成的非同步裝置探索結果。 + CheckAndApplyDiscoveryResults(); + // 裝置清單防抖與掃描邏輯。 if (_needsRefresh) { - // 若目前尚未連線任何裝置,直接重掃,不套用 500ms 防抖, + // 若目前尚未連線任何裝置,直接啟動探索,不套用 500ms 防抖, // 以縮短「未連線 → 新插入」的首段偵測延遲。 if (_device == null) { _reconnectCounter = 0; - TryFindDevice(); + StartDeviceDiscovery(); } - - // 尚未連線時已做過即時重掃,本幀不再進行第二次防抖重掃,避免重複列舉。 - if (_device != null) + else { long elapsedTicks = Stopwatch.GetTimestamp() - Interlocked.Read(ref _refreshRequestedTicks), elapsedMs = elapsedTicks / (Stopwatch.Frequency / 1000); @@ -1211,11 +1263,11 @@ private void Poll() { _reconnectCounter = 0; - TryFindDevice(); + StartDeviceDiscovery(); } } } - else if (_device == null) + else if (_device == null && _deviceDiscoveryTask == null) { _reconnectCounter++; @@ -1223,7 +1275,7 @@ private void Poll() { _reconnectCounter = 0; - TryFindDevice(); + StartDeviceDiscovery(); } } @@ -1404,7 +1456,67 @@ private void RefreshAfterCurrentDeviceBecameUnavailable() _needsRefresh = true; Interlocked.Exchange(ref _refreshRequestedTicks, Stopwatch.GetTimestamp()); - TryFindDevice(); + bool needsDisconnect = false, + needsConnectNotify = false; + + lock (_deviceLock) + { + GameInputDevice? deadDev = _device; + + if (deadDev != null) + { + _device = null; + _allDevices.Remove(deadDev); + + try + { + deadDev.Dispose(); + } + catch (Exception ex) + { + Debug.WriteLine($"[GameInput] 釋放斷線裝置代理失敗(已忽略):{ex.Message}"); + } + } + + // 若快取中還有其他已連線的控制器,立即無縫接手,不需等待探索。 + for (int i = 0; i < _allDevices.Count; i++) + { + GameInputDevice candidate = _allDevices[i]; + + if (IsDeviceConnected(candidate)) + { + _device = candidate; + _hasPreviousState = false; + _missingReadingFrameCounter = 0; + + UpdateDeviceInfo(); + InitializeDeviceState(); + SetupReadingCallback(); + + needsConnectNotify = true; + + break; + } + } + + if (_device == null) + { + needsDisconnect = true; + } + } + + if (needsDisconnect) + { + HandleDisconnect(); + } + + if (needsConnectNotify) + { + _isConnected = true; + ConnectionChanged?.Invoke(true); + } + + StartDeviceDiscovery(); } /// @@ -1422,7 +1534,7 @@ private bool HandleMissingCurrentReading() Interlocked.Exchange(ref _refreshRequestedTicks, Stopwatch.GetTimestamp()); LogGameInputDiagnosticsSnapshot("missing-reading-threshold"); - TryFindDevice(); + StartDeviceDiscovery(); return _device == null; } @@ -1739,17 +1851,110 @@ private void ResetTransientInputState(bool requireNeutralBeforeInput = true) } /// - /// 嘗試尋找裝置 + /// 啟動非同步裝置探索工作。 + /// 探索在背景執行且不持有 ,避免阻塞 60 FPS 輪詢迴圈或導致現有手把輸入遺失。 /// - private void TryFindDevice() + private void StartDeviceDiscovery() { - GameInputClient? gameInput = _gameInput; + if (_deviceDiscoveryTask != null || + _disposed != 0 || + _isPaused || + _gameInput == null) + { + return; + } - if (gameInput == null) + _needsRefresh = false; + + CancellationTokenSource? pollingCts = _ctsPolling; + CancellationToken pollingToken = pollingCts?.Token ?? CancellationToken.None; + + if (pollingToken.IsCancellationRequested) + { + return; + } + + CancellationTokenSource discoveryCts = CancellationTokenSource.CreateLinkedTokenSource(pollingToken); + _discoveryCts = discoveryCts; + + try + { + _deviceDiscoveryTask = _gameInput.EnumerateDevicesAsync( + GameInputKind.GameInputKindGamepad, + discoveryCts.Token); + } + catch (Exception ex) + { + _needsRefresh = true; + _deviceDiscoveryTask = null; + Interlocked.Exchange(ref _discoveryCts, null)?.Dispose(); + + LoggerService.LogException(ex, "GameInput 啟動裝置探索失敗"); + Debug.WriteLine($"[GameInput] 啟動裝置探索失敗:{ex.Message}"); + } + } + + /// + /// 檢查背景裝置探索工作是否完成,並於輪詢執行緒套用結果。 + /// + private void CheckAndApplyDiscoveryResults() + { + Task>? task = _deviceDiscoveryTask; + + if (task == null || !task.IsCompleted) { return; } + _deviceDiscoveryTask = null; + Interlocked.Exchange(ref _discoveryCts, null)?.Dispose(); + + try + { + if (task.IsCompletedSuccessfully) + { + IReadOnlyList discovered = task.Result; + + if (_disposed == 0 && + !_isPaused && + _gameInput != null) + { + ApplyDiscoveredDevices(discovered); + } + else + { + for (int i = 0; i < discovered.Count; i++) + { + try + { + discovered[i].Dispose(); + } + catch (Exception ex) + { + Debug.WriteLine($"[GameInput] 釋放未套用裝置失敗(已忽略):{ex.Message}"); + } + } + } + } + else if (task.IsFaulted && task.Exception != null) + { + LoggerService.LogException(task.Exception.GetBaseException(), "GameInput 裝置非同步探索失敗"); + Debug.WriteLine($"[GameInput] 裝置非同步探索失敗:{task.Exception.GetBaseException().Message}"); + } + } + catch (Exception ex) + { + LoggerService.LogException(ex, "GameInput 套用探索裝置失敗"); + Debug.WriteLine($"[GameInput] 套用探索裝置失敗:{ex.Message}"); + } + } + + /// + /// 套用探索到的裝置清單,更新已追蹤裝置與目前啟動裝置。 + /// + /// 新探索到的裝置清單。 + private void ApplyDiscoveredDevices(IReadOnlyList devices) + { bool needsDisconnect = false, needsConnectNotify = false; @@ -1757,10 +1962,6 @@ private void TryFindDevice() { _needsRefresh = false; - // 執行一次完整的列舉。 - IReadOnlyList devices = gameInput.EnumerateDevices( - GameInputKind.GameInputKindGamepad); - // 1. 釋放清單中已不再存在或已非 Connected 的舊裝置代理(Zero-allocation 替換 LINQ Any)。 for (int i = _allDevices.Count - 1; i >= 0; i--) { @@ -1921,6 +2122,35 @@ private void TryFindDevice() } } + /// + /// 同步尋找裝置(僅供需要立即探索的相容路徑使用,平時由背景分階段探索取代)。 + /// + private void TryFindDevice() + { + GameInputClient? gameInput = _gameInput; + + if (gameInput == null) + { + return; + } + + IReadOnlyList devices; + + try + { + devices = gameInput.EnumerateDevices(GameInputKind.GameInputKindGamepad); + } + catch (Exception ex) + { + LoggerService.LogException(ex, "GameInput 同步列舉裝置失敗"); + Debug.WriteLine($"[GameInput] 同步列舉裝置失敗:{ex.Message}"); + + return; + } + + ApplyDiscoveredDevices(devices); + } + /// /// 判斷 GameInput 裝置目前是否仍可用於輸入。 /// @@ -3171,6 +3401,34 @@ private Task DisposeResourcesAsync() deviceCallbackReg?.Dispose(); readingCallbackReg?.Dispose(); + // 若有進行中的背景探索工作,等待其完成並釋放所產生的裝置代理。 + Task>? discoveryTask = _deviceDiscoveryTask; + _deviceDiscoveryTask = null; + + if (discoveryTask != null) + { + try + { + IReadOnlyList pending = await discoveryTask.ConfigureAwait(false); + + for (int i = 0; i < pending.Count; i++) + { + try + { + pending[i].Dispose(); + } + catch (Exception ex) + { + Debug.WriteLine($"[GameInput] 處置時釋放探索裝置失敗(已忽略):{ex.Message}"); + } + } + } + catch (Exception ex) + { + Debug.WriteLine($"[GameInput] 處置時等待探索完成發生例外(已忽略):{ex.Message}"); + } + } + // 釋放所有連線中的裝置代理。 foreach (GameInputDevice d in devicesToDispose) { diff --git a/tests/InputBox.Tests/GameInputDirectUsageTests.cs b/tests/InputBox.Tests/GameInputDirectUsageTests.cs index 005a8b02..d1911c49 100644 --- a/tests/InputBox.Tests/GameInputDirectUsageTests.cs +++ b/tests/InputBox.Tests/GameInputDirectUsageTests.cs @@ -23,6 +23,7 @@ public void RequiredInputWeaveGamepadApi_Surface_IsAvailable() Assert.NotNull(typeof(GameInputClient).GetMethod(nameof(GameInputClient.Create), BindingFlags.Public | BindingFlags.Static)); Assert.NotNull(typeof(GameInputClient).GetMethod(nameof(GameInputClient.EnableBackgroundInput), [typeof(bool)])); Assert.NotNull(typeof(GameInputClient).GetMethod(nameof(GameInputClient.EnumerateDevices), [typeof(GameInputKind)])); + Assert.NotNull(typeof(GameInputClient).GetMethod(nameof(GameInputClient.EnumerateDevicesAsync), [typeof(GameInputKind), typeof(CancellationToken)])); Assert.NotNull(typeof(GameInputClient).GetMethod(nameof(GameInputClient.GetCurrentGamepad), [typeof(GameInputDevice)])); Assert.NotNull(typeof(GameInputClient).GetMethod(nameof(GameInputClient.RegisterReadingCallback), [typeof(GameInputDevice), typeof(GameInputKind), typeof(GameInputReadingHandler)])); Assert.NotNull(typeof(GameInputClient).GetMethod(nameof(GameInputClient.RegisterDeviceCallback), [typeof(GameInputDevice), typeof(GameInputKind), typeof(GameInputDeviceEventHandler)])); diff --git a/tests/InputBox.Tests/GamepadControllerPauseTests.cs b/tests/InputBox.Tests/GamepadControllerPauseTests.cs index 56da24da..909227ca 100644 --- a/tests/InputBox.Tests/GamepadControllerPauseTests.cs +++ b/tests/InputBox.Tests/GamepadControllerPauseTests.cs @@ -244,6 +244,59 @@ public void IsConnectedStatus_GameInputDeviceStatus_FiltersUnavailableDevices() Assert.False((bool)method.Invoke(null, [false])!); } + /// + /// GameInput 控制器在背景裝置探索未完成或無工作時,CheckAndApplyDiscoveryResults 不應改變狀態或丟出例外。 + /// + [Fact] + public void CheckAndApplyDiscoveryResults_WhenNoTask_DoesNotThrow() + { + using var controller = (GameInputGamepadController)Activator.CreateInstance( + typeof(GameInputGamepadController), + BindingFlags.Instance | BindingFlags.NonPublic, + binder: null, + args: [new StubInputContext(), null], + culture: null)!; + + MethodInfo method = typeof(GameInputGamepadController).GetMethod( + "CheckAndApplyDiscoveryResults", + BindingFlags.Instance | BindingFlags.NonPublic) + ?? throw new InvalidOperationException("找不到 GameInputGamepadController.CheckAndApplyDiscoveryResults。"); + + method.Invoke(controller, []); + + Assert.Null(GetPrivateField>?>(controller, "_deviceDiscoveryTask")); + } + + /// + /// GameInput 控制器在套用空裝置清單時,應將目前裝置設為 null 並觸發斷線流程。 + /// + [Fact] + public void ApplyDiscoveredDevices_EmptyList_ClearsDeviceAndNotifiesDisconnect() + { + using var controller = (GameInputGamepadController)Activator.CreateInstance( + typeof(GameInputGamepadController), + BindingFlags.Instance | BindingFlags.NonPublic, + binder: null, + args: [new StubInputContext(), null], + culture: null)!; + + bool? connectionEventStatus = null; + controller.ConnectionChanged += status => connectionEventStatus = status; + + SetPrivateField(controller, "_isConnected", true); + + MethodInfo method = typeof(GameInputGamepadController).GetMethod( + "ApplyDiscoveredDevices", + BindingFlags.Instance | BindingFlags.NonPublic) + ?? throw new InvalidOperationException("找不到 GameInputGamepadController.ApplyDiscoveredDevices。"); + + method.Invoke(controller, [Array.Empty()]); + + Assert.Null(GetPrivateField(controller, "_device")); + Assert.False(controller.IsConnected); + Assert.Equal(false, connectionEventStatus); + } + /// /// XInput 控制器在 ClearAllEvents 後,必須一併清除 LeftShoulderReleased 與 /// RightShoulderReleased 兩個事件訂閱,避免處置後仍殘留呼叫鏈造成事件洩漏。 diff --git a/tests/InputBox.Tests/README.md b/tests/InputBox.Tests/README.md index 964b4281..5b9c8e0b 100644 --- a/tests/InputBox.Tests/README.md +++ b/tests/InputBox.Tests/README.md @@ -21,7 +21,7 @@ | `FormInputStateManagerTests` | `FormInputStateManager` 輸入狀態切換 | 15 | | `GamepadDeadzoneHysteresisTests` | `GamepadDeadzoneHysteresis.ResolveDirection`(int / float 多載),含正負方向對稱性守門(硬體平等原則) | 14 | | `GamepadControllerFactoryTests` | 控制器後端建立策略,驗證 XInput 預設路徑、GameInput 成功路徑,以及 GameInput 執行階段不可用時退避至 XInput | 3 | -| `GamepadControllerPauseTests` | 控制器在 `Pause()` / `Resume()`、連線可用性語意、GameInput 讀取缺失斷線重列舉、裝置狀態過濾、震動停止安全性、`ClearAllEvents` 肩鍵釋放訂閱清除與原生對話框切換時的殘留輸入回歸保護 | 10 | +| `GamepadControllerPauseTests` | 控制器在 `Pause()` / `Resume()`、連線可用性語意、GameInput 讀取缺失斷線重列舉、非同步分階段裝置探索、裝置狀態過濾、震動停止安全性、`ClearAllEvents` 肩鍵釋放訂閱清除與原生對話框切換時的殘留輸入回歸保護 | 12 | | `GameInputDirectUsageTests` | `GameInputGamepadController` 直接使用 `InputWeave.GameInput` 遊戲控制器介面的守門、callback function pointer marshaling、官方 v3 按鍵位元、快照邊緣偵測、Release 日誌邊界、穩定裝置識別與震動參數保留 | 9 | | `FlashAlertAnimatorTests` | `FlashAlertAnimator` 共用閃爍警示:主題警示色、純淨底色至警示色的插值、整個脈衝過程文字對比 ≥4.5:1、高對比模式半強度切換,以及 1Hz 單次正弦脈衝強度 | 7 | | `GamepadBiasSmoothingTests` | `GamepadBiasSmoothing` 自適應 EMA 學習率公式:零誤差用基礎值、超出範圍用最大值,以及 XInput 與 GameInput 不同數值尺度下結果一致 | 5 | @@ -50,7 +50,7 @@ | `TextBoxSelectionExtensionsTests` | 右搖桿延伸選取共用的 `ResolveSelectionAnchor` 錨點解析(無選取、正向、反向、錨點失效)與 `GetWordJumpTarget` 單字跳轉目標(不改變目前選取、方向與邊界);原本三處複本集中後的一致性保護 | 6 | | `VibrationPatternsTests` | `VibrationPatterns` 與方向性震動設定、語意情境解析、能力感知的多段式微震動序列,以及歷程滾輪阻尼感、字數上限硬牆、震動強度預覽、右搖桿選取粒度、組合鍵進入提示與喚起握手回饋的回歸保護 | 37 | | `VibrationSafetyLimiterTests` | `VibrationSafetyLimiter` 熱保護、Duty Cycle 限制器與極端邊界保護;馬達數量熱成本倍率正規化,以及所有內建震動模式在冷啟動下不得被拒絕、單次超出預算改為降強度,以及Critical 自動連發(含不同模式交錯)降級、熱負載不失控,以及冷啟動短序列仍完整送出的回歸保護 | 20 | -| **合計** | | **447** | +| **合計** | | **449** | ## 二、執行方式 🚀 From 408a48ace7355acf10fa45511410e46cff6cd0c3 Mon Sep 17 00:00:00 2001 From: perditavojo <117562794+perditavojo@users.noreply.github.com> Date: Sat, 31 Oct 2026 10:18:23 +0800 Subject: [PATCH 2/6] =?UTF-8?q?fix(gameinput):=20=E4=BF=AE=E6=AD=A3?= =?UTF-8?q?=E8=A3=9D=E7=BD=AE=E6=8E=A2=E7=B4=A2=E7=AB=B6=E6=85=8B=E3=80=81?= =?UTF-8?q?=E7=86=B1=E6=8F=92=E6=8B=94=E6=97=97=E6=A8=99=E8=A6=86=E8=93=8B?= =?UTF-8?q?=E8=88=87=E4=BE=8B=E5=A4=96=E5=82=B3=E9=81=9E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 修正 GitHub PR #88 審查提出的 5 項 GameInput 裝置探索與輪詢議題: 1. 修正 StopPolling 與 CheckAndApplyDiscoveryResults 之間的探索工作所有權競態,在 Resume 時優先停止舊輪詢再解除暫停,並引入世代與同步鎖避免過期結果套用或重複釋放。 2. 修正 PollingLoopAsync 初次裝置列舉失敗時吞掉例外導致 initTcs 誤回報成功的問題,確保初次列舉例外能正確傳遞至 initTcs 以觸發 XInput 退避機制。 3. 修正 Pause 期間丟棄進行中探索導致 _needsRefresh 重新整理要求遺失的問題,確保 StopPolling 與 Resume 時皆保留探索要求。 4. 修正探索期間新熱插拔事件被 ApplyDiscoveredDevices 蓋回 false 的問題,改用版本號比對僅在無新事件時清除重新整理標記。 5. 修正背景探索失敗或取消時未恢復 _needsRefresh 的問題,確保錯誤後能重新嘗試探索。 6. 新增 5 項單元測試並同步更新測試文件。 --- .../Core/Input/GameInputGamepadController.cs | 338 ++++++++++++------ .../GamepadControllerPauseTests.cs | 155 +++++++- tests/InputBox.Tests/README.md | 4 +- 3 files changed, 378 insertions(+), 119 deletions(-) diff --git a/src/InputBox/Core/Input/GameInputGamepadController.cs b/src/InputBox/Core/Input/GameInputGamepadController.cs index 596e892b..93a83d36 100644 --- a/src/InputBox/Core/Input/GameInputGamepadController.cs +++ b/src/InputBox/Core/Input/GameInputGamepadController.cs @@ -114,6 +114,26 @@ internal sealed partial class GameInputGamepadController : IGamepadController /// private int _missingReadingFrameCounter; + /// + /// 保護背景裝置探索工作生命週期的同步鎖。 + /// + private readonly Lock _discoveryLock = new(); + + /// + /// 目前輪詢世代編號,用於辨識並捨棄過期輪詢迴圈的探索結果。 + /// + private int _pollingGeneration; + + /// + /// 裝置重新整理要求版本號,用於偵測探索期間是否發生新的熱插拔事件。 + /// + private long _refreshRequestVersion; + + /// + /// 目前進行中的背景裝置探索工作所捕捉的重新整理要求版本號。 + /// + private long _activeDiscoveryVersion; + /// /// 目前進行中的背景裝置探索工作 /// @@ -738,19 +758,30 @@ private void StartPolling() /// private void StopPolling() { + // 遞增世代以使舊輪詢迴圈與進行中的探索失效。 + Interlocked.Increment(ref _pollingGeneration); + CancellationTokenSource? cts = Interlocked.Exchange(ref _ctsPolling, null); - if (cts == null) + if (cts != null) { - return; + LogGameInputDiagnosticsSnapshot("stop-polling"); + cts.CancelAndDispose(); } - LogGameInputDiagnosticsSnapshot("stop-polling"); - cts.CancelAndDispose(); - - Interlocked.Exchange(ref _discoveryCts, null)?.CancelAndDispose(); + Task>? pendingDiscovery = null; + lock (_discoveryLock) + { + Interlocked.Exchange(ref _discoveryCts, null)?.CancelAndDispose(); + pendingDiscovery = _deviceDiscoveryTask; + _deviceDiscoveryTask = null; - Task>? pendingDiscovery = _deviceDiscoveryTask; - _deviceDiscoveryTask = null; + if (_disposed == 0) + { + _needsRefresh = true; + Interlocked.Exchange(ref _refreshRequestedTicks, Stopwatch.GetTimestamp()); + Interlocked.Increment(ref _refreshRequestVersion); + } + } if (pendingDiscovery != null) { @@ -758,24 +789,31 @@ private void StopPolling() { if (t.IsCompletedSuccessfully) { - IReadOnlyList devices = t.Result; - - for (int i = 0; i < devices.Count; i++) - { - try - { - devices[i].Dispose(); - } - catch (Exception ex) - { - Debug.WriteLine($"[GameInput] 取消後清理探索裝置失敗(已忽略):{ex.Message}"); - } - } + DisposeDevices(t.Result); } }, TaskScheduler.Default); } } + /// + /// 釋放未套用的 GameInput 裝置代理清單。 + /// + /// 要釋放的裝置清單。 + private static void DisposeDevices(IReadOnlyList devices) + { + for (int i = 0; i < devices.Count; i++) + { + try + { + devices[i].Dispose(); + } + catch (Exception ex) + { + Debug.WriteLine($"[GameInput] 釋放未套用裝置失敗(已忽略):{ex.Message}"); + } + } + } + /// /// 處理裝置斷線與清理邏輯 /// @@ -867,6 +905,8 @@ private void SetupReadingCallback() /// Task private async Task PollingLoopAsync(CancellationToken cancellationToken, TaskCompletionSource? initTcs = null) { + int pollingGeneration = Interlocked.Increment(ref _pollingGeneration); + // 在背景執行緒(MTA)建立正式使用的 GameInput 實體。 // 這樣 COM 物件的單元模型就會與輪詢執行緒完全一致,徹底解決 InvalidCastException 與跨執行緒存取失效的問題。 try @@ -903,6 +943,7 @@ private async Task PollingLoopAsync(CancellationToken cancellationToken, TaskCom // 記錄觸發當下的時間。 Interlocked.Exchange(ref _refreshRequestedTicks, Stopwatch.GetTimestamp()); + Interlocked.Increment(ref _refreshRequestVersion); } }); @@ -913,20 +954,27 @@ private async Task PollingLoopAsync(CancellationToken cancellationToken, TaskCom { try { + long initialVersion = Interlocked.Read(ref _refreshRequestVersion); IReadOnlyList initialDevices = await _gameInput.EnumerateDevicesAsync( GameInputKind.GameInputKindGamepad, cancellationToken).ConfigureAwait(false); ApplyDiscoveredDevices(initialDevices); + if (Interlocked.Read(ref _refreshRequestVersion) == initialVersion) + { + _needsRefresh = false; + } } - catch (OperationCanceledException) + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { - // 取消時正常退出。 + initTcs?.TrySetCanceled(cancellationToken); + return; } catch (Exception ex) { LoggerService.LogException(ex, "GameInput 初次裝置列舉失敗"); Debug.WriteLine($"[GameInput] 初次裝置列舉失敗:{ex.Message}"); + throw; } } } @@ -993,11 +1041,12 @@ private async Task PollingLoopAsync(CancellationToken cancellationToken, TaskCom // 裝置連線已由初始化快速掃描完成;此次呼叫的目的是在計時器首幀(16ms) // 延遲發生前,先讀取一次完整的按鍵/搖桿初始狀態,避免首幀狀態為空白。 if (!cancellationToken.IsCancellationRequested && - _disposed == 0) + _disposed == 0 && + pollingGeneration == Volatile.Read(ref _pollingGeneration)) { try { - Poll(); + Poll(pollingGeneration); } catch (Exception ex) { @@ -1008,14 +1057,15 @@ private async Task PollingLoopAsync(CancellationToken cancellationToken, TaskCom while (await periodicTimer.WaitForNextTickAsync(cancellationToken)) { if (_disposed != 0 || - cancellationToken.IsCancellationRequested) + cancellationToken.IsCancellationRequested || + pollingGeneration != Volatile.Read(ref _pollingGeneration)) { break; } try { - Poll(); + Poll(pollingGeneration); } catch (Exception ex) { @@ -1221,8 +1271,14 @@ private static string GetDisplayName(GameInputDeviceInfoSnapshot snapshot) /// /// 輪詢 /// - private void Poll() + /// 目前輪詢迴圈的世代編號。 + private void Poll(int pollingGeneration = 0) { + if (pollingGeneration != 0 && pollingGeneration != Volatile.Read(ref _pollingGeneration)) + { + return; + } + GameInputClient? gameInput = _gameInput; if (gameInput == null) @@ -1238,10 +1294,11 @@ private void Poll() { _needsRefresh = true; Interlocked.Exchange(ref _refreshRequestedTicks, Stopwatch.GetTimestamp()); + Interlocked.Increment(ref _refreshRequestVersion); } // 先檢查並套用已完成的非同步裝置探索結果。 - CheckAndApplyDiscoveryResults(); + CheckAndApplyDiscoveryResults(pollingGeneration); // 裝置清單防抖與掃描邏輯。 if (_needsRefresh) @@ -1252,7 +1309,7 @@ private void Poll() { _reconnectCounter = 0; - StartDeviceDiscovery(); + StartDeviceDiscovery(pollingGeneration); } else { @@ -1263,7 +1320,7 @@ private void Poll() { _reconnectCounter = 0; - StartDeviceDiscovery(); + StartDeviceDiscovery(pollingGeneration); } } } @@ -1275,7 +1332,7 @@ private void Poll() { _reconnectCounter = 0; - StartDeviceDiscovery(); + StartDeviceDiscovery(pollingGeneration); } } @@ -1299,7 +1356,7 @@ private void Poll() { Debug.WriteLine("[GameInput] 目前裝置狀態已非 Connected,立即重新整理裝置清單。"); LogGameInputDiagnosticsSnapshot("device-status-non-connected"); - RefreshAfterCurrentDeviceBecameUnavailable(); + RefreshAfterCurrentDeviceBecameUnavailable(pollingGeneration); return; } @@ -1310,7 +1367,7 @@ private void Poll() { RecordMissingReading(null, dev); - if (HandleMissingCurrentReading()) + if (HandleMissingCurrentReading(pollingGeneration)) { return; } @@ -1334,7 +1391,7 @@ private void Poll() RecordReadFailure(ex); Debug.WriteLine($"[GameInput] 讀取目前狀態失敗,稍後重新整理裝置:{ex.Message}"); - if (HandleMissingCurrentReading()) + if (HandleMissingCurrentReading(pollingGeneration)) { return; } @@ -1450,11 +1507,13 @@ private void Poll() /// /// 目前裝置已不可用時立即重新整理裝置清單。 /// - private void RefreshAfterCurrentDeviceBecameUnavailable() + /// 目前輪詢迴圈的世代編號。 + private void RefreshAfterCurrentDeviceBecameUnavailable(int pollingGeneration = 0) { _missingReadingFrameCounter = 0; _needsRefresh = true; Interlocked.Exchange(ref _refreshRequestedTicks, Stopwatch.GetTimestamp()); + Interlocked.Increment(ref _refreshRequestVersion); bool needsDisconnect = false, needsConnectNotify = false; @@ -1516,14 +1575,15 @@ private void RefreshAfterCurrentDeviceBecameUnavailable() ConnectionChanged?.Invoke(true); } - StartDeviceDiscovery(); + StartDeviceDiscovery(pollingGeneration); } /// /// 處理目前裝置連續讀不到 reading 的情境;超過閾值時立即重列舉以偵測斷線。 /// + /// 目前輪詢迴圈的世代編號。 /// 若已重列舉且目前幀應停止後續狀態處理則回傳 true。 - private bool HandleMissingCurrentReading() + private bool HandleMissingCurrentReading(int pollingGeneration = 0) { if (!ShouldRefreshAfterMissingCurrentReading()) { @@ -1532,9 +1592,10 @@ private bool HandleMissingCurrentReading() _needsRefresh = true; Interlocked.Exchange(ref _refreshRequestedTicks, Stopwatch.GetTimestamp()); + Interlocked.Increment(ref _refreshRequestVersion); LogGameInputDiagnosticsSnapshot("missing-reading-threshold"); - StartDeviceDiscovery(); + StartDeviceDiscovery(pollingGeneration); return _device == null; } @@ -1854,98 +1915,147 @@ private void ResetTransientInputState(bool requireNeutralBeforeInput = true) /// 啟動非同步裝置探索工作。 /// 探索在背景執行且不持有 ,避免阻塞 60 FPS 輪詢迴圈或導致現有手把輸入遺失。 /// - private void StartDeviceDiscovery() + /// 目前輪詢迴圈的世代編號。 + private void StartDeviceDiscovery(int pollingGeneration = 0) { - if (_deviceDiscoveryTask != null || - _disposed != 0 || - _isPaused || - _gameInput == null) + lock (_discoveryLock) { - return; - } - - _needsRefresh = false; + if (_deviceDiscoveryTask != null || + _disposed != 0 || + _isPaused || + _gameInput == null || + (pollingGeneration != 0 && pollingGeneration != Volatile.Read(ref _pollingGeneration))) + { + return; + } - CancellationTokenSource? pollingCts = _ctsPolling; - CancellationToken pollingToken = pollingCts?.Token ?? CancellationToken.None; + CancellationTokenSource? pollingCts = _ctsPolling; + CancellationToken pollingToken = pollingCts?.Token ?? CancellationToken.None; - if (pollingToken.IsCancellationRequested) - { - return; - } + if (pollingToken.IsCancellationRequested) + { + return; + } - CancellationTokenSource discoveryCts = CancellationTokenSource.CreateLinkedTokenSource(pollingToken); - _discoveryCts = discoveryCts; + CancellationTokenSource discoveryCts = CancellationTokenSource.CreateLinkedTokenSource(pollingToken); + _discoveryCts = discoveryCts; + _activeDiscoveryVersion = Interlocked.Read(ref _refreshRequestVersion); - try - { - _deviceDiscoveryTask = _gameInput.EnumerateDevicesAsync( - GameInputKind.GameInputKindGamepad, - discoveryCts.Token); - } - catch (Exception ex) - { - _needsRefresh = true; - _deviceDiscoveryTask = null; - Interlocked.Exchange(ref _discoveryCts, null)?.Dispose(); + try + { + _deviceDiscoveryTask = _gameInput.EnumerateDevicesAsync( + GameInputKind.GameInputKindGamepad, + discoveryCts.Token); + } + catch (Exception ex) + { + _needsRefresh = true; + Interlocked.Exchange(ref _refreshRequestedTicks, Stopwatch.GetTimestamp()); + Interlocked.Increment(ref _refreshRequestVersion); + _deviceDiscoveryTask = null; + Interlocked.Exchange(ref _discoveryCts, null)?.Dispose(); - LoggerService.LogException(ex, "GameInput 啟動裝置探索失敗"); - Debug.WriteLine($"[GameInput] 啟動裝置探索失敗:{ex.Message}"); + LoggerService.LogException(ex, "GameInput 啟動裝置探索失敗"); + Debug.WriteLine($"[GameInput] 啟動裝置探索失敗:{ex.Message}"); + } } } /// /// 檢查背景裝置探索工作是否完成,並於輪詢執行緒套用結果。 /// - private void CheckAndApplyDiscoveryResults() + /// 目前輪詢迴圈的世代編號。 + private void CheckAndApplyDiscoveryResults(int pollingGeneration = 0) { - Task>? task = _deviceDiscoveryTask; + IReadOnlyList? discoveredToApply = null; + IReadOnlyList? discoveredToDispose = null; + long capturedVersion = 0; - if (task == null || !task.IsCompleted) + lock (_discoveryLock) { - return; - } - - _deviceDiscoveryTask = null; - Interlocked.Exchange(ref _discoveryCts, null)?.Dispose(); + Task>? task = _deviceDiscoveryTask; - try - { - if (task.IsCompletedSuccessfully) + if (task == null || !task.IsCompleted) { - IReadOnlyList discovered = task.Result; + return; + } - if (_disposed == 0 && - !_isPaused && - _gameInput != null) - { - ApplyDiscoveredDevices(discovered); - } - else + _deviceDiscoveryTask = null; + Interlocked.Exchange(ref _discoveryCts, null)?.Dispose(); + capturedVersion = _activeDiscoveryVersion; + + try + { + if (task.IsCompletedSuccessfully) { - for (int i = 0; i < discovered.Count; i++) + IReadOnlyList discovered = task.Result; + + bool isCurrentGeneration = pollingGeneration == 0 || pollingGeneration == Volatile.Read(ref _pollingGeneration); + if (_disposed == 0 && + !_isPaused && + isCurrentGeneration) { - try - { - discovered[i].Dispose(); - } - catch (Exception ex) + discoveredToApply = discovered; + } + else + { + if (_disposed == 0) { - Debug.WriteLine($"[GameInput] 釋放未套用裝置失敗(已忽略):{ex.Message}"); + _needsRefresh = true; + Interlocked.Exchange(ref _refreshRequestedTicks, Stopwatch.GetTimestamp()); + Interlocked.Increment(ref _refreshRequestVersion); } + + discoveredToDispose = discovered; + } + } + else if (task.IsFaulted || task.IsCanceled) + { + _needsRefresh = true; + Interlocked.Exchange(ref _refreshRequestedTicks, Stopwatch.GetTimestamp()); + Interlocked.Increment(ref _refreshRequestVersion); + + if (task.IsFaulted && task.Exception != null) + { + LoggerService.LogException(task.Exception.GetBaseException(), "GameInput 裝置非同步探索失敗"); + Debug.WriteLine($"[GameInput] 裝置非同步探索失敗:{task.Exception.GetBaseException().Message}"); } } } - else if (task.IsFaulted && task.Exception != null) + catch (Exception ex) { - LoggerService.LogException(task.Exception.GetBaseException(), "GameInput 裝置非同步探索失敗"); - Debug.WriteLine($"[GameInput] 裝置非同步探索失敗:{task.Exception.GetBaseException().Message}"); + _needsRefresh = true; + Interlocked.Exchange(ref _refreshRequestedTicks, Stopwatch.GetTimestamp()); + Interlocked.Increment(ref _refreshRequestVersion); + + LoggerService.LogException(ex, "GameInput 檢查探索結果失敗"); + Debug.WriteLine($"[GameInput] 檢查探索結果失敗:{ex.Message}"); } } - catch (Exception ex) + + if (discoveredToApply != null) { - LoggerService.LogException(ex, "GameInput 套用探索裝置失敗"); - Debug.WriteLine($"[GameInput] 套用探索裝置失敗:{ex.Message}"); + try + { + ApplyDiscoveredDevices(discoveredToApply); + if (Interlocked.Read(ref _refreshRequestVersion) == capturedVersion) + { + _needsRefresh = false; + } + } + catch (Exception ex) + { + _needsRefresh = true; + Interlocked.Exchange(ref _refreshRequestedTicks, Stopwatch.GetTimestamp()); + Interlocked.Increment(ref _refreshRequestVersion); + + LoggerService.LogException(ex, "GameInput 套用探索裝置失敗"); + Debug.WriteLine($"[GameInput] 套用探索裝置失敗:{ex.Message}"); + } + } + else if (discoveredToDispose != null) + { + DisposeDevices(discoveredToDispose); } } @@ -1960,7 +2070,6 @@ private void ApplyDiscoveredDevices(IReadOnlyList devices) lock (_deviceLock) { - _needsRefresh = false; // 1. 釋放清單中已不再存在或已非 Connected 的舊裝置代理(Zero-allocation 替換 LINQ Any)。 for (int i = _allDevices.Count - 1; i >= 0; i--) @@ -3191,7 +3300,11 @@ public void Resume() } ResetTransientInputState(); + StopPolling(); _isPaused = false; + _needsRefresh = true; + Interlocked.Exchange(ref _refreshRequestedTicks, Stopwatch.GetTimestamp()); + Interlocked.Increment(ref _refreshRequestVersion); StartPolling(); } @@ -3402,26 +3515,19 @@ private Task DisposeResourcesAsync() readingCallbackReg?.Dispose(); // 若有進行中的背景探索工作,等待其完成並釋放所產生的裝置代理。 - Task>? discoveryTask = _deviceDiscoveryTask; - _deviceDiscoveryTask = null; + Task>? discoveryTask; + lock (_discoveryLock) + { + discoveryTask = _deviceDiscoveryTask; + _deviceDiscoveryTask = null; + } if (discoveryTask != null) { try { IReadOnlyList pending = await discoveryTask.ConfigureAwait(false); - - for (int i = 0; i < pending.Count; i++) - { - try - { - pending[i].Dispose(); - } - catch (Exception ex) - { - Debug.WriteLine($"[GameInput] 處置時釋放探索裝置失敗(已忽略):{ex.Message}"); - } - } + DisposeDevices(pending); } catch (Exception ex) { diff --git a/tests/InputBox.Tests/GamepadControllerPauseTests.cs b/tests/InputBox.Tests/GamepadControllerPauseTests.cs index 909227ca..c9e80c73 100644 --- a/tests/InputBox.Tests/GamepadControllerPauseTests.cs +++ b/tests/InputBox.Tests/GamepadControllerPauseTests.cs @@ -262,8 +262,161 @@ public void CheckAndApplyDiscoveryResults_WhenNoTask_DoesNotThrow() BindingFlags.Instance | BindingFlags.NonPublic) ?? throw new InvalidOperationException("找不到 GameInputGamepadController.CheckAndApplyDiscoveryResults。"); - method.Invoke(controller, []); + method.Invoke(controller, [0]); + + Assert.Null(GetPrivateField>?>(controller, "_deviceDiscoveryTask")); + } + + /// + /// GameInput 控制器在 Pause 後,應保留 _needsRefresh 重新整理標記並遞增版本號, + /// 確保原生對話框關閉或恢復輪詢時不會遺失探索需求。 + /// + [Fact] + public void Pause_GameInputController_PreservesNeedsRefreshAndIncrementsVersion() + { + using var controller = (GameInputGamepadController)Activator.CreateInstance( + typeof(GameInputGamepadController), + BindingFlags.Instance | BindingFlags.NonPublic, + binder: null, + args: [new StubInputContext(), null], + culture: null)!; + + SetPrivateField(controller, "_needsRefresh", false); + SetPrivateField(controller, "_refreshRequestVersion", 10L); + + CancellationTokenSource discoveryCts = new(); + SetPrivateField(controller, "_discoveryCts", discoveryCts); + SetPrivateField(controller, "_deviceDiscoveryTask", Task.FromResult>([])); + + controller.Pause(); + + Assert.True(GetPrivateField(controller, "_needsRefresh")); + Assert.True(GetPrivateField(controller, "_refreshRequestVersion") > 10L); + Assert.Null(GetPrivateField>?>(controller, "_deviceDiscoveryTask")); + Assert.True(discoveryCts.IsCancellationRequested); + } + + /// + /// GameInput 控制器在背景探索工作失敗(Faulted)時,CheckAndApplyDiscoveryResults 應重新設定 + /// _needsRefresh 為 true 並遞增版本號,確保後續輪詢能重新嘗試探索。 + /// + [Fact] + public void CheckAndApplyDiscoveryResults_WhenTaskFaulted_RestoresNeedsRefreshAndIncrementsVersion() + { + using var controller = (GameInputGamepadController)Activator.CreateInstance( + typeof(GameInputGamepadController), + BindingFlags.Instance | BindingFlags.NonPublic, + binder: null, + args: [new StubInputContext(), null], + culture: null)!; + + MethodInfo method = typeof(GameInputGamepadController).GetMethod( + "CheckAndApplyDiscoveryResults", + BindingFlags.Instance | BindingFlags.NonPublic) + ?? throw new InvalidOperationException("找不到 GameInputGamepadController.CheckAndApplyDiscoveryResults。"); + + SetPrivateField(controller, "_needsRefresh", false); + SetPrivateField(controller, "_refreshRequestVersion", 5L); + SetPrivateField( + controller, + "_deviceDiscoveryTask", + Task.FromException>(new InvalidOperationException("測試探索異常"))); + + method.Invoke(controller, [0]); + + Assert.True(GetPrivateField(controller, "_needsRefresh")); + Assert.True(GetPrivateField(controller, "_refreshRequestVersion") > 5L); + Assert.Null(GetPrivateField>?>(controller, "_deviceDiscoveryTask")); + } + + /// + /// GameInput 控制器在背景探索期間若收到新的重新整理要求(版本號改變), + /// CheckAndApplyDiscoveryResults 不應將 _needsRefresh 重設為 false,避免蓋過新插拔事件。 + /// + [Fact] + public void CheckAndApplyDiscoveryResults_WhenVersionChangedDuringDiscovery_PreservesNeedsRefresh() + { + using var controller = (GameInputGamepadController)Activator.CreateInstance( + typeof(GameInputGamepadController), + BindingFlags.Instance | BindingFlags.NonPublic, + binder: null, + args: [new StubInputContext(), null], + culture: null)!; + + MethodInfo method = typeof(GameInputGamepadController).GetMethod( + "CheckAndApplyDiscoveryResults", + BindingFlags.Instance | BindingFlags.NonPublic) + ?? throw new InvalidOperationException("找不到 GameInputGamepadController.CheckAndApplyDiscoveryResults。"); + + SetPrivateField(controller, "_needsRefresh", true); + SetPrivateField(controller, "_activeDiscoveryVersion", 1L); + SetPrivateField(controller, "_refreshRequestVersion", 2L); + SetPrivateField(controller, "_deviceDiscoveryTask", Task.FromResult>([])); + + method.Invoke(controller, [0]); + + Assert.True(GetPrivateField(controller, "_needsRefresh")); + Assert.Null(GetPrivateField>?>(controller, "_deviceDiscoveryTask")); + } + + /// + /// GameInput 控制器在背景探索期間若無新的重新整理要求(版本號相同), + /// CheckAndApplyDiscoveryResults 應正常將 _needsRefresh 重設為 false。 + /// + [Fact] + public void CheckAndApplyDiscoveryResults_WhenVersionUnchanged_ClearsNeedsRefresh() + { + using var controller = (GameInputGamepadController)Activator.CreateInstance( + typeof(GameInputGamepadController), + BindingFlags.Instance | BindingFlags.NonPublic, + binder: null, + args: [new StubInputContext(), null], + culture: null)!; + + MethodInfo method = typeof(GameInputGamepadController).GetMethod( + "CheckAndApplyDiscoveryResults", + BindingFlags.Instance | BindingFlags.NonPublic) + ?? throw new InvalidOperationException("找不到 GameInputGamepadController.CheckAndApplyDiscoveryResults。"); + + SetPrivateField(controller, "_needsRefresh", true); + SetPrivateField(controller, "_activeDiscoveryVersion", 3L); + SetPrivateField(controller, "_refreshRequestVersion", 3L); + SetPrivateField(controller, "_deviceDiscoveryTask", Task.FromResult>([])); + + method.Invoke(controller, [0]); + + Assert.False(GetPrivateField(controller, "_needsRefresh")); + Assert.Null(GetPrivateField>?>(controller, "_deviceDiscoveryTask")); + } + + /// + /// GameInput 控制器在過期輪詢世代執行時,CheckAndApplyDiscoveryResults 應捨棄探索結果、 + /// 恢復 _needsRefresh 為 true,且不套用至目前裝置。 + /// + [Fact] + public void CheckAndApplyDiscoveryResults_WhenStaleGeneration_DiscardsResultsAndRestoresNeedsRefresh() + { + using var controller = (GameInputGamepadController)Activator.CreateInstance( + typeof(GameInputGamepadController), + BindingFlags.Instance | BindingFlags.NonPublic, + binder: null, + args: [new StubInputContext(), null], + culture: null)!; + + MethodInfo method = typeof(GameInputGamepadController).GetMethod( + "CheckAndApplyDiscoveryResults", + BindingFlags.Instance | BindingFlags.NonPublic) + ?? throw new InvalidOperationException("找不到 GameInputGamepadController.CheckAndApplyDiscoveryResults。"); + + SetPrivateField(controller, "_pollingGeneration", 5); + SetPrivateField(controller, "_needsRefresh", false); + SetPrivateField(controller, "_refreshRequestVersion", 10L); + SetPrivateField(controller, "_deviceDiscoveryTask", Task.FromResult>([])); + + method.Invoke(controller, [4]); + Assert.True(GetPrivateField(controller, "_needsRefresh")); + Assert.True(GetPrivateField(controller, "_refreshRequestVersion") > 10L); Assert.Null(GetPrivateField>?>(controller, "_deviceDiscoveryTask")); } diff --git a/tests/InputBox.Tests/README.md b/tests/InputBox.Tests/README.md index 5b9c8e0b..e46c56da 100644 --- a/tests/InputBox.Tests/README.md +++ b/tests/InputBox.Tests/README.md @@ -21,7 +21,7 @@ | `FormInputStateManagerTests` | `FormInputStateManager` 輸入狀態切換 | 15 | | `GamepadDeadzoneHysteresisTests` | `GamepadDeadzoneHysteresis.ResolveDirection`(int / float 多載),含正負方向對稱性守門(硬體平等原則) | 14 | | `GamepadControllerFactoryTests` | 控制器後端建立策略,驗證 XInput 預設路徑、GameInput 成功路徑,以及 GameInput 執行階段不可用時退避至 XInput | 3 | -| `GamepadControllerPauseTests` | 控制器在 `Pause()` / `Resume()`、連線可用性語意、GameInput 讀取缺失斷線重列舉、非同步分階段裝置探索、裝置狀態過濾、震動停止安全性、`ClearAllEvents` 肩鍵釋放訂閱清除與原生對話框切換時的殘留輸入回歸保護 | 12 | +| `GamepadControllerPauseTests` | 控制器在 `Pause()` / `Resume()`、連線可用性語意、GameInput 讀取缺失斷線重列舉、非同步分階段裝置探索、探索所有權與競態防護、熱插拔版本防覆蓋、探索失敗重試保留、裝置狀態過濾、震動停止安全性、`ClearAllEvents` 肩鍵釋放訂閱清除與原生對話框切換時的殘留輸入回歸保護 | 17 | | `GameInputDirectUsageTests` | `GameInputGamepadController` 直接使用 `InputWeave.GameInput` 遊戲控制器介面的守門、callback function pointer marshaling、官方 v3 按鍵位元、快照邊緣偵測、Release 日誌邊界、穩定裝置識別與震動參數保留 | 9 | | `FlashAlertAnimatorTests` | `FlashAlertAnimator` 共用閃爍警示:主題警示色、純淨底色至警示色的插值、整個脈衝過程文字對比 ≥4.5:1、高對比模式半強度切換,以及 1Hz 單次正弦脈衝強度 | 7 | | `GamepadBiasSmoothingTests` | `GamepadBiasSmoothing` 自適應 EMA 學習率公式:零誤差用基礎值、超出範圍用最大值,以及 XInput 與 GameInput 不同數值尺度下結果一致 | 5 | @@ -50,7 +50,7 @@ | `TextBoxSelectionExtensionsTests` | 右搖桿延伸選取共用的 `ResolveSelectionAnchor` 錨點解析(無選取、正向、反向、錨點失效)與 `GetWordJumpTarget` 單字跳轉目標(不改變目前選取、方向與邊界);原本三處複本集中後的一致性保護 | 6 | | `VibrationPatternsTests` | `VibrationPatterns` 與方向性震動設定、語意情境解析、能力感知的多段式微震動序列,以及歷程滾輪阻尼感、字數上限硬牆、震動強度預覽、右搖桿選取粒度、組合鍵進入提示與喚起握手回饋的回歸保護 | 37 | | `VibrationSafetyLimiterTests` | `VibrationSafetyLimiter` 熱保護、Duty Cycle 限制器與極端邊界保護;馬達數量熱成本倍率正規化,以及所有內建震動模式在冷啟動下不得被拒絕、單次超出預算改為降強度,以及Critical 自動連發(含不同模式交錯)降級、熱負載不失控,以及冷啟動短序列仍完整送出的回歸保護 | 20 | -| **合計** | | **449** | +| **合計** | | **454** | ## 二、執行方式 🚀 From 83364c29b755ab095da49110c9e2db35df138b7f Mon Sep 17 00:00:00 2001 From: perditavojo <117562794+perditavojo@users.noreply.github.com> Date: Sat, 31 Oct 2026 10:37:02 +0800 Subject: [PATCH 3/6] =?UTF-8?q?fix(gameinput):=20=E4=BF=AE=E6=AD=A3?= =?UTF-8?q?=E8=BC=AA=E8=A9=A2=E4=B8=96=E4=BB=A3=E6=8E=92=E7=A8=8B=E5=88=86?= =?UTF-8?q?=E9=85=8D=E3=80=81=E5=BF=AB=E5=8F=96=E4=BA=A4=E6=8E=A5=E7=94=9F?= =?UTF-8?q?=E5=91=BD=E9=80=B1=E6=9C=9F=E8=88=87=E5=88=B7=E6=96=B0=E5=90=8C?= =?UTF-8?q?=E6=AD=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 修正 GitHub PR #88 最新審查提出的 3 項問題: 1. 改在排程前於呼叫端(InitializeAndStartPollingAsync 與 StartPolling)分配世代並傳入 PollingLoopAsync,避免排程延遲的舊工作在執行時遞增世代使最新迴圈誤判失效。 2. 統一最終生命週期驗證與快取所有權交接至 _deviceLock 同步邊界,確保在 Pause、StopPolling 或 Dispose 期間完成的探索結果均會被立即拒絕並釋放,防止過期代理洩漏或殘留。 3. 引入 _refreshLock 同步鎖與 NeedsDeviceRefresh / RequestRefresh / AcknowledgeRefresh 機制,讓 callback 發布與探索結算共用同步機制,解決版本比對後新事件被清除覆蓋的問題。 4. 新增 3 項單元測試並同步更新測試文件。 --- .../Core/Input/GameInputGamepadController.cs | 314 +++++++++++------- .../GamepadControllerPauseTests.cs | 105 ++++++ tests/InputBox.Tests/README.md | 4 +- 3 files changed, 298 insertions(+), 125 deletions(-) diff --git a/src/InputBox/Core/Input/GameInputGamepadController.cs b/src/InputBox/Core/Input/GameInputGamepadController.cs index 93a83d36..55c709d8 100644 --- a/src/InputBox/Core/Input/GameInputGamepadController.cs +++ b/src/InputBox/Core/Input/GameInputGamepadController.cs @@ -56,11 +56,70 @@ internal sealed partial class GameInputGamepadController : IGamepadController /// private volatile bool _needsRefresh = true; + /// + /// 保護裝置重新整理請求與版本號比對的同步鎖。 + /// + private readonly Lock _refreshLock = new(); + + /// + /// 裝置重新整理要求版本號,用於偵測探索期間是否發生新的熱插拔事件。 + /// + private long _refreshRequestVersion; + + /// + /// 最後一次成功結算並套用的重新整理要求版本號。 + /// + private long _lastCompletedRefreshVersion; + /// /// 記錄最後一次要求重新整理的時間點 (Tick) /// private long _refreshRequestedTicks; + /// + /// 判斷目前是否需要進行裝置清單重新整理。 + /// + private bool NeedsDeviceRefresh + { + get + { + lock (_refreshLock) + { + return _needsRefresh || (_refreshRequestVersion != _lastCompletedRefreshVersion); + } + } + } + + /// + /// 發出裝置重新整理要求,並記錄當下時間戳記與遞增要求版本號。 + /// + private void RequestRefresh() + { + lock (_refreshLock) + { + _needsRefresh = true; + _refreshRequestedTicks = Stopwatch.GetTimestamp(); + _refreshRequestVersion++; + } + } + + /// + /// 確認並結算特定版本的裝置探索結果,若無更新的要求則清除重新整理標記。 + /// + /// 探索工作啟動時所捕捉的要求版本號。 + private void AcknowledgeRefresh(long capturedVersion) + { + lock (_refreshLock) + { + _lastCompletedRefreshVersion = capturedVersion; + + if (_refreshRequestVersion == capturedVersion) + { + _needsRefresh = false; + } + } + } + /// /// 記錄最後一次收到讀取回呼的時間點;正式輸入仍由 60 FPS polling 消費。 /// @@ -124,11 +183,6 @@ internal sealed partial class GameInputGamepadController : IGamepadController /// private int _pollingGeneration; - /// - /// 裝置重新整理要求版本號,用於偵測探索期間是否發生新的熱插拔事件。 - /// - private long _refreshRequestVersion; - /// /// 目前進行中的背景裝置探索工作所捕捉的重新整理要求版本號。 /// @@ -729,7 +783,8 @@ private Task InitializeAndStartPollingAsync() TaskCompletionSource tcs = new(TaskCreationOptions.RunContinuationsAsynchronously); - _taskPolling = Task.Run(() => PollingLoopAsync(token, tcs), token); + int generation = Interlocked.Increment(ref _pollingGeneration); + _taskPolling = Task.Run(() => PollingLoopAsync(token, generation, tcs), token); return tcs.Task; } @@ -750,7 +805,8 @@ private void StartPolling() _ctsPolling = cts; - _taskPolling = Task.Run(() => PollingLoopAsync(token, null), token); + int generation = Interlocked.Increment(ref _pollingGeneration); + _taskPolling = Task.Run(() => PollingLoopAsync(token, generation, null), token); } /// @@ -777,9 +833,7 @@ private void StopPolling() if (_disposed == 0) { - _needsRefresh = true; - Interlocked.Exchange(ref _refreshRequestedTicks, Stopwatch.GetTimestamp()); - Interlocked.Increment(ref _refreshRequestVersion); + RequestRefresh(); } } @@ -903,9 +957,13 @@ private void SetupReadingCallback() /// CancellationToken /// 初始化結果回傳(僅在 CreateAsync 時傳入) /// Task - private async Task PollingLoopAsync(CancellationToken cancellationToken, TaskCompletionSource? initTcs = null) + private async Task PollingLoopAsync(CancellationToken cancellationToken, int pollingGeneration, TaskCompletionSource? initTcs = null) { - int pollingGeneration = Interlocked.Increment(ref _pollingGeneration); + if (pollingGeneration != Volatile.Read(ref _pollingGeneration)) + { + initTcs?.TrySetCanceled(cancellationToken); + return; + } // 在背景執行緒(MTA)建立正式使用的 GameInput 實體。 // 這樣 COM 物件的單元模型就會與輪詢執行緒完全一致,徹底解決 InvalidCastException 與跨執行緒存取失效的問題。 @@ -939,31 +997,28 @@ private async Task PollingLoopAsync(CancellationToken cancellationToken, TaskCom { if (deviceEvent is GameInputDeviceEvent.GameInputDeviceEventConnected or GameInputDeviceEvent.GameInputDeviceEventDisconnected) { - _needsRefresh = true; - - // 記錄觸發當下的時間。 - Interlocked.Exchange(ref _refreshRequestedTicks, Stopwatch.GetTimestamp()); - Interlocked.Increment(ref _refreshRequestVersion); + RequestRefresh(); } }); // 初始化時先非同步列舉一次以取得既有連線裝置。 - if (_needsRefresh && + if (NeedsDeviceRefresh && !cancellationToken.IsCancellationRequested && _disposed == 0) { try { - long initialVersion = Interlocked.Read(ref _refreshRequestVersion); + long initialVersion; + lock (_refreshLock) + { + initialVersion = _refreshRequestVersion; + } + IReadOnlyList initialDevices = await _gameInput.EnumerateDevicesAsync( GameInputKind.GameInputKindGamepad, cancellationToken).ConfigureAwait(false); - ApplyDiscoveredDevices(initialDevices); - if (Interlocked.Read(ref _refreshRequestVersion) == initialVersion) - { - _needsRefresh = false; - } + ApplyDiscoveredDevicesWithLifecycle(initialDevices, initialVersion, pollingGeneration); } catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { @@ -1292,16 +1347,22 @@ private void Poll(int pollingGeneration = 0) if (Interlocked.Exchange(ref _readingCallbackObservedTicks, 0) != 0 && _device == null) { - _needsRefresh = true; - Interlocked.Exchange(ref _refreshRequestedTicks, Stopwatch.GetTimestamp()); - Interlocked.Increment(ref _refreshRequestVersion); + RequestRefresh(); } // 先檢查並套用已完成的非同步裝置探索結果。 CheckAndApplyDiscoveryResults(pollingGeneration); // 裝置清單防抖與掃描邏輯。 - if (_needsRefresh) + bool needsRefresh; + long refreshTicks; + lock (_refreshLock) + { + needsRefresh = _needsRefresh || (_refreshRequestVersion != _lastCompletedRefreshVersion); + refreshTicks = _refreshRequestedTicks; + } + + if (needsRefresh) { // 若目前尚未連線任何裝置,直接啟動探索,不套用 500ms 防抖, // 以縮短「未連線 → 新插入」的首段偵測延遲。 @@ -1313,7 +1374,7 @@ private void Poll(int pollingGeneration = 0) } else { - long elapsedTicks = Stopwatch.GetTimestamp() - Interlocked.Read(ref _refreshRequestedTicks), + long elapsedTicks = Stopwatch.GetTimestamp() - refreshTicks, elapsedMs = elapsedTicks / (Stopwatch.Frequency / 1000); if (elapsedMs >= AppSettings.GamepadRefreshCooldownMs) @@ -1511,9 +1572,7 @@ private void Poll(int pollingGeneration = 0) private void RefreshAfterCurrentDeviceBecameUnavailable(int pollingGeneration = 0) { _missingReadingFrameCounter = 0; - _needsRefresh = true; - Interlocked.Exchange(ref _refreshRequestedTicks, Stopwatch.GetTimestamp()); - Interlocked.Increment(ref _refreshRequestVersion); + RequestRefresh(); bool needsDisconnect = false, needsConnectNotify = false; @@ -1590,9 +1649,7 @@ private bool HandleMissingCurrentReading(int pollingGeneration = 0) return false; } - _needsRefresh = true; - Interlocked.Exchange(ref _refreshRequestedTicks, Stopwatch.GetTimestamp()); - Interlocked.Increment(ref _refreshRequestVersion); + RequestRefresh(); LogGameInputDiagnosticsSnapshot("missing-reading-threshold"); StartDeviceDiscovery(pollingGeneration); @@ -1939,7 +1996,10 @@ private void StartDeviceDiscovery(int pollingGeneration = 0) CancellationTokenSource discoveryCts = CancellationTokenSource.CreateLinkedTokenSource(pollingToken); _discoveryCts = discoveryCts; - _activeDiscoveryVersion = Interlocked.Read(ref _refreshRequestVersion); + lock (_refreshLock) + { + _activeDiscoveryVersion = _refreshRequestVersion; + } try { @@ -1949,9 +2009,7 @@ private void StartDeviceDiscovery(int pollingGeneration = 0) } catch (Exception ex) { - _needsRefresh = true; - Interlocked.Exchange(ref _refreshRequestedTicks, Stopwatch.GetTimestamp()); - Interlocked.Increment(ref _refreshRequestVersion); + RequestRefresh(); _deviceDiscoveryTask = null; Interlocked.Exchange(ref _discoveryCts, null)?.Dispose(); @@ -1967,13 +2025,12 @@ private void StartDeviceDiscovery(int pollingGeneration = 0) /// 目前輪詢迴圈的世代編號。 private void CheckAndApplyDiscoveryResults(int pollingGeneration = 0) { - IReadOnlyList? discoveredToApply = null; - IReadOnlyList? discoveredToDispose = null; + Task>? task = null; long capturedVersion = 0; lock (_discoveryLock) { - Task>? task = _deviceDiscoveryTask; + task = _deviceDiscoveryTask; if (task == null || !task.IsCompleted) { @@ -1983,93 +2040,110 @@ private void CheckAndApplyDiscoveryResults(int pollingGeneration = 0) _deviceDiscoveryTask = null; Interlocked.Exchange(ref _discoveryCts, null)?.Dispose(); capturedVersion = _activeDiscoveryVersion; + } - try + try + { + if (task.IsCompletedSuccessfully) { - if (task.IsCompletedSuccessfully) - { - IReadOnlyList discovered = task.Result; - - bool isCurrentGeneration = pollingGeneration == 0 || pollingGeneration == Volatile.Read(ref _pollingGeneration); - if (_disposed == 0 && - !_isPaused && - isCurrentGeneration) - { - discoveredToApply = discovered; - } - else - { - if (_disposed == 0) - { - _needsRefresh = true; - Interlocked.Exchange(ref _refreshRequestedTicks, Stopwatch.GetTimestamp()); - Interlocked.Increment(ref _refreshRequestVersion); - } + ApplyDiscoveredDevicesWithLifecycle(task.Result, capturedVersion, pollingGeneration); + } + else if (task.IsFaulted || task.IsCanceled) + { + RequestRefresh(); - discoveredToDispose = discovered; - } - } - else if (task.IsFaulted || task.IsCanceled) + if (task.IsFaulted && task.Exception != null) { - _needsRefresh = true; - Interlocked.Exchange(ref _refreshRequestedTicks, Stopwatch.GetTimestamp()); - Interlocked.Increment(ref _refreshRequestVersion); - - if (task.IsFaulted && task.Exception != null) - { - LoggerService.LogException(task.Exception.GetBaseException(), "GameInput 裝置非同步探索失敗"); - Debug.WriteLine($"[GameInput] 裝置非同步探索失敗:{task.Exception.GetBaseException().Message}"); - } + LoggerService.LogException(task.Exception.GetBaseException(), "GameInput 裝置非同步探索失敗"); + Debug.WriteLine($"[GameInput] 裝置非同步探索失敗:{task.Exception.GetBaseException().Message}"); } } - catch (Exception ex) - { - _needsRefresh = true; - Interlocked.Exchange(ref _refreshRequestedTicks, Stopwatch.GetTimestamp()); - Interlocked.Increment(ref _refreshRequestVersion); + } + catch (Exception ex) + { + RequestRefresh(); - LoggerService.LogException(ex, "GameInput 檢查探索結果失敗"); - Debug.WriteLine($"[GameInput] 檢查探索結果失敗:{ex.Message}"); - } + LoggerService.LogException(ex, "GameInput 檢查探索結果失敗"); + Debug.WriteLine($"[GameInput] 檢查探索結果失敗:{ex.Message}"); } + } + + /// + /// 套用探索到的裝置清單(相容重載)。 + /// + /// 新探索到的裝置清單。 + private void ApplyDiscoveredDevices(IReadOnlyList devices) + { + ApplyDiscoveredDevicesWithLifecycle(devices, 0, 0); + } + + /// + /// 套用探索到的裝置清單,進行最終生命週期檢驗並更新已追蹤裝置與目前啟動裝置。 + /// + /// 新探索到的裝置清單。 + /// 探索工作啟動時所捕捉的要求版本號。 + /// 探索工作所屬的輪詢世代。 + private void ApplyDiscoveredDevicesWithLifecycle(IReadOnlyList devices, long capturedVersion, int pollingGeneration) + { + bool needsDisconnect = false, + needsConnectNotify = false; + List? staleDevicesToDispose = null; - if (discoveredToApply != null) + lock (_deviceLock) { - try + // 最終生命週期驗證:若在探索完成後已被處置、暫停、或輪詢世代已過期 + if (_disposed != 0 || + _isPaused || + (pollingGeneration != 0 && pollingGeneration != Volatile.Read(ref _pollingGeneration))) { - ApplyDiscoveredDevices(discoveredToApply); - if (Interlocked.Read(ref _refreshRequestVersion) == capturedVersion) + staleDevicesToDispose = [.. devices]; + + if (_disposed == 0) { - _needsRefresh = false; + RequestRefresh(); } } - catch (Exception ex) + else { - _needsRefresh = true; - Interlocked.Exchange(ref _refreshRequestedTicks, Stopwatch.GetTimestamp()); - Interlocked.Increment(ref _refreshRequestVersion); + ApplyDiscoveredDevicesCore(devices, ref needsDisconnect, ref needsConnectNotify); - LoggerService.LogException(ex, "GameInput 套用探索裝置失敗"); - Debug.WriteLine($"[GameInput] 套用探索裝置失敗:{ex.Message}"); + if (capturedVersion != 0) + { + AcknowledgeRefresh(capturedVersion); + } } } - else if (discoveredToDispose != null) + + if (staleDevicesToDispose != null) { - DisposeDevices(discoveredToDispose); + DisposeDevices(staleDevicesToDispose); + return; + } + + // 在鎖外執行,防止持鎖時觸發 ConnectionChanged 事件導致死鎖風險。 + if (needsDisconnect) + { + HandleDisconnect(); + } + + if (needsConnectNotify) + { + _isConnected = true; + ConnectionChanged?.Invoke(true); } } /// - /// 套用探索到的裝置清單,更新已追蹤裝置與目前啟動裝置。 + /// 在已持有 的前提下,更新快取裝置清單與目前啟動裝置。 /// /// 新探索到的裝置清單。 - private void ApplyDiscoveredDevices(IReadOnlyList devices) + /// 是否需要在鎖外通知斷線。 + /// 是否需要在鎖外通知連線。 + private void ApplyDiscoveredDevicesCore( + IReadOnlyList devices, + ref bool needsDisconnect, + ref bool needsConnectNotify) { - bool needsDisconnect = false, - needsConnectNotify = false; - - lock (_deviceLock) - { // 1. 釋放清單中已不再存在或已非 Connected 的舊裝置代理(Zero-allocation 替換 LINQ Any)。 for (int i = _allDevices.Count - 1; i >= 0; i--) @@ -2218,19 +2292,6 @@ private void ApplyDiscoveredDevices(IReadOnlyList devices) } } - // 在鎖外執行,防止持鎖時觸發 ConnectionChanged 事件導致死鎖風險。 - if (needsDisconnect) - { - HandleDisconnect(); - } - - if (needsConnectNotify) - { - _isConnected = true; - ConnectionChanged?.Invoke(true); - } - } - /// /// 同步尋找裝置(僅供需要立即探索的相容路徑使用,平時由背景分階段探索取代)。 /// @@ -3249,9 +3310,13 @@ public Task VibrateAsync( /// public void Pause() { - _isPaused = true; + lock (_deviceLock) + { + _isPaused = true; + ResetTransientInputState(); + } + StopPolling(); - ResetTransientInputState(); } /// @@ -3299,12 +3364,15 @@ public void Resume() return; } - ResetTransientInputState(); StopPolling(); - _isPaused = false; - _needsRefresh = true; - Interlocked.Exchange(ref _refreshRequestedTicks, Stopwatch.GetTimestamp()); - Interlocked.Increment(ref _refreshRequestVersion); + + lock (_deviceLock) + { + ResetTransientInputState(); + _isPaused = false; + } + + RequestRefresh(); StartPolling(); } diff --git a/tests/InputBox.Tests/GamepadControllerPauseTests.cs b/tests/InputBox.Tests/GamepadControllerPauseTests.cs index c9e80c73..d416fe49 100644 --- a/tests/InputBox.Tests/GamepadControllerPauseTests.cs +++ b/tests/InputBox.Tests/GamepadControllerPauseTests.cs @@ -420,6 +420,111 @@ public void CheckAndApplyDiscoveryResults_WhenStaleGeneration_DiscardsResultsAnd Assert.Null(GetPrivateField>?>(controller, "_deviceDiscoveryTask")); } + /// + /// 若舊輪詢工作傳入過期世代,PollingLoopAsync 應立即放棄並取消 initTcs,且不得竄改目前最新世代編號。 + /// + [Fact] + public async Task PollingLoopAsync_WhenStaleGeneration_AbortsWithoutMutatingPollingGeneration() + { + using var controller = (GameInputGamepadController)Activator.CreateInstance( + typeof(GameInputGamepadController), + BindingFlags.Instance | BindingFlags.NonPublic, + binder: null, + args: [new StubInputContext(), null], + culture: null)!; + + MethodInfo method = typeof(GameInputGamepadController).GetMethod( + "PollingLoopAsync", + BindingFlags.Instance | BindingFlags.NonPublic) + ?? throw new InvalidOperationException("找不到 GameInputGamepadController.PollingLoopAsync。"); + + SetPrivateField(controller, "_pollingGeneration", 3); + + using CancellationTokenSource cts = new(); + TaskCompletionSource tcs = new(); + + // 傳入過期世代 2 + var task = (Task)method.Invoke(controller, [cts.Token, 2, tcs])!; + await task; + + Assert.Equal(3, GetPrivateField(controller, "_pollingGeneration")); + Assert.True(tcs.Task.IsCanceled); + } + + /// + /// 在已暫停或已處置的狀態下,ApplyDiscoveredDevicesWithLifecycle 應拒絕寫入裝置快取,並標記需要重新整理。 + /// + [Fact] + public void ApplyDiscoveredDevicesWithLifecycle_WhenPaused_DoesNotPolluteDeviceCache() + { + using var controller = (GameInputGamepadController)Activator.CreateInstance( + typeof(GameInputGamepadController), + BindingFlags.Instance | BindingFlags.NonPublic, + binder: null, + args: [new StubInputContext(), null], + culture: null)!; + + MethodInfo method = typeof(GameInputGamepadController).GetMethod( + "ApplyDiscoveredDevicesWithLifecycle", + BindingFlags.Instance | BindingFlags.NonPublic) + ?? throw new InvalidOperationException("找不到 GameInputGamepadController.ApplyDiscoveredDevicesWithLifecycle。"); + + SetPrivateField(controller, "_isPaused", true); + SetPrivateField(controller, "_needsRefresh", false); + SetPrivateField(controller, "_pollingGeneration", 1); + + method.Invoke(controller, [Array.Empty(), 1L, 1]); + + Assert.True(GetPrivateField(controller, "_needsRefresh")); + Assert.Empty(GetPrivateField>(controller, "_allDevices")); + Assert.Null(GetPrivateField(controller, "_device")); + } + + /// + /// 若在探索完成結算時有新的重新整理請求發布(版本號已推進),AcknowledgeRefresh 不得清空重新整理標記。 + /// + [Fact] + public void AcknowledgeRefresh_WhenNewVersionPublishedConcurrently_RetainsNeedsDeviceRefresh() + { + using var controller = (GameInputGamepadController)Activator.CreateInstance( + typeof(GameInputGamepadController), + BindingFlags.Instance | BindingFlags.NonPublic, + binder: null, + args: [new StubInputContext(), null], + culture: null)!; + + MethodInfo reqMethod = typeof(GameInputGamepadController).GetMethod( + "RequestRefresh", + BindingFlags.Instance | BindingFlags.NonPublic) + ?? throw new InvalidOperationException("找不到 GameInputGamepadController.RequestRefresh。"); + + MethodInfo ackMethod = typeof(GameInputGamepadController).GetMethod( + "AcknowledgeRefresh", + BindingFlags.Instance | BindingFlags.NonPublic) + ?? throw new InvalidOperationException("找不到 GameInputGamepadController.AcknowledgeRefresh。"); + + PropertyInfo needsProp = typeof(GameInputGamepadController).GetProperty( + "NeedsDeviceRefresh", + BindingFlags.Instance | BindingFlags.NonPublic) + ?? throw new InvalidOperationException("找不到 GameInputGamepadController.NeedsDeviceRefresh。"); + + // 第一次請求,版本號變為 1 + reqMethod.Invoke(controller, []); + long capturedVersion = GetPrivateField(controller, "_refreshRequestVersion"); + Assert.Equal(1L, capturedVersion); + + // 模擬探索期間又有新設備熱插拔,發布第二個請求,版本號變為 2 + reqMethod.Invoke(controller, []); + Assert.Equal(2L, GetPrivateField(controller, "_refreshRequestVersion")); + + // 探索結算第一版 (1) + ackMethod.Invoke(controller, [capturedVersion]); + + // 因為版本 2 尚未處理,重新整理標記必須維持 true + Assert.True((bool)needsProp.GetValue(controller)!); + Assert.True(GetPrivateField(controller, "_needsRefresh")); + } + /// /// GameInput 控制器在套用空裝置清單時,應將目前裝置設為 null 並觸發斷線流程。 /// diff --git a/tests/InputBox.Tests/README.md b/tests/InputBox.Tests/README.md index e46c56da..70436d2e 100644 --- a/tests/InputBox.Tests/README.md +++ b/tests/InputBox.Tests/README.md @@ -21,7 +21,7 @@ | `FormInputStateManagerTests` | `FormInputStateManager` 輸入狀態切換 | 15 | | `GamepadDeadzoneHysteresisTests` | `GamepadDeadzoneHysteresis.ResolveDirection`(int / float 多載),含正負方向對稱性守門(硬體平等原則) | 14 | | `GamepadControllerFactoryTests` | 控制器後端建立策略,驗證 XInput 預設路徑、GameInput 成功路徑,以及 GameInput 執行階段不可用時退避至 XInput | 3 | -| `GamepadControllerPauseTests` | 控制器在 `Pause()` / `Resume()`、連線可用性語意、GameInput 讀取缺失斷線重列舉、非同步分階段裝置探索、探索所有權與競態防護、熱插拔版本防覆蓋、探索失敗重試保留、裝置狀態過濾、震動停止安全性、`ClearAllEvents` 肩鍵釋放訂閱清除與原生對話框切換時的殘留輸入回歸保護 | 17 | +| `GamepadControllerPauseTests` | 控制器在 `Pause()` / `Resume()`、連線可用性語意、GameInput 讀取缺失斷線重列舉、非同步分階段裝置探索、探索所有權與競態防護、世代分配隔離、熱插拔版本防覆蓋與請求共用同步、探索失敗重試保留、裝置狀態過濾、震動停止安全性、`ClearAllEvents` 肩鍵釋放訂閱清除與原生對話框切換時的殘留輸入回歸保護 | 20 | | `GameInputDirectUsageTests` | `GameInputGamepadController` 直接使用 `InputWeave.GameInput` 遊戲控制器介面的守門、callback function pointer marshaling、官方 v3 按鍵位元、快照邊緣偵測、Release 日誌邊界、穩定裝置識別與震動參數保留 | 9 | | `FlashAlertAnimatorTests` | `FlashAlertAnimator` 共用閃爍警示:主題警示色、純淨底色至警示色的插值、整個脈衝過程文字對比 ≥4.5:1、高對比模式半強度切換,以及 1Hz 單次正弦脈衝強度 | 7 | | `GamepadBiasSmoothingTests` | `GamepadBiasSmoothing` 自適應 EMA 學習率公式:零誤差用基礎值、超出範圍用最大值,以及 XInput 與 GameInput 不同數值尺度下結果一致 | 5 | @@ -50,7 +50,7 @@ | `TextBoxSelectionExtensionsTests` | 右搖桿延伸選取共用的 `ResolveSelectionAnchor` 錨點解析(無選取、正向、反向、錨點失效)與 `GetWordJumpTarget` 單字跳轉目標(不改變目前選取、方向與邊界);原本三處複本集中後的一致性保護 | 6 | | `VibrationPatternsTests` | `VibrationPatterns` 與方向性震動設定、語意情境解析、能力感知的多段式微震動序列,以及歷程滾輪阻尼感、字數上限硬牆、震動強度預覽、右搖桿選取粒度、組合鍵進入提示與喚起握手回饋的回歸保護 | 37 | | `VibrationSafetyLimiterTests` | `VibrationSafetyLimiter` 熱保護、Duty Cycle 限制器與極端邊界保護;馬達數量熱成本倍率正規化,以及所有內建震動模式在冷啟動下不得被拒絕、單次超出預算改為降強度,以及Critical 自動連發(含不同模式交錯)降級、熱負載不失控,以及冷啟動短序列仍完整送出的回歸保護 | 20 | -| **合計** | | **454** | +| **合計** | | **457** | ## 二、執行方式 🚀 From 4c8f91ce4af6034b3cb92fdffa817158b9edaaf0 Mon Sep 17 00:00:00 2001 From: perditavojo <117562794+perditavojo@users.noreply.github.com> Date: Sat, 31 Oct 2026 13:49:50 +0800 Subject: [PATCH 4/6] =?UTF-8?q?fix(gameinput):=20=E8=BF=BD=E8=B9=A4?= =?UTF-8?q?=E7=A7=BB=E4=BA=A4=E4=B9=8B=E6=8E=A2=E7=B4=A2=E6=B8=85=E7=90=86?= =?UTF-8?q?=E4=B8=A6=E5=9C=A8=E5=8F=96=E8=B5=B0=E5=B7=A5=E4=BD=9C=E5=89=8D?= =?UTF-8?q?=E6=8B=92=E7=B5=95=E9=81=8E=E6=9C=9F=E5=91=BC=E5=8F=AB=E8=80=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 修正 GitHub PR #88 最新審查提出的 2 項問題: 1. 追蹤 StopPolling 移交的探索清理工作(包含先前 Pause 留下的工作),在 DisposeResourcesAsync 處置 GameInputClient 與完成 DisposeAsync 前確實等待所有移交工作完成,避免客戶端提前釋放導致裝置代理生命週期錯位。 2. 在 CheckAndApplyDiscoveryResults 內取得 _discoveryLock 後、取走工作前即拒絕過期輪詢世代呼叫者,防止延遲執行的舊 Poll 清空或誤釋放新世代的探索工作。 3. 更新 GamepadControllerPauseTests 驗證過期呼叫者保留新世代工作,並新增清理追蹤等待測試。 --- .../Core/Input/GameInputGamepadController.cs | 68 ++++++++++++++++--- .../GamepadControllerPauseTests.cs | 64 ++++++++++++++--- tests/InputBox.Tests/README.md | 4 +- 3 files changed, 118 insertions(+), 18 deletions(-) diff --git a/src/InputBox/Core/Input/GameInputGamepadController.cs b/src/InputBox/Core/Input/GameInputGamepadController.cs index 55c709d8..2a206d29 100644 --- a/src/InputBox/Core/Input/GameInputGamepadController.cs +++ b/src/InputBox/Core/Input/GameInputGamepadController.cs @@ -188,6 +188,11 @@ private void AcknowledgeRefresh(long capturedVersion) /// private long _activeDiscoveryVersion; + /// + /// 追蹤所有已移交停止但尚未完成釋放的背景裝置探索清理工作(包含 Pause 留下的工作)。 + /// + private readonly List _pendingDiscoveryCleanups = []; + /// /// 目前進行中的背景裝置探索工作 /// @@ -835,17 +840,33 @@ private void StopPolling() { RequestRefresh(); } - } - if (pendingDiscovery != null) - { - _ = pendingDiscovery.ContinueWith(t => + if (pendingDiscovery != null) { - if (t.IsCompletedSuccessfully) + Task? cleanupTask = null; + cleanupTask = pendingDiscovery.ContinueWith(t => { - DisposeDevices(t.Result); - } - }, TaskScheduler.Default); + try + { + if (t.IsCompletedSuccessfully) + { + DisposeDevices(t.Result); + } + } + finally + { + lock (_discoveryLock) + { + if (cleanupTask != null) + { + _pendingDiscoveryCleanups.Remove(cleanupTask); + } + } + } + }, TaskScheduler.Default); + + _pendingDiscoveryCleanups.Add(cleanupTask); + } } } @@ -2030,6 +2051,12 @@ private void CheckAndApplyDiscoveryResults(int pollingGeneration = 0) lock (_discoveryLock) { + // 在取走工作前拒絕過期呼叫者,避免舊世代的 Poll 清空並誤釋放新世代的探索工作 + if (pollingGeneration != 0 && pollingGeneration != Volatile.Read(ref _pollingGeneration)) + { + return; + } + task = _deviceDiscoveryTask; if (task == null || !task.IsCompleted) @@ -3603,6 +3630,31 @@ private Task DisposeResourcesAsync() } } + // 等待所有已移交停止的探索清理工作(包含先前 Pause 留下的工作)完成, + // 確保先釋放探索產生的裝置代理,再處置 GameInputClient。 + while (true) + { + Task[] cleanupsToWait; + lock (_discoveryLock) + { + if (_pendingDiscoveryCleanups.Count == 0) + { + break; + } + + cleanupsToWait = [.. _pendingDiscoveryCleanups]; + } + + try + { + await Task.WhenAll(cleanupsToWait).ConfigureAwait(false); + } + catch (Exception ex) + { + Debug.WriteLine($"[GameInput] 處置時等待探索清理完成發生例外(已忽略):{ex.Message}"); + } + } + // 釋放所有連線中的裝置代理。 foreach (GameInputDevice d in devicesToDispose) { diff --git a/tests/InputBox.Tests/GamepadControllerPauseTests.cs b/tests/InputBox.Tests/GamepadControllerPauseTests.cs index d416fe49..6aaa0a6e 100644 --- a/tests/InputBox.Tests/GamepadControllerPauseTests.cs +++ b/tests/InputBox.Tests/GamepadControllerPauseTests.cs @@ -390,11 +390,11 @@ public void CheckAndApplyDiscoveryResults_WhenVersionUnchanged_ClearsNeedsRefres } /// - /// GameInput 控制器在過期輪詢世代執行時,CheckAndApplyDiscoveryResults 應捨棄探索結果、 - /// 恢復 _needsRefresh 為 true,且不套用至目前裝置。 + /// GameInput 控制器在過期輪詢世代執行時,CheckAndApplyDiscoveryResults 應拒絕取走工作, + /// 確保新世代進行中的探索工作不被過期呼叫者清空或誤釋放。 /// [Fact] - public void CheckAndApplyDiscoveryResults_WhenStaleGeneration_DiscardsResultsAndRestoresNeedsRefresh() + public void CheckAndApplyDiscoveryResults_WhenStaleGeneration_RetainsDiscoveryTaskForCurrentGeneration() { using var controller = (GameInputGamepadController)Activator.CreateInstance( typeof(GameInputGamepadController), @@ -408,16 +408,64 @@ public void CheckAndApplyDiscoveryResults_WhenStaleGeneration_DiscardsResultsAnd BindingFlags.Instance | BindingFlags.NonPublic) ?? throw new InvalidOperationException("找不到 GameInputGamepadController.CheckAndApplyDiscoveryResults。"); + Task> currentGenTask = Task.FromResult>([]); + SetPrivateField(controller, "_pollingGeneration", 5); - SetPrivateField(controller, "_needsRefresh", false); - SetPrivateField(controller, "_refreshRequestVersion", 10L); - SetPrivateField(controller, "_deviceDiscoveryTask", Task.FromResult>([])); + SetPrivateField(controller, "_deviceDiscoveryTask", currentGenTask); + // 傳入過期世代 4 method.Invoke(controller, [4]); - Assert.True(GetPrivateField(controller, "_needsRefresh")); - Assert.True(GetPrivateField(controller, "_refreshRequestVersion") > 10L); + // 驗證過期呼叫者被拒絕,新世代的工作未被清空 + Assert.Same(currentGenTask, GetPrivateField>?>(controller, "_deviceDiscoveryTask")); + } + + /// + /// StopPolling 應追蹤移交的探索清理工作,確保 DisposeResourcesAsync 完成前等待所有清理結束。 + /// + [Fact] + public async Task StopPolling_TracksPendingDiscoveryCleanup_WaitedBeforeDisposeResourcesCompletes() + { + using var controller = (GameInputGamepadController)Activator.CreateInstance( + typeof(GameInputGamepadController), + BindingFlags.Instance | BindingFlags.NonPublic, + binder: null, + args: [new StubInputContext(), null], + culture: null)!; + + TaskCompletionSource> discoveryTcs = new(); + + SetPrivateField(controller, "_deviceDiscoveryTask", discoveryTcs.Task); + + MethodInfo stopPollingMethod = typeof(GameInputGamepadController).GetMethod( + "StopPolling", + BindingFlags.Instance | BindingFlags.NonPublic) + ?? throw new InvalidOperationException("找不到 GameInputGamepadController.StopPolling。"); + + MethodInfo disposeResourcesMethod = typeof(GameInputGamepadController).GetMethod( + "DisposeResourcesAsync", + BindingFlags.Instance | BindingFlags.NonPublic) + ?? throw new InvalidOperationException("找不到 GameInputGamepadController.DisposeResourcesAsync。"); + + // 呼叫 StopPolling,進行中工作應被移交並加入清理追蹤清單 + stopPollingMethod.Invoke(controller, []); + Assert.Null(GetPrivateField>?>(controller, "_deviceDiscoveryTask")); + var pendingCleanups = GetPrivateField>(controller, "_pendingDiscoveryCleanups"); + Assert.Single(pendingCleanups); + + // 呼叫 DisposeResourcesAsync,在 discoveryTcs 未完成前,Dispose 任務不應結束 + var disposeTask = (Task)disposeResourcesMethod.Invoke(controller, [])!; + Assert.False(disposeTask.IsCompleted); + + // 完成探索工作 + discoveryTcs.SetResult([]); + + // 等待 Dispose 完成 + await disposeTask; + + Assert.True(disposeTask.IsCompletedSuccessfully); + Assert.Empty(GetPrivateField>(controller, "_pendingDiscoveryCleanups")); } /// diff --git a/tests/InputBox.Tests/README.md b/tests/InputBox.Tests/README.md index 70436d2e..1766f5bf 100644 --- a/tests/InputBox.Tests/README.md +++ b/tests/InputBox.Tests/README.md @@ -21,7 +21,7 @@ | `FormInputStateManagerTests` | `FormInputStateManager` 輸入狀態切換 | 15 | | `GamepadDeadzoneHysteresisTests` | `GamepadDeadzoneHysteresis.ResolveDirection`(int / float 多載),含正負方向對稱性守門(硬體平等原則) | 14 | | `GamepadControllerFactoryTests` | 控制器後端建立策略,驗證 XInput 預設路徑、GameInput 成功路徑,以及 GameInput 執行階段不可用時退避至 XInput | 3 | -| `GamepadControllerPauseTests` | 控制器在 `Pause()` / `Resume()`、連線可用性語意、GameInput 讀取缺失斷線重列舉、非同步分階段裝置探索、探索所有權與競態防護、世代分配隔離、熱插拔版本防覆蓋與請求共用同步、探索失敗重試保留、裝置狀態過濾、震動停止安全性、`ClearAllEvents` 肩鍵釋放訂閱清除與原生對話框切換時的殘留輸入回歸保護 | 20 | +| `GamepadControllerPauseTests` | 控制器在 `Pause()` / `Resume()`、連線可用性語意、GameInput 讀取缺失斷線重列舉、非同步分階段裝置探索、探索所有權與競態防護、世代分配隔離、過期呼叫者工作保護、探索清理移交追蹤、熱插拔版本防覆蓋與請求共用同步、探索失敗重試保留、裝置狀態過濾、震動停止安全性、`ClearAllEvents` 肩鍵釋放訂閱清除與原生對話框切換時的殘留輸入回歸保護 | 21 | | `GameInputDirectUsageTests` | `GameInputGamepadController` 直接使用 `InputWeave.GameInput` 遊戲控制器介面的守門、callback function pointer marshaling、官方 v3 按鍵位元、快照邊緣偵測、Release 日誌邊界、穩定裝置識別與震動參數保留 | 9 | | `FlashAlertAnimatorTests` | `FlashAlertAnimator` 共用閃爍警示:主題警示色、純淨底色至警示色的插值、整個脈衝過程文字對比 ≥4.5:1、高對比模式半強度切換,以及 1Hz 單次正弦脈衝強度 | 7 | | `GamepadBiasSmoothingTests` | `GamepadBiasSmoothing` 自適應 EMA 學習率公式:零誤差用基礎值、超出範圍用最大值,以及 XInput 與 GameInput 不同數值尺度下結果一致 | 5 | @@ -50,7 +50,7 @@ | `TextBoxSelectionExtensionsTests` | 右搖桿延伸選取共用的 `ResolveSelectionAnchor` 錨點解析(無選取、正向、反向、錨點失效)與 `GetWordJumpTarget` 單字跳轉目標(不改變目前選取、方向與邊界);原本三處複本集中後的一致性保護 | 6 | | `VibrationPatternsTests` | `VibrationPatterns` 與方向性震動設定、語意情境解析、能力感知的多段式微震動序列,以及歷程滾輪阻尼感、字數上限硬牆、震動強度預覽、右搖桿選取粒度、組合鍵進入提示與喚起握手回饋的回歸保護 | 37 | | `VibrationSafetyLimiterTests` | `VibrationSafetyLimiter` 熱保護、Duty Cycle 限制器與極端邊界保護;馬達數量熱成本倍率正規化,以及所有內建震動模式在冷啟動下不得被拒絕、單次超出預算改為降強度,以及Critical 自動連發(含不同模式交錯)降級、熱負載不失控,以及冷啟動短序列仍完整送出的回歸保護 | 20 | -| **合計** | | **457** | +| **合計** | | **458** | ## 二、執行方式 🚀 From d1733a458385675e44947d730a80a0ea1c5cc701 Mon Sep 17 00:00:00 2001 From: perditavojo <117562794+perditavojo@users.noreply.github.com> Date: Sat, 31 Oct 2026 14:52:59 +0800 Subject: [PATCH 5/6] =?UTF-8?q?fix(gameinput):=20=E4=BF=AE=E6=AD=A3?= =?UTF-8?q?=E5=AF=A6=E4=BE=8B=E7=94=9F=E5=91=BD=E9=80=B1=E6=9C=9F=E6=B4=A9?= =?UTF-8?q?=E6=BC=8F=E3=80=81=E4=B8=9F=E5=A4=B1=E8=AE=80=E5=8F=96=E9=87=8D?= =?UTF-8?q?=E5=88=97=E8=88=89=E4=B8=AD=E6=96=B7=E8=88=87=E6=8E=A2=E7=B4=A2?= =?UTF-8?q?=E5=8F=96=E6=B6=88=E5=BB=B6=E9=81=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 深度分析並修正 GameInput 控制器與背景探索生命週期的 5 項潛在問題與邊界風險: 1. 修正 CreateAsync 在初次列舉或執行期探測失敗時的實例洩漏:建構子註冊 FeedbackService 後,若初始化失敗應透過 DisposeAsync 解除註冊並釋放部分 COM 物件與背景輪詢任務,避免殘留於 ActiveControllers。 2. 修正 HandleMissingCurrentReading 回傳值錯誤:原先回傳 _device == null(恆為 false)導致連續丟失讀取達門檻後仍繼續執行當前幀的 _previousState 過期連發,改為回傳 true 依契約中斷本幀狀態評估。 3. 修正 DisposeResourcesAsync 探索權杖取消延遲:將探索工作捕捉與 _discoveryCts 取消提前至進入背景 Task.Run 之前同步執行,防止處置流程在探索進行中延遲等待 1.25 秒。 4. 修正 ScanForActiveDevice 多控制器切換時的馬達震動殘留:切換活躍裝置前先嘗試對舊裝置歸零 SetRumbleState,避免舊手把持續震動。 5. 補強 DisposeDevices null 守門、SetupReadingCallback 與 device callback 處置旗標過濾,並修正測試專案中未等候 Task 回傳所產生的 CS4014 編譯警告與 var 型別宣告。 6. 新增 4 項單元測試覆蓋上述情境,並同步更新測試文件。 --- .../Core/Input/GameInputGamepadController.cs | 70 ++++++++--- .../GamepadControllerPauseTests.cs | 117 +++++++++++++++++- tests/InputBox.Tests/README.md | 4 +- 3 files changed, 169 insertions(+), 22 deletions(-) diff --git a/src/InputBox/Core/Input/GameInputGamepadController.cs b/src/InputBox/Core/Input/GameInputGamepadController.cs index 2a206d29..1934867f 100644 --- a/src/InputBox/Core/Input/GameInputGamepadController.cs +++ b/src/InputBox/Core/Input/GameInputGamepadController.cs @@ -763,12 +763,20 @@ public static async Task CreateAsync( { GameInputGamepadController controller = new(context, repeatSettings); - // 透過 TCS 等待背景輪詢執行緒完成 GameInput 的初始化。 - // 這樣既能保證 COM 物件在輪詢執行緒上建立(避免 InvalidCastException 與執行緒綁定問題), - // 又能將初始化結果(成功或例外)回傳給呼叫者,達成探測與重用實例的雙重目的,提升 50% 啟動速度。 - await controller.InitializeAndStartPollingAsync().ConfigureAwait(false); + try + { + // 透過 TCS 等待背景輪詢執行緒完成 GameInput 的初始化。 + // 這樣既能保證 COM 物件在輪詢執行緒上建立(避免 InvalidCastException 與執行緒綁定問題), + // 又能將初始化結果(成功或例外)回傳給呼叫者,達成探測與重用實例的雙重目的,提升 50% 啟動速度。 + await controller.InitializeAndStartPollingAsync().ConfigureAwait(false); - return controller; + return controller; + } + catch + { + await controller.DisposeAsync().ConfigureAwait(false); + throw; + } } /// @@ -876,6 +884,11 @@ private void StopPolling() /// 要釋放的裝置清單。 private static void DisposeDevices(IReadOnlyList devices) { + if (devices == null) + { + return; + } + for (int i = 0; i < devices.Count; i++) { try @@ -946,7 +959,7 @@ private void SetupReadingCallback() _readingQueue.Clear(); - if (_device != null && _gameInput != null) + if (_device != null && _gameInput != null && _disposed == 0) { try { @@ -1016,7 +1029,8 @@ private async Task PollingLoopAsync(CancellationToken cancellationToken, int pol GameInputKind.GameInputKindGamepad, (deviceEvent, _) => { - if (deviceEvent is GameInputDeviceEvent.GameInputDeviceEventConnected or GameInputDeviceEvent.GameInputDeviceEventDisconnected) + if (_disposed == 0 && + deviceEvent is GameInputDeviceEvent.GameInputDeviceEventConnected or GameInputDeviceEvent.GameInputDeviceEventDisconnected) { RequestRefresh(); } @@ -1055,6 +1069,13 @@ private async Task PollingLoopAsync(CancellationToken cancellationToken, int pol } } + if (cancellationToken.IsCancellationRequested || + pollingGeneration != Volatile.Read(ref _pollingGeneration)) + { + initTcs?.TrySetCanceled(cancellationToken); + return; + } + // 成功完成初始化,通知 CreateAsync 解除等待 initTcs?.TrySetResult(); } @@ -1675,7 +1696,7 @@ private bool HandleMissingCurrentReading(int pollingGeneration = 0) LogGameInputDiagnosticsSnapshot("missing-reading-threshold"); StartDeviceDiscovery(pollingGeneration); - return _device == null; + return true; } /// @@ -2424,9 +2445,24 @@ private bool ScanForActiveDevice() // 重置原本的按鍵狀態,避免按住的按鍵殘留給新控制器。 ResetHoldStates(); + // 切換裝置參考前,先嘗試停止舊裝置馬達以防震動殘留。 + GameInputDevice? oldDev = _device; + // 切換裝置參考。 _device = otherDev; + if (oldDev != null) + { + try + { + oldDev.SetRumbleState(new GameInputRumbleParams()); + } + catch (Exception rumbleEx) + { + Debug.WriteLine($"[GameInput] 切換裝置時停止舊裝置馬達失敗(已忽略):{rumbleEx.Message}"); + } + } + UpdateDeviceInfo(); InitializeDeviceState(); SetupReadingCallback(); @@ -3576,6 +3612,15 @@ private Task DisposeResourcesAsync() _allDevices.Clear(); } + // 若有進行中的背景探索工作,立即發出取消並捕捉工作代理,確保不延遲處置。 + Task>? discoveryTask; + lock (_discoveryLock) + { + Interlocked.Exchange(ref _discoveryCts, null)?.CancelAndDispose(); + discoveryTask = _deviceDiscoveryTask; + _deviceDiscoveryTask = null; + } + _device = null; _gameInput = null; _deviceCallbackReg = null; @@ -3609,14 +3654,7 @@ private Task DisposeResourcesAsync() deviceCallbackReg?.Dispose(); readingCallbackReg?.Dispose(); - // 若有進行中的背景探索工作,等待其完成並釋放所產生的裝置代理。 - Task>? discoveryTask; - lock (_discoveryLock) - { - discoveryTask = _deviceDiscoveryTask; - _deviceDiscoveryTask = null; - } - + // 等待已捕獲的背景探索工作完成並釋放所產生的裝置代理。 if (discoveryTask != null) { try diff --git a/tests/InputBox.Tests/GamepadControllerPauseTests.cs b/tests/InputBox.Tests/GamepadControllerPauseTests.cs index 6aaa0a6e..b791fb16 100644 --- a/tests/InputBox.Tests/GamepadControllerPauseTests.cs +++ b/tests/InputBox.Tests/GamepadControllerPauseTests.cs @@ -451,11 +451,12 @@ public async Task StopPolling_TracksPendingDiscoveryCleanup_WaitedBeforeDisposeR stopPollingMethod.Invoke(controller, []); Assert.Null(GetPrivateField>?>(controller, "_deviceDiscoveryTask")); - var pendingCleanups = GetPrivateField>(controller, "_pendingDiscoveryCleanups"); - Assert.Single(pendingCleanups); + List pendingCleanups = GetPrivateField>(controller, "_pendingDiscoveryCleanups"); + Task cleanupTask = Assert.Single(pendingCleanups); + Assert.NotNull(cleanupTask); // 呼叫 DisposeResourcesAsync,在 discoveryTcs 未完成前,Dispose 任務不應結束 - var disposeTask = (Task)disposeResourcesMethod.Invoke(controller, [])!; + Task disposeTask = (Task)disposeResourcesMethod.Invoke(controller, [])!; Assert.False(disposeTask.IsCompleted); // 完成探索工作 @@ -492,7 +493,7 @@ public async Task PollingLoopAsync_WhenStaleGeneration_AbortsWithoutMutatingPoll TaskCompletionSource tcs = new(); // 傳入過期世代 2 - var task = (Task)method.Invoke(controller, [cts.Token, 2, tcs])!; + Task task = (Task)method.Invoke(controller, [cts.Token, 2, tcs])!; await task; Assert.Equal(3, GetPrivateField(controller, "_pollingGeneration")); @@ -651,6 +652,114 @@ public void ClearAllEvents_GameInputController_ClearsShoulderReleasedSubscriptio Assert.Null(GetEventDelegate(controller, "RightShoulderReleased")); } + /// + /// 連續丟失讀取達到重新整理閾值時,HandleMissingCurrentReading 應啟動重新整理並回傳 true, + /// 讓輪詢迴圈中斷當前幀的過期狀態評估。 + /// + [Fact] + public void HandleMissingCurrentReading_WhenThresholdReached_ReturnsTrueAndRequestsRefresh() + { + using var controller = (GameInputGamepadController)Activator.CreateInstance( + typeof(GameInputGamepadController), + BindingFlags.Instance | BindingFlags.NonPublic, + binder: null, + args: [new StubInputContext(), null], + culture: null)!; + + MethodInfo method = typeof(GameInputGamepadController).GetMethod( + "HandleMissingCurrentReading", + BindingFlags.Instance | BindingFlags.NonPublic) + ?? throw new InvalidOperationException("找不到 GameInputGamepadController.HandleMissingCurrentReading。"); + + SetPrivateField(controller, "_missingReadingFrameCounter", AppSettings.GamepadReconnectThresholdFrames - 1); + SetPrivateField(controller, "_needsRefresh", false); + + bool result = (bool)method.Invoke(controller, [0])!; + + Assert.True(result); + Assert.True(GetPrivateField(controller, "_needsRefresh")); + Assert.Equal(0, GetPrivateField(controller, "_missingReadingFrameCounter")); + } + + /// + /// 連續丟失讀取未達到重新整理閾值時,HandleMissingCurrentReading 應回傳 false 且不觸發探索。 + /// + [Fact] + public void HandleMissingCurrentReading_BeforeThresholdReached_ReturnsFalse() + { + using var controller = (GameInputGamepadController)Activator.CreateInstance( + typeof(GameInputGamepadController), + BindingFlags.Instance | BindingFlags.NonPublic, + binder: null, + args: [new StubInputContext(), null], + culture: null)!; + + MethodInfo method = typeof(GameInputGamepadController).GetMethod( + "HandleMissingCurrentReading", + BindingFlags.Instance | BindingFlags.NonPublic) + ?? throw new InvalidOperationException("找不到 GameInputGamepadController.HandleMissingCurrentReading。"); + + SetPrivateField(controller, "_missingReadingFrameCounter", 0); + SetPrivateField(controller, "_needsRefresh", false); + + bool result = (bool)method.Invoke(controller, [0])!; + + Assert.False(result); + Assert.False(GetPrivateField(controller, "_needsRefresh")); + Assert.Equal(1, GetPrivateField(controller, "_missingReadingFrameCounter")); + } + + /// + /// DisposeResourcesAsync 在等待進行中的背景探索工作前,應確實取消 _discoveryCts,防止處置延遲等待。 + /// + [Fact] + public async Task DisposeResourcesAsync_WhenDiscoveryTaskInFlight_CancelsDiscoveryCts() + { + using var controller = (GameInputGamepadController)Activator.CreateInstance( + typeof(GameInputGamepadController), + BindingFlags.Instance | BindingFlags.NonPublic, + binder: null, + args: [new StubInputContext(), null], + culture: null)!; + + CancellationTokenSource discoveryCts = new(); + TaskCompletionSource> discoveryTcs = new(); + + SetPrivateField(controller, "_discoveryCts", discoveryCts); + SetPrivateField(controller, "_deviceDiscoveryTask", discoveryTcs.Task); + + MethodInfo disposeResourcesMethod = typeof(GameInputGamepadController).GetMethod( + "DisposeResourcesAsync", + BindingFlags.Instance | BindingFlags.NonPublic) + ?? throw new InvalidOperationException("找不到 GameInputGamepadController.DisposeResourcesAsync。"); + + Task disposeTask = (Task)disposeResourcesMethod.Invoke(controller, [])!; + + // 驗證 _discoveryCts 已在 lock (_discoveryLock) 內被取消 + Assert.True(discoveryCts.IsCancellationRequested); + + // 完成探索工作以允許 dispose 完成 + discoveryTcs.SetResult([]); + await disposeTask; + + Assert.True(disposeTask.IsCompletedSuccessfully); + } + + /// + /// DisposeDevices 傳入 null 參數時應安全返回,杜絕 NullReferenceException。 + /// + [Fact] + public void DisposeDevices_WhenNull_DoesNotThrow() + { + MethodInfo method = typeof(GameInputGamepadController).GetMethod( + "DisposeDevices", + BindingFlags.Static | BindingFlags.NonPublic) + ?? throw new InvalidOperationException("找不到 GameInputGamepadController.DisposeDevices。"); + + Exception? ex = Record.Exception(() => method.Invoke(null, [null])); + Assert.Null(ex); + } + /// /// 透過反射呼叫控制器的 private ClearAllEvents 方法。 /// diff --git a/tests/InputBox.Tests/README.md b/tests/InputBox.Tests/README.md index 1766f5bf..b8467429 100644 --- a/tests/InputBox.Tests/README.md +++ b/tests/InputBox.Tests/README.md @@ -21,7 +21,7 @@ | `FormInputStateManagerTests` | `FormInputStateManager` 輸入狀態切換 | 15 | | `GamepadDeadzoneHysteresisTests` | `GamepadDeadzoneHysteresis.ResolveDirection`(int / float 多載),含正負方向對稱性守門(硬體平等原則) | 14 | | `GamepadControllerFactoryTests` | 控制器後端建立策略,驗證 XInput 預設路徑、GameInput 成功路徑,以及 GameInput 執行階段不可用時退避至 XInput | 3 | -| `GamepadControllerPauseTests` | 控制器在 `Pause()` / `Resume()`、連線可用性語意、GameInput 讀取缺失斷線重列舉、非同步分階段裝置探索、探索所有權與競態防護、世代分配隔離、過期呼叫者工作保護、探索清理移交追蹤、熱插拔版本防覆蓋與請求共用同步、探索失敗重試保留、裝置狀態過濾、震動停止安全性、`ClearAllEvents` 肩鍵釋放訂閱清除與原生對話框切換時的殘留輸入回歸保護 | 21 | +| `GamepadControllerPauseTests` | 控制器在 `Pause()` / `Resume()`、連線可用性語意、GameInput 讀取缺失斷線重列舉中斷、探索權杖取消保護、空裝置清單防護、非同步分階段裝置探索、探索所有權與競態防護、世代分配隔離、過期呼叫者工作保護、探索清理移交追蹤、熱插拔版本防覆蓋與請求共用同步、探索失敗重試保留、裝置狀態過濾、震動停止安全性、`ClearAllEvents` 肩鍵釋放訂閱清除與原生對話框切換時的殘留輸入回歸保護 | 25 | | `GameInputDirectUsageTests` | `GameInputGamepadController` 直接使用 `InputWeave.GameInput` 遊戲控制器介面的守門、callback function pointer marshaling、官方 v3 按鍵位元、快照邊緣偵測、Release 日誌邊界、穩定裝置識別與震動參數保留 | 9 | | `FlashAlertAnimatorTests` | `FlashAlertAnimator` 共用閃爍警示:主題警示色、純淨底色至警示色的插值、整個脈衝過程文字對比 ≥4.5:1、高對比模式半強度切換,以及 1Hz 單次正弦脈衝強度 | 7 | | `GamepadBiasSmoothingTests` | `GamepadBiasSmoothing` 自適應 EMA 學習率公式:零誤差用基礎值、超出範圍用最大值,以及 XInput 與 GameInput 不同數值尺度下結果一致 | 5 | @@ -50,7 +50,7 @@ | `TextBoxSelectionExtensionsTests` | 右搖桿延伸選取共用的 `ResolveSelectionAnchor` 錨點解析(無選取、正向、反向、錨點失效)與 `GetWordJumpTarget` 單字跳轉目標(不改變目前選取、方向與邊界);原本三處複本集中後的一致性保護 | 6 | | `VibrationPatternsTests` | `VibrationPatterns` 與方向性震動設定、語意情境解析、能力感知的多段式微震動序列,以及歷程滾輪阻尼感、字數上限硬牆、震動強度預覽、右搖桿選取粒度、組合鍵進入提示與喚起握手回饋的回歸保護 | 37 | | `VibrationSafetyLimiterTests` | `VibrationSafetyLimiter` 熱保護、Duty Cycle 限制器與極端邊界保護;馬達數量熱成本倍率正規化,以及所有內建震動模式在冷啟動下不得被拒絕、單次超出預算改為降強度,以及Critical 自動連發(含不同模式交錯)降級、熱負載不失控,以及冷啟動短序列仍完整送出的回歸保護 | 20 | -| **合計** | | **458** | +| **合計** | | **462** | ## 二、執行方式 🚀 From 39716663814154b179955017db2a5d3a85279c3c Mon Sep 17 00:00:00 2001 From: perditavojo <117562794+perditavojo@users.noreply.github.com> Date: Sat, 31 Oct 2026 15:14:26 +0800 Subject: [PATCH 6/6] =?UTF-8?q?fix(gameinput):=20=E4=BF=AE=E6=AD=A3?= =?UTF-8?q?=E6=96=B7=E7=B7=9A=E8=A3=9D=E7=BD=AE=E5=BF=AB=E5=8F=96=E6=AE=98?= =?UTF-8?q?=E7=95=99=E3=80=81=E8=AE=80=E5=8F=96=E4=B8=9F=E5=A4=B1=E9=80=A3?= =?UTF-8?q?=E7=99=BC=E9=87=8D=E5=85=A5=E3=80=81=E5=88=9D=E5=A7=8B=E5=8C=96?= =?UTF-8?q?=E5=8F=96=E6=B6=88=E6=AD=BB=E9=8E=96=E8=88=87=E8=99=95=E7=BD=AE?= =?UTF-8?q?=E5=81=A5=E5=85=A8=E6=80=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 深度分析並修復 GameInput 控制器在斷線清理、讀取缺失重連、初始化取消死鎖與裝置處置中的 5 項關鍵問題: 1. 修正 HandleDisconnect 裝置快取資訊未清理:因呼叫端已先將 _device 歸零,使原本位於 if (_device != null) 內之 UpdateDeviceInfo() 未被呼叫,導致斷線後 DeviceName、DeviceIdentity 與震動支援仍殘留舊裝置狀態;改為無條件重設快取,並補全連線中斷時所有肩鍵/板機/方向連發計數器的清理。 2. 修正 HandleMissingCurrentReading 在門檻後重入連發:丟失讀取達門檻時立即清除 _previousState、_previousProcessedButtons、_hasPreviousState 與按住狀態,杜絕手把掉線重列舉期間對最後一幀按鍵無限重複連發。 3. 修正 InitializeAndStartPollingAsync 快速取消死鎖:在回傳之 tcs 註冊 token 取消回呼,並移除 Task.Run 之 token 參數,防止在線程池排隊時即遭遇取消導致委派未執行且 tcs 永久等待。 4. 修正裝置切換與接管時的暫態連發與熱負載殘留:在候選裝置無縫接管、掃描活躍控制器切換與非同步探索啟用新裝置時,全面重置按住狀態、方向連發、按鍵連發與 VibrationSafetyLimiter 熱負載。 5. 補強處置階段 COM 隔離與防禦:處置所有連線裝置代理前先歸零馬達,並對每個裝置的處置與 Client 的處置個別套用 try-catch,防止單一例外阻礙後續資源釋放;同時修正 _discoveryCts 之處置為 CancelAndDispose() 並強化 ApplyDiscoveredDevicesWithLifecycle null 守門。 6. 新增 5 項單元測試覆蓋上述情境,更新測試專案總數至 467 項(456 通過,11 略過)。 --- .../Core/Input/GameInputGamepadController.cs | 119 +++++++++++-- .../GamepadControllerPauseTests.cs | 168 ++++++++++++++++++ tests/InputBox.Tests/README.md | 4 +- 3 files changed, 272 insertions(+), 19 deletions(-) diff --git a/src/InputBox/Core/Input/GameInputGamepadController.cs b/src/InputBox/Core/Input/GameInputGamepadController.cs index 1934867f..410c1e0a 100644 --- a/src/InputBox/Core/Input/GameInputGamepadController.cs +++ b/src/InputBox/Core/Input/GameInputGamepadController.cs @@ -796,8 +796,14 @@ private Task InitializeAndStartPollingAsync() TaskCompletionSource tcs = new(TaskCreationOptions.RunContinuationsAsynchronously); + CancellationTokenRegistration registration = token.UnsafeRegister( + static state => ((TaskCompletionSource)state!).TrySetCanceled(), + tcs); + + _ = tcs.Task.ContinueWith(_ => registration.Dispose(), TaskScheduler.Default); + int generation = Interlocked.Increment(ref _pollingGeneration); - _taskPolling = Task.Run(() => PollingLoopAsync(token, generation, tcs), token); + _taskPolling = Task.Run(() => PollingLoopAsync(token, generation, tcs)); return tcs.Task; } @@ -819,7 +825,7 @@ private void StartPolling() _ctsPolling = cts; int generation = Interlocked.Increment(ref _pollingGeneration); - _taskPolling = Task.Run(() => PollingLoopAsync(token, generation, null), token); + _taskPolling = Task.Run(() => PollingLoopAsync(token, generation, null)); } /// @@ -893,7 +899,7 @@ private static void DisposeDevices(IReadOnlyList devices) { try { - devices[i].Dispose(); + devices[i]?.Dispose(); } catch (Exception ex) { @@ -924,9 +930,16 @@ private void HandleDisconnect() // 重置狀態防止殘留,避免放開按鍵的事件遺失。 ResetHoldStates(); + ResetDirectionalRepeatState(); - _rsRepeatCounter = 0; - _rsRepeatDirection = 0; + _lbRepeatCounter = 0; + _currentLBRepeatInterval = 0; + _rbRepeatCounter = 0; + _currentRBRepeatInterval = 0; + _ltRepeatCounter = 0; + _currentLTRepeatInterval = 0; + _rtRepeatCounter = 0; + _currentRTRepeatInterval = 0; // 連線中斷時清空熱狀態,避免重連後沿用舊熱負載造成過度保守。 _vibrationSafetyLimiter.Reset(); @@ -940,14 +953,10 @@ private void HandleDisconnect() // 清空事件佇列。 _readingQueue.Clear(); - if (_device != null) - { - // 裝置的處置現在主要由 TryFindDevice 邏輯管理。 - _device = null; + _device = null; - // 更新快取,讓 DeviceName 等屬性反映斷線狀態。 - UpdateDeviceInfo(); - } + // 更新快取,讓 DeviceName、DeviceIdentity 與震動能力等屬性反映斷線狀態。 + UpdateDeviceInfo(); } /// @@ -1645,6 +1654,18 @@ private void RefreshAfterCurrentDeviceBecameUnavailable(int pollingGeneration = if (IsDeviceConnected(candidate)) { + ResetHoldStates(); + ResetDirectionalRepeatState(); + _lbRepeatCounter = 0; + _currentLBRepeatInterval = 0; + _rbRepeatCounter = 0; + _currentRBRepeatInterval = 0; + _ltRepeatCounter = 0; + _currentLTRepeatInterval = 0; + _rtRepeatCounter = 0; + _currentRTRepeatInterval = 0; + _vibrationSafetyLimiter.Reset(); + _device = candidate; _hasPreviousState = false; _missingReadingFrameCounter = 0; @@ -1691,6 +1712,14 @@ private bool HandleMissingCurrentReading(int pollingGeneration = 0) return false; } + // 連續丟失讀取達重連門檻時,清除過期暫態輸入快照與連發狀態, + // 避免在重列舉完成前持續對最後一幀的按鍵狀態執行重複連發。 + _hasPreviousState = false; + _previousState = null; + _previousProcessedButtons = 0; + ResetDirectionalRepeatState(); + ResetHoldStates(); + RequestRefresh(); LogGameInputDiagnosticsSnapshot("missing-reading-threshold"); @@ -2037,6 +2066,7 @@ private void StartDeviceDiscovery(int pollingGeneration = 0) } CancellationTokenSource discoveryCts = CancellationTokenSource.CreateLinkedTokenSource(pollingToken); + Interlocked.Exchange(ref _discoveryCts, null)?.CancelAndDispose(); _discoveryCts = discoveryCts; lock (_refreshLock) { @@ -2053,7 +2083,7 @@ private void StartDeviceDiscovery(int pollingGeneration = 0) { RequestRefresh(); _deviceDiscoveryTask = null; - Interlocked.Exchange(ref _discoveryCts, null)?.Dispose(); + Interlocked.Exchange(ref _discoveryCts, null)?.CancelAndDispose(); LoggerService.LogException(ex, "GameInput 啟動裝置探索失敗"); Debug.WriteLine($"[GameInput] 啟動裝置探索失敗:{ex.Message}"); @@ -2086,7 +2116,7 @@ private void CheckAndApplyDiscoveryResults(int pollingGeneration = 0) } _deviceDiscoveryTask = null; - Interlocked.Exchange(ref _discoveryCts, null)?.Dispose(); + Interlocked.Exchange(ref _discoveryCts, null)?.CancelAndDispose(); capturedVersion = _activeDiscoveryVersion; } @@ -2133,6 +2163,11 @@ private void ApplyDiscoveredDevices(IReadOnlyList devices) /// 探索工作所屬的輪詢世代。 private void ApplyDiscoveredDevicesWithLifecycle(IReadOnlyList devices, long capturedVersion, int pollingGeneration) { + if (devices == null) + { + return; + } + bool needsDisconnect = false, needsConnectNotify = false; List? staleDevicesToDispose = null; @@ -2318,6 +2353,18 @@ private void ApplyDiscoveredDevicesCore( { if (_device == null) { + ResetHoldStates(); + ResetDirectionalRepeatState(); + _lbRepeatCounter = 0; + _currentLBRepeatInterval = 0; + _rbRepeatCounter = 0; + _currentRBRepeatInterval = 0; + _ltRepeatCounter = 0; + _currentLTRepeatInterval = 0; + _rtRepeatCounter = 0; + _currentRTRepeatInterval = 0; + _vibrationSafetyLimiter.Reset(); + _device = _allDevices[0]; _hasPreviousState = false; @@ -2444,6 +2491,16 @@ private bool ScanForActiveDevice() { // 重置原本的按鍵狀態,避免按住的按鍵殘留給新控制器。 ResetHoldStates(); + ResetDirectionalRepeatState(); + _lbRepeatCounter = 0; + _currentLBRepeatInterval = 0; + _rbRepeatCounter = 0; + _currentRBRepeatInterval = 0; + _ltRepeatCounter = 0; + _currentLTRepeatInterval = 0; + _rtRepeatCounter = 0; + _currentRTRepeatInterval = 0; + _vibrationSafetyLimiter.Reset(); // 切換裝置參考前,先嘗試停止舊裝置馬達以防震動殘留。 GameInputDevice? oldDev = _device; @@ -3693,14 +3750,42 @@ private Task DisposeResourcesAsync() } } + if (dev != null && !devicesToDispose.Contains(dev)) + { + devicesToDispose.Add(dev); + } + // 釋放所有連線中的裝置代理。 foreach (GameInputDevice d in devicesToDispose) { - d.Dispose(); + try + { + d.SetRumbleState(new GameInputRumbleParams()); + } + catch (Exception ex) + { + Debug.WriteLine($"[GameInput] 處置裝置時停止馬達失敗(已忽略):{ex.Message}"); + } + + try + { + d.Dispose(); + } + catch (Exception ex) + { + Debug.WriteLine($"[GameInput] 處置裝置代理失敗(已忽略):{ex.Message}"); + } } - LogGameInputDiagnosticsSnapshot("dispose"); - gameInput?.Dispose(); + try + { + LogGameInputDiagnosticsSnapshot("dispose"); + gameInput?.Dispose(); + } + catch (Exception ex) + { + Debug.WriteLine($"[GameInput] 處置 GameInputClient 失敗(已忽略):{ex.Message}"); + } } catch (Exception ex) { diff --git a/tests/InputBox.Tests/GamepadControllerPauseTests.cs b/tests/InputBox.Tests/GamepadControllerPauseTests.cs index b791fb16..0d0aa94f 100644 --- a/tests/InputBox.Tests/GamepadControllerPauseTests.cs +++ b/tests/InputBox.Tests/GamepadControllerPauseTests.cs @@ -760,6 +760,174 @@ public void DisposeDevices_WhenNull_DoesNotThrow() Assert.Null(ex); } + /// + /// HandleDisconnect 即使在 _device 已被呼叫端設為 null 的情況下,仍應確實更新快取清空 DeviceName、DeviceIdentity 與震動狀態。 + /// + [Fact] + public void HandleDisconnect_Always_ClearsCachedDeviceInfoAndRumbleSupport() + { + using var controller = (GameInputGamepadController)Activator.CreateInstance( + typeof(GameInputGamepadController), + BindingFlags.Instance | BindingFlags.NonPublic, + binder: null, + args: [new StubInputContext(), null], + culture: null)!; + + SetPrivateField(controller, "_cachedDeviceName", "Xbox Wireless Controller"); + SetPrivateField(controller, "_cachedDeviceIdentity", "VID_045E PID_02FD"); + SetPrivateField(controller, "_supportsRumble", true); + SetPrivateField(controller, "_device", null); + + MethodInfo method = typeof(GameInputGamepadController).GetMethod( + "HandleDisconnect", + BindingFlags.Instance | BindingFlags.NonPublic) + ?? throw new InvalidOperationException("找不到 GameInputGamepadController.HandleDisconnect。"); + + method.Invoke(controller, []); + + Assert.Equal(string.Empty, GetPrivateField(controller, "_cachedDeviceName")); + Assert.Equal(string.Empty, controller.DeviceIdentity); + Assert.False(GetPrivateField(controller, "_supportsRumble")); + } + + /// + /// HandleDisconnect 在連線中斷時應重設 D-Pad 方向連發與肩鍵/板機等所有按鍵連發計數器。 + /// + [Fact] + public void HandleDisconnect_ClearsAllDirectionalAndButtonRepeatStates() + { + using var controller = (GameInputGamepadController)Activator.CreateInstance( + typeof(GameInputGamepadController), + BindingFlags.Instance | BindingFlags.NonPublic, + binder: null, + args: [new StubInputContext(), null], + culture: null)!; + + SetPrivateField(controller, "_isConnected", true); + SetPrivateField(controller, "_repeatDirection", GameInputGamepadButtons.GameInputGamepadDPadDown); + SetPrivateField(controller, "_repeatCounter", 10); + SetPrivateField(controller, "_currentRepeatInterval", 4); + SetPrivateField(controller, "_lbRepeatCounter", 6); + SetPrivateField(controller, "_currentLBRepeatInterval", 2); + SetPrivateField(controller, "_rbRepeatCounter", 7); + SetPrivateField(controller, "_currentRBRepeatInterval", 3); + SetPrivateField(controller, "_ltRepeatCounter", 8); + SetPrivateField(controller, "_currentLTRepeatInterval", 1); + SetPrivateField(controller, "_rtRepeatCounter", 9); + SetPrivateField(controller, "_currentRTRepeatInterval", 2); + + MethodInfo method = typeof(GameInputGamepadController).GetMethod( + "HandleDisconnect", + BindingFlags.Instance | BindingFlags.NonPublic) + ?? throw new InvalidOperationException("找不到 GameInputGamepadController.HandleDisconnect。"); + + method.Invoke(controller, []); + + Assert.Null(GetPrivateField(controller, "_repeatDirection")); + Assert.Equal(0, GetPrivateField(controller, "_repeatCounter")); + Assert.Equal(0, GetPrivateField(controller, "_currentRepeatInterval")); + Assert.Equal(0, GetPrivateField(controller, "_lbRepeatCounter")); + Assert.Equal(0, GetPrivateField(controller, "_currentLBRepeatInterval")); + Assert.Equal(0, GetPrivateField(controller, "_rbRepeatCounter")); + Assert.Equal(0, GetPrivateField(controller, "_currentRBRepeatInterval")); + Assert.Equal(0, GetPrivateField(controller, "_ltRepeatCounter")); + Assert.Equal(0, GetPrivateField(controller, "_currentLTRepeatInterval")); + Assert.Equal(0, GetPrivateField(controller, "_rtRepeatCounter")); + Assert.Equal(0, GetPrivateField(controller, "_currentRTRepeatInterval")); + } + + /// + /// HandleMissingCurrentReading 在連續丟失讀取達門檻時,應清除上一幀快照、加工後按鍵與按住狀態,杜絕過期輸入連發。 + /// + [Fact] + public void HandleMissingCurrentReading_WhenThresholdReached_ClearsPreviousStateAndHoldStates() + { + using var controller = (GameInputGamepadController)Activator.CreateInstance( + typeof(GameInputGamepadController), + BindingFlags.Instance | BindingFlags.NonPublic, + binder: null, + args: [new StubInputContext(), null], + culture: null)!; + + MethodInfo method = typeof(GameInputGamepadController).GetMethod( + "HandleMissingCurrentReading", + BindingFlags.Instance | BindingFlags.NonPublic) + ?? throw new InvalidOperationException("找不到 GameInputGamepadController.HandleMissingCurrentReading。"); + + SetPrivateField(controller, "_missingReadingFrameCounter", AppSettings.GamepadReconnectThresholdFrames - 1); + SetPrivateField(controller, "_hasPreviousState", true); + SetPrivateField(controller, "_previousProcessedButtons", GameInputGamepadButtons.GameInputGamepadA); + typeof(GameInputGamepadController).GetProperty("IsBHeld")!.SetValue(controller, true); + SetPrivateField(controller, "_repeatDirection", GameInputGamepadButtons.GameInputGamepadDPadLeft); + + bool result = (bool)method.Invoke(controller, [0])!; + + Assert.True(result); + Assert.False(GetPrivateField(controller, "_hasPreviousState")); + Assert.Null(GetPrivateField(controller, "_previousState")); + Assert.Equal((GameInputGamepadButtons)0, GetPrivateField(controller, "_previousProcessedButtons")); + Assert.False(controller.IsBHeld); + Assert.Null(GetPrivateField(controller, "_repeatDirection")); + } + + /// + /// ApplyDiscoveredDevicesWithLifecycle 傳入 null 裝置清單時應安全返回,避免拋出例外。 + /// + [Fact] + public void ApplyDiscoveredDevicesWithLifecycle_WhenDevicesNull_DoesNotThrow() + { + using var controller = (GameInputGamepadController)Activator.CreateInstance( + typeof(GameInputGamepadController), + BindingFlags.Instance | BindingFlags.NonPublic, + binder: null, + args: [new StubInputContext(), null], + culture: null)!; + + MethodInfo method = typeof(GameInputGamepadController).GetMethod( + "ApplyDiscoveredDevicesWithLifecycle", + BindingFlags.Instance | BindingFlags.NonPublic) + ?? throw new InvalidOperationException("找不到 GameInputGamepadController.ApplyDiscoveredDevicesWithLifecycle。"); + + Exception? ex = Record.Exception(() => method.Invoke(controller, [null, 0L, 0])); + Assert.Null(ex); + } + + /// + /// InitializeAndStartPollingAsync 若在輪詢開始前即被取消,應透過 CTS 取消回傳之 Task,避免呼叫端永久掛起死鎖。 + /// + [Fact] + public async Task InitializeAndStartPollingAsync_WhenCancelledEarly_CancelsTcsWithoutHanging() + { + using var controller = (GameInputGamepadController)Activator.CreateInstance( + typeof(GameInputGamepadController), + BindingFlags.Instance | BindingFlags.NonPublic, + binder: null, + args: [new StubInputContext(), null], + culture: null)!; + + MethodInfo initMethod = typeof(GameInputGamepadController).GetMethod( + "InitializeAndStartPollingAsync", + BindingFlags.Instance | BindingFlags.NonPublic) + ?? throw new InvalidOperationException("找不到 InitializeAndStartPollingAsync 方法。"); + + Task initTask = (Task)initMethod.Invoke(controller, [])!; + + // 立即呼叫 StopPolling,模擬 CreateAsync 初始化階段遭遇快速取消或處置 + MethodInfo stopMethod = typeof(GameInputGamepadController).GetMethod( + "StopPolling", + BindingFlags.Instance | BindingFlags.NonPublic) + ?? throw new InvalidOperationException("找不到 StopPolling 方法。"); + + stopMethod.Invoke(controller, []); + + // 驗證 initTask 會在合理時間內轉換為 Canceled 或 Faulted,而不會永久等待 + Task delayTask = Task.Delay(2000, TestContext.Current.CancellationToken); + Task completed = await Task.WhenAny(initTask, delayTask); + + Assert.Same(initTask, completed); + Assert.True(initTask.IsCanceled || initTask.IsFaulted || initTask.IsCompleted); + } + /// /// 透過反射呼叫控制器的 private ClearAllEvents 方法。 /// diff --git a/tests/InputBox.Tests/README.md b/tests/InputBox.Tests/README.md index b8467429..3c8d9786 100644 --- a/tests/InputBox.Tests/README.md +++ b/tests/InputBox.Tests/README.md @@ -21,7 +21,7 @@ | `FormInputStateManagerTests` | `FormInputStateManager` 輸入狀態切換 | 15 | | `GamepadDeadzoneHysteresisTests` | `GamepadDeadzoneHysteresis.ResolveDirection`(int / float 多載),含正負方向對稱性守門(硬體平等原則) | 14 | | `GamepadControllerFactoryTests` | 控制器後端建立策略,驗證 XInput 預設路徑、GameInput 成功路徑,以及 GameInput 執行階段不可用時退避至 XInput | 3 | -| `GamepadControllerPauseTests` | 控制器在 `Pause()` / `Resume()`、連線可用性語意、GameInput 讀取缺失斷線重列舉中斷、探索權杖取消保護、空裝置清單防護、非同步分階段裝置探索、探索所有權與競態防護、世代分配隔離、過期呼叫者工作保護、探索清理移交追蹤、熱插拔版本防覆蓋與請求共用同步、探索失敗重試保留、裝置狀態過濾、震動停止安全性、`ClearAllEvents` 肩鍵釋放訂閱清除與原生對話框切換時的殘留輸入回歸保護 | 25 | +| `GamepadControllerPauseTests` | 控制器在 `Pause()` / `Resume()`、連線可用性語意、GameInput 讀取缺失斷線重列舉中斷與暫態輸入清理、斷線快取與連發計數清除、探索權杖取消保護、空裝置清單防護、非同步分階段裝置探索、初始化快速取消死鎖防護、探索所有權與競態防護、世代分配隔離、過期呼叫者工作保護、探索清理移交追蹤、熱插拔版本防覆蓋與請求共用同步、探索失敗重試保留、裝置狀態過濾、震動停止安全性、`ClearAllEvents` 肩鍵釋放訂閱清除與原生對話框切換時的殘留輸入回歸保護 | 30 | | `GameInputDirectUsageTests` | `GameInputGamepadController` 直接使用 `InputWeave.GameInput` 遊戲控制器介面的守門、callback function pointer marshaling、官方 v3 按鍵位元、快照邊緣偵測、Release 日誌邊界、穩定裝置識別與震動參數保留 | 9 | | `FlashAlertAnimatorTests` | `FlashAlertAnimator` 共用閃爍警示:主題警示色、純淨底色至警示色的插值、整個脈衝過程文字對比 ≥4.5:1、高對比模式半強度切換,以及 1Hz 單次正弦脈衝強度 | 7 | | `GamepadBiasSmoothingTests` | `GamepadBiasSmoothing` 自適應 EMA 學習率公式:零誤差用基礎值、超出範圍用最大值,以及 XInput 與 GameInput 不同數值尺度下結果一致 | 5 | @@ -50,7 +50,7 @@ | `TextBoxSelectionExtensionsTests` | 右搖桿延伸選取共用的 `ResolveSelectionAnchor` 錨點解析(無選取、正向、反向、錨點失效)與 `GetWordJumpTarget` 單字跳轉目標(不改變目前選取、方向與邊界);原本三處複本集中後的一致性保護 | 6 | | `VibrationPatternsTests` | `VibrationPatterns` 與方向性震動設定、語意情境解析、能力感知的多段式微震動序列,以及歷程滾輪阻尼感、字數上限硬牆、震動強度預覽、右搖桿選取粒度、組合鍵進入提示與喚起握手回饋的回歸保護 | 37 | | `VibrationSafetyLimiterTests` | `VibrationSafetyLimiter` 熱保護、Duty Cycle 限制器與極端邊界保護;馬達數量熱成本倍率正規化,以及所有內建震動模式在冷啟動下不得被拒絕、單次超出預算改為降強度,以及Critical 自動連發(含不同模式交錯)降級、熱負載不失控,以及冷啟動短序列仍完整送出的回歸保護 | 20 | -| **合計** | | **462** | +| **合計** | | **467** | ## 二、執行方式 🚀