-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTabWindSwitcher.cpp
More file actions
1488 lines (1274 loc) · 60.3 KB
/
Copy pathTabWindSwitcher.cpp
File metadata and controls
1488 lines (1274 loc) · 60.3 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
#define NOMINMAX
#include <windows.h>
#include <gdiplus.h>
#include <vector>
#include <string>
#include <mutex>
#include <thread>
#include <algorithm>
#include <psapi.h>
#include <shlwapi.h>
#include <dwmapi.h>
#include "WindowFilter.h"
#pragma comment(lib, "gdiplus.lib")
#pragma comment(lib, "user32.lib")
#pragma comment(lib, "gdi32.lib")
#pragma comment(lib, "ole32.lib")
#pragma comment(lib, "psapi.lib")
#pragma comment(lib, "shlwapi.lib")
#pragma comment(lib, "dwmapi.lib")
#pragma comment(lib, "shell32.lib")
#define WM_APP_SWITCH_TO_WINDOW (WM_APP + 1)
#define WM_APP_TRAY (WM_APP + 2) // уведомления от иконки в трее
#define WM_APP_ICON_READY (WM_APP + 3)
// Идентификаторы меню трея
#define IDM_TRAY_ABOUT 101
#define IDM_TRAY_HOTKEYS 102
#define IDM_TRAY_MINIMIZE_ON 103
#define IDM_TRAY_MINIMIZE_OFF 104
#define IDM_TRAY_EXIT 199
#define MAIN_ICON 101
#define TRAY_UID 1 // уникальный ID иконки в трее (NOTIFYICONDATA)
// --- Data Structures ---
struct WindowInfo {
HWND hwnd;
DWORD processId;
std::wstring title;
std::wstring processPath;
Gdiplus::Bitmap* pIconBitmap;
};
struct EnumData {
std::vector<WindowInfo>* list;
DWORD targetPID;
};
struct AppSettings {
BYTE alpha = 220;
bool minimizeOthers = true;
Gdiplus::Color bgColor = Gdiplus::Color(220, 40, 40, 45);
Gdiplus::Color selectionColor = Gdiplus::Color(80, 120, 120, 140);
Gdiplus::Color textColor = Gdiplus::Color(255, 255, 255, 255);
int windowRadius = 12;
int selectionRadius = 6;
int iconTimeoutMs = 50;
};
class TabWindSwitcherApp {
public:
ULONG_PTR gdiplusToken = 0;
HHOOK keyboardHook = NULL;
HWND mainWnd = NULL;
HWND switcherWnd = NULL;
HANDLE instanceMutex = NULL;
NOTIFYICONDATAW trayIcon = {};
std::vector<WindowInfo> windowList;
std::vector<HWND> windowsToMinimize;
AppSettings settings;
size_t selectedIndex = 0;
size_t iconsPerRow = 0;
size_t rows = 0;
size_t visibleRows = 0;
size_t currentPage = 0;
size_t pageCount = 0;
UINT dpi = 96;
unsigned int iconGeneration = 0;
bool altDown = false;
std::mutex stateMutex;
std::thread iconWorker;
int Scale(int value) const {
return MulDiv(value, static_cast<int>(dpi), 96);
}
void ClearWindowListLocked() {
for (const auto& window : windowList) {
if (window.pIconBitmap) delete window.pIconBitmap;
}
windowList.clear();
}
void CancelIconLoadingLocked() {
++iconGeneration;
}
void ResetSwitcherStateLocked() {
ClearWindowListLocked();
switcherWnd = NULL;
selectedIndex = 0;
iconsPerRow = 0;
rows = 0;
visibleRows = 0;
currentPage = 0;
pageCount = 0;
CancelIconLoadingLocked();
}
void ClampCurrentPageLocked() {
if (pageCount == 0) {
currentPage = 0;
} else if (currentPage >= pageCount) {
currentPage = pageCount - 1;
}
}
void RecalculatePageForSelectionLocked() {
if (iconsPerRow == 0 || visibleRows == 0 || windowList.empty()) {
currentPage = 0;
return;
}
size_t selectedRow = selectedIndex / iconsPerRow;
size_t firstVisibleRow = currentPage * visibleRows;
size_t lastVisibleRow = firstVisibleRow + visibleRows - 1;
if (selectedRow < firstVisibleRow) {
currentPage = selectedRow / visibleRows;
} else if (selectedRow > lastVisibleRow) {
currentPage = selectedRow / visibleRows;
}
ClampCurrentPageLocked();
}
};
// --- Global Variables & Constants ---
TabWindSwitcherApp g_app;
const wchar_t MAIN_CLASS_NAME[] = L"TabWindSwitcherMainClass";
const wchar_t SWITCHER_CLASS_NAME[] = L"TabWindSwitcherUIClass";
const wchar_t MUTEX_NAME[] = L"TabWindSwitcher_InstanceMutex";
// INI Configuration
const wchar_t INI_FILENAME[] = L"TabWindSwitcher.ini";
const wchar_t INI_SECTION_SETTINGS[] = L"Settings";
const wchar_t INI_KEY_TRANSPARENCY[] = L"Transparency";
const wchar_t INI_KEY_MINIMIZE_OTHERS[] = L"MinimizeOthers"; // 0 = выкл, 1 = вкл
const wchar_t INI_KEY_BG_R[] = L"BgColorR";
const wchar_t INI_KEY_BG_G[] = L"BgColorG";
const wchar_t INI_KEY_BG_B[] = L"BgColorB";
const wchar_t INI_KEY_BG_A[] = L"BgColorA";
const wchar_t INI_KEY_SEL_R[] = L"SelColorR";
const wchar_t INI_KEY_SEL_G[] = L"SelColorG";
const wchar_t INI_KEY_SEL_B[] = L"SelColorB";
const wchar_t INI_KEY_SEL_A[] = L"SelColorA";
const wchar_t INI_KEY_TEXT_R[] = L"TextColorR";
const wchar_t INI_KEY_TEXT_G[] = L"TextColorG";
const wchar_t INI_KEY_TEXT_B[] = L"TextColorB";
const wchar_t INI_KEY_WINDOW_RADIUS[] = L"WindowRadius";
const wchar_t INI_KEY_SELECTION_RADIUS[]= L"SelectionRadius";
const wchar_t INI_KEY_ICON_TIMEOUT_MS[] = L"IconTimeoutMs";
const int DEFAULT_TRANSPARENCY = 220; // 0-255
const int DEFAULT_MINIMIZE_OTHERS = 1; // включено по умолчанию
// Layout Constants
const int ICON_SIZE = 64;
const int PADDING = 20;
const int ICON_PADDING_TOP = 10;
const int TITLE_HEIGHT = 40;
// --- Forward Declarations ---
LRESULT CALLBACK MainWndProc(HWND, UINT, WPARAM, LPARAM);
LRESULT CALLBACK SwitcherWndProc(HWND, UINT, WPARAM, LPARAM);
LRESULT CALLBACK LowLevelKeyboardProc(int, WPARAM, LPARAM);
BOOL CALLBACK EnumWindowsProc(HWND, LPARAM);
Gdiplus::Bitmap* GetBestIconForProcess(const wchar_t* exePath, HWND associatedHwnd);
void UpdateSwitcherLayeredWindow(HWND hwnd);
void AddRoundRectToPath(Gdiplus::GraphicsPath&, Gdiplus::RectF, Gdiplus::REAL);
void ShowSwitcher(bool filterByProcess, bool backwards);
void MoveSelection(int delta);
void ChangePage(int delta);
void StartIconLoading(unsigned int generation);
void StopIconWorker();
void EnableDpiAwareness();
UINT GetDpiForMonitorOrSystem(HMONITOR monitor);
std::wstring GetProcessImagePath(DWORD processId);
int ReadIniIntClamped(const wchar_t* iniPath, const wchar_t* key, int defaultValue, int minValue, int maxValue);
void ReadSettings();
void AddTrayIcon(HWND hwnd, HICON hIcon);
void RemoveTrayIcon();
void ShowTrayMenu(HWND hwnd);
HBITMAP CreateMenuIconBitmap(HDC hdcRef, const wchar_t* glyph, COLORREF color, int size);
// --- Entry Point ---
INT WINAPI WinMain(HINSTANCE hInstance, HINSTANCE /*hPrevInstance*/, PSTR /*lpCmdLine*/, INT /*nCmdShow*/) {
EnableDpiAwareness();
g_app.instanceMutex = CreateMutexW(NULL, TRUE, MUTEX_NAME);
if (g_app.instanceMutex == NULL || GetLastError() == ERROR_ALREADY_EXISTS) {
MessageBoxW(NULL, L"Another instance of TabWindSwitcher is already running.", L"TabWindSwitcher", MB_OK | MB_ICONINFORMATION);
if (g_app.instanceMutex) {
ReleaseMutex(g_app.instanceMutex);
CloseHandle(g_app.instanceMutex);
}
return 1;
}
HRESULT hrCo = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
bool coInitialized = SUCCEEDED(hrCo);
if (!coInitialized && hrCo != RPC_E_CHANGED_MODE) {
MessageBoxW(NULL, L"Cannot initialize COM.", L"TabWindSwitcher", MB_OK | MB_ICONERROR);
ReleaseMutex(g_app.instanceMutex);
CloseHandle(g_app.instanceMutex);
return 1;
}
Gdiplus::GdiplusStartupInput gdiplusStartupInput;
if (Gdiplus::GdiplusStartup(&g_app.gdiplusToken, &gdiplusStartupInput, NULL) != Gdiplus::Ok) {
MessageBoxW(NULL, L"Cannot initialize GDI+.", L"TabWindSwitcher", MB_OK | MB_ICONERROR);
if (coInitialized) CoUninitialize();
ReleaseMutex(g_app.instanceMutex);
CloseHandle(g_app.instanceMutex);
return 1;
}
HICON hAppIcon = LoadIconW(hInstance, MAKEINTRESOURCE(MAIN_ICON));
WNDCLASSEXW wcMain = {};
wcMain.cbSize = sizeof(WNDCLASSEXW);
wcMain.lpfnWndProc = MainWndProc;
wcMain.hInstance = hInstance;
wcMain.lpszClassName = MAIN_CLASS_NAME;
wcMain.hIcon = hAppIcon;
wcMain.hIconSm = hAppIcon;
if (!RegisterClassExW(&wcMain)) {
MessageBoxW(NULL, L"Cannot register main window class.", L"TabWindSwitcher", MB_OK | MB_ICONERROR);
Gdiplus::GdiplusShutdown(g_app.gdiplusToken);
if (coInitialized) CoUninitialize();
ReleaseMutex(g_app.instanceMutex);
CloseHandle(g_app.instanceMutex);
return 1;
}
WNDCLASSEXW wcSwitcher = {};
wcSwitcher.cbSize = sizeof(WNDCLASSEXW);
wcSwitcher.lpfnWndProc = SwitcherWndProc;
wcSwitcher.hInstance = hInstance;
wcSwitcher.hCursor = LoadCursor(NULL, IDC_ARROW);
wcSwitcher.lpszClassName = SWITCHER_CLASS_NAME;
wcSwitcher.hIcon = hAppIcon;
wcSwitcher.hIconSm = hAppIcon;
if (!RegisterClassExW(&wcSwitcher)) {
MessageBoxW(NULL, L"Cannot register switcher window class.", L"TabWindSwitcher", MB_OK | MB_ICONERROR);
Gdiplus::GdiplusShutdown(g_app.gdiplusToken);
if (coInitialized) CoUninitialize();
ReleaseMutex(g_app.instanceMutex);
CloseHandle(g_app.instanceMutex);
return 1;
}
g_app.mainWnd = CreateWindowExW(0, MAIN_CLASS_NAME, L"TabWindSwitcher Main", 0, 0, 0, 0, 0, HWND_MESSAGE, NULL, hInstance, NULL);
if (!g_app.mainWnd) {
MessageBoxW(NULL, L"Cannot create main message window.", L"TabWindSwitcher", MB_OK | MB_ICONERROR);
Gdiplus::GdiplusShutdown(g_app.gdiplusToken);
if (coInitialized) CoUninitialize();
ReleaseMutex(g_app.instanceMutex);
CloseHandle(g_app.instanceMutex);
return 1;
}
g_app.keyboardHook = SetWindowsHookExW(WH_KEYBOARD_LL, LowLevelKeyboardProc, hInstance, 0);
if (!g_app.keyboardHook) {
MessageBoxW(NULL, L"Cannot install keyboard hook.", L"TabWindSwitcher", MB_OK | MB_ICONERROR);
DestroyWindow(g_app.mainWnd);
Gdiplus::GdiplusShutdown(g_app.gdiplusToken);
if (coInitialized) CoUninitialize();
ReleaseMutex(g_app.instanceMutex);
CloseHandle(g_app.instanceMutex);
return 1;
}
ReadSettings();
// Добавляем иконку в системный трей
AddTrayIcon(g_app.mainWnd, hAppIcon);
MSG msg = {};
while (GetMessage(&msg, NULL, 0, 0) > 0) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
UnhookWindowsHookEx(g_app.keyboardHook);
RemoveTrayIcon();
StopIconWorker();
{
std::lock_guard<std::mutex> lock(g_app.stateMutex);
g_app.ResetSwitcherStateLocked();
}
Gdiplus::GdiplusShutdown(g_app.gdiplusToken);
if (coInitialized) CoUninitialize();
if (g_app.instanceMutex) {
ReleaseMutex(g_app.instanceMutex);
CloseHandle(g_app.instanceMutex);
}
return (int)msg.wParam;
}
// --- Window Procedures ---
LRESULT CALLBACK MainWndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
// Когда Проводник перезапускается (крэш/обновление), трей-иконки пропадают.
// Shell посылает RegisterWindowMessage("TaskbarCreated") - перерегистрируем иконку.
static const UINT WM_TASKBARCREATED = RegisterWindowMessageW(L"TaskbarCreated");
if (uMsg == WM_TASKBARCREATED) {
// Иконка пропала - добавляем заново
HICON hIcon = (HICON)GetClassLongPtrW(hwnd, GCLP_HICON);
AddTrayIcon(hwnd, hIcon);
return 0;
}
switch (uMsg) {
case WM_CLOSE:
DestroyWindow(hwnd);
return 0;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
case WM_APP_ICON_READY:
{
HWND switcherWnd = NULL;
{
std::lock_guard<std::mutex> lock(g_app.stateMutex);
switcherWnd = g_app.switcherWnd;
}
if (switcherWnd)
UpdateSwitcherLayeredWindow(switcherWnd);
return 0;
}
// --- Системный трей ---
case WM_APP_TRAY:
switch (LOWORD(lParam)) {
case WM_RBUTTONUP:
case WM_CONTEXTMENU:
ShowTrayMenu(hwnd);
break;
case WM_LBUTTONDBLCLK:
// Двойной клик - показать диалог About
MessageBoxW(hwnd,
L"TabWindSwitcher v1.0\n\n"
L"Alt + Tab - переключатель всех окон\n"
L"Alt + ` - переключатель окон текущего приложения\n"
L"Escape - закрыть переключатель",
L"TabWindSwitcher", MB_OK | MB_ICONINFORMATION);
break;
}
return 0;
case WM_APP_SWITCH_TO_WINDOW: {
HWND hwndToActivate = (HWND)wParam;
// Сначала активируем нужное окно, потом сворачиваем остальные.
// Порядок принципиален: если сворачивать до активации, фокус
// достанется случайному окну и SetForegroundWindow может не сработать.
if (hwndToActivate) {
DWORD foregroundThreadId = GetWindowThreadProcessId(GetForegroundWindow(), NULL);
DWORD ourThreadId = GetCurrentThreadId();
if (foregroundThreadId != ourThreadId)
AttachThreadInput(foregroundThreadId, ourThreadId, TRUE);
LockSetForegroundWindow(LSFW_UNLOCK);
AllowSetForegroundWindow(ASFW_ANY);
if (IsIconic(hwndToActivate))
ShowWindow(hwndToActivate, SW_RESTORE);
SetWindowPos(hwndToActivate, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
SetForegroundWindow(hwndToActivate);
SetActiveWindow(hwndToActivate);
SetFocus(hwndToActivate);
SetWindowPos(hwndToActivate, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
if (foregroundThreadId != ourThreadId)
AttachThreadInput(foregroundThreadId, ourThreadId, FALSE);
}
// Сворачиваем все остальные окна из списка (если фича включена в INI).
// Список уже готов: он был заполнен в хуке до DestroyWindow(switcherWnd).
std::vector<HWND> windowsToMinimize;
bool minimizeOthers = false;
{
std::lock_guard<std::mutex> lock(g_app.stateMutex);
minimizeOthers = g_app.settings.minimizeOthers;
windowsToMinimize.swap(g_app.windowsToMinimize);
}
if (minimizeOthers) {
for (HWND hwndMin : windowsToMinimize) {
// IsWindow - защита от окон, закрытых за время переключения.
if (IsWindow(hwndMin) && !IsIconic(hwndMin))
ShowWindow(hwndMin, SW_MINIMIZE);
}
}
return 0;
}
}
return DefWindowProcW(hwnd, uMsg, wParam, lParam);
}
LRESULT CALLBACK SwitcherWndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
switch (uMsg) {
case WM_KILLFOCUS:
// Потеря фокуса - закрываем переключатель без активации какого-либо окна.
// Типичный случай: пользователь кликнул мимо окна.
DestroyWindow(hwnd);
return 0;
case WM_DPICHANGED: {
{
std::lock_guard<std::mutex> lock(g_app.stateMutex);
g_app.dpi = HIWORD(wParam);
}
RECT* suggested = (RECT*)lParam;
SetWindowPos(hwnd, NULL,
suggested->left, suggested->top,
suggested->right - suggested->left,
suggested->bottom - suggested->top,
SWP_NOZORDER | SWP_NOACTIVATE);
UpdateSwitcherLayeredWindow(hwnd);
return 0;
}
case WM_NCDESTROY: {
StopIconWorker();
std::lock_guard<std::mutex> lock(g_app.stateMutex);
g_app.ResetSwitcherStateLocked();
return 0;
}
}
return DefWindowProcW(hwnd, uMsg, wParam, lParam);
}
// --- Drawing ---
void UpdateSwitcherLayeredWindow(HWND hwnd) {
RECT rcClient;
GetClientRect(hwnd, &rcClient);
int width = rcClient.right - rcClient.left;
int height = rcClient.bottom - rcClient.top;
if (width == 0 || height == 0) return;
RECT rcWindow;
GetWindowRect(hwnd, &rcWindow);
POINT ptDst = { rcWindow.left, rcWindow.top };
// FIX: UpdateLayeredWindow требует экранный DC (NULL), а не DC окна.
// Использование GetDC(hwnd) на layered-окне технически некорректно.
HDC hdcScreen = GetDC(NULL);
if (!hdcScreen) return;
HDC hdcMem = CreateCompatibleDC(hdcScreen);
if (!hdcMem) {
ReleaseDC(NULL, hdcScreen);
return;
}
HBITMAP hbmMem = CreateCompatibleBitmap(hdcScreen, width, height);
if (!hbmMem) {
DeleteDC(hdcMem);
ReleaseDC(NULL, hdcScreen);
return;
}
HBITMAP hbmOld = (HBITMAP)SelectObject(hdcMem, hbmMem);
if (!hbmOld) {
DeleteObject(hbmMem);
DeleteDC(hdcMem);
ReleaseDC(NULL, hdcScreen);
return;
}
BYTE alpha = DEFAULT_TRANSPARENCY;
{
std::lock_guard<std::mutex> lock(g_app.stateMutex);
Gdiplus::Graphics graphics(hdcMem);
graphics.SetInterpolationMode(Gdiplus::InterpolationModeHighQualityBicubic);
graphics.SetSmoothingMode(Gdiplus::SmoothingMode::SmoothingModeAntiAlias);
graphics.SetTextRenderingHint(Gdiplus::TextRenderingHint::TextRenderingHintAntiAlias);
graphics.Clear(Gdiplus::Color(0, 0, 0, 0));
alpha = g_app.settings.alpha;
int padding = g_app.Scale(PADDING);
int iconSize = g_app.Scale(ICON_SIZE);
int iconPaddingTop = g_app.Scale(ICON_PADDING_TOP);
int titleHeight = g_app.Scale(TITLE_HEIGHT);
int titleLineHeight = titleHeight / 2;
int itemContentWidth = g_app.Scale(128);
int itemContentHeight = iconPaddingTop + iconSize + titleHeight;
int itemCellWidth = itemContentWidth + padding;
int itemCellHeight = itemContentHeight + padding;
int contentWidth = (g_app.iconsPerRow > 0)
? static_cast<int>(g_app.iconsPerRow * itemCellWidth - padding)
: 0;
int startX = (width - contentWidth) / 2;
Gdiplus::GraphicsPath path;
AddRoundRectToPath(path,
Gdiplus::RectF(0.0f, 0.0f, (Gdiplus::REAL)width, (Gdiplus::REAL)height),
(Gdiplus::REAL)g_app.Scale(g_app.settings.windowRadius));
Gdiplus::SolidBrush bgBrush(g_app.settings.bgColor);
graphics.FillPath(&bgBrush, &path);
Gdiplus::Font titleFont(L"Segoe UI", (Gdiplus::REAL)g_app.Scale(13),
Gdiplus::FontStyleRegular, Gdiplus::UnitPixel);
Gdiplus::SolidBrush textBrush(g_app.settings.textColor);
if (g_app.iconsPerRow > 0 && g_app.visibleRows > 0) {
size_t firstRow = g_app.currentPage * g_app.visibleRows;
size_t lastRow = std::min(g_app.rows, firstRow + g_app.visibleRows);
size_t firstIndex = firstRow * g_app.iconsPerRow;
size_t lastIndex = std::min(g_app.windowList.size(), lastRow * g_app.iconsPerRow);
for (size_t i = firstIndex; i < lastIndex; ++i) {
size_t absoluteRow = i / g_app.iconsPerRow;
size_t visibleRow = absoluteRow - firstRow;
size_t col = i % g_app.iconsPerRow;
int x = static_cast<int>(startX + col * itemCellWidth);
int y = static_cast<int>(padding + visibleRow * itemCellHeight);
if (i == g_app.selectedIndex) {
Gdiplus::GraphicsPath selectionPath;
int selectionPad = g_app.Scale(4);
AddRoundRectToPath(selectionPath,
Gdiplus::RectF((Gdiplus::REAL)(x - selectionPad), (Gdiplus::REAL)(y - selectionPad),
(Gdiplus::REAL)(itemContentWidth + 2 * selectionPad),
(Gdiplus::REAL)(itemContentHeight + 2 * selectionPad)),
(Gdiplus::REAL)g_app.Scale(g_app.settings.selectionRadius));
Gdiplus::SolidBrush selectionBrush(g_app.settings.selectionColor);
graphics.FillPath(&selectionBrush, &selectionPath);
}
int iconDrawX = x + (itemContentWidth - iconSize) / 2;
if (g_app.windowList[i].pIconBitmap) {
graphics.DrawImage(g_app.windowList[i].pIconBitmap,
iconDrawX, y + iconPaddingTop, iconSize, iconSize);
}
Gdiplus::StringFormat strFormat;
strFormat.SetAlignment(Gdiplus::StringAlignmentCenter);
strFormat.SetLineAlignment(Gdiplus::StringAlignmentNear);
strFormat.SetFormatFlags(Gdiplus::StringFormatFlagsLineLimit);
strFormat.SetTrimming(Gdiplus::StringTrimmingEllipsisCharacter);
Gdiplus::RectF textRect(
(Gdiplus::REAL)x,
(Gdiplus::REAL)(y + iconPaddingTop + iconSize),
(Gdiplus::REAL)itemContentWidth,
(Gdiplus::REAL)(titleLineHeight * 2));
graphics.DrawString(g_app.windowList[i].title.c_str(), -1, &titleFont, textRect, &strFormat, &textBrush);
}
}
}
BLENDFUNCTION blend = { AC_SRC_OVER, 0, alpha, AC_SRC_ALPHA };
POINT ptSrc = { 0, 0 };
SIZE size = { width, height };
UpdateLayeredWindow(hwnd, hdcScreen, &ptDst, &size, hdcMem, &ptSrc, 0, &blend, ULW_ALPHA);
SelectObject(hdcMem, hbmOld);
DeleteObject(hbmMem);
DeleteDC(hdcMem);
ReleaseDC(NULL, hdcScreen); // FIX: соответствует GetDC(NULL) выше
}
// --- Main Logic ---
void ShowSwitcher(bool filterByProcess, bool backwards) {
bool hasSwitcher = false;
{
std::lock_guard<std::mutex> lock(g_app.stateMutex);
hasSwitcher = (g_app.switcherWnd != NULL);
}
if (hasSwitcher) {
MoveSelection(backwards ? -1 : 1);
return;
}
StopIconWorker();
{
std::lock_guard<std::mutex> lock(g_app.stateMutex);
g_app.ClearWindowListLocked();
g_app.CancelIconLoadingLocked();
}
DWORD targetPID = 0;
if (filterByProcess) {
HWND fg_hwnd = GetForegroundWindow();
if (fg_hwnd) GetWindowThreadProcessId(fg_hwnd, &targetPID);
}
std::vector<WindowInfo> windows;
EnumData data = { &windows, targetPID };
EnumWindows(EnumWindowsProc, (LPARAM)&data);
if (!windows.empty()) {
// FIX: стандартное поведение Alt+Tab - при первом показе переключателя
// сразу выделяется следующее окно (индекс 1), а не текущее (индекс 0).
// Если окно одно - деваться некуда, остаёмся на 0.
POINT cursorPos;
GetCursorPos(&cursorPos);
HMONITOR hMonitor = MonitorFromPoint(cursorPos, MONITOR_DEFAULTTONEAREST);
MONITORINFO monitorInfo = { sizeof(monitorInfo) };
int screenWidth, screenHeight, screenX, screenY;
if (GetMonitorInfo(hMonitor, &monitorInfo)) {
screenWidth = monitorInfo.rcMonitor.right - monitorInfo.rcMonitor.left;
screenHeight = monitorInfo.rcMonitor.bottom - monitorInfo.rcMonitor.top;
screenX = monitorInfo.rcMonitor.left;
screenY = monitorInfo.rcMonitor.top;
} else {
screenWidth = GetSystemMetrics(SM_CXSCREEN);
screenHeight = GetSystemMetrics(SM_CYSCREEN);
screenX = 0;
screenY = 0;
}
UINT dpi = GetDpiForMonitorOrSystem(hMonitor);
int windowWidth = 0;
int windowHeight = 0;
unsigned int iconGeneration = 0;
{
std::lock_guard<std::mutex> lock(g_app.stateMutex);
g_app.dpi = dpi;
g_app.windowList.swap(windows);
++g_app.iconGeneration;
iconGeneration = g_app.iconGeneration;
g_app.selectedIndex = backwards
? g_app.windowList.size() - 1
: ((g_app.windowList.size() > 1) ? 1 : 0);
int padding = g_app.Scale(PADDING);
int iconSize = g_app.Scale(ICON_SIZE);
int iconPaddingTop = g_app.Scale(ICON_PADDING_TOP);
int titleHeight = g_app.Scale(TITLE_HEIGHT);
int itemContentWidth = g_app.Scale(128);
int itemContentHeight = iconPaddingTop + iconSize + titleHeight;
int itemCellWidth = itemContentWidth + padding;
int itemCellHeight = itemContentHeight + padding;
int maxIconsPerRow = static_cast<int>((screenWidth * 0.9 - 2 * padding) / itemCellWidth);
if (maxIconsPerRow < 1) maxIconsPerRow = 1;
g_app.iconsPerRow = (g_app.windowList.size() < (size_t)maxIconsPerRow)
? g_app.windowList.size()
: (size_t)maxIconsPerRow;
g_app.rows = (g_app.windowList.size() + g_app.iconsPerRow - 1) / g_app.iconsPerRow;
int maxVisibleRows = static_cast<int>((screenHeight * 0.9 - 2 * padding) / itemCellHeight);
if (maxVisibleRows < 1) maxVisibleRows = 1;
g_app.visibleRows = std::min(g_app.rows, (size_t)maxVisibleRows);
if (g_app.visibleRows < 1) g_app.visibleRows = 1;
g_app.pageCount = (g_app.rows + g_app.visibleRows - 1) / g_app.visibleRows;
g_app.currentPage = 0;
g_app.RecalculatePageForSelectionLocked();
int contentWidth = static_cast<int>(g_app.iconsPerRow * itemCellWidth - padding);
windowWidth = static_cast<int>(contentWidth + 2 * padding);
windowHeight = static_cast<int>(g_app.visibleRows * itemCellHeight + padding);
}
if (windowWidth > (int)(screenWidth * 0.9))
windowWidth = (int)(screenWidth * 0.9);
int x = screenX + (screenWidth - windowWidth) / 2;
int y = screenY + (screenHeight - windowHeight) / 2;
HWND switcherWnd = CreateWindowExW(
WS_EX_TOPMOST | WS_EX_LAYERED,
SWITCHER_CLASS_NAME, L"Switcher", WS_POPUP | WS_VISIBLE,
x, y, windowWidth, windowHeight, NULL, NULL, GetModuleHandle(NULL), NULL);
{
std::lock_guard<std::mutex> lock(g_app.stateMutex);
g_app.switcherWnd = switcherWnd;
}
if (g_app.switcherWnd) {
UpdateSwitcherLayeredWindow(g_app.switcherWnd);
StartIconLoading(iconGeneration);
}
}
}
void MoveSelection(int delta) {
HWND hwnd = NULL;
{
std::lock_guard<std::mutex> lock(g_app.stateMutex);
if (g_app.windowList.empty()) return;
size_t count = g_app.windowList.size();
if (delta < 0) {
size_t step = (size_t)(-delta) % count;
g_app.selectedIndex = (g_app.selectedIndex + count - step) % count;
} else {
g_app.selectedIndex = (g_app.selectedIndex + (size_t)delta) % count;
}
g_app.RecalculatePageForSelectionLocked();
hwnd = g_app.switcherWnd;
}
if (hwnd) UpdateSwitcherLayeredWindow(hwnd);
}
void ChangePage(int delta) {
HWND hwnd = NULL;
{
std::lock_guard<std::mutex> lock(g_app.stateMutex);
if (g_app.pageCount <= 1 || g_app.iconsPerRow == 0 || g_app.visibleRows == 0)
return;
size_t oldPage = g_app.currentPage;
if (delta < 0) {
g_app.currentPage = (g_app.currentPage == 0) ? g_app.pageCount - 1 : g_app.currentPage - 1;
} else {
g_app.currentPage = (g_app.currentPage + 1) % g_app.pageCount;
}
if (g_app.currentPage != oldPage) {
size_t firstRow = g_app.currentPage * g_app.visibleRows;
size_t firstIndex = firstRow * g_app.iconsPerRow;
if (firstIndex < g_app.windowList.size())
g_app.selectedIndex = firstIndex;
else
g_app.selectedIndex = g_app.windowList.size() - 1;
}
hwnd = g_app.switcherWnd;
}
if (hwnd) UpdateSwitcherLayeredWindow(hwnd);
}
LRESULT CALLBACK LowLevelKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam) {
if (nCode == HC_ACTION) {
KBDLLHOOKSTRUCT* pkbhs = (KBDLLHOOKSTRUCT*)lParam;
bool keyDown = (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN);
bool keyUp = (wParam == WM_KEYUP || wParam == WM_SYSKEYUP);
if (pkbhs->vkCode == VK_LMENU || pkbhs->vkCode == VK_RMENU) {
if (keyDown) {
std::lock_guard<std::mutex> lock(g_app.stateMutex);
g_app.altDown = true;
} else if (keyUp) {
HWND switcherWnd = NULL;
HWND hwndToActivate = NULL;
HWND mainWnd = NULL;
{
std::lock_guard<std::mutex> lock(g_app.stateMutex);
g_app.altDown = false;
switcherWnd = g_app.switcherWnd;
mainWnd = g_app.mainWnd;
if (switcherWnd && g_app.selectedIndex < g_app.windowList.size()) {
hwndToActivate = g_app.windowList[g_app.selectedIndex].hwnd;
// FIX: Заполняем список окон для сворачивания ДО DestroyWindow.
// DestroyWindow вызывает WM_NCDESTROY синхронно и немедленно
// очищает g_app.windowList - после него список уже недоступен.
// PostMessage асинхронен и будет обработан позже в главном цикле.
g_app.windowsToMinimize.clear();
for (const auto& wi : g_app.windowList) {
if (wi.hwnd != hwndToActivate)
g_app.windowsToMinimize.push_back(wi.hwnd);
}
}
}
if (hwndToActivate)
PostMessage(mainWnd, WM_APP_SWITCH_TO_WINDOW, (WPARAM)hwndToActivate, 0);
if (switcherWnd) {
DestroyWindow(switcherWnd); // очищает g_app.windowList - но нам уже не нужен
}
}
}
bool altDown = false;
{
std::lock_guard<std::mutex> lock(g_app.stateMutex);
altDown = g_app.altDown;
}
if (altDown && keyDown) {
if (pkbhs->vkCode == VK_PRIOR) { ChangePage(-1); return 1; }
if (pkbhs->vkCode == VK_NEXT) { ChangePage(1); return 1; }
bool backwards = (GetAsyncKeyState(VK_SHIFT) & 0x8000) != 0;
if (pkbhs->vkCode == VK_TAB) { ShowSwitcher(false, backwards); return 1; }
if (pkbhs->vkCode == VK_OEM_3) { ShowSwitcher(true, backwards); return 1; }
}
// Escape закрывает переключатель без переключения (с любым состоянием Alt)
if (pkbhs->vkCode == VK_ESCAPE && keyDown) {
HWND switcherWnd = NULL;
{
std::lock_guard<std::mutex> lock(g_app.stateMutex);
switcherWnd = g_app.switcherWnd;
if (switcherWnd)
g_app.windowsToMinimize.clear(); // сворачивать ничего не нужно
}
if (switcherWnd) {
DestroyWindow(switcherWnd);
return 1;
}
}
}
return CallNextHookEx(g_app.keyboardHook, nCode, wParam, lParam);
}
// --- Icon and Window Enumeration Helpers ---
Gdiplus::Bitmap* GetBestIconForProcess(const wchar_t* exePath, HWND associatedHwnd) {
HICON hIcon = NULL;
bool ownIcon = false; // TRUE только если иконка создана нами (нужен DestroyIcon)
if (exePath && exePath[0] != L'\0') {
// LOAD_LIBRARY_AS_IMAGE_RESOURCE нужен для PE с нестандартным выравниванием секций
HMODULE hModule = LoadLibraryExW(exePath, NULL, LOAD_LIBRARY_AS_DATAFILE | LOAD_LIBRARY_AS_IMAGE_RESOURCE);
if (hModule) {
wchar_t groupName[256] = {0};
EnumResourceNamesW(hModule, RT_GROUP_ICON,
[](HMODULE, LPCWSTR, LPWSTR lpName, LONG_PTR lParam) -> BOOL {
if (IS_INTRESOURCE(lpName)) wsprintfW((wchar_t*)lParam, L"#%d", (int)(intptr_t)lpName);
else wcscpy_s((wchar_t*)lParam, 256, lpName);
return FALSE; // останавливаемся на первой группе
}, (LONG_PTR)groupName);
if (groupName[0] != L'\0') {
HRSRC hResource = FindResourceW(hModule, groupName, RT_GROUP_ICON);
if (hResource) {
HGLOBAL hMem = LoadResource(hModule, hResource);
void* pIconDir = hMem ? LockResource(hMem) : NULL;
if (pIconDir) {
int iconId = LookupIconIdFromDirectoryEx((PBYTE)pIconDir, TRUE, 256, 256, LR_DEFAULTCOLOR);
HRSRC hIconResource = FindResourceW(hModule, MAKEINTRESOURCEW(iconId), RT_ICON);
if (hIconResource) {
HGLOBAL hIconMem = LoadResource(hModule, hIconResource);
void* pIconData = hIconMem ? LockResource(hIconMem) : NULL;
if (pIconData) {
hIcon = CreateIconFromResourceEx((PBYTE)pIconData,
SizeofResource(hModule, hIconResource),
TRUE, 0x00030000, 0, 0, LR_DEFAULTCOLOR);
if (hIcon) ownIcon = true; // мы создали иконку - мы её и уничтожаем
}
}
}
}
}
FreeLibrary(hModule);
}
}
if (!hIcon) {
// WM_GETICON возвращает shared-иконку - DestroyIcon вызывать нельзя (ownIcon остаётся false)
DWORD_PTR dwResult = 0;
int timeoutMs = 50;
{
std::lock_guard<std::mutex> lock(g_app.stateMutex);
timeoutMs = g_app.settings.iconTimeoutMs;
}
if (SendMessageTimeout(associatedHwnd, WM_GETICON, ICON_BIG, 0,
SMTO_ABORTIFHUNG, timeoutMs, &dwResult) && dwResult)
hIcon = (HICON)(HANDLE)dwResult;
}
if (!hIcon) {
// ICON_SMALL2 - иконка в реальном разрешении без масштабирования
DWORD_PTR dwResult = 0;
int timeoutMs = 50;
{
std::lock_guard<std::mutex> lock(g_app.stateMutex);
timeoutMs = g_app.settings.iconTimeoutMs;
}
if (SendMessageTimeout(associatedHwnd, WM_GETICON, ICON_SMALL2, 0,
SMTO_ABORTIFHUNG, timeoutMs, &dwResult) && dwResult)
hIcon = (HICON)(HANDLE)dwResult;
}
if (!hIcon) {
// Последний резерв: иконка, прописанная в классе окна (тоже shared)
hIcon = (HICON)(HANDLE)GetClassLongPtrW(associatedHwnd, GCLP_HICON);
}
// ownIcon остаётся false для всех трёх путей выше - shared-иконки не уничтожаем
if (hIcon) {
ICONINFO ii = {0};
if (GetIconInfo(hIcon, &ii)) {
BITMAP bm = {0};
if (!ii.hbmColor || GetObject(ii.hbmColor, sizeof(bm), &bm) == 0
|| bm.bmWidth <= 0 || bm.bmHeight <= 0) {
if (ii.hbmColor) DeleteObject(ii.hbmColor);
if (ii.hbmMask) DeleteObject(ii.hbmMask);
const int fallbackSize = 32;
Gdiplus::Bitmap* fallback = new Gdiplus::Bitmap(fallbackSize, fallbackSize, PixelFormat32bppARGB);
Gdiplus::Graphics graphics(fallback);
graphics.Clear(Gdiplus::Color(0, 0, 0, 0));
HDC hdc = graphics.GetHDC();
if (hdc) {
DrawIconEx(hdc, 0, 0, hIcon, fallbackSize, fallbackSize, 0, NULL, DI_NORMAL);
graphics.ReleaseHDC(hdc);
}
if (ownIcon) DestroyIcon(hIcon);
return fallback;
}
Gdiplus::Bitmap* result = new Gdiplus::Bitmap(bm.bmWidth, bm.bmHeight, PixelFormat32bppARGB);
Gdiplus::Rect rect(0, 0, bm.bmWidth, bm.bmHeight);
Gdiplus::BitmapData bmpData;
if (result->LockBits(&rect, Gdiplus::ImageLockModeWrite, PixelFormat32bppARGB, &bmpData) == Gdiplus::Ok) {
// Копируем построчно, учитывая что stride в GDI+ и bmWidthBytes у HBITMAP
// могут различаться (хотя для 32bpp обычно совпадают).
std::vector<BYTE> colorBits(bm.bmWidthBytes * bm.bmHeight);
GetBitmapBits(ii.hbmColor, (LONG)colorBits.size(), colorBits.data());
for (int row = 0; row < bm.bmHeight; ++row) {
const BYTE* srcRow = colorBits.data() + row * bm.bmWidthBytes;
BYTE* dstRow = (BYTE*)bmpData.Scan0 + row * bmpData.Stride;
memcpy(dstRow, srcRow, bm.bmWidth * sizeof(UINT32));
}
// Проверяем наличие альфа-канала.
bool hasAlpha = false;
for (int row = 0; row < bm.bmHeight && !hasAlpha; ++row) {
const UINT32* rowPtr = (const UINT32*)((BYTE*)bmpData.Scan0 + row * bmpData.Stride);
for (int col = 0; col < bm.bmWidth; ++col) {
if (rowPtr[col] & 0xFF000000) { hasAlpha = true; break; }
}
}
// Если альфы нет - строим маску прозрачности из маскового битмапа.
if (!hasAlpha && ii.hbmMask) {
BITMAP bmMask = {0};
GetObject(ii.hbmMask, sizeof(bmMask), &bmMask);
std::vector<BYTE> maskBits(bmMask.bmWidthBytes * bmMask.bmHeight);
GetBitmapBits(ii.hbmMask, (LONG)maskBits.size(), maskBits.data());
for (int row = 0; row < bm.bmHeight; ++row) {
UINT32* dstRow = (UINT32*)((BYTE*)bmpData.Scan0 + row * bmpData.Stride);
for (int col = 0; col < bm.bmWidth; ++col) {
// FIX: правильное индексирование с учётом bmWidthBytes (выравнивание строк).
// Старый код: maskBits[i/8] - игнорировал padding в конце каждой строки.
int byteIdx = row * bmMask.bmWidthBytes + col / 8;
int bitIdx = 7 - (col % 8);
if ((maskBits[byteIdx] >> bitIdx) & 1)
dstRow[col] &= 0x00FFFFFF; // прозрачный
else
dstRow[col] |= 0xFF000000; // непрозрачный
}
}
}
result->UnlockBits(&bmpData);
}
DeleteObject(ii.hbmColor);
if (ii.hbmMask) DeleteObject(ii.hbmMask);
if (ownIcon) DestroyIcon(hIcon); // shared-иконки (WM_GETICON, GCLP_HICON) не трогаем
return result;
}
if (ownIcon) DestroyIcon(hIcon); // GetIconInfo не удался, но иконка наша - освобождаем
}
// Пустая заглушка, если иконку добыть не удалось.
return new Gdiplus::Bitmap(32, 32, PixelFormat32bppARGB);
}
BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam) {
DWORD currentPID = 0;
GetWindowThreadProcessId(hwnd, ¤tPID);
EnumData* pData = (EnumData*)lParam;