-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwindows-11-start-menu-buttons.wh.cpp
More file actions
1865 lines (1588 loc) · 70.1 KB
/
windows-11-start-menu-buttons.wh.cpp
File metadata and controls
1865 lines (1588 loc) · 70.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
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
// ==WindhawkMod==
// @id windows-11-start-menu-buttons
// @name Windows 11 Start Menu Buttons
// @description Customizable buttons for the Windows 11 Start menu.
// @description:ru-RU Настраиваемые кнопки для меню «Пуск» Windows 11.
// @version 2.1
// @author Salyts
// @license MIT
// @github https://github.com/Salyts
// @include StartMenuExperienceHost.exe
// @include explorer.exe
// @architecture x86-64
// @compilerOptions -lcomctl32 -lole32 -loleaut32 -lruntimeobject -lshlwapi -lshell32 -luuid -luser32 -lwtsapi32 -lpowrprof -lgdi32 -lgdiplus -lshcore -lcrypt32
// ==/WindhawkMod==
// ==WindhawkModReadme==
/*
# Windows 11 Start Menu Buttons 2.1
Replaces the default bottom row of the Windows 11 Start menu with fully customizable buttons.
❗**There may be issues with mods:** Windows 11 Start Menu Styler, Windows 11 Start Menu Power Buttons.


---
## Quick Start
1. Open Windhawk settings for this mod.
2. Add buttons using the **Buttons** list.
3. For each button, pick a **Preset** or set **Preset = Custom** and fill in Name, Icon, Action.
4. Save — the Start menu updates immediately.
---
## Button fields
| Field | Description |
|----------|-------------|
| **Preset** | Ready-made button. Set to `Custom` to define your own. |
| **Name** | Tooltip shown on hover. Leave empty on presets to use their default name. |
| **Icon** | [Segoe Fluent Icons](https://learn.microsoft.com/en-us/windows/apps/design/iconography/segoe-ui-symbol-font) glyph (e.g. `\uE7E8`) **or** full path to an image file (PNG, ICO, JPG, BMP). |
| **Action** | Used only when Preset = `Custom`. See action formats below. |
| **Submenu** | Optional list of child items shown in a flyout. If any submenu items are defined, the button opens the flyout instead of running a direct action. |
---
## Action formats (Custom preset only)
| Prefix | Example | Description |
|--------|---------|-------------|
| `" "` | `"C:\Program Files\Windhawk\windhawk.exe"` | Opens a file or folder by absolute path. |
| `~` | `~Downloads` and `~windhawk.exe` | Opens a folder or file by name. |
| `cmd:` | `cmd:control` | Runs a command through `cmd.exe`. |
| `shell:` | `shell:shutdown /r /f /t 0` | Runs through `powershell.exe`. |
| `press:` | `press:Win+E` or `press:0x5B;0x45` | Keyboard key press using a [Win32 key code](https://learn.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes). |
| `web:` | `web:https://windhawk.net/` | Opens a URL in the default browser. |
| `ms-settings:` | `ms-settings:bluetooth` | Opens a Windows Settings page. |
### Modifier signs (prepend to any action)
| Sign | Example | Description |
|--------|---------|-------------|
| `-` | `-"C:\Program Files\app.exe"` or `-shell:shutdown /r /f /t 0` | Runs as administrator. |
| `*` | `*cmd:tasklist` or `*shell:Get-Process` | Execution with a terminal window. (only for `cmd:` and `shell:` prefixes). |
Signs can be combined: `-*cmd:tasklist` runs cmd in a visible window as admin.
---
## Icon field
| Type | Example | Description |
|---|---|---|
| **Glyph** | `E774` or `\uE774` | Hex code of a [Segoe Fluent Icons](https://learn.microsoft.com/en-us/windows/apps/design/iconography/segoe-ui-symbol-font) glyph. 4-digit hex, `\u` prefix is optional. |
| **Image file** | `C:\Icons\name.png` | Full path to an image. Supported: `.png` `.ico` `.jpg` `.bmp` `.webp`. Recommended: 32x32 px, transparent background. |
| **App path** | `C:\Program Files\Windhawk\windhawk.exe` | Full path to an executable file (`.exe`, `.dll`). The icon will be extracted from the application. |
---
## Presets
| # | Name | Icon | Description |
|---|---|---|---|
| 1 | `Settings` | \uE713 | Opens Windows Settings. |
| 2 | `Explorer` | \uEC50 | Opens File Explorer. |
| 3 | `Documents` | \uE8A5 | Opens the Documents folder. |
| 4 | `Music` | \uEC4F | Opens the Music folder. |
| 5 | `Downloads` | \uE896 | Opens the Downloads folder. |
| 6 | `Pictures` | \uE91B | Opens the Pictures folder. |
| 7 | `Videos` | \uE714 | Opens the Videos folder. |
| 8 | `Network` | \uEC27 | Opens Network places. |
| 9 | `Personal Folder` | \uEC25 | Opens the user's profile folder. |
| 10 | `Shut down` | \uE7E8 | Shuts down the PC. |
| 11 | `Restart` | \uE777 | Restarts the PC. |
| 12 | `Sign out`| \uF3B1 | Logs out of the current account. |
| 13 | `Sleep` | \uE708 | Puts the PC to sleep. |
| 14 | `Hibernate` | \uE823 | Hibernates the PC. |
| 15 | `Lock` | \uE72E | Locks the PC session. |
| 16 | `Power Menu` | \uE7E8 | Opens the power options menu. |
---
## Submenus
Fill in the **Submenu** entries for a button. Each submenu item has its own Name, Icon, and Action.
When at least one submenu item exists, the button opens a flyout menu instead of executing a direct action.
---
Thank you so much, [@SharkIT-sys](https://github.com/SharkIT-sys), for helping to improve the mod!
*/
// ==/WindhawkModReadme==
// ==WindhawkModSettings==
/*
- preset_language: en
$name: Preset language
$description: Language for the tooltip names of preset buttons.
$options:
- en: English
- ru: Russian (Русский)
- alignment: right
$name: Button alignment
$description: Horizontal alignment of the custom button container within the Start menu bottom bar.
$options:
- left: Left
- center: Center
- right: Right
- account_button: left
$name: Account button
$description: Position or visibility of the user account avatar button.
$options:
- left: Left
- center: Center
- right: Right
- hide: Hide
- invert_buttons: true
$name: Invert button order
$description: Reverses the order in which custom buttons appear. Useful when alignment is set to Right.
- invert_icons_submenus: false
$name: Invert icons in submenus
$description: Reverses the order in which icons are displayed in submenus.
- close_start_menu: true
$name: Close Start menu after click
$description: Automatically closes the Start menu after clicking any custom button (except buttons that open a submenu), does not work for the “press:” prefix.
- button_spacing: 0
$name: Spacing between buttons (px)
$description: Horizontal margin between each button.
- container_margin_left: -16
$name: Container left margin (px)
$description: Left margin of the custom button container. Negative values let it overlap the default padding.
- container_margin_right: -16
$name: Container right margin (px)
$description: Right margin of the custom button container. Negative values let it overlap the default padding.
- buttons:
- - Preset: menu_shutdown
$name: Preset
$description: "Choose a built-in preset button, or select Custom to define your own Name / Icon / Action."
$options:
- custom: Custom
- settings: Settings
- explorer: Explorer
- documents: Documents
- downloads: Downloads
- music: Music
- pictures: Pictures
- videos: Videos
- network: Network
- personal_folder: Personal Folder
- shutdown: Shut down
- restart: Restart
- sign_out: Sign out
- sleep: Sleep
- hibernate: Hibernate
- lock: Lock
- menu_shutdown: Power Menu
- Name: ""
$name: Name
$description: "Tooltip shown on hover. Leave empty on preset buttons to use the preset default."
- Icon: ""
$name: Icon
$description: "Segoe Fluent glyph (e.g. E7E8 or \\uE7E8), image path (e.g. C:\\Icons\\app.png), or app path (e.g. C:\\Program Files\\app.exe). Leave empty for preset default."
- Action: ""
$name: Action
$description: "Only used when Preset = Custom. See mod description for supported formats."
- submenu:
- - name: ""
$name: Item name
- icon: ""
$name: Item icon
- action: ""
$name: Item action
$name: Submenu items
$description: "If any items are added here, the button will open a flyout instead of running the direct action."
- - Preset: settings
- - Preset: explorer
$name: Buttons
$description: "Only used when Preset = Custom. See mod description for supported formats."
*/
// ==/WindhawkModSettings==
#include <atomic>
#include <mutex>
#include <string>
#include <vector>
#include <algorithm>
#include <numeric>
#include <windows.h>
#include <shlobj.h>
#include <knownfolders.h>
#include <powrprof.h>
#include <shellapi.h>
#include <shlwapi.h>
#include <shcore.h>
#include <wincrypt.h>
#undef GetCurrentTime
#include <winrt/base.h>
#include <winrt/Windows.Foundation.h>
#include <winrt/Windows.Foundation.Collections.h>
#include <winrt/Windows.System.h>
#include <winrt/Windows.UI.h>
#include <winrt/Windows.UI.Core.h>
#include <winrt/Windows.UI.Xaml.h>
#include <winrt/Windows.UI.Xaml.Controls.h>
#include <winrt/Windows.UI.Xaml.Controls.Primitives.h>
#include <winrt/Windows.UI.Xaml.Media.h>
#include <winrt/Windows.UI.Xaml.Media.Imaging.h>
#include <winrt/Windows.Storage.h>
#include <winrt/Windows.Storage.Streams.h>
#pragma comment(lib, "gdiplus.lib")
#include <gdiplus.h>
namespace wu = winrt::Windows::UI;
namespace wux = winrt::Windows::UI::Xaml;
namespace wuxc = winrt::Windows::UI::Xaml::Controls;
namespace wuxm = winrt::Windows::UI::Xaml::Media;
namespace wuxmi = winrt::Windows::UI::Xaml::Media::Imaging;
namespace wuc = winrt::Windows::UI::Core;
namespace wss = winrt::Windows::Storage::Streams;
static const wchar_t* CONTAINER_TAG = L"WH_SMB_Container";
static const wchar_t* PROXY_WINDOW_CLASS = L"WH_SMB_Proxy_Class";
static const wchar_t* PROXY_WINDOW_NAME = L"WH_SMB_Proxy_Window";
static const wchar_t* THREAD_CALL_MSG = L"WH_SMB_ThreadCall";
static constexpr ULONG_PTR kCopyDataMagic = 0x534D4231;
static constexpr UINT_PTR kRetryTimerId = 0x574831AA;
static const wchar_t* FALLBACK_ICON = L"\uE783";
static std::atomic<bool> g_initialized{false};
static std::atomic<bool> g_unloading{false};
static std::atomic<bool> g_buttonsInjected{false};
static std::atomic<bool> g_monitoringActive{false};
static std::atomic<bool> g_forceRebuild{false};
static std::atomic<bool> g_closeStartMenu{true};
static std::atomic<bool> g_invertIconsSubmenus{false};
static std::mutex g_settingsMutex;
static ULONG_PTR g_gdiplusToken = 0;
static std::mutex g_gdipMutex;
enum class AccountButtonMode { Left, Center, Right, Hide };
struct Settings {
wux::HorizontalAlignment alignment = wux::HorizontalAlignment::Right;
AccountButtonMode accountButton = AccountButtonMode::Left;
bool invertButtons = true;
bool invertIconsSubmenus = false;
bool closeStartMenu = true;
int buttonSpacing = 0;
int containerMarginLeft = -16;
int containerMarginRight = -16;
bool langRussian = false;
};
struct ActionItem {
std::wstring name;
std::wstring icon;
std::wstring action;
std::vector<ActionItem> submenu;
};
static Settings g_settings;
static std::vector<ActionItem> g_buttons;
static winrt::weak_ref<wuxc::Panel> g_parentPanel{nullptr};
static winrt::weak_ref<wux::FrameworkElement> g_originalPowerButton{nullptr};
static winrt::weak_ref<wuxc::StackPanel> g_buttonContainer{nullptr};
static HWND g_proxyWindow = NULL;
static HANDLE g_proxyThread = NULL;
static DWORD g_proxyThreadId = 0;
static HWND g_retryHwnd = NULL;
static winrt::event_token g_visibilityToken{};
static winrt::event_token g_activatedToken{};
static std::wstring Trim(std::wstring s) {
auto isSpace = [](wchar_t c) { return !!iswspace(c); };
while (!s.empty() && isSpace(s.front())) s.erase(s.begin());
while (!s.empty() && isSpace(s.back())) s.pop_back();
return s;
}
static std::wstring ToLower(std::wstring s) {
for (auto& c : s) c = static_cast<wchar_t>(towlower(c));
return s;
}
static bool StartsWithCI(const std::wstring& s, const std::wstring& prefix) {
return s.size() >= prefix.size() &&
_wcsnicmp(s.c_str(), prefix.c_str(), prefix.size()) == 0;
}
static std::wstring StripOuterQuotes(const std::wstring& s) {
if (s.size() >= 2 && s.front() == L'"' && s.back() == L'"')
return s.substr(1, s.size() - 2);
return s;
}
static void SafeFreeString(PCWSTR s) {
if (s) Wh_FreeStringSetting(s);
}
static bool IsImagePath(const std::wstring& s) {
if (s.size() < 4) return false;
if (s.size() >= 2 && s[1] == L':') return true;
if (s.size() >= 2 && s[0] == L'\\' && s[1] == L'\\') return true;
std::wstring lo = ToLower(s);
for (const wchar_t* ext : { L".png", L".ico", L".jpg", L".jpeg", L".bmp", L".webp" }) {
size_t elen = wcslen(ext);
if (lo.size() >= elen && lo.compare(lo.size() - elen, elen, ext) == 0)
return true;
}
return false;
}
static bool IsExePath(const std::wstring& s) {
if (s.size() < 5) return false;
std::wstring lo = ToLower(s);
for (const wchar_t* ext : { L".exe", L".dll" }) {
size_t elen = wcslen(ext);
if (lo.size() >= elen && lo.compare(lo.size() - elen, elen, ext) == 0)
return true;
}
return false;
}
static std::wstring MakeFileUri(const std::wstring& path) {
std::wstring result;
result.reserve(path.size() + 8);
result = L"file:///";
for (wchar_t c : path) {
if (c == L'\\') {
result += L'/';
} else if (c == L' ') {
result += L"%20";
} else {
result += c;
}
}
return result;
}
static std::wstring DecodeEscapes(const std::wstring& in) {
std::wstring out;
out.reserve(in.size());
for (size_t i = 0; i < in.size(); ++i) {
if (in[i] == L'\\' && i + 1 < in.size()) {
wchar_t next = in[i + 1];
if (next == L'u' && i + 5 < in.size()) {
unsigned v = 0; bool ok = true;
for (size_t j = i + 2; j < i + 6; ++j) {
wchar_t c = in[j]; v <<= 4;
if (c >= L'0' && c <= L'9') v |= static_cast<unsigned>(c - L'0');
else if (c >= L'a' && c <= L'f') v |= static_cast<unsigned>(10 + c - L'a');
else if (c >= L'A' && c <= L'F') v |= static_cast<unsigned>(10 + c - L'A');
else { ok = false; break; }
}
if (ok) { out.push_back(static_cast<wchar_t>(v)); i += 5; continue; }
}
switch (next) {
case L'\\': out.push_back(L'\\'); ++i; continue;
case L'"': out.push_back(L'"'); ++i; continue;
case L'n': out.push_back(L'\n'); ++i; continue;
case L'r': out.push_back(L'\r'); ++i; continue;
case L't': out.push_back(L'\t'); ++i; continue;
default: break;
}
}
out.push_back(in[i]);
}
return out;
}
static std::wstring NormalizeIconString(const std::wstring& raw) {
std::wstring s = Trim(raw);
if (s.empty()) return s;
if (IsImagePath(s) || IsExePath(s)) return s;
if (s.size() >= 2 && s[0] == L'/' && s[1] == L'u')
return L"\\" + s.substr(1);
if (s.size() == 4 && std::all_of(s.begin(), s.end(), [](wchar_t c) {
return (c >= L'0' && c <= L'9') || (c >= L'a' && c <= L'f') || (c >= L'A' && c <= L'F');
}))
return L"\\u" + s;
if (s.size() == 6 && s[0] == L'\\' && s[1] == L'u' &&
std::all_of(s.begin() + 2, s.end(), [](wchar_t c) {
return (c >= L'0' && c <= L'9') || (c >= L'a' && c <= L'f') || (c >= L'A' && c <= L'F');
}))
return s;
return s;
}
static void EnsureGdiplus() {
std::lock_guard<std::mutex> lk(g_gdipMutex);
if (g_gdiplusToken == 0) {
Gdiplus::GdiplusStartupInput input;
Gdiplus::GdiplusStartup(&g_gdiplusToken, &input, nullptr);
}
}
static HICON LoadIconFromExe(const std::wstring& path, int size) {
HICON hLarge = nullptr, hSmall = nullptr;
if (ExtractIconExW(path.c_str(), 0, &hLarge, &hSmall, 1) == 0)
return nullptr;
if (size > 16) {
if (hSmall) DestroyIcon(hSmall);
return hLarge;
} else {
if (hLarge) DestroyIcon(hLarge);
return hSmall;
}
}
static std::wstring CreateDataUriFromIcon(HICON hIcon) {
if (!hIcon) return L"";
ICONINFO info{};
if (!GetIconInfo(hIcon, &info)) return L"";
struct BitmapGuard {
HBITMAP color, mask;
~BitmapGuard() {
if (color) DeleteObject(color);
if (mask) DeleteObject(mask);
}
} bmpGuard{ info.hbmColor, info.hbmMask };
BITMAP bm{};
GetObject(info.hbmColor ? info.hbmColor : info.hbmMask, sizeof(bm), &bm);
HDC screenDC = GetDC(nullptr);
HDC memDC = CreateCompatibleDC(screenDC);
BITMAPINFO bmi{};
bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bmi.bmiHeader.biWidth = bm.bmWidth;
bmi.bmiHeader.biHeight = -bm.bmHeight;
bmi.bmiHeader.biPlanes = 1;
bmi.bmiHeader.biBitCount = 32;
bmi.bmiHeader.biCompression = BI_RGB;
void* bits = nullptr;
HBITMAP dib = CreateDIBSection(screenDC, &bmi, DIB_RGB_COLORS, &bits, nullptr, 0);
std::wstring result;
if (dib && bits) {
HBITMAP oldBmp = static_cast<HBITMAP>(SelectObject(memDC, dib));
DrawIconEx(memDC, 0, 0, hIcon, bm.bmWidth, bm.bmHeight, 0, nullptr, DI_NORMAL);
SelectObject(memDC, oldBmp);
try {
wss::InMemoryRandomAccessStream stream;
EnsureGdiplus();
Gdiplus::Bitmap srcBmp(bm.bmWidth, bm.bmHeight, bm.bmWidth * 4,
PixelFormat32bppARGB, static_cast<BYTE*>(bits));
if (srcBmp.GetLastStatus() == Gdiplus::Ok) {
IStream* pStream = nullptr;
if (SUCCEEDED(CreateStreamOverRandomAccessStream(
winrt::get_unknown(stream), IID_PPV_ARGS(&pStream)))) {
CLSID pngClsid;
CLSIDFromString(L"{557CF406-1A04-11D3-9A73-0000F81EF32E}", &pngClsid);
if (srcBmp.Save(pStream, &pngClsid, nullptr) == Gdiplus::Ok) {
stream.Seek(0);
uint64_t size = stream.Size();
if (size > 0 && size < 10 * 1024 * 1024) {
wss::Buffer buffer(static_cast<uint32_t>(size));
stream.ReadAsync(buffer, static_cast<uint32_t>(size), wss::InputStreamOptions::None).get();
auto dataReader = wss::DataReader::FromBuffer(buffer);
std::vector<uint8_t> pngData(static_cast<uint32_t>(size));
dataReader.ReadBytes(pngData);
DWORD base64Len = 0;
CryptBinaryToStringW(pngData.data(), static_cast<DWORD>(pngData.size()),
CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF,
nullptr, &base64Len);
if (base64Len > 0) {
std::vector<wchar_t> base64(base64Len);
if (CryptBinaryToStringW(pngData.data(), static_cast<DWORD>(pngData.size()),
CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF,
base64.data(), &base64Len)) {
result = L"data:image/png;base64," + std::wstring(base64.data(), base64Len - 1);
}
}
}
}
pStream->Release();
}
}
} catch (...) {
Wh_Log(L"Exception creating data URI from icon");
}
DeleteObject(dib);
}
DeleteDC(memDC);
ReleaseDC(nullptr, screenDC);
return result;
}
static wuxmi::BitmapSource CreateBitmapSourceFromIcon(HICON hIcon) {
if (!hIcon) return nullptr;
ICONINFO info{};
if (!GetIconInfo(hIcon, &info)) return nullptr;
struct BitmapGuard {
HBITMAP color, mask;
~BitmapGuard() {
if (color) DeleteObject(color);
if (mask) DeleteObject(mask);
}
} bmpGuard{ info.hbmColor, info.hbmMask };
BITMAP bm{};
GetObject(info.hbmColor ? info.hbmColor : info.hbmMask, sizeof(bm), &bm);
HDC screenDC = GetDC(nullptr);
HDC memDC = CreateCompatibleDC(screenDC);
BITMAPINFO bmi{};
bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bmi.bmiHeader.biWidth = bm.bmWidth;
bmi.bmiHeader.biHeight = -bm.bmHeight;
bmi.bmiHeader.biPlanes = 1;
bmi.bmiHeader.biBitCount = 32;
bmi.bmiHeader.biCompression = BI_RGB;
void* bits = nullptr;
HBITMAP dib = CreateDIBSection(screenDC, &bmi, DIB_RGB_COLORS, &bits, nullptr, 0);
wuxmi::BitmapSource result = nullptr;
if (dib && bits) {
HBITMAP oldBmp = static_cast<HBITMAP>(SelectObject(memDC, dib));
DrawIconEx(memDC, 0, 0, hIcon, bm.bmWidth, bm.bmHeight, 0, nullptr, DI_NORMAL);
SelectObject(memDC, oldBmp);
try {
wss::InMemoryRandomAccessStream stream;
EnsureGdiplus();
Gdiplus::Bitmap srcBmp(bm.bmWidth, bm.bmHeight, bm.bmWidth * 4,
PixelFormat32bppARGB, static_cast<BYTE*>(bits));
if (srcBmp.GetLastStatus() == Gdiplus::Ok) {
IStream* pStream = nullptr;
if (SUCCEEDED(CreateStreamOverRandomAccessStream(
winrt::get_unknown(stream), IID_PPV_ARGS(&pStream)))) {
CLSID pngClsid;
CLSIDFromString(L"{557CF406-1A04-11D3-9A73-0000F81EF32E}", &pngClsid);
if (srcBmp.Save(pStream, &pngClsid, nullptr) == Gdiplus::Ok) {
stream.Seek(0);
wuxmi::BitmapImage bmpImage;
bmpImage.SetSource(stream);
result = bmpImage;
}
pStream->Release();
}
}
} catch (...) {
Wh_Log(L"Exception creating in-memory bitmap from icon");
}
DeleteObject(dib);
}
DeleteDC(memDC);
ReleaseDC(nullptr, screenDC);
return result;
}
static std::wstring SaveIconToPng(HICON hIcon) {
if (!hIcon) return L"";
wchar_t tempDir[MAX_PATH], placeholder[MAX_PATH];
if (!GetTempPathW(MAX_PATH, tempDir)) return L"";
if (!GetTempFileNameW(tempDir, L"ICO", 0, placeholder)) return L"";
struct AutoDelete {
wchar_t path[MAX_PATH];
~AutoDelete() { DeleteFileW(path); }
} guard;
wcscpy_s(guard.path, placeholder);
std::wstring pngPath = std::wstring(placeholder) + L".png";
ICONINFO info{};
if (!GetIconInfo(hIcon, &info)) return L"";
struct BitmapGuard {
HBITMAP color, mask;
~BitmapGuard() {
if (color) DeleteObject(color);
if (mask) DeleteObject(mask);
}
} bmpGuard{ info.hbmColor, info.hbmMask };
BITMAP bm{};
GetObject(info.hbmColor ? info.hbmColor : info.hbmMask, sizeof(bm), &bm);
HDC screenDC = GetDC(nullptr);
HDC memDC = CreateCompatibleDC(screenDC);
BITMAPINFO bmi{};
bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bmi.bmiHeader.biWidth = bm.bmWidth;
bmi.bmiHeader.biHeight = -bm.bmHeight;
bmi.bmiHeader.biPlanes = 1;
bmi.bmiHeader.biBitCount = 32;
bmi.bmiHeader.biCompression = BI_RGB;
void* bits = nullptr;
HBITMAP dib = CreateDIBSection(screenDC, &bmi, DIB_RGB_COLORS, &bits, nullptr, 0);
std::wstring result;
if (dib && bits) {
HBITMAP oldBmp = static_cast<HBITMAP>(SelectObject(memDC, dib));
DrawIconEx(memDC, 0, 0, hIcon, bm.bmWidth, bm.bmHeight, 0, nullptr, DI_NORMAL);
SelectObject(memDC, oldBmp);
EnsureGdiplus();
Gdiplus::Bitmap srcBmp(bm.bmWidth, bm.bmHeight, bm.bmWidth * 4,
PixelFormat32bppARGB, static_cast<BYTE*>(bits));
if (srcBmp.GetLastStatus() == Gdiplus::Ok) {
CLSID pngClsid;
CLSIDFromString(L"{557CF406-1A04-11D3-9A73-0000F81EF32E}", &pngClsid);
if (srcBmp.Save(pngPath.c_str(), &pngClsid, nullptr) == Gdiplus::Ok)
result = pngPath;
}
DeleteObject(dib);
}
DeleteDC(memDC);
ReleaseDC(nullptr, screenDC);
return result;
}
static wuxmi::BitmapSource ResolveExeIconInMemory(const std::wstring& iconStr, int size) {
if (iconStr.empty() || !IsExePath(iconStr)) return nullptr;
if (GetFileAttributesW(iconStr.c_str()) == INVALID_FILE_ATTRIBUTES) {
Wh_Log(L"Executable not found for icon: %s", iconStr.c_str());
return nullptr;
}
HICON hIcon = LoadIconFromExe(iconStr, size);
if (!hIcon) return nullptr;
auto bmpSource = CreateBitmapSourceFromIcon(hIcon);
DestroyIcon(hIcon);
return bmpSource;
}
static std::wstring ResolveExeIcon(const std::wstring& iconStr, int size) {
if (iconStr.empty() || !IsExePath(iconStr)) return iconStr;
if (GetFileAttributesW(iconStr.c_str()) == INVALID_FILE_ATTRIBUTES) {
Wh_Log(L"Executable not found for icon: %s", iconStr.c_str());
return L"";
}
HICON hIcon = LoadIconFromExe(iconStr, size);
if (!hIcon) return L"";
std::wstring png = SaveIconToPng(hIcon);
DestroyIcon(hIcon);
return png;
}
static std::wstring GlyphOrEmpty(const std::wstring& s) {
return (!s.empty() && !IsImagePath(s) && !IsExePath(s)) ? s : std::wstring{};
}
static wux::UIElement MakeButtonIcon(const std::wstring& iconStr) {
if (IsExePath(iconStr)) {
auto bmpSource = ResolveExeIconInMemory(iconStr, 32);
if (bmpSource) {
try {
wuxc::Image img;
img.Width(16); img.Height(16);
img.Stretch(wuxm::Stretch::Uniform);
img.Source(bmpSource);
return img;
} catch (...) {
Wh_Log(L"Exception creating button icon from in-memory bitmap: %s", iconStr.c_str());
}
}
}
std::wstring resolved = ResolveExeIcon(iconStr, 32);
if (!resolved.empty() && IsImagePath(resolved)) {
if (GetFileAttributesW(resolved.c_str()) != INVALID_FILE_ATTRIBUTES) {
try {
wuxmi::BitmapImage bmp;
bmp.DecodePixelWidth(32);
bmp.DecodePixelHeight(32);
bmp.UriSource(winrt::Windows::Foundation::Uri(MakeFileUri(resolved)));
bmp.ImageFailed([resolved](auto&&, auto&&) {
Wh_Log(L"Button icon load failed: %s", resolved.c_str());
});
wuxc::Image img;
img.Width(16); img.Height(16);
img.Stretch(wuxm::Stretch::Uniform);
img.Source(bmp);
return img;
} catch (...) {
Wh_Log(L"Exception creating button image icon: %s", resolved.c_str());
}
} else {
Wh_Log(L"Icon file not found: %s", resolved.c_str());
}
}
wuxc::FontIcon fi;
fi.FontFamily(wuxm::FontFamily(L"Segoe Fluent Icons"));
fi.FontSize(16);
std::wstring glyph = GlyphOrEmpty(resolved.empty() ? iconStr : resolved);
fi.Glyph(!glyph.empty() ? glyph : FALLBACK_ICON);
return fi;
}
static wuxc::IconElement MakeMenuIcon(const std::wstring& iconStr) {
if (IsExePath(iconStr)) {
if (GetFileAttributesW(iconStr.c_str()) != INVALID_FILE_ATTRIBUTES) {
HICON hIcon = LoadIconFromExe(iconStr, 16);
if (hIcon) {
std::wstring dataUri = CreateDataUriFromIcon(hIcon);
DestroyIcon(hIcon);
if (!dataUri.empty()) {
try {
wuxc::BitmapIcon bi;
bi.UriSource(winrt::Windows::Foundation::Uri(dataUri));
bi.ShowAsMonochrome(false);
bi.Width(16); bi.Height(16);
return bi;
} catch (...) {
Wh_Log(L"Exception creating menu icon from data URI: %s", iconStr.c_str());
}
}
}
}
}
std::wstring resolved = iconStr;
if (!IsExePath(iconStr)) {
resolved = ResolveExeIcon(iconStr, 16);
}
if (!resolved.empty() && IsImagePath(resolved)) {
if (GetFileAttributesW(resolved.c_str()) != INVALID_FILE_ATTRIBUTES) {
try {
wuxc::BitmapIcon bi;
bi.UriSource(winrt::Windows::Foundation::Uri(MakeFileUri(resolved)));
bi.ShowAsMonochrome(false);
bi.Width(16); bi.Height(16);
return bi;
} catch (...) {
Wh_Log(L"Exception creating menu image icon: %s", resolved.c_str());
}
} else {
Wh_Log(L"Menu icon file not found: %s", resolved.c_str());
}
}
wuxc::FontIcon fi;
fi.FontFamily(wuxm::FontFamily(L"Segoe Fluent Icons"));
fi.FontSize(16);
std::wstring glyph = GlyphOrEmpty(resolved.empty() ? iconStr : resolved);
fi.Glyph(!glyph.empty() ? glyph : FALLBACK_ICON);
return fi;
}
struct PresetDef {
const wchar_t* key;
const wchar_t* nameEn;
const wchar_t* nameRu;
const wchar_t* icon;
const wchar_t* action;
};
static const PresetDef kPresets[] = {
{ L"settings", L"Settings", L"Параметры", L"\uE713", L"__preset:settings" },
{ L"explorer", L"Explorer", L"Проводник", L"\uEC50", L"__preset:explorer" },
{ L"documents", L"Documents", L"Документы", L"\uE8A5", L"__preset:documents" },
{ L"downloads", L"Downloads", L"Загрузки", L"\uE896", L"__preset:downloads" },
{ L"music", L"Music", L"Музыка", L"\uEC4F", L"__preset:music" },
{ L"pictures", L"Pictures", L"Изображения", L"\uE91B", L"__preset:pictures" },
{ L"videos", L"Videos", L"Видео", L"\uE714", L"__preset:videos" },
{ L"network", L"Network", L"Сеть", L"\uEC27", L"__preset:network" },
{ L"personal_folder", L"Personal Folder", L"Личная папка", L"\uEC25", L"__preset:personal_folder" },
{ L"shutdown", L"Shut down", L"Завершение работы", L"\uE7E8", L"__preset:shutdown" },
{ L"restart", L"Restart", L"Перезагрузка", L"\uE777", L"__preset:restart" },
{ L"sign_out", L"Sign out", L"Выйти", L"\uF3B1", L"__preset:sign_out" },
{ L"sleep", L"Sleep", L"Спящий режим", L"\uE708", L"__preset:sleep" },
{ L"hibernate", L"Hibernate", L"Гибернация", L"\uE823", L"__preset:hibernate" },
{ L"lock", L"Lock", L"Блокировка", L"\uE72E", L"__preset:lock" },
{ L"menu_shutdown", L"Power", L"Выключение", L"\uE7E8", nullptr },
};
static constexpr int kPresetCount = static_cast<int>(std::size(kPresets));
static const PresetDef* FindPreset(const std::wstring& key) {
std::wstring k = ToLower(Trim(key));
if (k.empty() || k == L"custom") return nullptr;
for (int i = 0; i < kPresetCount; ++i)
if (k == kPresets[i].key) return &kPresets[i];
Wh_Log(L"Unknown preset key: '%s'", key.c_str());
return nullptr;
}
static std::wstring PresetName(const PresetDef& pd, bool russian) {
return russian ? pd.nameRu : pd.nameEn;
}
static bool GetKnownFolderPath(const wchar_t* id, std::wstring& out) {
std::wstring n = ToLower(id);
KNOWNFOLDERID fid{};
if (n == L"downloads") fid = FOLDERID_Downloads;
else if (n == L"documents" || n == L"personal") fid = FOLDERID_Documents;
else if (n == L"music") fid = FOLDERID_Music;
else if (n == L"pictures") fid = FOLDERID_Pictures;
else if (n == L"videos") fid = FOLDERID_Videos;
else if (n == L"desktop") fid = FOLDERID_Desktop;
else if (n == L"profile" || n == L"home") fid = FOLDERID_Profile;
else return false;
PWSTR raw = nullptr;
bool ok = SUCCEEDED(SHGetKnownFolderPath(fid, 0, nullptr, &raw)) && raw;
if (ok) out = raw;
CoTaskMemFree(raw);
return ok;
}
static void OpenKnownFolder(const wchar_t* name) {
std::wstring path;
if (GetKnownFolderPath(name, path))
ShellExecuteW(nullptr, L"open", path.c_str(), nullptr, nullptr, SW_SHOWNORMAL);
}
static bool EnableShutdownPrivilege() {
HANDLE hToken = NULL;
if (!OpenProcessToken(GetCurrentProcess(),
TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
return false;
TOKEN_PRIVILEGES tkp{};
tkp.PrivilegeCount = 1;
tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
bool ok = LookupPrivilegeValueW(nullptr, SE_SHUTDOWN_NAME,
&tkp.Privileges[0].Luid) &&
AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, nullptr, nullptr);
CloseHandle(hToken);
return ok;
}
static bool PerformPresetAction(const std::wstring& action) {
if (!StartsWithCI(action, L"__preset:")) return false;
std::wstring key = ToLower(action.substr(9));
if (key == L"settings") ShellExecuteW(nullptr, L"open", L"ms-settings:", nullptr, nullptr, SW_SHOWNORMAL);
else if (key == L"explorer") ShellExecuteW(nullptr, L"open", L"explorer.exe", nullptr, nullptr, SW_SHOWNORMAL);
else if (key == L"documents") OpenKnownFolder(L"documents");
else if (key == L"downloads") OpenKnownFolder(L"downloads");
else if (key == L"music") OpenKnownFolder(L"music");
else if (key == L"pictures") OpenKnownFolder(L"pictures");
else if (key == L"videos") OpenKnownFolder(L"videos");
else if (key == L"network") ShellExecuteW(nullptr, L"open", L"shell:NetworkPlacesFolder", nullptr, nullptr, SW_SHOWNORMAL);
else if (key == L"personal_folder") OpenKnownFolder(L"profile");
else if (key == L"shutdown") { EnableShutdownPrivilege(); ExitWindowsEx(EWX_SHUTDOWN | EWX_FORCE, SHTDN_REASON_MAJOR_OTHER); }
else if (key == L"restart") { EnableShutdownPrivilege(); ExitWindowsEx(EWX_REBOOT | EWX_FORCE, SHTDN_REASON_MAJOR_OTHER); }
else if (key == L"sign_out") { EnableShutdownPrivilege(); ExitWindowsEx(EWX_LOGOFF | EWX_FORCE, 0); }
else if (key == L"sleep") SetSuspendState(FALSE, FALSE, FALSE);
else if (key == L"hibernate") SetSuspendState(TRUE, FALSE, FALSE);
else if (key == L"lock") LockWorkStation();
else return false;
return true;
}
static bool SearchRecursive(const std::wstring& root, const std::wstring& name,
int depth, std::wstring& out) {
if (depth < 0) return false;
std::wstring mask = root;
if (!mask.empty() && mask.back() != L'\\') mask += L'\\';
mask += L'*';
WIN32_FIND_DATAW fd{};
HANDLE h = FindFirstFileW(mask.c_str(), &fd);
if (h == INVALID_HANDLE_VALUE) return false;
bool found = false;
do {
if (!wcscmp(fd.cFileName, L".") || !wcscmp(fd.cFileName, L"..")) continue;
std::wstring full = root;
if (!full.empty() && full.back() != L'\\') full += L'\\';
full += fd.cFileName;
if (!_wcsicmp(fd.cFileName, name.c_str())) {
out = full; found = true; break;
}
if ((fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
!(fd.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
if (SearchRecursive(full, name, depth - 1, out)) { found = true; break; }
}
} while (FindNextFileW(h, &fd));
FindClose(h);
return found;
}
static bool SearchByName(const std::wstring& name, std::wstring& out) {
wchar_t buf[MAX_PATH * 4]{};
if (SearchPathW(nullptr, name.c_str(), nullptr, ARRAYSIZE(buf), buf, nullptr)) {
out = buf; return true;
}
std::vector<std::wstring> roots;
auto addEnvDir = [&](const wchar_t* var) {
wchar_t tmp[MAX_PATH * 2]{};
if (GetEnvironmentVariableW(var, tmp, ARRAYSIZE(tmp))) roots.emplace_back(tmp);
};
addEnvDir(L"ProgramFiles"); addEnvDir(L"ProgramFiles(x86)"); addEnvDir(L"ProgramW6432");
addEnvDir(L"SystemRoot"); addEnvDir(L"LOCALAPPDATA"); addEnvDir(L"APPDATA");
addEnvDir(L"USERPROFILE");
for (const wchar_t* folder : { L"desktop", L"documents", L"downloads",
L"music", L"pictures", L"videos" }) {
std::wstring p;
if (GetKnownFolderPath(folder, p)) roots.push_back(std::move(p));
}
for (const auto& r : roots)
if (SearchRecursive(r, name, 5, out)) return true;
return false;
}
static WORD ResolveKeyToken(const std::wstring& tok) {
if (tok.empty()) return 0;
std::wstring lo = ToLower(tok);
struct { const wchar_t* name; WORD vk; } named[] = {
{ L"ctrl", VK_CONTROL }, { L"alt", VK_MENU },
{ L"shift", VK_SHIFT }, { L"win", VK_LWIN },
{ L"enter", VK_RETURN }, { L"esc", VK_ESCAPE },
{ L"escape", VK_ESCAPE }, { L"tab", VK_TAB },
{ L"space", VK_SPACE }, { L"backspace", VK_BACK },
{ L"delete", VK_DELETE }, { L"del", VK_DELETE },
{ L"insert", VK_INSERT }, { L"ins", VK_INSERT },
{ L"home", VK_HOME }, { L"end", VK_END },
{ L"pageup", VK_PRIOR }, { L"pgup", VK_PRIOR },