| | | 1 | | using System; |
| | | 2 | | using System.Collections.Generic; |
| | | 3 | | using System.Linq; |
| | | 4 | | using System.Threading; |
| | | 5 | | using System.Threading.Tasks; |
| | | 6 | | using SwitchBlade.Contracts; |
| | | 7 | | |
| | | 8 | | namespace SwitchBlade.Services |
| | | 9 | | { |
| | | 10 | | /// <summary> |
| | | 11 | | /// Coordinates parallel execution of window providers. |
| | | 12 | | /// Handles structural diffing, caching, and icon population (via IWindowReconciler). |
| | | 13 | | /// |
| | | 14 | | /// Delegates provider execution to <see cref="IProviderRunner"/> strategies: |
| | | 15 | | /// - In-process runners for fast, non-UIA providers |
| | | 16 | | /// - Out-of-process runners for UIA providers (prevents memory leaks) |
| | | 17 | | /// </summary> |
| | 52 | 18 | | public class WindowOrchestrationService( |
| | 52 | 19 | | IEnumerable<IWindowProvider> providers, |
| | 52 | 20 | | IWindowReconciler reconciler, |
| | 52 | 21 | | IUiaWorkerClient uiaWorkerClient, |
| | 52 | 22 | | INativeInteropWrapper nativeInterop, |
| | 52 | 23 | | IProviderRunner fastRunner, |
| | 52 | 24 | | IProviderRunner uiaRunner, |
| | 52 | 25 | | ILogger? logger = null) : IWindowOrchestrationService, IDisposable |
| | | 26 | | { |
| | 62 | 27 | | private readonly List<IWindowProvider> _providers = providers?.ToList() ?? throw new ArgumentNullException(nameo |
| | 60 | 28 | | private readonly IWindowReconciler _reconciler = reconciler ?? throw new ArgumentNullException(nameof(reconciler |
| | 58 | 29 | | private readonly INativeInteropWrapper _nativeInterop = nativeInterop ?? throw new ArgumentNullException(nameof( |
| | 56 | 30 | | private readonly IProviderRunner _fastRunner = fastRunner ?? throw new ArgumentNullException(nameof(fastRunner)) |
| | 55 | 31 | | private readonly IProviderRunner _uiaRunner = uiaRunner ?? throw new ArgumentNullException(nameof(uiaRunner)); |
| | 54 | 32 | | private readonly IUiaWorkerClient _uiaWorkerClient = uiaWorkerClient ?? throw new ArgumentNullException(nameof(u |
| | 52 | 33 | | private readonly ILogger? _logger = logger; |
| | 52 | 34 | | private readonly List<WindowItem> _allWindows = []; |
| | | 35 | | |
| | 52 | 36 | | private readonly Lock _lock = new(); |
| | | 37 | | // Re-entrancy guard for fast (Non-UIA) providers. |
| | 52 | 38 | | private readonly SemaphoreSlim _fastRefreshLock = new(1, 1); |
| | | 39 | | private bool _disposed; |
| | | 40 | | |
| | | 41 | | public event EventHandler<WindowListUpdatedEventArgs>? WindowListUpdated; |
| | | 42 | | |
| | | 43 | | public IReadOnlyList<WindowItem> AllWindows |
| | | 44 | | { |
| | | 45 | | get |
| | 40 | 46 | | { |
| | | 47 | | lock (_lock) |
| | 40 | 48 | | { |
| | 40 | 49 | | return [.. _allWindows]; |
| | | 50 | | } |
| | 40 | 51 | | } |
| | | 52 | | } |
| | | 53 | | |
| | | 54 | | public async Task RefreshAsync(IEnumerable<string> disabledPlugins) |
| | 60 | 55 | | { |
| | | 56 | | // Non-blocking re-entrancy guard for fast (Non-UIA) providers. |
| | 60 | 57 | | if (!await _fastRefreshLock.WaitAsync(0)) |
| | 3 | 58 | | { |
| | 3 | 59 | | _logger?.Log("RefreshAsync skipped: fast-path scan already in progress."); |
| | 3 | 60 | | return; |
| | | 61 | | } |
| | | 62 | | |
| | | 63 | | try |
| | 57 | 64 | | { |
| | 57 | 65 | | disabledPlugins ??= new HashSet<string>(); |
| | | 66 | | |
| | | 67 | | // Clear process cache for fresh lookups |
| | 57 | 68 | | _nativeInterop.ClearProcessCache(); |
| | | 69 | | |
| | | 70 | | // 1. Reload settings and gather handled processes (for all providers) |
| | 57 | 71 | | var handledProcesses = new HashSet<string>(StringComparer.OrdinalIgnoreCase); |
| | 295 | 72 | | foreach (var provider in _providers) |
| | 62 | 73 | | { |
| | | 74 | | try |
| | 62 | 75 | | { |
| | 62 | 76 | | if (provider is IConfigurablePlugin configurable) |
| | 55 | 77 | | { |
| | 55 | 78 | | configurable.ReloadSettings(); |
| | 53 | 79 | | } |
| | | 80 | | |
| | 60 | 81 | | if (provider is IProviderExclusionSettings exclusionSettings) |
| | 58 | 82 | | { |
| | 180 | 83 | | foreach (var p in exclusionSettings.GetHandledProcesses()) |
| | 3 | 84 | | { |
| | 3 | 85 | | handledProcesses.Add(p); |
| | 3 | 86 | | } |
| | 58 | 87 | | } |
| | 60 | 88 | | } |
| | 2 | 89 | | catch (Exception ex) |
| | 2 | 90 | | { |
| | 2 | 91 | | _logger?.LogError($"Error reloading settings for {provider.PluginName}", ex); |
| | 2 | 92 | | } |
| | 62 | 93 | | } |
| | | 94 | | |
| | | 95 | | // 2. Inject exclusions (for all providers) |
| | 295 | 96 | | foreach (var provider in _providers) |
| | 62 | 97 | | { |
| | 62 | 98 | | if (provider is IProviderExclusionSettings exclusionSettings) |
| | 60 | 99 | | { |
| | 60 | 100 | | exclusionSettings.SetExclusions(handledProcesses); |
| | 60 | 101 | | } |
| | 62 | 102 | | } |
| | | 103 | | |
| | | 104 | | // 3. Split providers into UIA (out-of-process) and non-UIA (in-process) |
| | 119 | 105 | | var nonUiaProviders = _providers.Where(p => !(p is IExtrusionStrategy s && s.IsUiaProvider)).ToList(); |
| | 119 | 106 | | var uiaProviders = _providers.Where(p => p is IExtrusionStrategy s && s.IsUiaProvider).ToList(); |
| | | 107 | | |
| | | 108 | | // 4a. Run fast providers via the fast runner strategy |
| | 57 | 109 | | await _fastRunner.RunAsync(nonUiaProviders, disabledPlugins, handledProcesses, ProcessProviderResults); |
| | | 110 | | |
| | | 111 | | // 4b. Run UIA providers via the UIA runner strategy (background) |
| | | 112 | | // UIA providers: fire-and-forget in background to avoid blocking core updates |
| | 54 | 113 | | if (uiaProviders.Count > 0) |
| | 11 | 114 | | { |
| | 11 | 115 | | _ = LaunchUiaRefresh(uiaProviders, disabledPlugins, handledProcesses); |
| | 11 | 116 | | } |
| | 54 | 117 | | } |
| | 3 | 118 | | catch (Exception ex) |
| | 3 | 119 | | { |
| | 3 | 120 | | _logger?.LogError("Critical error during RefreshAsync", ex); |
| | 3 | 121 | | } |
| | | 122 | | finally |
| | 57 | 123 | | { |
| | 57 | 124 | | _fastRefreshLock.Release(); |
| | 57 | 125 | | } |
| | 60 | 126 | | } |
| | | 127 | | |
| | | 128 | | private async Task LaunchUiaRefresh(List<IWindowProvider> uiaProviders, IEnumerable<string> disabledPlugins, IEn |
| | 11 | 129 | | { |
| | | 130 | | try |
| | 11 | 131 | | { |
| | 11 | 132 | | _logger?.Log($"Launching background UIA refresh for {uiaProviders.Count} providers"); |
| | 11 | 133 | | await _uiaRunner.RunAsync(uiaProviders, disabledPlugins, handledProcesses, ProcessProviderResults); |
| | 9 | 134 | | } |
| | 2 | 135 | | catch (Exception ex) |
| | 2 | 136 | | { |
| | 2 | 137 | | _logger?.LogError("Background UIA refresh failed", ex); |
| | 2 | 138 | | } |
| | 11 | 139 | | } |
| | | 140 | | |
| | | 141 | | private void ProcessProviderResults(IWindowProvider provider, List<WindowItem> results) |
| | 53 | 142 | | { |
| | 53 | 143 | | WindowListUpdatedEventArgs args = null!; |
| | 53 | 144 | | List<WindowItem>? reconciled = null; |
| | | 145 | | lock (_lock) |
| | 53 | 146 | | { |
| | | 147 | | // Check LKG condition |
| | 85 | 148 | | if (results.Count > 0 && results.All(r => r.IsFallback)) |
| | 7 | 149 | | { |
| | 7 | 150 | | bool hasExistingRealItems = HasExistingRealItems(provider); |
| | 7 | 151 | | if (hasExistingRealItems) |
| | 3 | 152 | | { |
| | 4 | 153 | | _logger?.Log($"[LKG] {provider.PluginName}: Transient failure (only fallback items received). Pr |
| | | 154 | | |
| | | 155 | | // DEFER Event Emission to outside the lock |
| | 3 | 156 | | args = new WindowListUpdatedEventArgs(provider, false); |
| | 3 | 157 | | goto EmitAndReturn; |
| | | 158 | | } |
| | 4 | 159 | | } |
| | | 160 | | |
| | 50 | 161 | | long start = System.Diagnostics.Stopwatch.GetTimestamp(); |
| | | 162 | | |
| | | 163 | | // Normal path: Replace existing items with new results |
| | 130 | 164 | | for (int i = _allWindows.Count - 1; i >= 0; i--) |
| | 15 | 165 | | { |
| | 15 | 166 | | if (_allWindows[i].Source == provider) |
| | 12 | 167 | | _allWindows.RemoveAt(i); |
| | 15 | 168 | | } |
| | | 169 | | |
| | 50 | 170 | | reconciled = _reconciler.Reconcile(results, provider); |
| | 50 | 171 | | _allWindows.AddRange(reconciled); |
| | | 172 | | |
| | 50 | 173 | | args = new WindowListUpdatedEventArgs(provider, true); |
| | | 174 | | |
| | 50 | 175 | | if (_logger != null && SwitchBlade.Core.Logger.IsDebugEnabled) |
| | 1 | 176 | | { |
| | 1 | 177 | | var elapsed = System.Diagnostics.Stopwatch.GetElapsedTime(start); |
| | 1 | 178 | | _logger.Log($"[Perf] Reconciled {reconciled.Count} items for {provider.PluginName} in {elapsed.Total |
| | 1 | 179 | | } |
| | 50 | 180 | | } |
| | | 181 | | |
| | 53 | 182 | | EmitAndReturn: |
| | | 183 | | // Emit event IMMEDIATELY so UI shows text - icons will pop in later |
| | 53 | 184 | | EmitEvent(args); |
| | | 185 | | |
| | | 186 | | // If we jumped here from LKG, reconciled is null/empty, so we shouldn't populate icons. |
| | 52 | 187 | | if (reconciled != null && reconciled.Count > 0) |
| | 28 | 188 | | { |
| | 28 | 189 | | Task.Run(() => |
| | 28 | 190 | | { |
| | 28 | 191 | | try |
| | 28 | 192 | | { |
| | 28 | 193 | | _reconciler.PopulateIcons(reconciled); |
| | 26 | 194 | | } |
| | 2 | 195 | | catch (Exception ex) |
| | 2 | 196 | | { |
| | 2 | 197 | | _logger?.LogError($"Error populating icons for {provider.PluginName}", ex); |
| | 2 | 198 | | } |
| | 56 | 199 | | }); |
| | 28 | 200 | | } |
| | 52 | 201 | | return; |
| | 52 | 202 | | } |
| | | 203 | | |
| | | 204 | | private void EmitEvent(WindowListUpdatedEventArgs args) |
| | 53 | 205 | | { |
| | 53 | 206 | | WindowListUpdated?.Invoke(this, args); |
| | 52 | 207 | | } |
| | | 208 | | |
| | | 209 | | /// <summary> |
| | | 210 | | /// Checks whether any cached items for the given provider are non-fallback (real). |
| | | 211 | | /// Extracted for deterministic branch coverage of both conditions. |
| | | 212 | | /// </summary> |
| | | 213 | | private bool HasExistingRealItems(IWindowProvider provider) |
| | 11 | 214 | | { |
| | 49 | 215 | | foreach (var w in _allWindows) |
| | 10 | 216 | | { |
| | 10 | 217 | | if (w.Source == provider && !w.IsFallback) |
| | 4 | 218 | | return true; |
| | 6 | 219 | | } |
| | 7 | 220 | | return false; |
| | 11 | 221 | | } |
| | | 222 | | |
| | | 223 | | #region Encapsulated Cache Mutators (Delegated to Reconciler) |
| | | 224 | | |
| | | 225 | | /// <summary> |
| | | 226 | | /// Gets the total number of cached window items (HWND + Provider records). |
| | | 227 | | /// Used for memory diagnostics. |
| | | 228 | | /// </summary> |
| | 1 | 229 | | public int CacheCount => _reconciler.CacheCount; |
| | | 230 | | |
| | | 231 | | #endregion |
| | | 232 | | |
| | | 233 | | public void Dispose() |
| | 6 | 234 | | { |
| | 7 | 235 | | if (_disposed) return; |
| | 5 | 236 | | _disposed = true; |
| | | 237 | | |
| | 23 | 238 | | foreach (var provider in _providers) |
| | 4 | 239 | | { |
| | 4 | 240 | | if (provider is IDisposable disposable) |
| | 4 | 241 | | { |
| | | 242 | | try |
| | 4 | 243 | | { |
| | 4 | 244 | | disposable.Dispose(); |
| | 2 | 245 | | } |
| | 2 | 246 | | catch (Exception ex) |
| | 2 | 247 | | { |
| | 2 | 248 | | _logger?.LogError($"Error disposing provider {provider.PluginName}", ex); |
| | 2 | 249 | | } |
| | 4 | 250 | | } |
| | 4 | 251 | | } |
| | | 252 | | |
| | 5 | 253 | | _uiaWorkerClient.Dispose(); |
| | 5 | 254 | | _fastRefreshLock.Dispose(); |
| | | 255 | | |
| | 5 | 256 | | if (_uiaRunner is IDisposable disposableRunner) |
| | 4 | 257 | | { |
| | 4 | 258 | | disposableRunner.Dispose(); |
| | 4 | 259 | | } |
| | 5 | 260 | | GC.SuppressFinalize(this); |
| | 6 | 261 | | } |
| | | 262 | | } |
| | | 263 | | } |