-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshell02_wallpaper_engine.cpp
More file actions
4572 lines (4024 loc) · 154 KB
/
shell02_wallpaper_engine.cpp
File metadata and controls
4572 lines (4024 loc) · 154 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
#ifndef UNICODE
#define UNICODE
#endif
#ifndef _UNICODE
#define _UNICODE
#endif
// windows.h MUST come first on MinGW — it defines HRESULT, CALLBACK,
// DECLSPEC_IMPORT etc. that all other Win32 headers depend on.
#include <windows.h>
#include <windowsx.h>
#include <winuser.h>
#include "json.hpp"
#include <algorithm>
#include <commctrl.h>
#include <dwmapi.h>
#include <fstream>
#include <gdiplus.h>
#include <initguid.h>
#include <map>
#include <powrprof.h>
#include <psapi.h>
#include <shellapi.h>
#include <shlguid.h>
#include <shlobj.h>
#include <set>
#include <string>
#include <tchar.h>
#include <tlhelp32.h>
#include <vector>
#ifdef NO_JSON
void SaveDesktopPositions() {}
void LoadDesktopPositions() {}
void SaveStartMenuPositions() {}
void LoadStartMenuPositions() {}
void SaveTaskbarConfig() {}
void LoadTaskbarConfig() {}
void LoadWindowPositions() {}
#endif
#pragma comment(lib, "shell32.lib")
#pragma comment(lib, "comctl32.lib")
#pragma comment(lib, "ole32.lib")
#pragma comment(lib, "uuid.lib")
#pragma comment(lib, "gdiplus.lib")
#pragma comment(lib, "dwmapi.lib")
#pragma comment(lib, "PowrProf.lib")
HWND g_hDesktopWnd = NULL;
HWND g_hTaskbarWnd = NULL;
HWND g_hStartMenuWnd = NULL;
HWND g_hWeWorkerW =
NULL; // WE's render-target WorkerW — we stay just above this
static HWINEVENTHOOK g_hWinEventHook = NULL;
HINSTANCE g_hInst = NULL;
int g_taskbarHeight = 64;
bool g_taskbarVisible = true; // Track taskbar visibility state
bool g_taskbarVisibleBeforeWinKey =
true; // Track taskbar state before Windows key press
bool g_startMenuOpenedByWinKey =
false; // Track if start menu was opened by Windows key
static bool g_fullscreenActive = false; // Track if a fullscreen app is running
// Keyboard hook for Windows key
static HHOOK g_keyboardHook = NULL;
static bool g_winKeyPressed = false;
// Set true before injecting Win+combo so the hook lets it pass through
static bool g_suppressWinKeyHook = false;
// AppBar callback message
#define APPBAR_CALLBACK (WM_APP + 1)
// Custom colors for taskbar and start menu
static COLORREF g_taskbarColor = RGB(45, 45, 48); // Default dark gray
static COLORREF g_startMenuColor = RGB(50, 100, 160); // Default blue
#define IDM_ITEM_OPEN 40001
#define IDM_ITEM_PROPERTIES 40002
#define IDM_DESKTOP_REFRESH 40003
#define IDM_RESTART_SHELL 40005
#define IDM_ITEM_RENAME 40006
// New command IDs
#define IDM_VIEW_LARGE 50001
#define IDM_VIEW_MEDIUM 50002
#define IDM_VIEW_SMALL 50003
#define IDM_SORT_NAME 50011
#define IDM_SORT_TYPE 50012
#define IDM_SORT_DATE 50013
#define IDM_TOGGLE_SHOW_ICONS 50021
#define IDM_AUTO_ARRANGE 50022
#define IDM_ALIGN_TO_GRID 50023
#define IDM_CHANGE_BACKGROUND 50024
#define IDM_CHANGE_TASKBAR_COLOR 50025
#define IDM_CHANGE_STARTMENU_COLOR 50026
int g_rightClickSelection = -1;
// Icon/layout constants
// ICON_SIZE_DEFAULT is the pixel size for the default "medium" view mode (mode
// index 1).
const int ICON_SIZE_DEFAULT = 48;
const int ICON_X_SPACING_DEFAULT = 120;
const int ICON_Y_SPACING_DEFAULT = 100;
const int ICON_X_START = 50;
const int ICON_Y_START = 20;
// Current view state
int g_viewMode = 1; // Medium by default
int g_iconSize = ICON_SIZE_DEFAULT;
int g_iconXSpacing = ICON_X_SPACING_DEFAULT;
int g_iconYSpacing = ICON_Y_SPACING_DEFAULT;
bool g_showIcons = true;
bool g_autoArrange = false;
static WNDPROC g_origDesktopProc = NULL;
static WNDPROC g_realDesktopProc = NULL; // The actual DesktopWndProc address
static IContextMenu2 *g_pcm2 = NULL;
static IContextMenu3 *g_pcm3 = NULL;
static Gdiplus::GdiplusStartupInput gdiplusStartupInput;
static ULONG_PTR gdiplusToken;
// Desktop background image
static Gdiplus::Bitmap *g_backgroundImage = NULL;
static std::wstring g_backgroundPath;
struct DesktopItem {
wchar_t name[MAX_PATH];
wchar_t path[MAX_PATH];
HICON hIcon;
FILETIME ftWrite;
std::wstring extension;
int x; // pixel position for custom placement
int y;
bool hasPos; // whether x/y have been assigned
};
std::vector<DesktopItem> g_desktopItems;
// Structure for sidebar items with positions
struct SidebarItemInfo {
bool isFolder;
std::wstring name;
std::wstring fullPath;
int yPos; // Actual screen position
int height;
};
static std::vector<SidebarItemInfo> g_sidebarItems;
// Structure for running apps
struct RunningApp {
DWORD processId;
HWND hwnd;
std::wstring exePath;
std::wstring displayName;
HICON hIcon;
bool visible;
};
static std::vector<RunningApp> g_runningApps;
// For Windows 11 taskbar behavior
static HWND g_lastForegroundWindow = NULL;
static std::map<HWND, bool> g_windowMinimizedState;
// ==================== SYSTEM TRAY IMPROVEMENTS ====================
// Structure for REAL system tray icons (using Windows Shell API)
struct RealTrayIcon {
NOTIFYICONDATAW nid; // Original notify data
std::wstring tooltip; // Tooltip text
HICON hIcon; // Current icon
DWORD processId; // Process ID
HWND hWnd; // Owner window
UINT uID; // Icon ID
GUID guid; // GUID (for modern apps)
bool hidden; // Hidden in overflow
int trayIndex; // Index in tray display
RECT displayRect; // Display rectangle
bool isModernApp; // UWP/Modern app
std::wstring appName; // App name
};
static std::vector<RealTrayIcon> g_realTrayIcons;
static HWND g_trayNotifyWnd = NULL;
static bool g_trayIconsInitialized = false;
static int g_trayIconSize = 20; // Smaller size for tray icons
static int g_trayIconSpacing = 8; // Increased from 4 to 8 for better spacing
static bool g_showTrayIcons = true;
// Structure for our drawn tray icons
struct TrayIcon {
std::wstring name;
HICON hIcon;
int x;
int y;
int width;
int height;
bool isRealIcon; // Is this a real system tray icon?
UINT realIconId; // Original icon ID if real
HWND realOwner; // Owner window if real
};
static std::vector<TrayIcon> g_trayIcons;
// Hidden icons tracking
static int g_chevronX = 0;
static int g_chevronY = 0;
static int g_chevronSize = 40;
static bool g_hasHiddenIcons = false;
static std::vector<int> g_hiddenIconIndices; // Indices of hidden real icons
// ==================== HELPER FUNCTIONS ====================
// Gets a properly sized icon using SHGetImageList — no pixelation.
// Uses SHIL_EXTRALARGE (48x48) or SHIL_JUMBO (256x256) instead of the
// blurry 32x32 that SHGetFileInfo+SHGFI_LARGEICON returns.
// Caller is responsible for DestroyIcon().
// MinGW doesn't fully declare IImageList — define the GUID manually.
// {46EB5926-582E-4017-9FDF-E8998DAA0950}
static const GUID CLSID_IImageList = {
0x46eb5926, 0x582e, 0x4017,
{ 0x9f, 0xdf, 0xe8, 0x99, 0x8d, 0xaa, 0x09, 0x50 }
};
static HICON GetIconForPath(const std::wstring &path, int size) {
int shil = SHIL_LARGE; // 32x32
if (size >= 48) shil = SHIL_EXTRALARGE; // 48x48
if (size >= 256) shil = SHIL_JUMBO; // 256x256
SHFILEINFOW sfi = {};
if (!SHGetFileInfoW(path.c_str(), 0, &sfi, sizeof(sfi), SHGFI_SYSICONINDEX))
return NULL;
// Use HIMAGELIST + ImageList_GetIcon to avoid MinGW's incomplete IImageList
HIMAGELIST hil = NULL;
if (FAILED(SHGetImageList(shil, CLSID_IImageList, (void **)&hil)) || !hil)
return NULL;
HICON hIcon = ImageList_GetIcon(hil, sfi.iIcon, ILD_TRANSPARENT);
return hIcon;
}
// Returns true if the given file path should be blocked from appearing in the
// taskbar, start menu, or being launched. Centralises the previously duplicated
// explorer/shell filtering that was copy-pasted 5+ times across the codebase.
static bool IsBlockedApp(const std::wstring &appPath) {
size_t slash = appPath.find_last_of(L"\\/");
std::wstring fileName =
(slash != std::wstring::npos) ? appPath.substr(slash + 1) : appPath;
std::wstring lower = fileName;
std::transform(lower.begin(), lower.end(), lower.begin(), ::towlower);
return lower.find(L"explorer") != std::wstring::npos ||
lower.find(L"shell.exe") != std::wstring::npos ||
lower.find(L"shell.lnk") != std::wstring::npos ||
lower.find(L"customshell") != std::wstring::npos;
}
std::wstring GetAppDataPath() {
PWSTR pszPath = NULL;
std::wstring result;
if (SUCCEEDED(
SHGetKnownFolderPath(FOLDERID_RoamingAppData, 0, NULL, &pszPath))) {
result = pszPath;
result += L"\\CustomShell";
CoTaskMemFree(pszPath);
}
return result;
}
void SaveDesktopPositions() {
try {
nlohmann::json jPositions = nlohmann::json::array();
for (const auto &item : g_desktopItems) {
nlohmann::json jItem;
char pathBuf[MAX_PATH];
WideCharToMultiByte(CP_UTF8, 0, item.path, -1, pathBuf, sizeof(pathBuf),
NULL, NULL);
jItem["path"] = pathBuf;
jItem["x"] = item.x;
jItem["y"] = item.y;
jPositions.push_back(jItem);
}
std::wstring appDataPath = GetAppDataPath();
CreateDirectoryW(appDataPath.c_str(), NULL);
std::wstring configPath = appDataPath + L"\\positions.json";
std::ofstream file(configPath.c_str());
if (file.is_open()) {
file << jPositions.dump(2);
file.close();
}
} catch (...) {
#ifdef _DEBUG
OutputDebugStringW(L"CustomShell: exception swallowed\n");
#endif
}
}
void LoadDesktopPositions() {
try {
std::wstring appDataPath = GetAppDataPath();
std::wstring configPath = appDataPath + L"\\positions.json";
std::ifstream file(configPath.c_str());
if (file.is_open()) {
nlohmann::json jPositions;
file >> jPositions;
file.close();
for (const auto &jItem : jPositions) {
std::string pathStr = jItem["path"];
wchar_t pathW[MAX_PATH];
MultiByteToWideChar(CP_UTF8, 0, pathStr.c_str(), -1, pathW, MAX_PATH);
for (auto &item : g_desktopItems) {
if (_wcsicmp(item.path, pathW) == 0) {
item.x = jItem["x"];
item.y = jItem["y"];
item.hasPos = true;
break;
}
}
}
}
} catch (...) {
#ifdef _DEBUG
OutputDebugStringW(L"CustomShell: exception swallowed\n");
#endif
}
}
void DrawIconWithGDIPlus(Gdiplus::Graphics *g, HICON hIcon, int x, int y,
int size) {
if (!g || !hIcon)
return;
ICONINFO iconInfo;
if (GetIconInfo(hIcon, &iconInfo)) {
HDC hdc = g->GetHDC();
if (hdc) {
DrawIconEx(hdc, x, y, hIcon, size, size, 0, NULL, DI_NORMAL);
g->ReleaseHDC(hdc);
}
if (iconInfo.hbmColor)
DeleteObject(iconInfo.hbmColor);
if (iconInfo.hbmMask)
DeleteObject(iconInfo.hbmMask);
}
}
static std::vector<std::wstring>
g_pinnedApps; // Paths of pinned apps in start menu
static std::vector<std::wstring>
g_removedApps; // Apps removed from start menu (don't show)
static std::wstring g_currentSidebarFolder =
L"C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs"; // Current
// sidebar
// folder
static int g_sidebarScrollOffset = 0;
// Structure for sidebar items (mixed folders and files)
struct SidebarItem {
bool isFolder;
std::wstring name;
std::wstring fullPath;
};
// Structure for taskbar icons
struct TaskbarIcon {
std::wstring path;
HICON hIcon;
int x; // x position
int y;
int width;
int height;
bool visible; // whether to show on taskbar
};
static std::vector<TaskbarIcon> g_taskbarIcons;
static std::vector<std::wstring>
g_taskbarPinned; // Apps pinned to taskbar (persisted)
// Drag state for moving icons (desktop)
static bool g_dragging = false;
static int g_dragIndex = -1;
static int g_dragOffsetX = 0;
static int g_dragOffsetY = 0;
// Drag state for Start menu tiles
static bool g_startMenuDragging = false;
static int g_startMenuDragIndex = -1;
static int g_startMenuDragOffsetX = 0;
static int g_startMenuDragOffsetY = 0;
static std::vector<int> g_tilePositionsX; // Store tile X positions
static std::vector<int> g_tilePositionsY; // Store tile Y positions
static int g_startMenuScrollOffset = 0; // Scroll offset for main area
static int g_hoveredIcon = -1; // Track which icon is under cursor
// Forward declarations
void ResizeShellWindows(int dpi = 96);
void ShowShellContextMenu(HWND hwnd, POINT pt, LPCWSTR pszPath);
void ShowDesktopContextMenu(HWND hwnd, POINT pt);
void LaunchApp(LPCWSTR path);
void LaunchExplorer();
void UpdateViewMode(int mode);
void SortByName();
void SortByTypeThenName();
void SortByDateDesc();
void AlignIconsToGrid();
void PopulateDesktopIcons();
void ResetDesktopPositions();
void SaveDesktopPositions();
void LoadDesktopPositions();
void PopulateStartMenuApps();
void DrawIconWithGDIPlus(Gdiplus::Graphics *g, HICON hIcon, int x, int y,
int size);
std::wstring GetAppDataPath();
void RegisterAppBar(HWND hwnd);
void SetAppBarPos(HWND hwnd);
void UnregisterAppBar(HWND hwnd);
static void ForceFocusToDesktop();
static void BringShellToTopmost();
static void RestoreShellZOrder();
void CALLBACK WinEventProc(HWINEVENTHOOK hHook, DWORD event, HWND hwnd,
LONG idObject, LONG idChild, DWORD dwEventThread,
DWORD dwmsEventTime);
// Progman window proc that handles Wallpaper Engine's 0x052C spawn message.
// WE sends this undocumented message to the Progman window so it creates a
// WorkerW below itself for WE to render animated wallpapers into.
// Without handling this, WE cannot find a valid render target.
LRESULT CALLBACK ProgmanWndProc(HWND hwnd, UINT msg, WPARAM wParam,
LPARAM lParam) {
// 0x052C is Wallpaper Engine's undocumented message that causes Progman to
// spawn a WorkerW render target. We pass it through DefWindowProc so it
// performs its internal work, then return the result. Previously this called
// DefWindowProc twice (once discarded, once returned), which was redundant.
return DefWindowProcW(hwnd, msg, wParam, lParam);
}
// New functions for running apps
void UpdateRunningAppsList();
void AddCommonTrayIcons();
std::wstring GetAppExeName(LPCWSTR appPath);
void DestroyTaskbar();
void RecreateTaskbar();
void ResizeShellWindows(int dpi);
// ==================== SYSTEM TRAY FUNCTIONS ====================
// Find the real Windows tray notification window
HWND FindTrayNotifyWnd() {
HWND hTrayWnd = FindWindowW(L"Shell_TrayWnd", NULL);
if (!hTrayWnd)
return NULL;
// Look for TrayNotifyWnd inside Shell_TrayWnd
HWND hTrayNotifyWnd = FindWindowExW(hTrayWnd, NULL, L"TrayNotifyWnd", NULL);
if (!hTrayNotifyWnd) {
// Try alternative names for newer Windows versions
hTrayNotifyWnd = FindWindowExW(
hTrayWnd, NULL, L"Windows.UI.Composition.DesktopWindowContentBridge",
NULL);
}
return hTrayNotifyWnd;
}
// Hook into Windows Shell to get tray icons
BOOL CALLBACK EnumTrayWindowsProc(HWND hwnd, LPARAM lParam) {
wchar_t className[256];
GetClassNameW(hwnd, className, ARRAYSIZE(className));
// Collect the tray notify / overflow window handle so callers can use it.
// Previously both branches returned TRUE without storing anything — now we
// write the found HWND back through lParam so the caller receives it.
if (wcsstr(className, L"NotifyIconOverflowWindow")) {
HWND *pResult = reinterpret_cast<HWND *>(lParam);
if (pResult)
*pResult = hwnd;
return FALSE; // Stop enumeration — we found what we needed
}
return TRUE; // Continue searching
}
// Get process name from PID
std::wstring GetProcessName(DWORD processId) {
HANDLE hProcess =
OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, processId);
if (hProcess) {
wchar_t exePath[MAX_PATH] = {0};
DWORD pathSize = MAX_PATH;
if (QueryFullProcessImageNameW(hProcess, 0, exePath, &pathSize)) {
CloseHandle(hProcess);
std::wstring pathStr = exePath;
size_t lastSlash = pathStr.find_last_of(L"\\");
if (lastSlash != std::wstring::npos) {
return pathStr.substr(lastSlash + 1);
}
return pathStr;
}
CloseHandle(hProcess);
}
return L"Unknown";
}
// Get window text safely
std::wstring GetWindowTextSafe(HWND hwnd) {
wchar_t buffer[256];
int len = GetWindowTextW(hwnd, buffer, 256);
if (len > 0) {
return std::wstring(buffer);
}
return L"";
}
// Simulate getting tray icons by enumerating windows with tray-like properties
void PopulateRealTrayIcons() {
// Clear old icons
for (auto &icon : g_realTrayIcons) {
if (icon.hIcon) {
DestroyIcon(icon.hIcon);
}
}
g_realTrayIcons.clear();
// Clear our drawn tray icons
for (auto &icon : g_trayIcons) {
if (icon.hIcon && !icon.isRealIcon) {
DestroyIcon(icon.hIcon);
}
}
g_trayIcons.clear();
// ADD SYSTEM ICONS FIRST so they always show
AddCommonTrayIcons();
// Get all top-level windows and look for tray-like behavior
std::vector<HWND> potentialTrayWindows;
EnumWindows(
[](HWND hwnd, LPARAM lParam) -> BOOL {
auto &windows = *reinterpret_cast<std::vector<HWND> *>(lParam);
if (!IsWindowVisible(hwnd))
return TRUE;
// Get window class
wchar_t className[256];
GetClassNameW(hwnd, className, ARRAYSIZE(className));
// Look for windows that might have tray icons
// Many apps create hidden windows for tray notifications
DWORD processId;
GetWindowThreadProcessId(hwnd, &processId);
// Check window style and extended style
LONG style = GetWindowLongW(hwnd, GWL_STYLE);
LONG exStyle = GetWindowLongW(hwnd, GWL_EXSTYLE);
// Hidden windows with tooltip styles might be tray owners
if ((style & WS_POPUP) && (exStyle & WS_EX_TOOLWINDOW)) {
windows.push_back(hwnd);
}
return TRUE;
},
reinterpret_cast<LPARAM>(&potentialTrayWindows));
// Now try to communicate with these windows to get tray data
// This is a simplified approach - real implementation would use Shell Hook
for (HWND hwnd : potentialTrayWindows) {
DWORD processId;
GetWindowThreadProcessId(hwnd, &processId);
// Try to get the window's icon
HICON hIcon = (HICON)SendMessageW(hwnd, WM_GETICON, ICON_SMALL, 0);
if (!hIcon) {
hIcon = (HICON)SendMessageW(hwnd, WM_GETICON, ICON_BIG, 0);
}
if (!hIcon) {
hIcon = (HICON)GetClassLongPtrW(hwnd, GCLP_HICONSM);
}
if (hIcon) {
RealTrayIcon trayIcon = {};
trayIcon.hWnd = hwnd;
trayIcon.processId = processId;
trayIcon.hIcon = CopyIcon(hIcon); // Copy the icon
trayIcon.tooltip = GetWindowTextSafe(hwnd);
trayIcon.appName = GetProcessName(processId);
trayIcon.hidden = false;
g_realTrayIcons.push_back(trayIcon);
}
}
// NOW add the detected real tray icons AFTER system icons
for (size_t i = 0; i < g_realTrayIcons.size(); ++i) {
TrayIcon ti;
ti.name = g_realTrayIcons[i].appName;
ti.hIcon = CopyIcon(g_realTrayIcons[i].hIcon);
ti.isRealIcon = true;
ti.realOwner = g_realTrayIcons[i].hWnd;
ti.width = g_trayIconSize;
ti.height = g_trayIconSize;
g_trayIcons.push_back(ti);
}
}
void AddCommonTrayIcons() {
// Load shell32 once for all icon lookups
HMODULE hShell32 = LoadLibraryW(L"shell32.dll");
// Volume icon
{
TrayIcon ti;
ti.name = L"Volume";
ti.isRealIcon = false;
ti.hIcon = hShell32 ? (HICON)LoadImageW(hShell32, MAKEINTRESOURCE(168),
IMAGE_ICON, g_trayIconSize,
g_trayIconSize, LR_SHARED)
: NULL;
ti.width = g_trayIconSize;
ti.height = g_trayIconSize;
g_trayIcons.push_back(ti);
}
// Network icon
{
TrayIcon ti;
ti.name = L"Network";
ti.isRealIcon = false;
ti.hIcon = hShell32 ? (HICON)LoadImageW(hShell32, MAKEINTRESOURCE(17),
IMAGE_ICON, g_trayIconSize,
g_trayIconSize, LR_SHARED)
: NULL;
ti.width = g_trayIconSize;
ti.height = g_trayIconSize;
g_trayIcons.push_back(ti);
}
// Power/battery
{
TrayIcon ti;
ti.name = L"Power";
ti.isRealIcon = false;
ti.hIcon = hShell32 ? (HICON)LoadImageW(hShell32, MAKEINTRESOURCE(244),
IMAGE_ICON, g_trayIconSize,
g_trayIconSize, LR_SHARED)
: NULL;
ti.width = g_trayIconSize;
ti.height = g_trayIconSize;
g_trayIcons.push_back(ti);
}
if (hShell32)
FreeLibrary(hShell32);
// Clock (last, on the right)
{
TrayIcon ti;
ti.name = L"Clock";
ti.isRealIcon = false;
ti.hIcon = NULL; // Will draw text
ti.width = 55; // Wider for bigger time display (increased from 40)
ti.height = g_trayIconSize;
g_trayIcons.push_back(ti);
}
}
// Draw time in tray
void DrawTrayTime(Gdiplus::Graphics *g, int x, int y, int width, int height) {
SYSTEMTIME st;
GetLocalTime(&st);
wchar_t timeStr[64];
wsprintfW(timeStr, L"%02d:%02d", st.wHour, st.wMinute);
Gdiplus::FontFamily fontFamily(L"Segoe UI");
Gdiplus::Font timeFont(&fontFamily, 13, Gdiplus::FontStyleRegular,
Gdiplus::UnitPixel); // Increased from 11 to 13
Gdiplus::SolidBrush textBrush(Gdiplus::Color(255, 240, 240, 240));
Gdiplus::RectF textRect(x, y, width, height);
Gdiplus::StringFormat format;
format.SetAlignment(Gdiplus::StringAlignmentCenter);
format.SetLineAlignment(Gdiplus::StringAlignmentCenter);
g->DrawString(timeStr, -1, &timeFont, textRect, &format, &textBrush);
}
// Handle tray icon clicks
void HandleTrayIconClick(int index, bool rightClick) {
if (index < 0 || index >= (int)g_trayIcons.size())
return;
TrayIcon &icon = g_trayIcons[index];
if (icon.isRealIcon && icon.realOwner) {
// Notify the real tray icon owner using the callback message registered
// in its NOTIFYICONDATA (uCallbackMessage). Guessing WM_USER+1 was wrong —
// we must use the ID the app registered so it can dispatch the event.
// The lParam carries the mouse notification; wParam is the icon ID.
UINT callbackMsg = icon.realIconId; // icon ID stored at registration time
if (rightClick) {
// Use WM_CONTEXTMENU so the owner can position its context menu
// correctly.
POINT cursorPos;
GetCursorPos(&cursorPos);
SendMessageW(icon.realOwner, WM_CONTEXTMENU, (WPARAM)icon.realOwner,
MAKELPARAM(cursorPos.x, cursorPos.y));
} else {
// Deliver standard tray-click notifications using the app's registered
// callback message. If callbackMsg is 0 fall back to NIN_SELECT.
UINT msg = (callbackMsg != 0) ? callbackMsg : WM_APP;
SendMessageW(icon.realOwner, msg, (WPARAM)icon.realIconId,
MAKELPARAM(WM_LBUTTONDOWN, icon.realIconId));
SendMessageW(icon.realOwner, msg, (WPARAM)icon.realIconId,
MAKELPARAM(WM_LBUTTONUP, icon.realIconId));
}
} else {
// Handle our built-in icons
if (icon.name == L"Volume") {
if (rightClick) {
// Open sound control panel
ShellExecuteW(NULL, L"open", L"control.exe", L"mmsys.cpl", NULL,
SW_SHOW);
} else {
// Open legacy volume control that works without explorer
ShellExecuteW(NULL, L"open", L"sndvol.exe", NULL, NULL, SW_SHOW);
}
} else if (icon.name == L"Network") {
// Open network connections control panel
ShellExecuteW(NULL, L"open", L"control.exe", L"ncpa.cpl", NULL, SW_SHOW);
} else if (icon.name == L"Power") {
// Open power options control panel
ShellExecuteW(NULL, L"open", L"control.exe", L"powercfg.cpl", NULL,
SW_SHOW);
} else if (icon.name == L"Clock") {
// Open Date & Time control panel
ShellExecuteW(NULL, L"open", L"control.exe", L"timedate.cpl", NULL,
SW_SHOW);
}
}
}
// ==================== WINDOWS 11 MINIMIZE/RESTORE ====================
void FlashWindowIfMinimized(HWND hwnd) {
if (IsWindow(hwnd) && IsIconic(hwnd)) {
FLASHWINFO fwi;
fwi.cbSize = sizeof(FLASHWINFO);
fwi.hwnd = hwnd;
fwi.dwFlags = FLASHW_STOP;
fwi.uCount = 0;
fwi.dwTimeout = 0;
FlashWindowEx(&fwi);
fwi.dwFlags = FLASHW_TRAY | FLASHW_TIMERNOFG;
fwi.uCount = 3;
fwi.dwTimeout = 0;
FlashWindowEx(&fwi);
}
}
// MODIFIED: Added Start Menu position saving
void SaveStartMenuPositions() {
try {
nlohmann::json jPositions = nlohmann::json::object();
jPositions["pinnedApps"] = nlohmann::json::array();
for (const auto &app : g_pinnedApps) {
char pathBuf[MAX_PATH];
WideCharToMultiByte(CP_UTF8, 0, app.c_str(), -1, pathBuf, sizeof(pathBuf),
NULL, NULL);
jPositions["pinnedApps"].push_back(pathBuf);
}
std::wstring appDataPath = GetAppDataPath();
CreateDirectoryW(appDataPath.c_str(), NULL);
std::wstring configPath = appDataPath + L"\\startmenu_positions.json";
std::ofstream file(configPath.c_str());
if (file.is_open()) {
file << jPositions.dump(2);
file.close();
}
} catch (...) {
#ifdef _DEBUG
OutputDebugStringW(L"CustomShell: exception swallowed\n");
#endif
}
}
void LoadStartMenuPositions() {
try {
std::wstring appDataPath = GetAppDataPath();
std::wstring configPath = appDataPath + L"\\startmenu_positions.json";
std::ifstream file(configPath.c_str());
if (file.is_open()) {
nlohmann::json jPositions;
file >> jPositions;
file.close();
if (jPositions.contains("pinnedApps") &&
jPositions["pinnedApps"].is_array()) {
g_pinnedApps.clear();
for (const auto &item : jPositions["pinnedApps"]) {
std::string pathStr = item;
wchar_t pathW[MAX_PATH];
MultiByteToWideChar(CP_UTF8, 0, pathStr.c_str(), -1, pathW, MAX_PATH);
g_pinnedApps.push_back(pathW);
}
}
}
} catch (...) {
#ifdef _DEBUG
OutputDebugStringW(L"CustomShell: exception swallowed\n");
#endif
}
}
// NEW FUNCTION: Clean up explorer and shell from all lists
void CleanupExplorerAndShellFromLists() {
// Clean up from start menu
g_pinnedApps.erase(
std::remove_if(g_pinnedApps.begin(), g_pinnedApps.end(), IsBlockedApp),
g_pinnedApps.end());
// Clean up from taskbar
g_taskbarPinned.erase(std::remove_if(g_taskbarPinned.begin(),
g_taskbarPinned.end(), IsBlockedApp),
g_taskbarPinned.end());
// Clean up from taskbar icons
for (auto it = g_taskbarIcons.begin(); it != g_taskbarIcons.end();) {
if (IsBlockedApp(it->path)) {
if (it->hIcon)
DestroyIcon(it->hIcon);
it = g_taskbarIcons.erase(it);
} else {
++it;
}
}
}
// MODIFIED: Updated PopulateStartMenuApps to filter explorer and shell
void PopulateStartMenuApps() {
// First try to load saved positions
LoadStartMenuPositions();
// FILTER OUT EXPLORER AND SHELL FROM SAVED POSITIONS TOO
CleanupExplorerAndShellFromLists();
// If no saved positions, load default
if (g_pinnedApps.empty()) {
std::wstring startMenuPath =
L"C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs";
// Scan for .lnk files
WIN32_FIND_DATAW findData;
HANDLE hFind =
FindFirstFileW((startMenuPath + L"\\*.lnk").c_str(), &findData);
if (hFind != INVALID_HANDLE_VALUE) {
do {
if (!(findData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)) {
std::wstring fullPath = startMenuPath + L"\\" + findData.cFileName;
std::wstring fileName = findData.cFileName;
if (!IsBlockedApp(fullPath)) {
g_pinnedApps.push_back(fullPath);
}
}
} while (FindNextFileW(hFind, &findData));
FindClose(hFind);
}
// Save filtered positions
SaveStartMenuPositions();
}
}
void SaveTaskbarConfig() {
try {
nlohmann::json jConfig = nlohmann::json::object();
// Save pinned apps array
nlohmann::json jApps = nlohmann::json::array();
for (const auto &app : g_taskbarPinned) {
jApps.push_back(app);
}
jConfig["apps"] = jApps;
// Save window positions
nlohmann::json jWindows = nlohmann::json::object();
if (g_hTaskbarWnd) {
RECT rect;
GetWindowRect(g_hTaskbarWnd, &rect);
jWindows["taskbar"] = {{"x", rect.left},
{"y", rect.top},
{"width", rect.right - rect.left},
{"height", rect.bottom - rect.top}};
}
if (g_hStartMenuWnd) {
RECT rect;
GetWindowRect(g_hStartMenuWnd, &rect);
jWindows["startmenu"] = {{"x", rect.left},
{"y", rect.top},
{"width", rect.right - rect.left},
{"height", rect.bottom - rect.top}};
}
jConfig["windows"] = jWindows;
// Save background image path
if (!g_backgroundPath.empty()) {
char bgPath[MAX_PATH];
WideCharToMultiByte(CP_UTF8, 0, g_backgroundPath.c_str(), -1, bgPath,
sizeof(bgPath), NULL, NULL);
jConfig["background"] = bgPath;
}
// Save custom colors
jConfig["taskbarColor"] = {{"r", GetRValue(g_taskbarColor)},
{"g", GetGValue(g_taskbarColor)},
{"b", GetBValue(g_taskbarColor)}};
jConfig["startMenuColor"] = {{"r", GetRValue(g_startMenuColor)},
{"g", GetGValue(g_startMenuColor)},
{"b", GetBValue(g_startMenuColor)}};
std::wstring appDataPath = GetAppDataPath();
CreateDirectoryW(appDataPath.c_str(), NULL);
char filePath[MAX_PATH];
WideCharToMultiByte(CP_UTF8, 0,
(appDataPath + L"\\shell_config.json").c_str(), -1,
filePath, sizeof(filePath), NULL, NULL);
std::ofstream file(filePath);
if (file.is_open()) {
file << jConfig.dump(2);
file.close();
}
#ifdef _DEBUG
else {
OutputDebugStringW(
L"SaveTaskbarConfig: failed to open config file for writing\n");
}
#endif
} catch (...) {
// Silently fail if can't save
#ifdef _DEBUG
OutputDebugStringW(L"SaveTaskbarConfig: exception during save\n");
#endif
}
}
void LoadTaskbarConfig() {
try {
std::wstring appDataPath = GetAppDataPath();
char filePath[MAX_PATH];
WideCharToMultiByte(CP_UTF8, 0,
(appDataPath + L"\\shell_config.json").c_str(), -1,
filePath, sizeof(filePath), NULL, NULL);
std::ifstream file(filePath);
if (file.is_open()) {
nlohmann::json jConfig;
file >> jConfig;
file.close();
// Load pinned apps
if (jConfig.contains("apps") && jConfig["apps"].is_array()) {
g_taskbarPinned.clear();
for (const auto &item : jConfig["apps"]) {
g_taskbarPinned.push_back(item.template get<std::wstring>());
}
}
}
} catch (...) {
// Use defaults if can't load
}
}
int g_taskbarX = 0, g_taskbarY = 0, g_taskbarWidth = 0;
int g_startMenuX = 10, g_startMenuY = 0, g_startMenuWidth = 0,
g_startMenuHeightCfg = 0;
void LoadWindowPositions() {
try {
std::wstring appDataPath = GetAppDataPath();
char filePath[MAX_PATH];
WideCharToMultiByte(CP_UTF8, 0,
(appDataPath + L"\\shell_config.json").c_str(), -1,