diff --git a/src/InputBox/Core/Input/GameInputGamepadController.cs b/src/InputBox/Core/Input/GameInputGamepadController.cs
index 17a93812..410c1e0a 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 消費。
///
@@ -114,6 +173,36 @@ internal sealed partial class GameInputGamepadController : IGamepadController
///
private int _missingReadingFrameCounter;
+ ///
+ /// 保護背景裝置探索工作生命週期的同步鎖。
+ ///
+ private readonly Lock _discoveryLock = new();
+
+ ///
+ /// 目前輪詢世代編號,用於辨識並捨棄過期輪詢迴圈的探索結果。
+ ///
+ private int _pollingGeneration;
+
+ ///
+ /// 目前進行中的背景裝置探索工作所捕捉的重新整理要求版本號。
+ ///
+ private long _activeDiscoveryVersion;
+
+ ///
+ /// 追蹤所有已移交停止但尚未完成釋放的背景裝置探索清理工作(包含 Pause 留下的工作)。
+ ///
+ private readonly List _pendingDiscoveryCleanups = [];
+
+ ///
+ /// 目前進行中的背景裝置探索工作
+ ///
+ private Task>? _deviceDiscoveryTask;
+
+ ///
+ /// 背景裝置探索工作的取消權杖來源
+ ///
+ private CancellationTokenSource? _discoveryCts;
+
///
/// 輪詢任務的 CancellationTokenSource
///
@@ -674,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;
+ }
}
///
@@ -699,7 +796,14 @@ private Task InitializeAndStartPollingAsync()
TaskCompletionSource tcs = new(TaskCreationOptions.RunContinuationsAsynchronously);
- _taskPolling = Task.Run(() => PollingLoopAsync(token, tcs), token);
+ 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));
return tcs.Task;
}
@@ -720,7 +824,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));
}
///
@@ -728,14 +833,79 @@ private void StartPolling()
///
private void StopPolling()
{
+ // 遞增世代以使舊輪詢迴圈與進行中的探索失效。
+ Interlocked.Increment(ref _pollingGeneration);
+
CancellationTokenSource? cts = Interlocked.Exchange(ref _ctsPolling, null);
- if (cts == null)
+ if (cts != null)
+ {
+ LogGameInputDiagnosticsSnapshot("stop-polling");
+ cts.CancelAndDispose();
+ }
+
+ Task>? pendingDiscovery = null;
+ lock (_discoveryLock)
+ {
+ Interlocked.Exchange(ref _discoveryCts, null)?.CancelAndDispose();
+ pendingDiscovery = _deviceDiscoveryTask;
+ _deviceDiscoveryTask = null;
+
+ if (_disposed == 0)
+ {
+ RequestRefresh();
+ }
+
+ if (pendingDiscovery != null)
+ {
+ Task? cleanupTask = null;
+ cleanupTask = pendingDiscovery.ContinueWith(t =>
+ {
+ try
+ {
+ if (t.IsCompletedSuccessfully)
+ {
+ DisposeDevices(t.Result);
+ }
+ }
+ finally
+ {
+ lock (_discoveryLock)
+ {
+ if (cleanupTask != null)
+ {
+ _pendingDiscoveryCleanups.Remove(cleanupTask);
+ }
+ }
+ }
+ }, TaskScheduler.Default);
+
+ _pendingDiscoveryCleanups.Add(cleanupTask);
+ }
+ }
+ }
+
+ ///
+ /// 釋放未套用的 GameInput 裝置代理清單。
+ ///
+ /// 要釋放的裝置清單。
+ private static void DisposeDevices(IReadOnlyList devices)
+ {
+ if (devices == null)
{
return;
}
- LogGameInputDiagnosticsSnapshot("stop-polling");
- cts.CancelAndDispose();
+ for (int i = 0; i < devices.Count; i++)
+ {
+ try
+ {
+ devices[i]?.Dispose();
+ }
+ catch (Exception ex)
+ {
+ Debug.WriteLine($"[GameInput] 釋放未套用裝置失敗(已忽略):{ex.Message}");
+ }
+ }
}
///
@@ -760,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();
@@ -776,14 +953,10 @@ private void HandleDisconnect()
// 清空事件佇列。
_readingQueue.Clear();
- if (_device != null)
- {
- // 裝置的處置現在主要由 TryFindDevice 邏輯管理。
- _device = null;
+ _device = null;
- // 更新快取,讓 DeviceName 等屬性反映斷線狀態。
- UpdateDeviceInfo();
- }
+ // 更新快取,讓 DeviceName、DeviceIdentity 與震動能力等屬性反映斷線狀態。
+ UpdateDeviceInfo();
}
///
@@ -795,7 +968,7 @@ private void SetupReadingCallback()
_readingQueue.Clear();
- if (_device != null && _gameInput != null)
+ if (_device != null && _gameInput != null && _disposed == 0)
{
try
{
@@ -827,8 +1000,14 @@ 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)
{
+ if (pollingGeneration != Volatile.Read(ref _pollingGeneration))
+ {
+ initTcs?.TrySetCanceled(cancellationToken);
+ return;
+ }
+
// 在背景執行緒(MTA)建立正式使用的 GameInput 實體。
// 這樣 COM 物件的單元模型就會與輪詢執行緒完全一致,徹底解決 InvalidCastException 與跨執行緒存取失效的問題。
try
@@ -853,31 +1032,57 @@ 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,
(deviceEvent, _) =>
{
- if (deviceEvent is GameInputDeviceEvent.GameInputDeviceEventConnected or GameInputDeviceEvent.GameInputDeviceEventDisconnected)
+ if (_disposed == 0 &&
+ deviceEvent is GameInputDeviceEvent.GameInputDeviceEventConnected or GameInputDeviceEvent.GameInputDeviceEventDisconnected)
{
- _needsRefresh = true;
-
- // 記錄觸發當下的時間。
- Interlocked.Exchange(ref _refreshRequestedTicks, Stopwatch.GetTimestamp());
+ RequestRefresh();
}
});
+
+ // 初始化時先非同步列舉一次以取得既有連線裝置。
+ if (NeedsDeviceRefresh &&
+ !cancellationToken.IsCancellationRequested &&
+ _disposed == 0)
+ {
+ try
+ {
+ long initialVersion;
+ lock (_refreshLock)
+ {
+ initialVersion = _refreshRequestVersion;
+ }
+
+ IReadOnlyList initialDevices = await _gameInput.EnumerateDevicesAsync(
+ GameInputKind.GameInputKindGamepad,
+ cancellationToken).ConfigureAwait(false);
+
+ ApplyDiscoveredDevicesWithLifecycle(initialDevices, initialVersion, pollingGeneration);
+ }
+ catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
+ {
+ initTcs?.TrySetCanceled(cancellationToken);
+ return;
+ }
+ catch (Exception ex)
+ {
+ LoggerService.LogException(ex, "GameInput 初次裝置列舉失敗");
+ Debug.WriteLine($"[GameInput] 初次裝置列舉失敗:{ex.Message}");
+ throw;
+ }
+ }
+ }
+
+ if (cancellationToken.IsCancellationRequested ||
+ pollingGeneration != Volatile.Read(ref _pollingGeneration))
+ {
+ initTcs?.TrySetCanceled(cancellationToken);
+ return;
}
// 成功完成初始化,通知 CreateAsync 解除等待
@@ -942,11 +1147,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)
{
@@ -957,14 +1163,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)
{
@@ -1170,8 +1377,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)
@@ -1185,37 +1398,45 @@ private void Poll()
if (Interlocked.Exchange(ref _readingCallbackObservedTicks, 0) != 0 &&
_device == null)
{
- _needsRefresh = true;
- Interlocked.Exchange(ref _refreshRequestedTicks, Stopwatch.GetTimestamp());
+ RequestRefresh();
}
+ // 先檢查並套用已完成的非同步裝置探索結果。
+ CheckAndApplyDiscoveryResults(pollingGeneration);
+
// 裝置清單防抖與掃描邏輯。
- if (_needsRefresh)
+ bool needsRefresh;
+ long refreshTicks;
+ lock (_refreshLock)
+ {
+ needsRefresh = _needsRefresh || (_refreshRequestVersion != _lastCompletedRefreshVersion);
+ refreshTicks = _refreshRequestedTicks;
+ }
+
+ if (needsRefresh)
{
- // 若目前尚未連線任何裝置,直接重掃,不套用 500ms 防抖,
+ // 若目前尚未連線任何裝置,直接啟動探索,不套用 500ms 防抖,
// 以縮短「未連線 → 新插入」的首段偵測延遲。
if (_device == null)
{
_reconnectCounter = 0;
- TryFindDevice();
+ StartDeviceDiscovery(pollingGeneration);
}
-
- // 尚未連線時已做過即時重掃,本幀不再進行第二次防抖重掃,避免重複列舉。
- if (_device != null)
+ else
{
- long elapsedTicks = Stopwatch.GetTimestamp() - Interlocked.Read(ref _refreshRequestedTicks),
+ long elapsedTicks = Stopwatch.GetTimestamp() - refreshTicks,
elapsedMs = elapsedTicks / (Stopwatch.Frequency / 1000);
if (elapsedMs >= AppSettings.GamepadRefreshCooldownMs)
{
_reconnectCounter = 0;
- TryFindDevice();
+ StartDeviceDiscovery(pollingGeneration);
}
}
}
- else if (_device == null)
+ else if (_device == null && _deviceDiscoveryTask == null)
{
_reconnectCounter++;
@@ -1223,7 +1444,7 @@ private void Poll()
{
_reconnectCounter = 0;
- TryFindDevice();
+ StartDeviceDiscovery(pollingGeneration);
}
}
@@ -1247,7 +1468,7 @@ private void Poll()
{
Debug.WriteLine("[GameInput] 目前裝置狀態已非 Connected,立即重新整理裝置清單。");
LogGameInputDiagnosticsSnapshot("device-status-non-connected");
- RefreshAfterCurrentDeviceBecameUnavailable();
+ RefreshAfterCurrentDeviceBecameUnavailable(pollingGeneration);
return;
}
@@ -1258,7 +1479,7 @@ private void Poll()
{
RecordMissingReading(null, dev);
- if (HandleMissingCurrentReading())
+ if (HandleMissingCurrentReading(pollingGeneration))
{
return;
}
@@ -1282,7 +1503,7 @@ private void Poll()
RecordReadFailure(ex);
Debug.WriteLine($"[GameInput] 讀取目前狀態失敗,稍後重新整理裝置:{ex.Message}");
- if (HandleMissingCurrentReading())
+ if (HandleMissingCurrentReading(pollingGeneration))
{
return;
}
@@ -1398,33 +1619,113 @@ private void Poll()
///
/// 目前裝置已不可用時立即重新整理裝置清單。
///
- private void RefreshAfterCurrentDeviceBecameUnavailable()
+ /// 目前輪詢迴圈的世代編號。
+ private void RefreshAfterCurrentDeviceBecameUnavailable(int pollingGeneration = 0)
{
_missingReadingFrameCounter = 0;
- _needsRefresh = true;
- Interlocked.Exchange(ref _refreshRequestedTicks, Stopwatch.GetTimestamp());
+ RequestRefresh();
+
+ 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))
+ {
+ 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;
+
+ UpdateDeviceInfo();
+ InitializeDeviceState();
+ SetupReadingCallback();
+
+ needsConnectNotify = true;
+
+ break;
+ }
+ }
+
+ if (_device == null)
+ {
+ needsDisconnect = true;
+ }
+ }
+
+ if (needsDisconnect)
+ {
+ HandleDisconnect();
+ }
- TryFindDevice();
+ if (needsConnectNotify)
+ {
+ _isConnected = true;
+ ConnectionChanged?.Invoke(true);
+ }
+
+ StartDeviceDiscovery(pollingGeneration);
}
///
/// 處理目前裝置連續讀不到 reading 的情境;超過閾值時立即重列舉以偵測斷線。
///
+ /// 目前輪詢迴圈的世代編號。
/// 若已重列舉且目前幀應停止後續狀態處理則回傳 true。
- private bool HandleMissingCurrentReading()
+ private bool HandleMissingCurrentReading(int pollingGeneration = 0)
{
if (!ShouldRefreshAfterMissingCurrentReading())
{
return false;
}
- _needsRefresh = true;
- Interlocked.Exchange(ref _refreshRequestedTicks, Stopwatch.GetTimestamp());
+ // 連續丟失讀取達重連門檻時,清除過期暫態輸入快照與連發狀態,
+ // 避免在重列舉完成前持續對最後一幀的按鍵狀態執行重複連發。
+ _hasPreviousState = false;
+ _previousState = null;
+ _previousProcessedButtons = 0;
+ ResetDirectionalRepeatState();
+ ResetHoldStates();
+
+ RequestRefresh();
LogGameInputDiagnosticsSnapshot("missing-reading-threshold");
- TryFindDevice();
+ StartDeviceDiscovery(pollingGeneration);
- return _device == null;
+ return true;
}
///
@@ -1739,27 +2040,193 @@ private void ResetTransientInputState(bool requireNeutralBeforeInput = true)
}
///
- /// 嘗試尋找裝置
+ /// 啟動非同步裝置探索工作。
+ /// 探索在背景執行且不持有 ,避免阻塞 60 FPS 輪詢迴圈或導致現有手把輸入遺失。
///
- private void TryFindDevice()
+ /// 目前輪詢迴圈的世代編號。
+ private void StartDeviceDiscovery(int pollingGeneration = 0)
{
- GameInputClient? gameInput = _gameInput;
+ lock (_discoveryLock)
+ {
+ if (_deviceDiscoveryTask != null ||
+ _disposed != 0 ||
+ _isPaused ||
+ _gameInput == null ||
+ (pollingGeneration != 0 && pollingGeneration != Volatile.Read(ref _pollingGeneration)))
+ {
+ return;
+ }
- if (gameInput == null)
+ CancellationTokenSource? pollingCts = _ctsPolling;
+ CancellationToken pollingToken = pollingCts?.Token ?? CancellationToken.None;
+
+ if (pollingToken.IsCancellationRequested)
+ {
+ return;
+ }
+
+ CancellationTokenSource discoveryCts = CancellationTokenSource.CreateLinkedTokenSource(pollingToken);
+ Interlocked.Exchange(ref _discoveryCts, null)?.CancelAndDispose();
+ _discoveryCts = discoveryCts;
+ lock (_refreshLock)
+ {
+ _activeDiscoveryVersion = _refreshRequestVersion;
+ }
+
+ try
+ {
+ _deviceDiscoveryTask = _gameInput.EnumerateDevicesAsync(
+ GameInputKind.GameInputKindGamepad,
+ discoveryCts.Token);
+ }
+ catch (Exception ex)
+ {
+ RequestRefresh();
+ _deviceDiscoveryTask = null;
+ Interlocked.Exchange(ref _discoveryCts, null)?.CancelAndDispose();
+
+ LoggerService.LogException(ex, "GameInput 啟動裝置探索失敗");
+ Debug.WriteLine($"[GameInput] 啟動裝置探索失敗:{ex.Message}");
+ }
+ }
+ }
+
+ ///
+ /// 檢查背景裝置探索工作是否完成,並於輪詢執行緒套用結果。
+ ///
+ /// 目前輪詢迴圈的世代編號。
+ private void CheckAndApplyDiscoveryResults(int pollingGeneration = 0)
+ {
+ Task>? task = null;
+ long capturedVersion = 0;
+
+ lock (_discoveryLock)
+ {
+ // 在取走工作前拒絕過期呼叫者,避免舊世代的 Poll 清空並誤釋放新世代的探索工作
+ if (pollingGeneration != 0 && pollingGeneration != Volatile.Read(ref _pollingGeneration))
+ {
+ return;
+ }
+
+ task = _deviceDiscoveryTask;
+
+ if (task == null || !task.IsCompleted)
+ {
+ return;
+ }
+
+ _deviceDiscoveryTask = null;
+ Interlocked.Exchange(ref _discoveryCts, null)?.CancelAndDispose();
+ capturedVersion = _activeDiscoveryVersion;
+ }
+
+ try
+ {
+ if (task.IsCompletedSuccessfully)
+ {
+ ApplyDiscoveredDevicesWithLifecycle(task.Result, capturedVersion, pollingGeneration);
+ }
+ else if (task.IsFaulted || task.IsCanceled)
+ {
+ RequestRefresh();
+
+ if (task.IsFaulted && task.Exception != null)
+ {
+ LoggerService.LogException(task.Exception.GetBaseException(), "GameInput 裝置非同步探索失敗");
+ Debug.WriteLine($"[GameInput] 裝置非同步探索失敗:{task.Exception.GetBaseException().Message}");
+ }
+ }
+ }
+ catch (Exception ex)
+ {
+ RequestRefresh();
+
+ 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)
+ {
+ if (devices == null)
{
return;
}
bool needsDisconnect = false,
needsConnectNotify = false;
+ List? staleDevicesToDispose = null;
lock (_deviceLock)
{
- _needsRefresh = false;
+ // 最終生命週期驗證:若在探索完成後已被處置、暫停、或輪詢世代已過期
+ if (_disposed != 0 ||
+ _isPaused ||
+ (pollingGeneration != 0 && pollingGeneration != Volatile.Read(ref _pollingGeneration)))
+ {
+ staleDevicesToDispose = [.. devices];
+
+ if (_disposed == 0)
+ {
+ RequestRefresh();
+ }
+ }
+ else
+ {
+ ApplyDiscoveredDevicesCore(devices, ref needsDisconnect, ref needsConnectNotify);
+
+ if (capturedVersion != 0)
+ {
+ AcknowledgeRefresh(capturedVersion);
+ }
+ }
+ }
+
+ if (staleDevicesToDispose != null)
+ {
+ DisposeDevices(staleDevicesToDispose);
+ return;
+ }
+
+ // 在鎖外執行,防止持鎖時觸發 ConnectionChanged 事件導致死鎖風險。
+ if (needsDisconnect)
+ {
+ HandleDisconnect();
+ }
- // 執行一次完整的列舉。
- IReadOnlyList devices = gameInput.EnumerateDevices(
- GameInputKind.GameInputKindGamepad);
+ if (needsConnectNotify)
+ {
+ _isConnected = true;
+ ConnectionChanged?.Invoke(true);
+ }
+ }
+
+ ///
+ /// 在已持有 的前提下,更新快取裝置清單與目前啟動裝置。
+ ///
+ /// 新探索到的裝置清單。
+ /// 是否需要在鎖外通知斷線。
+ /// 是否需要在鎖外通知連線。
+ private void ApplyDiscoveredDevicesCore(
+ IReadOnlyList devices,
+ ref bool needsDisconnect,
+ ref bool needsConnectNotify)
+ {
// 1. 釋放清單中已不再存在或已非 Connected 的舊裝置代理(Zero-allocation 替換 LINQ Any)。
for (int i = _allDevices.Count - 1; i >= 0; i--)
@@ -1886,6 +2353,18 @@ private void TryFindDevice()
{
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;
@@ -1908,17 +2387,33 @@ private void TryFindDevice()
}
}
- // 在鎖外執行,防止持鎖時觸發 ConnectionChanged 事件導致死鎖風險。
- if (needsDisconnect)
+ ///
+ /// 同步尋找裝置(僅供需要立即探索的相容路徑使用,平時由背景分階段探索取代)。
+ ///
+ private void TryFindDevice()
+ {
+ GameInputClient? gameInput = _gameInput;
+
+ if (gameInput == null)
{
- HandleDisconnect();
+ return;
}
- if (needsConnectNotify)
+ IReadOnlyList devices;
+
+ try
{
- _isConnected = true;
- ConnectionChanged?.Invoke(true);
+ devices = gameInput.EnumerateDevices(GameInputKind.GameInputKindGamepad);
}
+ catch (Exception ex)
+ {
+ LoggerService.LogException(ex, "GameInput 同步列舉裝置失敗");
+ Debug.WriteLine($"[GameInput] 同步列舉裝置失敗:{ex.Message}");
+
+ return;
+ }
+
+ ApplyDiscoveredDevices(devices);
}
///
@@ -1996,10 +2491,35 @@ 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;
// 切換裝置參考。
_device = otherDev;
+ if (oldDev != null)
+ {
+ try
+ {
+ oldDev.SetRumbleState(new GameInputRumbleParams());
+ }
+ catch (Exception rumbleEx)
+ {
+ Debug.WriteLine($"[GameInput] 切換裝置時停止舊裝置馬達失敗(已忽略):{rumbleEx.Message}");
+ }
+ }
+
UpdateDeviceInfo();
InitializeDeviceState();
SetupReadingCallback();
@@ -2910,9 +3430,13 @@ public Task VibrateAsync(
///
public void Pause()
{
- _isPaused = true;
+ lock (_deviceLock)
+ {
+ _isPaused = true;
+ ResetTransientInputState();
+ }
+
StopPolling();
- ResetTransientInputState();
}
///
@@ -2960,8 +3484,15 @@ public void Resume()
return;
}
- ResetTransientInputState();
- _isPaused = false;
+ StopPolling();
+
+ lock (_deviceLock)
+ {
+ ResetTransientInputState();
+ _isPaused = false;
+ }
+
+ RequestRefresh();
StartPolling();
}
@@ -3138,6 +3669,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;
@@ -3171,14 +3711,81 @@ private Task DisposeResourcesAsync()
deviceCallbackReg?.Dispose();
readingCallbackReg?.Dispose();
+ // 等待已捕獲的背景探索工作完成並釋放所產生的裝置代理。
+ if (discoveryTask != null)
+ {
+ try
+ {
+ IReadOnlyList pending = await discoveryTask.ConfigureAwait(false);
+ DisposeDevices(pending);
+ }
+ catch (Exception ex)
+ {
+ Debug.WriteLine($"[GameInput] 處置時等待探索完成發生例外(已忽略):{ex.Message}");
+ }
+ }
+
+ // 等待所有已移交停止的探索清理工作(包含先前 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}");
+ }
+ }
+
+ 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/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..0d0aa94f 100644
--- a/tests/InputBox.Tests/GamepadControllerPauseTests.cs
+++ b/tests/InputBox.Tests/GamepadControllerPauseTests.cs
@@ -244,6 +244,366 @@ 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, [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 應拒絕取走工作,
+ /// 確保新世代進行中的探索工作不被過期呼叫者清空或誤釋放。
+ ///
+ [Fact]
+ public void CheckAndApplyDiscoveryResults_WhenStaleGeneration_RetainsDiscoveryTaskForCurrentGeneration()
+ {
+ 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。");
+
+ Task> currentGenTask = Task.FromResult>([]);
+
+ SetPrivateField(controller, "_pollingGeneration", 5);
+ SetPrivateField(controller, "_deviceDiscoveryTask", currentGenTask);
+
+ // 傳入過期世代 4
+ method.Invoke(controller, [4]);
+
+ // 驗證過期呼叫者被拒絕,新世代的工作未被清空
+ 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"));
+ List pendingCleanups = GetPrivateField>(controller, "_pendingDiscoveryCleanups");
+ Task cleanupTask = Assert.Single(pendingCleanups);
+ Assert.NotNull(cleanupTask);
+
+ // 呼叫 DisposeResourcesAsync,在 discoveryTcs 未完成前,Dispose 任務不應結束
+ Task disposeTask = (Task)disposeResourcesMethod.Invoke(controller, [])!;
+ Assert.False(disposeTask.IsCompleted);
+
+ // 完成探索工作
+ discoveryTcs.SetResult([]);
+
+ // 等待 Dispose 完成
+ await disposeTask;
+
+ Assert.True(disposeTask.IsCompletedSuccessfully);
+ Assert.Empty(GetPrivateField>(controller, "_pendingDiscoveryCleanups"));
+ }
+
+ ///
+ /// 若舊輪詢工作傳入過期世代,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
+ Task 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 並觸發斷線流程。
+ ///
+ [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 兩個事件訂閱,避免處置後仍殘留呼叫鏈造成事件洩漏。
@@ -292,6 +652,282 @@ 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);
+ }
+
+ ///
+ /// 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 964b4281..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` 肩鍵釋放訂閱清除與原生對話框切換時的殘留輸入回歸保護 | 10 |
+| `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 |
-| **合計** | | **447** |
+| **合計** | | **467** |
## 二、執行方式 🚀