-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWindowTracker.cs
More file actions
337 lines (281 loc) · 11.1 KB
/
WindowTracker.cs
File metadata and controls
337 lines (281 loc) · 11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
using System.Diagnostics;
namespace MonitorWindowsRestore;
public class WindowTracker
{
private readonly Config _config;
private readonly WindowState _state;
private readonly MonitorWatcher _monitorWatcher;
private readonly HashSet<string> _processNames;
private IntPtr _foregroundHook;
private IntPtr _locationHook;
private NativeMethods.WinEventDelegate? _winEventDelegate;
private readonly Dictionary<IntPtr, System.Timers.Timer> _pendingCaptures = new();
private readonly object _lock = new();
private int _zOrderCounter;
private System.Timers.Timer? _saveTimer;
private bool _savePending;
public event Action<string>? OnLog;
public WindowTracker(Config config, WindowState state, MonitorWatcher monitorWatcher)
{
_config = config;
_state = state;
_monitorWatcher = monitorWatcher;
_processNames = new HashSet<string>(_config.Programs, StringComparer.OrdinalIgnoreCase);
}
public void Start()
{
// Initial scan to populate state
TrackWindows();
// Keep delegate alive to prevent GC
_winEventDelegate = OnWindowEvent;
// Install hooks for foreground (focus) and location changes
_foregroundHook = NativeMethods.SetWinEventHook(
NativeMethods.EVENT_SYSTEM_FOREGROUND,
NativeMethods.EVENT_SYSTEM_FOREGROUND,
IntPtr.Zero,
_winEventDelegate,
0, 0,
NativeMethods.WINEVENT_OUTOFCONTEXT);
_locationHook = NativeMethods.SetWinEventHook(
NativeMethods.EVENT_OBJECT_LOCATIONCHANGE,
NativeMethods.EVENT_OBJECT_LOCATIONCHANGE,
IntPtr.Zero,
_winEventDelegate,
0, 0,
NativeMethods.WINEVENT_OUTOFCONTEXT);
if (_foregroundHook == IntPtr.Zero || _locationHook == IntPtr.Zero)
{
OnLog?.Invoke("Warning: Failed to install one or more event hooks");
}
OnLog?.Invoke("Window tracking started (event hooks)");
}
public void Stop()
{
if (_foregroundHook != IntPtr.Zero)
{
NativeMethods.UnhookWinEvent(_foregroundHook);
_foregroundHook = IntPtr.Zero;
}
if (_locationHook != IntPtr.Zero)
{
NativeMethods.UnhookWinEvent(_locationHook);
_locationHook = IntPtr.Zero;
}
// Dispose all pending capture timers
lock (_lock)
{
foreach (var timer in _pendingCaptures.Values)
{
timer.Stop();
timer.Dispose();
}
_pendingCaptures.Clear();
}
_saveTimer?.Stop();
_saveTimer?.Dispose();
_saveTimer = null;
OnLog?.Invoke("Window tracking stopped");
}
private void OnWindowEvent(IntPtr hWinEventHook, uint eventType, IntPtr hwnd,
int idObject, int idChild, uint dwEventThread, uint dwmsEventTime)
{
// Don't capture during display reconfiguration
if (_monitorWatcher.IsFrozen) return;
// Only handle window-level events, not child objects
if (idObject != NativeMethods.OBJID_WINDOW) return;
if (hwnd == IntPtr.Zero) return;
// Check if this is an app window we care about
if (!NativeMethods.IsAppWindow(hwnd)) return;
// Get process info
NativeMethods.GetWindowThreadProcessId(hwnd, out uint processId);
string? processName = null;
try
{
var process = Process.GetProcessById((int)processId);
processName = process.ProcessName + ".exe";
}
catch (ArgumentException) { return; }
catch (InvalidOperationException) { return; }
// Only track configured programs
if (!_processNames.Contains(processName)) return;
// Only track when required monitors are connected
if (Screen.AllScreens.Length < _config.RequiredMonitorCount) return;
// Update Z-order on focus change
if (eventType == NativeMethods.EVENT_SYSTEM_FOREGROUND)
{
Interlocked.Increment(ref _zOrderCounter);
}
// Start or reset debounce timer for this window
StartDebounceTimer(hwnd, eventType == NativeMethods.EVENT_SYSTEM_FOREGROUND);
}
private void StartDebounceTimer(IntPtr hwnd, bool isFocusChange)
{
lock (_lock)
{
if (_pendingCaptures.TryGetValue(hwnd, out var existingTimer))
{
// Reset existing timer
existingTimer.Stop();
existingTimer.Start();
}
else
{
// Create new timer
var timer = new System.Timers.Timer(_config.DebounceDelayMs);
timer.AutoReset = false;
var capturedHwnd = hwnd;
var capturedZOrder = _zOrderCounter;
timer.Elapsed += (_, _) => CaptureWindow(capturedHwnd, capturedZOrder);
_pendingCaptures[hwnd] = timer;
timer.Start();
}
// Update the captured Z-order if this is a focus change
if (isFocusChange && _pendingCaptures.TryGetValue(hwnd, out var t))
{
// Re-create timer to capture updated Z-order
t.Stop();
t.Dispose();
var timer = new System.Timers.Timer(_config.DebounceDelayMs);
timer.AutoReset = false;
var capturedHwnd = hwnd;
var capturedZOrder = _zOrderCounter;
timer.Elapsed += (_, _) => CaptureWindow(capturedHwnd, capturedZOrder);
_pendingCaptures[hwnd] = timer;
timer.Start();
}
}
}
private void CaptureWindow(IntPtr hwnd, int zOrder)
{
lock (_lock)
{
_pendingCaptures.Remove(hwnd);
}
// Check window still exists and get its rect
if (!NativeMethods.GetWindowRect(hwnd, out var rect)) return;
// Skip minimized windows - keep existing position
if (NativeMethods.IsIconic(hwnd)) return;
// Skip hung windows
if (NativeMethods.IsHungAppWindow(hwnd)) return;
// Get window info
NativeMethods.GetWindowThreadProcessId(hwnd, out uint processId);
string? processName = null;
try
{
var process = Process.GetProcessById((int)processId);
processName = process.ProcessName + ".exe";
}
catch { return; }
var title = NativeMethods.GetWindowTitle(hwnd);
if (string.IsNullOrEmpty(title)) return;
var id = WindowInfo.GenerateId(processName, title);
bool isMaximized = NativeMethods.IsZoomed(hwnd);
var info = new WindowInfo
{
ProcessName = processName,
WindowTitle = title,
Id = id,
X = rect.Left,
Y = rect.Top,
Width = rect.Right - rect.Left,
Height = rect.Bottom - rect.Top,
IsMaximized = isMaximized,
ZOrder = zOrder
};
_state.Windows[id] = info;
ScheduleSave();
}
private void ScheduleSave()
{
lock (_lock)
{
if (_savePending) return;
_savePending = true;
_saveTimer?.Stop();
_saveTimer?.Dispose();
_saveTimer = new System.Timers.Timer(100); // Batch saves within 100ms
_saveTimer.AutoReset = false;
_saveTimer.Elapsed += (_, _) =>
{
lock (_lock) { _savePending = false; }
_state.Save();
OnLog?.Invoke($"Saved {_state.Windows.Count} windows");
};
_saveTimer.Start();
}
}
/// <summary>
/// Manual full scan - used for "Track Now" menu and initial population
/// </summary>
public void TrackWindows()
{
// Only track when required monitors are connected
if (Screen.AllScreens.Length < _config.RequiredMonitorCount)
{
OnLog?.Invoke($"Only {Screen.AllScreens.Length}/{_config.RequiredMonitorCount} monitors, skipping tracking");
return;
}
var foundWindows = new HashSet<string>();
int zOrderCounter = 0;
NativeMethods.EnumWindows((hWnd, _) =>
{
if (!NativeMethods.IsAppWindow(hWnd)) return true;
NativeMethods.GetWindowThreadProcessId(hWnd, out uint processId);
try
{
var process = Process.GetProcessById((int)processId);
var processName = process.ProcessName + ".exe";
if (!_processNames.Contains(processName)) return true;
// Skip hung/unresponsive windows
if (NativeMethods.IsHungAppWindow(hWnd))
{
OnLog?.Invoke($"Skipping unresponsive window: {processName}");
return true;
}
var title = NativeMethods.GetWindowTitle(hWnd);
if (string.IsNullOrEmpty(title)) return true;
var id = WindowInfo.GenerateId(processName, title);
foundWindows.Add(id);
// Skip minimized windows - keep existing position if we have one
if (NativeMethods.IsIconic(hWnd)) return true;
NativeMethods.GetWindowRect(hWnd, out var rect);
bool isMaximized = NativeMethods.IsZoomed(hWnd);
var info = new WindowInfo
{
ProcessName = processName,
WindowTitle = title,
Id = id,
X = rect.Left,
Y = rect.Top,
Width = rect.Right - rect.Left,
Height = rect.Bottom - rect.Top,
IsMaximized = isMaximized,
ZOrder = zOrderCounter++
};
_state.Windows[id] = info;
}
catch (ArgumentException)
{
// Process no longer exists
}
catch (InvalidOperationException)
{
// Process has exited
}
return true;
}, IntPtr.Zero);
// Remove windows that no longer exist (or have null values from corrupt state)
var toRemove = _state.Windows.Keys.Except(foundWindows).ToList();
foreach (var id in toRemove)
{
var windowInfo = _state.Windows[id];
var title = windowInfo?.WindowTitle ?? id;
OnLog?.Invoke($"Removing closed window: {title}");
_state.Windows.Remove(id);
}
// Update the Z-order counter to be above all enumerated windows
_zOrderCounter = zOrderCounter;
_state.Save();
OnLog?.Invoke($"Tracked {_state.Windows.Count} windows");
}
}