-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainWindow.xaml.cs
More file actions
1578 lines (1323 loc) · 52.4 KB
/
MainWindow.xaml.cs
File metadata and controls
1578 lines (1323 loc) · 52.4 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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Threading;
using System.Collections.ObjectModel;
using System.Diagnostics;
namespace WindowThumbWall;
public partial class MainWindow : Window
{
private const int AutoAddMaintenanceIntervalTicks = 4;
private const string SlotDragFormat = "WindowThumbWall.SlotIndex";
private const double DeadspaceWeight = 1.0;
private const double DistortionWeight = 0.9;
private const double SlotTitleFontSize = 12;
private static readonly Thickness CellMargin = new(2);
private static readonly Thickness CellBorderThickness = new(1);
private static readonly Thickness SlotLabelPadding = new(6, 3, 6, 3);
private static readonly TimeSpan ThumbnailUpdateMinInterval = TimeSpan.FromMilliseconds(50);
private static readonly TimeSpan ThumbnailRefreshDebounce = TimeSpan.FromMilliseconds(160);
private static readonly TimeSpan ThumbnailRefreshMinInterval = TimeSpan.FromMilliseconds(1500);
private IntPtr _mainHwnd;
private readonly List<Border> _cellBorders = [];
private readonly List<TextBlock> _cellLabels = [];
private readonly List<Border> _cellHitLayers = [];
private readonly List<ThumbHost> _cellHosts = [];
private readonly List<ThumbnailSlot> _slots = [];
private Point _dragStartPoint;
private int _dragSourceIndex = -1;
private bool _dragMoved;
private Border? _dropPreviewLayer;
private Window? _dragGhost;
private ShortcutGuideWindow? _shortcutGuideWindow;
private bool _isFullScreen;
private WindowStyle _savedWindowStyle;
private WindowState _savedWindowState;
private GridLength _savedLeftColWidth;
private GridLength _savedSplitterColWidth;
private readonly DispatcherTimer _timer = new() { Interval = TimeSpan.FromMilliseconds(1000) };
private readonly DispatcherTimer _stateSaveTimer = new() { Interval = TimeSpan.FromMilliseconds(400) };
private readonly DispatcherTimer _thumbnailSettleTimer = new() { Interval = TimeSpan.FromMilliseconds(120) };
private readonly DispatcherTimer _thumbnailThrottleTimer = new();
private readonly DispatcherTimer _thumbnailRefreshTimer = new() { Interval = ThumbnailRefreshDebounce };
private readonly List<WindowInfo> _windowCache = [];
private readonly ObservableCollection<AutoAddAppEntry> _autoAddApps = [];
private readonly HashSet<string> _autoAddAppSet = new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, string> _appDisplayNameCache = new(StringComparer.OrdinalIgnoreCase);
private Point _appListDragStartPoint;
private string? _appListDragSourceProcessName;
private int _autoAddMaintenanceTick;
private bool _notificationAttentionRequested;
private bool _notificationAttentionEnabled;
private uint _shellHookMsgId;
private readonly HashSet<IntPtr> _flashingWindows = [];
private readonly List<AttentionVisualState> _slotAttentionVisualStates = [];
private IntPtr _activeSourceHwnd;
private static readonly SolidColorBrush NormalBorderBrush =
new(Color.FromRgb(0x55, 0x55, 0x55));
private static readonly SolidColorBrush ActiveBorderBrush = new(Colors.White);
private static readonly Thickness ActiveBorderThickness = new(2);
private static readonly Thickness AttentionBorderThickness = new(3);
static MainWindow()
{
NormalBorderBrush.Freeze();
ActiveBorderBrush.Freeze();
}
private AppState? _pendingRestore;
private bool _stateTrackingEnabled;
private bool _gridRebuildPending;
private bool _thumbnailUpdatePending;
private bool _thumbnailUpdateRequestedWhilePending;
private int _lastGridItemCount = -1;
private int _lastGridRows = -1;
private int _lastGridCols = -1;
private long _lastThumbnailUpdateTicks;
private readonly HashSet<IntPtr> _thumbnailRefreshPendingWindows = [];
private readonly Dictionary<IntPtr, long> _lastThumbnailRefreshTicks = [];
public MainWindow()
{
InitializeComponent();
ApplyLocalization();
// Restore window geometry before the window is shown.
_pendingRestore = AppState.Load();
_notificationAttentionRequested = _pendingRestore.EnableOsNotificationAttention;
_notificationAttentionEnabled = _notificationAttentionRequested && SupportsNotificationAttentionRuntime();
if (_pendingRestore.Geometry is { Width: > 0, Height: > 0 } geo)
{
WindowStartupLocation = WindowStartupLocation.Manual;
Left = geo.Left;
Top = geo.Top;
Width = geo.Width;
Height = geo.Height;
if (geo.IsMaximized)
WindowState = WindowState.Maximized;
}
_timer.Tick += Timer_Tick;
InitializeNotificationFollowUpTimer();
_stateSaveTimer.Tick += StateSaveTimer_Tick;
_thumbnailSettleTimer.Tick += ThumbnailSettleTimer_Tick;
_thumbnailThrottleTimer.Tick += ThumbnailThrottleTimer_Tick;
_thumbnailRefreshTimer.Tick += ThumbnailRefreshTimer_Tick;
Loaded += OnLoaded;
Closed += OnClosed;
LocationChanged += OnLocationChanged;
SizeChanged += OnSizeChanged;
LeftPanel.SizeChanged += OnPanelSizeChanged;
AppList.SizeChanged += OnPanelSizeChanged;
ThumbGrid.SizeChanged += OnThumbGridSizeChanged;
WindowList.MouseDoubleClick += WindowList_DoubleClick;
WindowList.PreviewMouseRightButtonDown += WindowList_RightClick;
AppList.PreviewMouseRightButtonDown += AppList_RightClick;
AppList.PreviewMouseLeftButtonDown += AppList_PreviewMouseLeftButtonDown;
AppList.PreviewMouseMove += AppList_PreviewMouseMove;
AppList.DragOver += AppList_DragOver;
AppList.Drop += AppList_Drop;
FilterBox.TextChanged += FilterBox_TextChanged;
AppList.ItemsSource = _autoAddApps;
}
// Lifecycle
private void OnLoaded(object sender, RoutedEventArgs e)
{
_mainHwnd = new WindowInteropHelper(this).Handle;
// Register for shell hook messages (flash / activation).
_shellHookMsgId = NativeMethods.RegisterWindowMessage("SHELLHOOK");
NativeMethods.RegisterShellHookWindow(_mainHwnd);
HwndSource.FromHwnd(_mainHwnd)?.AddHook(WndProc);
RestorePanelLayout();
RestoreAutoAddApps();
RestoreSlots();
SyncActiveSourceWindow(forceRefresh: true);
if (_notificationAttentionEnabled)
InitializeNotificationListenerAsync();
_timer.Start();
_stateTrackingEnabled = true;
}
private void OnClosed(object? sender, EventArgs e)
{
_timer.Stop();
_notificationFollowUpTimer.Stop();
_stateSaveTimer.Stop();
_thumbnailSettleTimer.Stop();
_thumbnailThrottleTimer.Stop();
_thumbnailRefreshTimer.Stop();
_stateTrackingEnabled = false;
DisposeNotificationListener();
NativeMethods.DeregisterShellHookWindow(_mainHwnd);
SaveState();
foreach (var slot in _slots) slot.Clear();
}
private void OnSizeChanged(object sender, SizeChangedEventArgs e)
{
RequestStateSave();
RequestGridRebuild();
}
private void OnLocationChanged(object? sender, EventArgs e) => RequestStateSave();
private void OnPanelSizeChanged(object sender, SizeChangedEventArgs e)
{
if (e.WidthChanged || e.HeightChanged)
{
RequestStateSave();
RequestGridRebuild();
}
}
private void OnThumbGridSizeChanged(object sender, SizeChangedEventArgs e)
{
if (!e.WidthChanged && !e.HeightChanged)
return;
RequestGridRebuild();
ScheduleThumbnailSettle();
}
// State persistence
private void SaveState()
{
var bounds = (WindowState == WindowState.Maximized || _isFullScreen)
? RestoreBounds
: new Rect(Left, Top, Width, Height);
var state = new AppState
{
IsFullScreen = _isFullScreen,
Geometry = new WindowGeometry
{
Left = bounds.Left,
Top = bounds.Top,
Width = bounds.Width,
Height = bounds.Height,
IsMaximized = !_isFullScreen && WindowState == WindowState.Maximized
},
LeftPanelWidth = GetPersistedLength(
_isFullScreen ? _savedLeftColWidth : LeftColumnDefinition.Width,
LeftPanel.ActualWidth),
AppListHeight = GetPersistedLength(AppListRowDefinition.Height, AppList.ActualHeight),
EnableOsNotificationAttention = _notificationAttentionRequested
};
foreach (var slot in _slots)
{
if (!slot.IsOccupied) continue;
state.Slots.Add(new SlotState
{
ProcessName = slot.SourceProcessName,
Title = slot.SourceTitle
});
}
foreach (var app in _autoAddApps)
state.AutoAddApps.Add(app.ProcessName);
state.Save();
}
private void RequestStateSave()
{
if (!_stateTrackingEnabled) return;
_stateSaveTimer.Stop();
_stateSaveTimer.Start();
}
private void StateSaveTimer_Tick(object? sender, EventArgs e)
{
_stateSaveTimer.Stop();
SaveState();
}
private void RestorePanelLayout()
{
if (_pendingRestore == null) return;
if (_pendingRestore.LeftPanelWidth > 120)
LeftColumnDefinition.Width = new GridLength(_pendingRestore.LeftPanelWidth);
if (_pendingRestore.AppListHeight > 80)
AppListRowDefinition.Height = new GridLength(_pendingRestore.AppListHeight);
}
private static double GetPersistedLength(GridLength gridLength, double actualFallback)
{
if (gridLength.IsAbsolute && gridLength.Value > 0)
return gridLength.Value;
return actualFallback > 0 ? actualFallback : 0;
}
private void RestoreAutoAddApps()
{
if (_pendingRestore is not { AutoAddApps.Count: > 0 } state) return;
foreach (var app in state.AutoAddApps)
AddAppToAutoList(app);
}
private void RestoreSlots()
{
if (_pendingRestore is not { Slots.Count: > 0 } state)
{
_pendingRestore = null;
return;
}
// Enumerate all current windows.
var allWindows = new List<(IntPtr Handle, string Title, string ProcessName)>();
NativeMethods.EnumWindows((hWnd, _) =>
{
if (hWnd == _mainHwnd) return true;
if (!NativeMethods.IsAltTabWindow(hWnd)) return true;
allWindows.Add((hWnd, NativeMethods.GetWindowTitle(hWnd), NativeMethods.GetProcessName(hWnd)));
return true;
}, IntPtr.Zero);
var usedHandles = new HashSet<IntPtr>();
foreach (var saved in state.Slots)
{
// 1. Exact match: same process + same title.
var match = allWindows.FirstOrDefault(w =>
!usedHandles.Contains(w.Handle) &&
w.ProcessName.Equals(saved.ProcessName, StringComparison.OrdinalIgnoreCase) &&
w.Title == saved.Title);
// 2. Fallback: same process name, any title.
if (match.Handle == IntPtr.Zero)
{
match = allWindows.FirstOrDefault(w =>
!usedHandles.Contains(w.Handle) &&
w.ProcessName.Equals(saved.ProcessName, StringComparison.OrdinalIgnoreCase));
}
if (match.Handle == IntPtr.Zero) continue;
usedHandles.Add(match.Handle);
int idx = AddSlot();
AssignSlot(idx, match.Handle, match.Title, match.ProcessName);
}
if (state.IsFullScreen && _slots.Count > 0)
ToggleFullScreen();
_pendingRestore = null;
}
// Keyboard
protected override void OnPreviewKeyDown(KeyEventArgs e)
{
switch (e.Key)
{
case Key.Enter when _isFullScreen || !FilterBox.IsFocused:
ToggleFullScreen();
e.Handled = true;
break;
case Key.Escape when _isFullScreen:
ToggleFullScreen();
e.Handled = true;
break;
}
base.OnPreviewKeyDown(e);
}
// Dynamic grid
private (int rows, int cols) CalcGridSize(int count)
{
if (count <= 0) return (1, 1);
double width = Math.Max(ThumbGrid.ActualWidth, 1);
double height = Math.Max(ThumbGrid.ActualHeight, 1);
if (width <= 1 || height <= 1)
{
int fallbackCols = (int)Math.Ceiling(Math.Sqrt(count));
int fallbackRows = (int)Math.Ceiling((double)count / fallbackCols);
return (fallbackRows, fallbackCols);
}
double titleBarHeight = EstimateTitleBarHeight();
double horizontalChrome = CellMargin.Left + CellMargin.Right + CellBorderThickness.Left + CellBorderThickness.Right;
double verticalChrome = CellMargin.Top + CellMargin.Bottom + CellBorderThickness.Top + CellBorderThickness.Bottom;
double fallbackAspectRatio =
Math.Max(width - horizontalChrome, 0.01) /
Math.Max(height - verticalChrome - titleBarHeight, 0.01);
var aspectRatios = CollectActiveAspectRatios(fallbackAspectRatio);
return GridLayoutScorer.ChooseGrid(
count,
width,
height,
aspectRatios,
titleBarHeight,
horizontalChrome,
verticalChrome,
DeadspaceWeight,
DistortionWeight);
}
private List<double> CollectActiveAspectRatios(double fallback)
{
var ratios = new List<double>();
for (int i = 0; i < _slots.Count; i++)
{
if (!_slots[i].IsOccupied) continue;
double ratio = NativeMethods.GetWindowAspectRatio(_slots[i].SourceHwnd, fallback);
if (ratio > 0.01)
ratios.Add(ratio);
}
if (ratios.Count == 0)
ratios.Add(Math.Max(fallback, 0.01));
return ratios;
}
private double EstimateTitleBarHeight()
{
double measuredHeight = 0;
for (int i = 0; i < _cellLabels.Count; i++)
{
measuredHeight = Math.Max(measuredHeight, _cellLabels[i].ActualHeight);
}
if (measuredHeight > 0)
return measuredHeight;
var probe = new TextBlock
{
Text = LocalizedText.Get("slot.empty"),
Padding = SlotLabelPadding,
FontSize = SlotTitleFontSize,
TextTrimming = TextTrimming.CharacterEllipsis
};
probe.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
return Math.Max(probe.DesiredSize.Height, 0.01);
}
private int AddSlot()
{
int idx = _cellBorders.Count;
var label = new TextBlock
{
Text = LocalizedText.Get("slot.empty"),
Foreground = Brushes.LightGray,
Padding = SlotLabelPadding,
FontSize = SlotTitleFontSize,
TextTrimming = TextTrimming.CharacterEllipsis
};
var titleBar = new Border
{
Background = new SolidColorBrush(Color.FromRgb(0x33, 0x33, 0x33)),
Child = label,
Cursor = Cursors.Arrow
};
DockPanel.SetDock(titleBar, Dock.Top);
var host = new ThumbHost();
var panel = new DockPanel();
panel.Children.Add(titleBar);
panel.Children.Add(host);
var hitLayer = new Border
{
Background = new SolidColorBrush(Color.FromArgb(1, 255, 255, 255)),
Tag = idx,
Cursor = Cursors.Hand,
AllowDrop = true
};
hitLayer.PreviewMouseLeftButtonDown += Cell_PreviewMouseLeftButtonDown;
hitLayer.PreviewMouseMove += Cell_PreviewMouseMove;
hitLayer.PreviewMouseLeftButtonUp += Cell_PreviewMouseLeftButtonUp;
hitLayer.MouseRightButtonDown += Cell_RightClick;
hitLayer.DragOver += Cell_DragOver;
hitLayer.Drop += Cell_Drop;
hitLayer.DragLeave += Cell_DragLeave;
hitLayer.SizeChanged += CellLayout_SizeChanged;
var cellRoot = new Grid();
cellRoot.Children.Add(panel);
cellRoot.Children.Add(hitLayer);
var border = new Border
{
BorderBrush = new SolidColorBrush(Color.FromRgb(0x55, 0x55, 0x55)),
BorderThickness = CellBorderThickness,
Margin = CellMargin,
Background = Brushes.Black,
Child = cellRoot,
Tag = idx,
Cursor = Cursors.Arrow
};
border.SizeChanged += CellLayout_SizeChanged;
host.SizeChanged += CellLayout_SizeChanged;
ThumbGrid.Children.Add(border);
_cellBorders.Add(border);
_cellLabels.Add(label);
_cellHitLayers.Add(hitLayer);
_cellHosts.Add(host);
_slotAttentionVisualStates.Add(AttentionVisualState.None);
RebuildGrid();
// Force layout so BuildWindowCore runs and the HWND is ready.
ThumbGrid.UpdateLayout();
_slots.Add(new ThumbnailSlot(host, _mainHwnd));
return idx;
}
private void RemoveSlot(int idx)
{
IntPtr sourceHwnd = _slots[idx].SourceHwnd;
ClearNotificationAttentionGroupsForWindow(sourceHwnd);
_flashingWindows.Remove(sourceHwnd);
_thumbnailRefreshPendingWindows.Remove(sourceHwnd);
_lastThumbnailRefreshTicks.Remove(sourceHwnd);
_slots[idx].Clear();
_cellBorders[idx].SizeChanged -= CellLayout_SizeChanged;
_cellHitLayers[idx].SizeChanged -= CellLayout_SizeChanged;
_cellHosts[idx].SizeChanged -= CellLayout_SizeChanged;
ThumbGrid.Children.Remove(_cellBorders[idx]);
_cellHosts[idx].Dispose();
_cellBorders.RemoveAt(idx);
_cellLabels.RemoveAt(idx);
_cellHitLayers.RemoveAt(idx);
_cellHosts.RemoveAt(idx);
_slots.RemoveAt(idx);
_slotAttentionVisualStates.RemoveAt(idx);
SyncActiveSourceWindow(forceRefresh: true);
for (int i = 0; i < _cellBorders.Count; i++)
{
_cellBorders[i].Tag = i;
_cellHitLayers[i].Tag = i;
}
RebuildGrid();
RequestStateSave();
QueueNotificationAttentionSync();
}
private void RebuildGrid()
{
int count = _cellBorders.Count;
if (count == 0)
{
if (_lastGridItemCount != 0 || _lastGridRows != 0 || _lastGridCols != 0)
{
ThumbGrid.RowDefinitions.Clear();
ThumbGrid.ColumnDefinitions.Clear();
_lastGridItemCount = 0;
_lastGridRows = 0;
_lastGridCols = 0;
}
return;
}
var (rows, cols) = CalcGridSize(count);
bool gridShapeChanged = _lastGridItemCount != count || _lastGridRows != rows || _lastGridCols != cols;
if (gridShapeChanged)
{
ThumbGrid.RowDefinitions.Clear();
ThumbGrid.ColumnDefinitions.Clear();
for (int r = 0; r < rows; r++)
ThumbGrid.RowDefinitions.Add(new RowDefinition());
for (int c = 0; c < cols; c++)
ThumbGrid.ColumnDefinitions.Add(new ColumnDefinition());
_lastGridItemCount = count;
_lastGridRows = rows;
_lastGridCols = cols;
}
for (int i = 0; i < count; i++)
{
Grid.SetRow(_cellBorders[i], i / cols);
Grid.SetColumn(_cellBorders[i], i % cols);
Grid.SetRowSpan(_cellBorders[i], 1);
Grid.SetColumnSpan(_cellBorders[i], 1);
}
RequestThumbnailUpdate();
ScheduleThumbnailSettle();
}
private void RequestGridRebuild()
{
if (_gridRebuildPending || _cellBorders.Count == 0) return;
_gridRebuildPending = true;
Dispatcher.BeginInvoke(DispatcherPriority.Render, () =>
{
_gridRebuildPending = false;
RebuildGrid();
});
}
// Timer
private void Timer_Tick(object? sender, EventArgs e)
{
RefreshWindowList();
SyncMonitoredSlotTitles();
_autoAddMaintenanceTick++;
if (_autoAddMaintenanceTick >= AutoAddMaintenanceIntervalTicks)
{
_autoAddMaintenanceTick = 0;
RefreshAutoAddAppDisplayNames();
AutoAddWindowsForRegisteredApps();
}
ValidateSlots();
RecoverMissingThumbnailRegistrations();
SyncActiveSourceWindow();
CheckFlashState();
}
// Window list
private void RefreshWindowList()
{
_windowCache.Clear();
NativeMethods.EnumWindows((hWnd, _) =>
{
if (hWnd == _mainHwnd) return true;
if (!NativeMethods.IsAltTabWindow(hWnd)) return true;
_windowCache.Add(new WindowInfo
{
Handle = hWnd,
Title = NativeMethods.GetWindowTitle(hWnd),
ProcessName = NativeMethods.GetProcessName(hWnd)
});
return true;
}, IntPtr.Zero);
ApplyFilter();
}
private void SyncMonitoredSlotTitles()
{
if (_slots.Count == 0) return;
var titleByHandle = new Dictionary<IntPtr, string>();
foreach (var item in _windowCache)
titleByHandle[item.Handle] = item.Title;
bool changed = false;
for (int i = 0; i < _slots.Count; i++)
{
if (!_slots[i].IsOccupied) continue;
string latestTitle = titleByHandle.TryGetValue(_slots[i].SourceHwnd, out string? titleFromList)
? titleFromList
: NativeMethods.GetWindowTitle(_slots[i].SourceHwnd);
if (string.IsNullOrWhiteSpace(latestTitle)) continue;
if (string.Equals(_slots[i].SourceTitle, latestTitle, StringComparison.Ordinal)) continue;
_slots[i].UpdateSourceTitle(latestTitle);
_cellLabels[i].Text = latestTitle;
changed = true;
}
if (changed)
RequestStateSave();
}
private void FilterBox_TextChanged(object sender, TextChangedEventArgs e) => ApplyFilter();
private void ApplyFilter()
{
string filter = FilterBox.Text.Trim();
var items = string.IsNullOrEmpty(filter)
? _windowCache.ToList()
: _windowCache
.Where(w =>
w.Title.Contains(filter, StringComparison.OrdinalIgnoreCase) ||
w.ProcessName.Contains(filter, StringComparison.OrdinalIgnoreCase))
.ToList();
var sel = WindowList.SelectedItem as WindowInfo;
WindowList.ItemsSource = items;
if (sel != null)
WindowList.SelectedItem = items.FirstOrDefault(w => w.Handle == sel.Handle);
}
private void WindowList_DoubleClick(object sender, MouseButtonEventArgs e)
{
if (WindowList.SelectedItem is not WindowInfo info) return;
AddWindowToMonitor(info);
}
private void AddWindowToMonitor(WindowInfo info, int? insertIndex = null)
{
// Skip if already assigned.
foreach (var slot in _slots)
if (slot.IsOccupied && slot.SourceHwnd == info.Handle) return;
if (insertIndex is int targetIndex)
{
targetIndex = Math.Clamp(targetIndex, 0, _slots.Count);
int sourceIndex = -1;
for (int i = 0; i < _slots.Count; i++)
{
if (!_slots[i].IsOccupied)
{
sourceIndex = i;
break;
}
}
bool createdNew = false;
if (sourceIndex == -1)
{
sourceIndex = AddSlot();
createdNew = true;
}
if (!AssignSlot(sourceIndex, info.Handle, info.Title, info.ProcessName))
{
if (createdNew)
RemoveSlot(sourceIndex);
return;
}
if (sourceIndex != targetIndex)
InsertSlot(sourceIndex, targetIndex);
else
RequestStateSave();
return;
}
// First free slot.
int target = -1;
for (int i = 0; i < _slots.Count; i++)
{
if (!_slots[i].IsOccupied)
{
target = i;
break;
}
}
// No free slot -> add a new one.
if (target == -1)
target = AddSlot();
if (AssignSlot(target, info.Handle, info.Title, info.ProcessName))
{
RequestStateSave();
}
}
private static T? FindVisualParent<T>(DependencyObject? source) where T : DependencyObject
{
while (source != null && source is not T)
source = VisualTreeHelper.GetParent(source);
return source as T;
}
private void WindowList_RightClick(object sender, MouseButtonEventArgs e)
{
if (sender is not ListBox list) return;
var item = FindVisualParent<ListBoxItem>(e.OriginalSource as DependencyObject);
if (item == null) return;
item.IsSelected = true;
if (list.SelectedItem is not WindowInfo info) return;
var menu = new ContextMenu();
var addToMonitorItem = new MenuItem { Header = LocalizedText.Get("menu.addToMonitor") };
addToMonitorItem.Click += (_, _) => AddWindowToMonitor(info);
var addAppItem = new MenuItem { Header = LocalizedText.Get("menu.addApp") };
addAppItem.Click += (_, _) =>
AddAppToAutoList(info.ProcessName, ResolveDisplayNameFromWindow(info.Handle, info.ProcessName));
menu.Items.Add(addToMonitorItem);
menu.Items.Add(addAppItem);
menu.PlacementTarget = item;
menu.IsOpen = true;
e.Handled = true;
}
private void AppList_RightClick(object sender, MouseButtonEventArgs e)
{
if (sender is not ListBox list) return;
var item = FindVisualParent<ListBoxItem>(e.OriginalSource as DependencyObject);
if (item == null) return;
item.IsSelected = true;
if (list.SelectedItem is not AutoAddAppEntry app) return;
int index = _autoAddApps.IndexOf(app);
var menu = new ContextMenu();
var moveUpItem = new MenuItem { Header = LocalizedText.Get("menu.moveUp"), IsEnabled = index > 0 };
moveUpItem.Click += (_, _) => MoveAutoApp(index, index - 1);
var moveDownItem = new MenuItem
{
Header = LocalizedText.Get("menu.moveDown"),
IsEnabled = index >= 0 && index < _autoAddApps.Count - 1
};
moveDownItem.Click += (_, _) => MoveAutoApp(index, index + 1);
var removeItem = new MenuItem { Header = LocalizedText.Get("menu.removeAutoAdd") };
removeItem.Click += (_, _) => RemoveAppFromAutoList(app.ProcessName);
menu.Items.Add(moveUpItem);
menu.Items.Add(moveDownItem);
menu.Items.Add(removeItem);
menu.PlacementTarget = item;
menu.IsOpen = true;
e.Handled = true;
}
private void AddAppToAutoList(string processName, string? displayName = null)
{
if (string.IsNullOrWhiteSpace(processName)) return;
if (!string.IsNullOrWhiteSpace(displayName))
_appDisplayNameCache[processName] = displayName;
if (!_autoAddAppSet.Add(processName))
{
if (!string.IsNullOrWhiteSpace(displayName))
{
int existingIndex = _autoAddApps
.Select((app, idx) => new { app, idx })
.FirstOrDefault(x => x.app.ProcessName.Equals(processName, StringComparison.OrdinalIgnoreCase))
?.idx ?? -1;
if (existingIndex >= 0 && _autoAddApps[existingIndex].DisplayName != displayName)
{
_autoAddApps[existingIndex].DisplayName = displayName;
RequestStateSave();
}
}
return;
}
_autoAddApps.Add(new AutoAddAppEntry
{
ProcessName = processName,
DisplayName = string.IsNullOrWhiteSpace(displayName) ? processName : displayName
});
RequestStateSave();
}
private void RemoveAppFromAutoList(string processName)
{
if (!_autoAddAppSet.Remove(processName)) return;
_appDisplayNameCache.Remove(processName);
AutoAddAppEntry? existing = _autoAddApps.FirstOrDefault(a =>
a.ProcessName.Equals(processName, StringComparison.OrdinalIgnoreCase));
if (existing != null)
{
_autoAddApps.Remove(existing);
RequestStateSave();
}
}
private void MoveAutoApp(int sourceIndex, int targetIndex)
{
if (sourceIndex < 0 || sourceIndex >= _autoAddApps.Count) return;
if (targetIndex < 0 || targetIndex >= _autoAddApps.Count) return;
if (sourceIndex == targetIndex) return;
AutoAddAppEntry item = _autoAddApps[sourceIndex];
_autoAddApps.RemoveAt(sourceIndex);
_autoAddApps.Insert(targetIndex, item);
RequestStateSave();
}
private void AppList_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
_appListDragStartPoint = e.GetPosition(AppList);
var item = FindVisualParent<ListBoxItem>(e.OriginalSource as DependencyObject);
_appListDragSourceProcessName = (item?.DataContext as AutoAddAppEntry)?.ProcessName;
}
private void AppList_PreviewMouseMove(object sender, MouseEventArgs e)
{
if (e.LeftButton != MouseButtonState.Pressed) return;
if (_appListDragSourceProcessName == null) return;
Point current = e.GetPosition(AppList);
Vector delta = current - _appListDragStartPoint;
if (Math.Abs(delta.X) < SystemParameters.MinimumHorizontalDragDistance &&
Math.Abs(delta.Y) < SystemParameters.MinimumVerticalDragDistance)
return;
string dragSource = _appListDragSourceProcessName;
_appListDragSourceProcessName = null;
DragDrop.DoDragDrop(AppList, new DataObject("WindowThumbWall.AppListItem", dragSource), DragDropEffects.Move);
}
private void AppList_DragOver(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent("WindowThumbWall.AppListItem"))
e.Effects = DragDropEffects.Move;
else
e.Effects = DragDropEffects.None;
e.Handled = true;
}
private void AppList_Drop(object sender, DragEventArgs e)
{
if (!e.Data.GetDataPresent("WindowThumbWall.AppListItem")) return;
if (e.Data.GetData("WindowThumbWall.AppListItem") is not string sourceApp) return;
int sourceIndex = _autoAddApps
.Select((app, idx) => new { app.ProcessName, idx })
.FirstOrDefault(x => x.ProcessName.Equals(sourceApp, StringComparison.OrdinalIgnoreCase))
?.idx ?? -1;
if (sourceIndex < 0) return;
int targetIndex = _autoAddApps.Count - 1;
var targetItem = FindVisualParent<ListBoxItem>(e.OriginalSource as DependencyObject);
if (targetItem != null)
{
int targetItemIndex = AppList.ItemContainerGenerator.IndexFromContainer(targetItem);
Point pos = e.GetPosition(targetItem);
targetIndex = pos.Y <= targetItem.ActualHeight / 2 ? targetItemIndex : targetItemIndex + 1;
if (sourceIndex < targetIndex)
targetIndex--;
targetIndex = Math.Clamp(targetIndex, 0, _autoAddApps.Count - 1);
}
MoveAutoApp(sourceIndex, targetIndex);
}
private void AutoAddWindowsForRegisteredApps()
{
if (_autoAddAppSet.Count == 0) return;
Dictionary<string, int> nextInsertIndexByProcess = BuildAutoAddInsertIndexes();
foreach (var info in _windowCache)
{
if (!_autoAddAppSet.Contains(info.ProcessName)) continue;
if (!nextInsertIndexByProcess.TryGetValue(info.ProcessName, out int insertIndex))
continue;
AddWindowToMonitor(info, insertIndex);
nextInsertIndexByProcess[info.ProcessName] = Math.Min(insertIndex + 1, _slots.Count);
}
}
private Dictionary<string, int> BuildAutoAddInsertIndexes()
{
var hwndToProcess = _windowCache
.GroupBy(window => window.Handle)
.ToDictionary(group => group.Key, group => group.First().ProcessName);
var nextInsertIndexByProcess = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
int lastMatchingSlotIndex = -1;
foreach (var app in _autoAddApps)
{
for (int i = lastMatchingSlotIndex + 1; i < _slots.Count; i++)
{
var slot = _slots[i];
if (!slot.IsOccupied)
continue;
string? slotProcess = slot.SourceProcessName;
if (string.IsNullOrWhiteSpace(slotProcess) &&
!hwndToProcess.TryGetValue(slot.SourceHwnd, out slotProcess))
{
continue;
}
if (slotProcess!.Equals(app.ProcessName, StringComparison.OrdinalIgnoreCase))
lastMatchingSlotIndex = i;
}
nextInsertIndexByProcess[app.ProcessName] = lastMatchingSlotIndex + 1;
}
return nextInsertIndexByProcess;
}
private void RefreshAutoAddAppDisplayNames()
{
var representativeWindows = new Dictionary<string, IntPtr>(StringComparer.OrdinalIgnoreCase);
foreach (var window in _windowCache)
{
if (string.IsNullOrWhiteSpace(window.ProcessName) || representativeWindows.ContainsKey(window.ProcessName))
continue;
representativeWindows[window.ProcessName] = window.Handle;
}
for (int i = 0; i < _autoAddApps.Count; i++)
{
AutoAddAppEntry entry = _autoAddApps[i];
if (!representativeWindows.TryGetValue(entry.ProcessName, out IntPtr hWnd))
continue;
if (!_appDisplayNameCache.TryGetValue(entry.ProcessName, out string? displayName) ||
string.IsNullOrWhiteSpace(displayName))
{
displayName = ResolveDisplayNameFromWindow(hWnd, entry.ProcessName);
_appDisplayNameCache[entry.ProcessName] = displayName;
}
if (displayName == entry.DisplayName) continue;
entry.DisplayName = displayName;
}
}